code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __download( self, symbols, request_limit = True, in_memory = True, **kwargs): <NEW_LINE> <INDENT> download_result = {} <NEW_LINE> symbols = symbols if isinstance(symbols, list) else [symbols] <NEW_LINE> start_time = time() <NEW_LINE> errors = 0 <NEW_LINE> for i, symbol in enumerate(symbols): <NEW_LINE> <INDENT> pri... | Download interface. | 625941c301c39578d7e74df5 |
def stacksize(since=0.0): <NEW_LINE> <INDENT> return _VmB('VmStk:') - since | Return stack size in bytes. | 625941c37047854f462a13c6 |
def mean_rrank_at_k_batch(train_data, vad_data, test_data, Et, Eb, user_idx, k=5): <NEW_LINE> <INDENT> batch_users = user_idx.stop - user_idx.start <NEW_LINE> X_pred = _make_prediction(train_data, vad_data, Et, Eb, user_idx, batch_users) <NEW_LINE> all_rrank = 1. / (np.argsort(np.argsort(-X_pred, axis=1), axis=1) + 1) ... | mean reciprocal rank@k: For each user, make predictions and rank for
all the items. Then calculate the mean reciprocal rank for the top K that
are in the held-out test set. | 625941c37cff6e4e81117940 |
def ListItemsInFolder(self, path='/', types_to_fetch=EntryType.FILES_AND_FOLDERS, include_dates=False): <NEW_LINE> <INDENT> items = [] <NEW_LINE> if path[-1] != '/': <NEW_LINE> <INDENT> path += '/' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> info = self.zip_file.getinfo(path[1:]) <NEW_LINE> <DEDENT> except KeyError: <... | Returns a list of files and/or folders in a list
Format of list = [ {'name':'got.txt', 'type':EntryType.FILES, 'size':10}, .. ]
'path' should be linux style using forward-slash like '/var/db/xxyy/file.tdc'
and starting at root / | 625941c34f88993c3716c023 |
def close_ssh(self): <NEW_LINE> <INDENT> self.client.close() <NEW_LINE> logging.debug('## {} - {}.close_ssh()'.format(__name__, self)) | Closes the SSH connection to the target server. | 625941c39b70327d1c4e0d8e |
def setAmplitude(self, amplitude): <NEW_LINE> <INDENT> self.arcradius = amplitude <NEW_LINE> return self | Set the size of the oscillation. | 625941c331939e2706e4ce26 |
def _init_unit_combo(self, combo_box): <NEW_LINE> <INDENT> store = Gtk.ListStore(str) <NEW_LINE> combo_box.set_model(store) <NEW_LINE> for label in (x.label for x in gaupol.length_units): <NEW_LINE> <INDENT> store.append((label,)) <NEW_LINE> <DEDENT> renderer = Gtk.CellRendererText() <NEW_LINE> combo_box.pack_start(ren... | Initialize line length unit `combo_box`. | 625941c363b5f9789fde709f |
def commit(*args): <NEW_LINE> <INDENT> cmd = ['git', 'commit'] + list(args) <NEW_LINE> return _exec(cmd) | Performs `git commit`. | 625941c321a7993f00bc7ca6 |
def test_check_for_export_with_some_volume_missing(self): <NEW_LINE> <INDENT> volume_id_list = self._attach_volume() <NEW_LINE> instance_uuid = '12345678-1234-5678-1234-567812345678' <NEW_LINE> tid = db.volume_get_iscsi_target_num(self.context, volume_id_list[0]) <NEW_LINE> self.mox.StubOutWithMock(self.volume.driver.t... | Output a warning message when some volumes are not recognied
by ietd. | 625941c36aa9bd52df036d5d |
@pytest.fixture() <NEW_LINE> def insert_parent_task( repo: Repository, ) -> Tuple[RecurrentTask, Task]: <NEW_LINE> <INDENT> parent_task = factories.RecurrentTaskFactory.create(state="backlog") <NEW_LINE> child_task = parent_task.breed_children() <NEW_LINE> repo.add(parent_task) <NEW_LINE> repo.add(child_task) <NEW_LINE... | Insert a RecurrentTask and it's children Task in the FakeRepository. | 625941c3187af65679ca50d8 |
def compute_autocorr(precip,model_dict): <NEW_LINE> <INDENT> print('---> Computing auto-correlations') <NEW_LINE> nlon=len(precip.coord('longitude').points) <NEW_LINE> nlat=len(precip.coord('latitude').points) <NEW_LINE> autocorr_length = model_dict['autocorr_length'] <NEW_LINE> max_box_distance,max_boxes,max_timesteps... | Compute the lagged auto-correlation of precipitatio
across all points in the analysis domain.
Arguments:
* precip:
An iris cube of precipitation to analyse
* model_dict:
The dictionary of information about this dataset
Returns:
* time_correlations (max_timesteps):
Composite lagged auto-correlations across... | 625941c323e79379d52ee520 |
def fit_transform(self, raw_inputs): <NEW_LINE> <INDENT> return self.fit(raw_inputs).transform(raw_inputs) | Fit to `raw_inputs`, then transform `raw_inputs`. | 625941c373bcbd0ca4b2c030 |
def write_to_file(correct_tweets, path): <NEW_LINE> <INDENT> with open(path, 'w+') as outfile: <NEW_LINE> <INDENT> for l_tweet in correct_tweets: <NEW_LINE> <INDENT> json.dump(l_tweet, outfile) <NEW_LINE> outfile.write('\n') | Write labeled tweets to a file | 625941c307f4c71912b1143b |
def __init__( self, face: Face, face_basis: Basis, face_reference_frame_transformation_matrix: Mat, displacement: List[Callable], ): <NEW_LINE> <INDENT> displacement_vector = Integration.get_face_pressure_vector_in_face( face, face_basis, face_reference_frame_transformation_matrix, displacement ) <NEW_LINE> self.displa... | ================================================================================================================
Class :
================================================================================================================
=====================================================================================... | 625941c34527f215b584c413 |
def __init__(self, keyword_list): <NEW_LINE> <INDENT> self.keywords = keyword_list <NEW_LINE> logging.Filter.__init__(self) | Acquires a list of keywords to check records with | 625941c321bff66bcd68490f |
def white_code_words(language_id: str) -> Dict[str, List[str]]: <NEW_LINE> <INDENT> assert language_id is not None <NEW_LINE> assert language_id.islower() <NEW_LINE> return _LANGUAGE_TO_WHITE_WORDS_MAP.get(language_id, set()) | Words that do not count as code if it is the only word in a line. | 625941c3b830903b967e98c7 |
def __processSSI(self, txt, filename, root): <NEW_LINE> <INDENT> if not filename: <NEW_LINE> <INDENT> return txt <NEW_LINE> <DEDENT> incRe = re.compile( r"""<!--#include[ \t]+(virtual|file)=[\"']([^\"']+)[\"']\s*-->""", re.IGNORECASE) <NEW_LINE> baseDir = os.path.dirname(os.path.abspath(filename)) <NEW_LINE> docRoot = ... | Private method to process the given text for SSI statements.
Note: Only a limited subset of SSI statements are supported.
@param txt text to be processed (string)
@param filename name of the file associated with the given text
(string)
@param root directory of the document root (string)
@return processed HTML (st... | 625941c37b180e01f3dc47bb |
def get_status(self): <NEW_LINE> <INDENT> return GetStatus(*self.ipcon.send_request(self, BrickletGPS.FUNCTION_GET_STATUS, (), '', 'B B B')) | Returns the current fix status, the number of satellites that are in view and
the number of satellites that are currently used.
Possible fix status values can be:
.. csv-table::
:header: "Value", "Description"
:widths: 10, 100
"1", "No Fix, :func:`GetCoordinates`, :func:`GetAltitude` and :func:`GetMotion` return ... | 625941c392d797404e304144 |
def solo(*args, **kwargs): <NEW_LINE> <INDENT> args += ('chef-solo',) <NEW_LINE> return __exec_cmd(*args, **kwargs) | Execute a chef solo run and return a dict with the stderr, stdout,
return code, etc.
CLI Example:
.. code-block:: bash
salt '*' chef.solo config=/etc/chef/solo.rb -l debug | 625941c3f548e778e58cd537 |
def add_commentor(self, lang, *args, **kwargs): <NEW_LINE> <INDENT> commentor_cls = kwargs.get('commentor_cls', Commentor) <NEW_LINE> if lang not in self.__registry: <NEW_LINE> <INDENT> self.set_commentor(lang, *args, commentor_cls=commentor_cls) | check if a commentor exists and call set_commentor if necessary | 625941c376e4537e8c35162b |
def activate(self, X): <NEW_LINE> <INDENT> X = self._transform(X, fit=False) <NEW_LINE> return self.Activation(X) | Activates NN on particular dataset
:param numpy.array X: of shape [n_samples, n_features]
:return: numpy.array with results of shape [n_samples] | 625941c356b00c62f0f14613 |
def _oauth2_callback(self): <NEW_LINE> <INDENT> code = self.request.get('code', None) <NEW_LINE> logging.info('code is: %s' % code) <NEW_LINE> error = self.request.get('error', None) <NEW_LINE> callback_url = self._callback_uri() <NEW_LINE> access_token_url = URLS[1] <NEW_LINE> consumer_key, consumer_secret = self._get... | Step 2 of OAuth 2.0, whenever the user accepts or denies access. | 625941c330bbd722463cbd7f |
def test_composition_all_3(): <NEW_LINE> <INDENT> add1 = Add1() <NEW_LINE> sum_all = list_x.All(actions=[add1, add1, list_x.Success(), add1, add1]).execute( rez=Rez(result=10.1) ) <NEW_LINE> assert sum_all.result == 14.1 | Show that introduction of Success does not impact the result. | 625941c3379a373c97cfaaff |
def get_pair_dict(path, t, user=None, haploscores=False, nomask=False, merge_len=-1): <NEW_LINE> <INDENT> s_list = read_matchfile(path, haploscores) <NEW_LINE> pair_dict = {} <NEW_LINE> for seg in s_list: <NEW_LINE> <INDENT> assert isinstance(seg, SharedSegment) <NEW_LINE> assert seg.lengthUnit == "cM" <NEW_LINE> if se... | Reads from path and collapses the input data into a dictionary
mapping pairs to SharedSegments.
Parameters
----------
path : str
t : float
Filter out results less than t (in cM)
user : str | None
filter input by user identification
haploscores : bool
True if the input matchfile contains haploscores in a... | 625941c330dc7b7665901923 |
def inverse_mask(self): <NEW_LINE> <INDENT> return self.invert_mask() | Alias for :func:`invert_mask`
See Also:
:func:`invert_mask`
Returns: | 625941c360cbc95b062c64fd |
def goodTree(length, level): <NEW_LINE> <INDENT> angle = 17 <NEW_LINE> width = 4 <NEW_LINE> turtle.width(width) <NEW_LINE> turtle.left(90) <NEW_LINE> turtle.forward(length) <NEW_LINE> def treeHelp(length, level): <NEW_LINE> <INDENT> width = turtle.width() <NEW_LINE> turtle.width(3 / 4 * width) <NEW_LINE> length = lengt... | a better fractal tree with turtle for extra credit | 625941c3d10714528d5ffc9c |
def getKeyboardButtonPoll(text: str, request_poll={}) -> Dict: <NEW_LINE> <INDENT> return {'text': text, 'request_poll': request_poll} | This object represents poll button of the reply keyboard
Notes:
For more info -> https://github.com/xSklero/python-telegram-api/wiki/KeyboardButton
Args:
text (str): Text of the button.
request_poll (Dict, optional): If specified, the user will be asked to create a poll and send it to the bot when the but... | 625941c324f1403a92600b23 |
def sync(self, importer, state, log=None, max_changes=None, window=None, begin=None, end=None, stats=None): <NEW_LINE> <INDENT> importer.store = None <NEW_LINE> return _ics.sync(self, self.mapistore, importer, state, log or self.log, max_changes, window=window, begin=begin, end=end, stats=stats) | Perform synchronization against server node.
:param importer: importer instance with callbacks to process changes
:param state: start from this state (has to be given)
:log: logger instance to receive important warnings/errors | 625941c35fcc89381b1e1678 |
def twovec(axdef, indexa, plndef, indexp): <NEW_LINE> <INDENT> axdef = stypes.toDoubleVector(axdef) <NEW_LINE> indexa = ctypes.c_int(indexa) <NEW_LINE> plndef = stypes.toDoubleVector(plndef) <NEW_LINE> indexp = ctypes.c_int(indexp) <NEW_LINE> mout = stypes.emptyDoubleMatrix() <NEW_LINE> libspice.twovec_c(axdef, indexa,... | Find the transformation to the right-handed frame having a
given vector as a specified axis and having a second given
vector lying in a specified coordinate plane.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/twovec_c.html
:param axdef: Vector defining a principal axis.
:type axdef: 3-Element Array of flo... | 625941c35fdd1c0f98dc01ed |
def topological_sort(graph, depth_first=False): <NEW_LINE> <INDENT> import networkx as nx <NEW_LINE> nodesort = list(nx.topological_sort(graph)) <NEW_LINE> if not depth_first: <NEW_LINE> <INDENT> return nodesort, None <NEW_LINE> <DEDENT> logger.debug("Performing depth first search") <NEW_LINE> nodes = [] <NEW_LINE> gro... | Returns a depth first sorted order if depth_first is True
| 625941c33d592f4c4ed1d02d |
def unmuted(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_pwr_squelch_ff_sptr_unmuted(self) | unmuted(self) -> bool | 625941c326068e7796caec97 |
def submit_delete_problem_state_for_all_students(request, usage_key): <NEW_LINE> <INDENT> modulestore().get_item(usage_key) <NEW_LINE> task_type = 'delete_problem_state' <NEW_LINE> task_class = delete_problem_state <NEW_LINE> task_input, task_key = encode_problem_and_student_input(usage_key) <NEW_LINE> return submit_ta... | Request to have state deleted for a problem as a background task.
The problem's state will be deleted for all students who have accessed the
particular problem in a course. Parameters are the `course_id` and
the `usage_key`, which must be a :class:`Location`.
ItemNotFoundException is raised if the problem doesn't ex... | 625941c3596a897236089a7d |
def run_from_copy(server_name, user_id, user_password, local_file, remote_file) : <NEW_LINE> <INDENT> sf = paramiko.Transport((server_name,22)) <NEW_LINE> sf.connect(username = user_id, password = user_password) <NEW_LINE> sftp = paramiko.SFTPClient.from_transport(sf) <NEW_LINE> return sftp.get(remote_file,local_file ) | Copy file from remote to local.
Remark: No handing of any kind of exeception.
Args:
server_name(string): Name of the host to connect.
user_id(string): User to connect with.
user_password(string): User password.
local_file(string): Absolute path of file in local.
remote_file(string): Absolute path of file in r... | 625941c3236d856c2ad44793 |
def test_urgency_set(self): <NEW_LINE> <INDENT> self.launcher.set_urgent() <NEW_LINE> self.assertTrue( self.launcher.entry.props.urgent, "The launcher should be set to urgent.") <NEW_LINE> self.launcher.set_urgent(False) <NEW_LINE> self.assertFalse( self.launcher.entry.props.urgent, "The launcher should not be set to u... | The urgency of the launcher is set. | 625941c3435de62698dfdc07 |
def expand_unit_rules(rules, lhs_fn, rhs_fn, rule_init_fn, nonterminal_prefix): <NEW_LINE> <INDENT> unit_tuples = set() <NEW_LINE> other_rules = [] <NEW_LINE> for rule in rules: <NEW_LINE> <INDENT> tokens = rhs_fn(rule).split(" ") <NEW_LINE> if len(tokens) == 1 and tokens[0].startswith(nonterminal_prefix): <NEW_LINE> <... | Removes unit rules, i.e.
X -> Y where X and Y are non-terminals.
Args:
rules: List of rule objects.
lhs_fn: Returns `lhs` of a rule.
rhs_fn: Returns `rhs` of a rule.
rule_init_fn: Function that takes (lhs, rule) and returns a copy of `rule`
but with the lhs symbol set to `lhs`.
nonterminal_prefix: Strin... | 625941c316aa5153ce362433 |
def plot_2d_rint(_df,_column_interv, _column_x, _column_y, _title = 'example', _filename = ''): <NEW_LINE> <INDENT> for value in _df[_column_interv].value_counts().index.tolist(): <NEW_LINE> <INDENT> df_sub = _df[_df[_column_interv] == value] <NEW_LINE> fig = plt.figure(figsize=(20, 10)) <NEW_LINE> ax = fig.add_subplot... | Creazione di molteplici plot per ogni valore distinto di un attributo di un Dataframe.
Analisi bidimensionale.
:param _df: Dataframe
Dataframe da analizzare
:param _column_interv: str
colonna del Dataframe su cui partizionare i plot. Per ogni suo valore univoco verrà creato un plot e un subset.
:param _column_... | 625941c34d74a7450ccd417e |
def control_q(self): <NEW_LINE> <INDENT> if self.success_rate == None: <NEW_LINE> <INDENT> print("Error, first compute success rate") <NEW_LINE> exit(-1) <NEW_LINE> <DEDENT> self.q = self.evaluate_map('q', self.success_rate) | Use population success rate to update Xi | 625941c382261d6c526ab457 |
def seal_is_valid(self): <NEW_LINE> <INDENT> if self.seal_data == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> signature = binascii.unhexlify(hex(self.seal_data)[2:].zfill(96)) <NEW_LINE> pk = VerifyingKey.from_string(self.get_public_key()) <NEW_LINE> try: <NEW_LINE> <INDENT> return pk.verify(signature, self... | Checks whether a block's seal_data forms a valid seal.
In PoA, this means that Verif(PK, [block, sig]) = accept.
(aka the unsealed block header is validly signed under the authority's public key)
Returns:
bool: True only if a block's seal data forms a valid seal according to PoA. | 625941c3ad47b63b2c509f3a |
def on_uiButtonBox_clicked(self, button): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from gns3.main_window import MainWindow <NEW_LINE> if button == self.uiButtonBox.button(QtGui.QDialogButtonBox.Apply): <NEW_LINE> <INDENT> self.applySettings() <NEW_LINE> <DEDENT> elif button == self.uiButtonBox.button(QtGui.QDialogB... | Slot called when a button of the uiButtonBox is clicked.
:param button: button that was clicked (QAbstractButton) | 625941c315fb5d323cde0ac8 |
def read_bitcoin_config(dbdir): <NEW_LINE> <INDENT> from ConfigParser import SafeConfigParser <NEW_LINE> class FakeSecHead(object): <NEW_LINE> <INDENT> def __init__(self, fp): <NEW_LINE> <INDENT> self.fp = fp <NEW_LINE> self.sechead = '[all]\n' <NEW_LINE> <DEDENT> def readline(self): <NEW_LINE> <INDENT> if self.sechead... | Read the insurance.conf file from dbdir, returns dictionary of settings | 625941c399cbb53fe6792ba2 |
def __add__(self, val): <NEW_LINE> <INDENT> v = val if isinstance(val, Variable) else IndependentVariable(val) <NEW_LINE> return Sum(self, v) | Addition of two variables, or of a variable and a scalar. | 625941c3d268445f265b4e29 |
def get_game_config_val_int(key): <NEW_LINE> <INDENT> _game_config = client_configs['game_config'] <NEW_LINE> for item in _game_config: <NEW_LINE> <INDENT> if item['key'] == key: <NEW_LINE> <INDENT> return int(item['val']) <NEW_LINE> <DEDENT> <DEDENT> return 0 | 获取游戏数据表值
BattleSpeedLineTime 111
BattleEnemyScale 1
BattleModuleLevelScale 0.000
PlayerCreateMonster 1,4,7
PlayerStaminaRecover 10
PlayerMaxStamina 120
UpgradeStarCard 3,3,3,6
UpgradeStarGold 10000,20000,500000,1000000
TeamOpenLevel 1,3,5,8,12
LevelOpe... | 625941c36e29344779a625cf |
def __init__(self, version, response, solution): <NEW_LINE> <INDENT> super(BrandedCallPage, self).__init__(version, response) <NEW_LINE> self._solution = solution | Initialize the BrandedCallPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:returns: twilio.rest.preview.trusted_comms.branded_call.BrandedCallPage
:rtype: twilio.rest.preview.trusted_comms.branded_call.BrandedCallPage | 625941c3f8510a7c17cf96b6 |
def test_remove_from_error(self, client): <NEW_LINE> <INDENT> vm = mfactory.VirtualMachineFactory(operstate='ERROR') <NEW_LINE> mfactory.NetworkInterfaceFactory(machine=vm) <NEW_LINE> msg = self.create_msg(operation='OP_INSTANCE_REMOVE', instance=vm.backend_vm_id) <NEW_LINE> with mocked_quotaholder(): <NEW_LINE> <INDEN... | Test that error removes delete error builds | 625941c3a8370b771705285b |
def exit_config_mode(self, exit_config: str = "return", pattern: str = r">") -> str: <NEW_LINE> <INDENT> return super().exit_config_mode(exit_config=exit_config, pattern=pattern) | Exit configuration mode. | 625941c371ff763f4b549643 |
def update(self, grid): <NEW_LINE> <INDENT> nid = grid.nid <NEW_LINE> add_grid = self.check_if_current(nid, self.nid) <NEW_LINE> if add_grid: <NEW_LINE> <INDENT> self.add(nid, grid.xyz, cp=grid.cp, cd=grid.cd, ps=grid.ps, seid=grid.seid, comment=grid.comment) <NEW_LINE> self.is_current = False <NEW_LINE> <DEDENT> else:... | functions like a dictionary | 625941c345492302aab5e27c |
def detect_faces(self, *args, **kwargs): <NEW_LINE> <INDENT> super().detect_faces(*args, **kwargs) <NEW_LINE> self.rotate_queue = queue_manager.get_queue("s3fd_rotate", 8, False) <NEW_LINE> prediction_queue = queue_manager.get_queue("s3fd_pred", 8, False) <NEW_LINE> post_queue = queue_manager.get_queue("s3fd_post", 8, ... | Detect faces in rgb image | 625941c3004d5f362079a2ef |
def send_mouse_event(self, mouse_event): <NEW_LINE> <INDENT> if mouse_event: <NEW_LINE> <INDENT> self.mouse_pos[0] = mouse_event.pos[0] <NEW_LINE> self.mouse_pos[1] = mouse_event.pos[1] <NEW_LINE> self.language_engine.global_symbol_table['mouse.x'] = self.mouse_pos[0] <NEW_LINE> self.language_engine.global_symbol_table... | Translate pygame mouse events (including no buttons pressed) to
appropriate pygame_maker mouse events. | 625941c34c3428357757c2e5 |
def reGenChain(self): <NEW_LINE> <INDENT> self.m_rigElement.clear() <NEW_LINE> self.genChain() | Method: reGenChain
A method to regenerate the chain based on a new set of parameters | 625941c33c8af77a43ae3759 |
def move_up(): <NEW_LINE> <INDENT> return move('up') | Move straight up.
Convenience function for user facing portion.
:return: result of move(direction) | 625941c32ae34c7f2600d0ed |
def get_manuals(): <NEW_LINE> <INDENT> docs = glob.glob(os.path.join("doc", "manual", "*.html")) <NEW_LINE> docs.append(os.path.join("doc", "manual", "manual.css")) <NEW_LINE> if get_command() == "sdist": <NEW_LINE> <INDENT> docs.append(os.path.join("doc", "manual.tex")) <NEW_LINE> docs.append(os.path.join("doc", ".lat... | Returns a list of all manual files | 625941c3d4950a0f3b08c30b |
def unindex_object(self): <NEW_LINE> <INDENT> pass | No action.
Unindex of subdevices will happen in manage_deleteAdministrativeRole | 625941c382261d6c526ab458 |
@pytest.fixture <NEW_LINE> def backend_with_a_poll(backend_with_a_round): <NEW_LINE> <INDENT> backend_with_a_round.add_poll(GAME_ID, ROUND_NAME) <NEW_LINE> return backend_with_a_round | Return a persistence backend holding one game with one round. | 625941c3287bf620b61d3a20 |
def is_server(self, location): <NEW_LINE> <INDENT> return location in self.servers | Return True if 'location' is an index server.
| 625941c30a50d4780f666e4c |
def publish_status_information(): <NEW_LINE> <INDENT> if cf.has_option("defaults", "status_publish") and cf.status_publish: <NEW_LINE> <INDENT> status_topic = cf.g("defaults", "status_topic", "mqttwarn/$SYS") <NEW_LINE> logger.info(f"Publishing status information to {status_topic}") <NEW_LINE> publications = [ ("versio... | Implement `$SYS` topic, like Mosquitto's "Broker Status".
https://mosquitto.org/man/mosquitto-8.html#idm289
Idea from Mosquitto::
$ mosquitto_sub -t '$SYS/broker/version' -v
$SYS/broker/version mosquitto version 2.0.10
Synopsis::
$ mosquitto_sub -t 'mqttwarn/$SYS/#' -v
mqttwarn/$SYS/version 0.26.2
mqttwa... | 625941c3be7bc26dc91cd5be |
def facts(self, name=None, value=None, **kwargs): <NEW_LINE> <INDENT> if name is not None and value is not None: <NEW_LINE> <INDENT> path = '{0}/{1}'.format(name, value) <NEW_LINE> <DEDENT> elif name is not None and value is None: <NEW_LINE> <INDENT> path = name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path = None... | Query for facts limited by either name, value and/or query.
:param name: (Optional) Only return facts that match this name.
:type name: :obj:`string`
:param value: (Optional) Only return facts of `name` that\
match this value. Use of this parameter requires the `name`\
parameter be set.
:type value: :obj:`stri... | 625941c3baa26c4b54cb10dc |
def default_view(self, **kwargs): <NEW_LINE> <INDENT> v = ColorTranslationDiagnostic(op = self) <NEW_LINE> v.trait_set(**kwargs) <NEW_LINE> return v | Returns a diagnostic plot to see if the bleedthrough spline estimation
is working.
Returns
-------
IView
A diagnostic view, call `ColorTranslationDiagnostic.plot` to
see the diagnostic plots | 625941c394891a1f4081ba64 |
def write_org_ratios_to_database(self, org_type): <NEW_LINE> <INDENT> for datum in self.get_rows_as_dicts(self.table_name(org_type)): <NEW_LINE> <INDENT> datum["measure_id"] = self.measure.id <NEW_LINE> if self.measure.is_cost_based: <NEW_LINE> <INDENT> datum["cost_savings"] = convertSavingsToDict(datum) <NEW_LINE> <DE... | Create measure values for organisation ratios. | 625941c3c432627299f04c00 |
def invoke_hook (self, msg_id, domain, result, body=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = int(result) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> log.error("Received response code is not valid: %s! Abort callback..." % result) <NEW_LINE> return <NEW_LINE> <DEDENT> if (domain, msg_i... | Main entry point to invoke a callback based on the extracted data from
received message.
:param msg_id: message id
:type msg_id: str
:param domain: domain name
:type domain: str
:param result: result of the callback
:type result: str
:param body: parsed callback body (optional)
:type body: str or None
:return: None | 625941c33cc13d1c6d3c7336 |
def epsilon_action(a,eps = 0.1): <NEW_LINE> <INDENT> rand_number = np.random.random() <NEW_LINE> if rand_number < (1-eps): <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.random.choice(CONST_ACTION_LST) | epsilon greedy. Chooses either action a or an radom action with epsioln probablility
Args: None
Return: None | 625941c35fc7496912cc3939 |
def Oracle(X, B, s, t, list_V): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> Dmax = 1 <NEW_LINE> global num_senses <NEW_LINE> global num_moves <NEW_LINE> global num_experiments <NEW_LINE> t = t[:-3] <NEW_LINE> num_moves += len(t) <NEW_LINE> random_board = Board() <NEW_LINE> random_board.load_random_board() <... | determine if s and t are equivilant | 625941c3442bda511e8be3d6 |
def test_bad_attribute_access(): <NEW_LINE> <INDENT> program = f"x = 1\n" f"x.wrong_name\n" <NEW_LINE> module, inferer = cs._parse_text(program) <NEW_LINE> expr_node = next(module.nodes_of_class(nodes.Expr)) <NEW_LINE> expected_msg = "TypeFail: Invalid attribute lookup x.wrong_name" <NEW_LINE> assert expr_node.inf_type... | User tries to access a non-existing attribute; or misspells the attribute name. | 625941c3aad79263cf3909fa |
def countSubstrings(self, s): <NEW_LINE> <INDENT> output = [] <NEW_LINE> def substring(index1, index2): <NEW_LINE> <INDENT> if index1 < 0 or index2 == len(s): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if index1 == index2: <NEW_LINE> <INDENT> output.append(1) <NEW_LINE> substring(index1, index2 + 1) <NEW_LINE> subs... | :type s: str
:rtype: int | 625941c3851cf427c661a4cd |
def __ConnectAndDrop(self): <NEW_LINE> <INDENT> connection = self.pool.acquire() <NEW_LINE> cursor = connection.cursor() <NEW_LINE> cursor.execute("select count(*) from TestNumbers") <NEW_LINE> count, = cursor.fetchone() <NEW_LINE> self.failUnlessEqual(count, 10) | Connect to the database, perform a query and drop the connection. | 625941c326238365f5f0ee27 |
def read_prefixlist(): <NEW_LINE> <INDENT> global d_prefix <NEW_LINE> try: <NEW_LINE> <INDENT> with open(config['prefixlist'], "r") as fp: <NEW_LINE> <INDENT> prefixdata = fp.readlines() <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> print("cannot read the prefixlist file") <NEW_LINE> return <NEW_LINE> <DEDEN... | Read the prefixlist and stotr in the memory object list | 625941c3377c676e91272165 |
def get_modal_lit(self): <NEW_LINE> <INDENT> for disjunct in self.disjuncts: <NEW_LINE> <INDENT> if u.is_complex(disjunct): <NEW_LINE> <INDENT> if isinstance(disjunct[0], parser.Modality): <NEW_LINE> <INDENT> self.disjuncts.remove(disjunct) <NEW_LINE> return disjunct <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None | Returns first modal atom in a given disjunction.
| 625941c391af0d3eaac9b9d2 |
def levelOrder(self, root): <NEW_LINE> <INDENT> ans = [] <NEW_LINE> if not root: return ans <NEW_LINE> q = [root] <NEW_LINE> while q: <NEW_LINE> <INDENT> ans.append([x.val for x in q]) <NEW_LINE> nq = [] <NEW_LINE> for node in q: <NEW_LINE> <INDENT> if node.left: nq.append(node.left) <NEW_LINE> if node.right: nq.append... | :type root: TreeNode
:rtype: List[List[int]] | 625941c37c178a314d6ef418 |
def test_cfl_max_report(): <NEW_LINE> <INDENT> test_utils.assert_report(DEMO_ID, 'CFL_max', 0.0, tolerance=0.05, relative=False) | Fluid should be at rest by the end of simulation | 625941c31f037a2d8b9461ba |
def merge_(self, other): <NEW_LINE> <INDENT> self.data[0] = min(self.data[0], other[0]) <NEW_LINE> self.data[1] = max(self.data[1], other[1]) <NEW_LINE> return self | Merges inplace two ranges together
Parameters
----------
other : Range
a range
Returns
-------
Range
the range itself | 625941c3b5575c28eb68dfba |
def isAnagram(self, s, t): <NEW_LINE> <INDENT> dic = {} <NEW_LINE> if len(s) != len(t): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for cs,ct in zip(s,t): <NEW_LINE> <INDENT> if cs not in dic.keys(): <NEW_LINE> <INDENT> dic[cs] = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dic[cs] += 1 <NEW_LINE> <DEDENT> ... | :type s: str
:type t: str
:rtype: bool | 625941c371ff763f4b549644 |
def close(self, event=None): <NEW_LINE> <INDENT> if self.cluster_name_ant is not None: <NEW_LINE> <INDENT> xssh.close_ssh_client_connection(self.ssh_client) <NEW_LINE> <DEDENT> self.main.label_process['text'] = '' <NEW_LINE> self.main.close_current_form() | Close "FormShowStatusBatchJobs". | 625941c3ff9c53063f47c1b0 |
def itered(self): <NEW_LINE> <INDENT> return self.elts | An iterator over the elements this node contains.
:returns: The contents of this node.
:rtype: iterable(NodeNG) | 625941c3d7e4931a7ee9ded8 |
def _maybe_pad_seqs(seqs, dtype, depth): <NEW_LINE> <INDENT> if not len(seqs): <NEW_LINE> <INDENT> return np.zeros((0, 0, depth), dtype) <NEW_LINE> <DEDENT> lengths = [len(s) for s in seqs] <NEW_LINE> if len(set(lengths)) == 1: <NEW_LINE> <INDENT> return np.array(seqs, dtype) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN... | Pads sequences to match the longest and returns as a numpy array. | 625941c3091ae35668666f1d |
def gcd_approx(a, b, min_fraction=1E-8, tolerance=1E-5): <NEW_LINE> <INDENT> a=abs(a) <NEW_LINE> b=abs(b) <NEW_LINE> a,b = max(a,b), min(a,b) <NEW_LINE> a0,b0 = a,b <NEW_LINE> if b==0: <NEW_LINE> <INDENT> raise ArithmeticError("Can't find GCD if one of numbers is 0") <NEW_LINE> <DEDENT> min_gcd=b*min_fraction <NEW_LINE... | Approximate Euclid's algorithm for possible non-integer values.
Try to find a number `d` such that ``a/d`` and ``b/d`` are less than `tolerance` away from a closest integer.
If GCD becomes less than ``min_fraction * min(a, b)``, raise :exc:`ArithmeticError`. | 625941c3a17c0f6771cbe00e |
def show(self, str): <NEW_LINE> <INDENT> self.set_numbers(str) <NEW_LINE> self.__ic_tm1637.set_command(0x44) <NEW_LINE> for i in range(min(4, len(self.__numbers))): <NEW_LINE> <INDENT> dp = True if self.__numbers[i].count('.') > 0 else False <NEW_LINE> num = self.__numbers[i].replace('.','') <NEW_LINE> if num == '#': <... | Set the numbers array to show and enable the display
:return: void | 625941c35166f23b2e1a5115 |
def update(self): <NEW_LINE> <INDENT> data_stored = self.data_stored <NEW_LINE> simulator = self.simulator <NEW_LINE> next_step = simulator.get_next_step() <NEW_LINE> if not next_step: <NEW_LINE> <INDENT> timer = self.timer <NEW_LINE> timer.stop() <NEW_LINE> return <NEW_LINE> <DEDENT> trial, noise_level, circuit_size =... | Takes a simulation step, updating labels, circuit, and parameter map. | 625941c3ac7a0e7691ed408b |
def get_features(self, **kwargs): <NEW_LINE> <INDENT> return PaginatedList( Feature, self._requester, "GET", "accounts/{}/features".format(self.id), {"account_id": self.id}, _kwargs=combine_kwargs(**kwargs), ) | Lists all of the features of an account.
:calls: `GET /api/v1/accounts/:account_id/features <https://canvas.instructure.com/doc/api/feature_flags.html#method.feature_flags.index>`_
:rtype: :class:`canvasapi.paginated_list.PaginatedList` of
:class:`canvasapi.feature.Feature` | 625941c399fddb7c1c9de34d |
def get_box_position(box): <NEW_LINE> <INDENT> row = box[ROW_INDEX] <NEW_LINE> cell = box[CELL_INDEX] <NEW_LINE> x = MARGIN_SIZE + (BOX_SIZE * cell) + (GAP_SIZE * cell) <NEW_LINE> y = MARGIN_SIZE + INFO_SIZE + (BOX_SIZE * row) + (GAP_SIZE * row) <NEW_LINE> return x, y | Returns the x and y coordinates of the specified box | 625941c34428ac0f6e5ba7ad |
def add(self, name, tagged_name, rewrite=True): <NEW_LINE> <INDENT> node = self._trie <NEW_LINE> for token in tagged_name: <NEW_LINE> <INDENT> word = token[0].lower() <NEW_LINE> node = node.setdefault(word, {}) <NEW_LINE> <DEDENT> if rewrite or TermsTrie._TERM_END not in node: <NEW_LINE> <INDENT> node[TermsTrie._TERM_E... | Add new term to termtrie
:name: [unicode] name of the term
:tagged_name: list of tagged tokens | 625941c3a79ad161976cc101 |
def validate(self) -> None: <NEW_LINE> <INDENT> err_collector = GdsCollector_() <NEW_LINE> if not self.validate_(err_collector, recursive=True): <NEW_LINE> <INDENT> raise NuspecValidationError( "Invalid NugetPackage specification", *err_collector.get_messages() ) | Ensures that the definition is well-formed according to the Nuspec
XML schema definition. See Scripts
egenerate_nuspec.ds.py for more details. | 625941c32c8b7c6e89b3577d |
def set_orientation_period(self, period): <NEW_LINE> <INDENT> self.ipcon.send_request(self, IMU.FUNCTION_SET_ORIENTATION_PERIOD, (period,), 'I', '') | Sets the period in ms with which the :func:`Orientation` callback is triggered
periodically. A value of 0 turns the callback off. | 625941c391af0d3eaac9b9d3 |
def _addWall(self, map_object, cell, x, y, column, row): <NEW_LINE> <INDENT> cur_wall = wall.sokobanWall(self) <NEW_LINE> cur_wall.SetPoint(x, y) <NEW_LINE> self.RegDecor(cur_wall) <NEW_LINE> return cur_wall | Create wall object. | 625941c3711fe17d8254232b |
def brosok(guess, toss): <NEW_LINE> <INDENT> logging.debug('Начало подпрограммы.') <NEW_LINE> if guess == 'решка': <NEW_LINE> <INDENT> guess = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> guess = 1 <NEW_LINE> <DEDENT> logging.debug('guess = ' + str(guess) + ' toss = ' + str(toss)) <NEW_LINE> if toss == guess: <NEW_L... | Функция проверки результата | 625941c39f2886367277a84a |
def run_experiment(): <NEW_LINE> <INDENT> demographics_input() <NEW_LINE> init_pygame_and_exp() <NEW_LINE> load_stimuli() <NEW_LINE> start_welcome_block() <NEW_LINE> start_inst1_block() <NEW_LINE> start_inst2_block() <NEW_LINE> start_begintask_block() <NEW_LINE> start_task() <NEW_LINE> start_endtask_block(1.0) <NEW_LIN... | runs the experiment. | 625941c3d99f1b3c44c6754d |
def load_model(filename): <NEW_LINE> <INDENT> network = keras.models.load_model(filename) <NEW_LINE> return network | Loads an entire model
Args:
- filename: is the path of the file that the model should be loaded
from
Returns: the loaded model | 625941c399fddb7c1c9de34e |
def choose_action(self, actions, qvalues): <NEW_LINE> <INDENT> action = self._get_maxq_action(actions, qvalues) <NEW_LINE> if self._is_active: <NEW_LINE> <INDENT> self._tau *= self._decay <NEW_LINE> pmf = gibbs.pmf(np.asarray(qvalues), self._tau) <NEW_LINE> action = actions[np.random.choice(np.arange(len(np.asarray(qva... | Choose the next action.
Choose the next action according to the Gibbs
distribution.
Parameters
----------
actions : list[Actions]
The available actions.
qvalues : list[float]
The q-value for each action.
Returns
-------
Action :
The action with maximum q-value that can be taken
from the given state. | 625941c3a4f1c619b28afff9 |
def human_bytes(n): <NEW_LINE> <INDENT> if n < 1024: <NEW_LINE> <INDENT> return '%d B' % n <NEW_LINE> <DEDENT> k = n/1024 <NEW_LINE> if k < 1024: <NEW_LINE> <INDENT> return '%d KB' % round(k) <NEW_LINE> <DEDENT> m = k/1024 <NEW_LINE> if m < 1024: <NEW_LINE> <INDENT> return '%.1f MB' % m <NEW_LINE> <DEDENT> g = m/1024 <... | Return the number of bytes n in more human readable form. | 625941c301c39578d7e74df7 |
def __init__(self, entries, length_mi, route_id, route_name = None, elevation_gain_ft = None): <NEW_LINE> <INDENT> self.name = route_name <NEW_LINE> self.id = route_id <NEW_LINE> self.entries = entries <NEW_LINE> self.elevation_gain_ft = elevation_gain_ft <NEW_LINE> self.length_mi = length_mi | Inits the storage members of the class:
- entries: A list of Entry objects
- length_mi: The total length of the route, in miles.
- route_id: The RWGPS route # for this route
- route_name: The name of this route (Optional)
- elevation_gain_ft : The amount of climb in this route, in ft (Optional) | 625941c38e71fb1e9831d766 |
def __init__( self, *, name: str, type: Union[str, "RuleType"], definition: "ManagementPolicyDefinition", enabled: Optional[bool] = None, **kwargs ): <NEW_LINE> <INDENT> super(ManagementPolicyRule, self).__init__(**kwargs) <NEW_LINE> self.enabled = enabled <NEW_LINE> self.name = name <NEW_LINE> self.type = type <NEW_LI... | :keyword enabled: Rule is enabled if set to true.
:paramtype enabled: bool
:keyword name: Required. A rule name can contain any combination of alpha numeric characters.
Rule name is case-sensitive. It must be unique within a policy.
:paramtype name: str
:keyword type: Required. The valid value is Lifecycle. Possible v... | 625941c3baa26c4b54cb10dd |
def rename(self, curName, newName): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> i = self.__objNameList.index(curName) <NEW_LINE> self.__objNameList[i] = newName <NEW_LINE> self.__objCatalog[newName] = self.__objCatalog[curName] <NEW_LINE> self.__objCatalog[newName].setName(newName) <NEW_LINE> return True <NEW_LINE> <D... | Change the name of an object in place - | 625941c344b2445a33932053 |
def test_get_image_id(self): <NEW_LINE> <INDENT> img_id = str(uuid.uuid4()) <NEW_LINE> img_name = 'myfakeimage' <NEW_LINE> self.my_image.id = img_id <NEW_LINE> self.my_image.name = img_name <NEW_LINE> self.sahara_client.images.get.return_value = self.my_image <NEW_LINE> self.sahara_client.images.find.side_effect = [[se... | Tests the get_image_id function. | 625941c338b623060ff0adaa |
def merge_station_data( stats, var_name, pref_attr=None, sort_by_largest=True, fill_missing_nan=True, add_meta_keys=None, resample_how=None, min_num_obs=None, ): <NEW_LINE> <INDENT> if isinstance(var_name, list): <NEW_LINE> <INDENT> if len(var_name) > 1: <NEW_LINE> <INDENT> raise NotImplementedError("Merging of multiva... | Merge multiple StationData objects (from one station) into one instance
Note
----
all input :class:`StationData` objects need to have same attributes
``station_name``, ``latitude``, ``longitude`` and ``altitude``
Parameters
----------
stats : list
list containing :class:`StationData` objects (note: all of these
... | 625941c3d164cc6175782d0a |
def begin(self, now=None, batchSize=None, inTransaction=False): <NEW_LINE> <INDENT> log.info("Maintenance window %s starting" % self.displayName()) <NEW_LINE> if not now: <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> <DEDENT> self.started = now <NEW_LINE> self.setProdState(self.startProductionState, batchSize=batchS... | Hook for entering the Maintenance Window: call if you override | 625941c3cc40096d6159590d |
def int_pair(s, default=(0, None)): <NEW_LINE> <INDENT> s = re.split(r'[^0-9]+', str(s).strip()) <NEW_LINE> if len(s) and len(s[0]): <NEW_LINE> <INDENT> if len(s) > 1 and len(s[1]): <NEW_LINE> <INDENT> return (int(s[0]), int(s[1])) <NEW_LINE> <DEDENT> return (int(s[0]), default[1]) <NEW_LINE> <DEDENT> return default | Return the digits to either side of a single non-digit character as a 2-tuple of integers
>>> int_pair('90210-007')
(90210, 7)
>>> int_pair('04321.0123')
(4321, 123) | 625941c373bcbd0ca4b2c032 |
@pytest.mark.parametrize('fmt,path', get_cases(bconv.LOADERS), ids=path_id) <NEW_LINE> def test_loads(fmt, path, expected): <NEW_LINE> <INDENT> with xopen(path, fmt) as f: <NEW_LINE> <INDENT> parsed = bconv.loads(f.read(), fmt, id=path.stem) <NEW_LINE> <DEDENT> _validate(parsed, fmt, expected) | Test the loads function. | 625941c3460517430c394146 |
def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'id_estabelecimento': 'int', 'id_adquirente': 'int', 'codigo_estabelecimento_adquirente': 'str' } <NEW_LINE> self.attribute_map = { 'id_estabelecimento': 'idEstabelecimento', 'id_adquirente': 'idAdquirente', 'codigo_estabelecimento_adquirente': 'codigoEstab... | VinculoEstabelecimentoAdquirentePersist - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941c3cdde0d52a9e52fed |
@app.route('/logout') <NEW_LINE> def logout(): <NEW_LINE> <INDENT> session.pop('logged_in', None) <NEW_LINE> oauth_provider = session.pop('oauth_provider', None) <NEW_LINE> if oauth_provider: <NEW_LINE> <INDENT> if 'google' in oauth_provider: <NEW_LINE> <INDENT> gdisconnect() <NEW_LINE> <DEDENT> elif 'facebook' in oaut... | this view will be used to log out the user | 625941c321bff66bcd684911 |
def create_app(config_file: Optional[Union[str, PurePath]] = None) -> Flask: <NEW_LINE> <INDENT> app = Flask(__name__) <NEW_LINE> app.config.from_object('commandment.default_settings') <NEW_LINE> if config_file is not None: <NEW_LINE> <INDENT> app.config.from_pyfile(config_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN... | Create the Flask Application.
Configuration is looked up the following order:
- default_settings.py in the commandment package.
- config_file parameter passed to this factory method.
- environment variable ``COMMANDMENT_SETTINGS`` pointing to a .cfg file.
Args:
config_file (Union[str, PurePath]): Path to configu... | 625941c31b99ca400220aa6d |
def calculate_grid_position(index, start_position = (0, 0)): <NEW_LINE> <INDENT> return ( BORDER + (index % PREFERRED_WIDTH + 1) * GRID - GRID / 2, BORDER + int(index / PREFERRED_WIDTH + 1) * GRID - GRID / 2, ) | Determines the position of an item in a simple grid, based on default values defined here | 625941c32eb69b55b151c869 |
def p_program(p): <NEW_LINE> <INDENT> if len(p) == 3: <NEW_LINE> <INDENT> p[0] = Node("program", [p[1], p[2]]) <NEW_LINE> <DEDENT> elif len(p) == 2: <NEW_LINE> <INDENT> p[0] = Node("program", [p[1]]) | program : program stmt_list
| stmt_list | 625941c38c0ade5d55d3e975 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.