code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def import_dashboard(data, actions): <NEW_LINE> <INDENT> id_mappings = { 'dashboards' : {}, 'widgets': {}, 'visualizations': {}, 'queries': {} } <NEW_LINE> with models.db.database.atomic() as atx: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for model in ('dashboards', 'queries', 'visualizations', 'widgets'): <NEW_LINE...
Iterates thru all the items (in a specific order), updating the id_mapping structure, as each item gets inserted. Then updates the dashboard layout to reference the newly inserted widgets. Everything gets done within the context of a transaction, to be able to rollback in case something goes wrong and prevent the datab...
625941cb97e22403b379d072
def comune_from_id(self, id): <NEW_LINE> <INDENT> return self._location_query('comuni', id)
return an Location city object from primary key
625941cba219f33f34628a43
def test_no_display_device(self): <NEW_LINE> <INDENT> self.assertRaises(dbus.exceptions.DBusException, self.obj_upower.GetDisplayDevice) <NEW_LINE> self.assertRaises(dbus.exceptions.DBusException, self.dbusmock.SetupDisplayDevice, 2, 1, 50.0, 40.0, 80.0, 2.5, 3600, 1800, True, 'half-battery', 3) <NEW_LINE> display_dev ...
0.9 API has no display device
625941cbf7d966606f6aa0dd
@patch("salt.utils.path.which", MagicMock(return_value="/usr/sbin/sysctl")) <NEW_LINE> def test_osx_memdata(): <NEW_LINE> <INDENT> def _cmd_side_effect(cmd): <NEW_LINE> <INDENT> if "hw.memsize" in cmd: <NEW_LINE> <INDENT> return "4294967296" <NEW_LINE> <DEDENT> elif "vm.swapusage" in cmd: <NEW_LINE> <INDENT> return "to...
test osx memdata
625941cb66656f66f7cbc283
def test_lv_present(self): <NEW_LINE> <INDENT> name = '/dev/sda5' <NEW_LINE> comt = ('Logical Volume {0} already present'.format(name)) <NEW_LINE> ret = {'name': name, 'changes': {}, 'result': True, 'comment': comt} <NEW_LINE> mock = MagicMock(side_effect=[True, False]) <NEW_LINE> with patch.dict(lvm.__salt__, {'lvm.lv...
Test to create a new logical volume
625941cbf9cc0f698b1406d5
def predict(self, data_X): <NEW_LINE> <INDENT> a, r = self.particle_input.feed_forward(data_X) <NEW_LINE> for layer in self.layers: <NEW_LINE> <INDENT> a, r = layer.feed_forward(a, r) <NEW_LINE> <DEDENT> return a
Pass given input through network to compute the output prediction :param data_X: :return:
625941cb287bf620b61d3b3d
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bright_assignments.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. A...
Run administrative tasks.
625941cb7cff6e4e81117a5f
def get_local_handle(self, current_process=CURRENT_PROCESS): <NEW_LINE> <INDENT> if self.UniqueProcessId == current_process.pid: <NEW_LINE> <INDENT> return self.HandleValue <NEW_LINE> <DEDENT> local_handle = wintypes.HANDLE() <NEW_LINE> kernel32.DuplicateHandle( self.process._handle, self.HandleValue, current_process._...
Get a local copy of the handle. :return: (int)
625941cb5166f23b2e1a5232
def register_dispatchers(): <NEW_LINE> <INDENT> op_list = ( _UNARY_ELEMENTWISE_OPS + _UNARY_LIST_ELEMENTWISE_OPS + _BINARY_ELEMENTWISE_OPS + [x[0] for x in _RAGGED_DISPATCH_OPS]) <NEW_LINE> for op in op_list: <NEW_LINE> <INDENT> _, undecorated_op = tf_decorator.unwrap(op) <NEW_LINE> if not hasattr(undecorated_op, tf_ex...
Constructs & registers OpDispatchers for ragged ops.
625941cbd6c5a10208144124
def remove(self, elem): <NEW_LINE> <INDENT> self.skiplist.remove(elem)
(MultiSet, object) -> NoneType Remove one occurrence of element elem from this MultiSet.
625941cb925a0f43d2549f50
def scan(root): <NEW_LINE> <INDENT> protocols = [ { **protocol, **protocol_parser.parse(get_protocol_pyfile(protocol)), **markdown_parser.parse(get_protocol_mdfile(protocol)) } for protocol in get_valid_protocols(root) if protocol['status'] != 'empty' and protocol['slug'] != '.' and not protocol['flags']['ignore'] ] <N...
Recursively scan through root returning the list of protocol dictionary items.
625941cb7d43ff24873a2d79
def caesar_cipher_decrypt(cipher_text, shift): <NEW_LINE> <INDENT> dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" <NEW_LINE> shift %= len(dictionary) <NEW_LINE> map_dictionary = dictionary[shift:] + dictionary[:shift] <NEW_LINE> plain_text = str() <NEW_LINE> for each_char in cipher_text: ...
默认字典为: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 :param cipher_text: 待解密的密文 :param shift: 偏移 :return: str()
625941cb9b70327d1c4e0eae
def resize(self, *, percentage=None, vertical=None, horizontal=None): <NEW_LINE> <INDENT> h, w = self.image.shape[:2] <NEW_LINE> if vertical is not None and horizontal is None: <NEW_LINE> <INDENT> factor = vertical / h <NEW_LINE> <DEDENT> elif vertical is not None and horizontal is not None: <NEW_LINE> <INDENT> self.im...
resize image. Args: percentage: what percent size the image should be from the original vertical: desired vertical. horizontal will be scaled. horizontal: same but vis-versa
625941cbbe8e80087fb20d1c
def plotOverview(plot_context): <NEW_LINE> <INDENT> ert = plot_context.ert() <NEW_LINE> key = plot_context.key() <NEW_LINE> config = plot_context.plotConfig() <NEW_LINE> axes = plot_context.figure().add_subplot(111) <NEW_LINE> case_list = plot_context.cases() <NEW_LINE> for case in case_list: <NEW_LINE> <INDENT> data =...
@type plot_context: ert_gui.plottery.PlotContext
625941cba4f1c619b28b0113
def get_status(self): <NEW_LINE> <INDENT> if self._device.is_moving_error or self._device.error_code != 0: <NEW_LINE> <INDENT> status = "E" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> is_moving = self._device.is_motor_moving() <NEW_LINE> if is_moving: <NEW_LINE> <INDENT> status = "N" <NEW_LINE> <DEDENT> else: <NEW_LI...
Returns: the moving status of the motor, N not at position, P at position, E error
625941cb507cdc57c6306db3
def test_set_timeout_lower_than_1(self) -> None: <NEW_LINE> <INDENT> given = 0.5 <NEW_LINE> self.assertRaises(ValueError, lambda: self.query_tool.set_timeout(given))
Tests the method which let us set the timeout to work with for the case that the given timeout is less than 1.
625941cba17c0f6771cbe12a
def clearSignals(self): <NEW_LINE> <INDENT> for signalwidget in self.refDict.values(): <NEW_LINE> <INDENT> signalwidget.deleteLater() <NEW_LINE> <DEDENT> self.refDict.clear() <NEW_LINE> self.setRowCount(0) <NEW_LINE> self.resizeColumnsToContents() <NEW_LINE> self.resizeRowsToContents()
Remove all all signals
625941cb462c4b4f79d1d7aa
def test_path_with_file(self): <NEW_LINE> <INDENT> self.config.config_dir = '/tmp/ha-config' <NEW_LINE> assert "/tmp/ha-config/test.conf" == self.config.path("test.conf")
Test get_config_path method.
625941cbfbf16365ca6f629d
@fill <NEW_LINE> def floating_triangle(token): <NEW_LINE> <INDENT> a, b = token.uniform(0.1, 0.3), token.uniform(0.1, 0.3) <NEW_LINE> if (token.value) >= 1 or (token.value + a) >= 1 or (a) >= 1 or (b) >= 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> graphics.context.move_to(token.value, a) <NEW_LINE> graphics.conte...
Stincil - A single floating triangle. Due to the imperative nature of cairo, they all face the same direction.
625941cb8c0ade5d55d3ea94
def remove_ace(self, ace): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._validate_ace(ace) <NEW_LINE> <DEDENT> except OnepIllegalArgumentException as e: <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> if ace in self._l2_ace_list: <NEW_LINE> <INDENT> self._l2_ace_list.remove(ace) <NEW_LINE> try: <NEW_LINE> <INDENT>...
Remove a L2 Access Control Element(ACE) from L2 Access Control List(ACL). Attempt to remove an ace which is not added to the L2 ACL raises no exception. @param ace: L2 ACE instance to be removed from L2 ACL. @type ace: L{L2Ace<onep.policy.L2Ace.L2Ace>} @raise OnepIllegalArgumentException: If ace is invalid. @raise O...
625941cbdd821e528d63b282
def update_from_file(self, opts_file): <NEW_LINE> <INDENT> print(" RELION_IT: reading options from {}".format(opts_file)) <NEW_LINE> other_opts = {} <NEW_LINE> with open(opts_file) as opt_fd: <NEW_LINE> <INDENT> for line in opt_fd: <NEW_LINE> <INDENT> if line.strip().startswith("#"): <NEW_LINE> <INDENT> continue <NEW_L...
Update this RelionItOptions object from a file containing options as key = value pairs.
625941cb627d3e7fe0d68f29
def _get_encapsulate_header(self): <NEW_LINE> <INDENT> return self.__encapsulate_header
Getter method for encapsulate_header, mapped from YANG variable /network_instances/network_instance/afts/aft/entries/entry/next_hops/next_hop/state/encapsulate_header (oc-aftt:encapsulation-header-type) YANG Description: When forwarding a packet to the specified next-hop the local system performs an encapsulat...
625941cb44b2445a3393216f
def aux_analyzer( dictionary, key, inspection_list, index=0, final_message=True ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> inspection_list[0][0] = inspection_list[0][0].upper() <NEW_LINE> instrument = inspection_list[0][0] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if not inspection_l...
Función auxiliar de analyzer.
625941cb99fddb7c1c9de46a
def test_after_import_to_backend_sale(self): <NEW_LINE> <INDENT> proc = mock.MagicMock() <NEW_LINE> with mock.patch.object(self.unit, 'binder_for'): <NEW_LINE> <INDENT> self.unit.binder_for().to_odoo.return_value = proc <NEW_LINE> self.unit.binder_for().to_backend.side_effect = EndTestException <NEW_LINE> with self.ass...
It should get backend record for binding
625941cb4f88993c3716c140
def getIntersectionNode(self, headA, headB): <NEW_LINE> <INDENT> len_A,len_B = 0,0 <NEW_LINE> temp = headA <NEW_LINE> while(temp): <NEW_LINE> <INDENT> len_A +=1 <NEW_LINE> temp = temp.next <NEW_LINE> <DEDENT> temp = headB <NEW_LINE> while(temp): <NEW_LINE> <INDENT> len_B += 1 <NEW_LINE> temp = temp.next <NEW_LINE> <DED...
:type head1, head1: ListNode :rtype: ListNode
625941cb9f2886367277a967
def code_e0(gb): <NEW_LINE> <INDENT> d8 = gb.cpu.read_next_byte_from_cartridge() <NEW_LINE> address = (0xFF00 + d8) & 0xFFFF <NEW_LINE> gb.memory.write_8bit(address,gb.cpu.register.A) <NEW_LINE> return 12
LDH (d8),A or LD ($FF00+d8),A - Put A into address ($FF00 + d8)
625941cb956e5f7376d70f47
def _input_fn(): <NEW_LINE> <INDENT> logging.info("Reading files from %s", input_dir) <NEW_LINE> def gzip_reader(): <NEW_LINE> <INDENT> return tf.TFRecordReader( options=tf.python_io.TFRecordOptions( compression_type=TFRecordCompressionType.GZIP)) <NEW_LINE> <DEDENT> reader_fn = gzip_reader <NEW_LINE> num_epochs = None...
Supplies the input to the model. Returns: A tuple consisting of 1) a dictionary of tensors whose keys are the feature names, and 2) a tensor of target labels if the mode is not INFER (and None, otherwise).
625941cbd58c6744b4257d39
def rendered_items(self): <NEW_LINE> <INDENT> self.cat = self.request.get('ajax_category_expand') <NEW_LINE> self.contentFilter[self.category_index] = self.request.get('cat') <NEW_LINE> clear_states = ['inactive_state', 'review_state', 'cancellation_state'] <NEW_LINE> for clear_state in clear_states: <NEW_LINE> <INDENT...
If you set table_only to true, then nothing outside of the <table/> tag will be printed (form tags, authenticator, etc). Then you can insert your own form tags around it.
625941cb097d151d1a222f33
def predict_note_authentication(variance,skewness,curtosis,entropy): <NEW_LINE> <INDENT> prediction=classifier.predict([[variance,skewness,curtosis,entropy]]) <NEW_LINE> print(prediction) <NEW_LINE> return prediction
Let's rate the docs This is using docstrings for specifications. --- parameters: - name: variance in: query type: number required: true - name: skewness in: query type: number required: true - name: curtosis in: query type: number required: true - name: entropy in: que...
625941cbb5575c28eb68e0da
def get_pop_iter(self, number): <NEW_LINE> <INDENT> for i in range(number): <NEW_LINE> <INDENT> if self.demographics is not None: <NEW_LINE> <INDENT> profession = None <NEW_LINE> roll = np.random.rand() <NEW_LINE> for profession in self.demographics['professions']: <NEW_LINE> <INDENT> if roll > self.demographics['profe...
Generate a population of a given size and iterate through them
625941cb507cdc57c6306db4
def randomPaste(bg_img, img): <NEW_LINE> <INDENT> if img.shape[0] > bg_img.shape[0] or img.shape[1] > bg_img.shape[1]: <NEW_LINE> <INDENT> log.error("Failed to paste: inner is bigger.") <NEW_LINE> return img <NEW_LINE> <DEDENT> x_offset = random.randint(0, bg_img.shape[1] - img.shape[1]) <NEW_LINE> y_offset = random.ra...
randomly paste img into bg_img.
625941cb0a366e3fb873e8f3
def get_errors(): <NEW_LINE> <INDENT> for server in get_enabled_servers(): <NEW_LINE> <INDENT> if server.has_error: <NEW_LINE> <INDENT> return True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return False
find out if any server has any error, used by statusbar error label
625941cbaad79263cf390b1a
def open_in_gui_thread(self, timeout_secs=5): <NEW_LINE> <INDENT> GUI.invoke_later(self.open) <NEW_LINE> counter = 0 <NEW_LINE> while(getattr(self, '_start_time', -1) == -1 and counter < timeout_secs * 2): <NEW_LINE> <INDENT> sleep(0.5) <NEW_LINE> counter += 1 <NEW_LINE> <DEDENT> return getattr(self, '_start_time', -1)...
Open dialog in gui thread and wait to return until open up to timeout_sec seconds The superclass open method sets the _start_time variable which is used as a signal for whether open has occured. Parameters ---------- timeouts_secs : int Number of seconds to wait for widget to initialize. Returns ---------- Tr...
625941cbcc0a2c11143dcf6a
@pytest.fixture <NEW_LINE> def expected_result(): <NEW_LINE> <INDENT> return {}
Expected result to be returned.
625941cb283ffb24f3c559db
def rstr2any(self, inp, trim=True): <NEW_LINE> <INDENT> encoding = self.encoding <NEW_LINE> divisor = len(encoding) <NEW_LINE> def get_quotient_remainder(dividend): <NEW_LINE> <INDENT> quotient = [] <NEW_LINE> remainder = 0 <NEW_LINE> for dividend_ele in dividend: <NEW_LINE> <INDENT> remainder = (remainder << 16) + div...
Convert a raw string to encoded string Set trim to false for keeping leading zeros. The generated string only contains characters from self.charset.
625941cbd58c6744b4257d3a
def body_to_string(xml_node): <NEW_LINE> <INDENT> return (xml_node.text.lstrip() + ''.join(etree.tostring(c) for c in xml_node) + xml_node.tail.rstrip())
Create a string from the text of this node and its children (without the outer tag)
625941cbdc8b845886cb560e
def set_playable_format(self, value): <NEW_LINE> <INDENT> self._play_api.output_format = value
Sets the output format for play related api requests :param value: new output format. Possible values: ['json', 'xml', 'm3u', 'pls']
625941cb97e22403b379d073
def get_formatted_name(first_name,last_name): <NEW_LINE> <INDENT> full_name = first_name + ' ' + last_name <NEW_LINE> return full_name.title()
返回值
625941cbe5267d203edcdd78
def run_mainline(self, ip1, ip2): <NEW_LINE> <INDENT> with DockerHost('host', dind=False) as host: <NEW_LINE> <INDENT> network = host.create_network(str(uuid.uuid4())) <NEW_LINE> node1 = host.create_workload(str(uuid.uuid4()), network=network) <NEW_LINE> node2 = host.create_workload(str(uuid.uuid4()), network=network) ...
Setup two endpoints on one host and check connectivity.
625941cbff9c53063f47c2cd
def test_O1bound(my_N, my_ind): <NEW_LINE> <INDENT> res = get_xlmhg_test_result(my_N, my_ind, pval_thresh=0.07, exact_pval='if_necessary') <NEW_LINE> assert res.pval == 0.0696594427244582
Test if we return the O(1)-bound if that's "<=" `pval_thresh`
625941cbc432627299f04d1f
def Conifold(self, names='u x y v', base_ring=QQ): <NEW_LINE> <INDENT> return self._make_ToricVariety('Conifold', names, base_ring)
Construct the conifold as a toric variety. INPUT: - ``names`` -- string. Names for the homogeneous coordinates. See :func:`~sage.schemes.toric.variety.normalize_names` for acceptable formats. - ``base_ring`` -- a ring (default: `\QQ`). The base ring for the toric variety. OUTPUT: A :class:`toric variety <s...
625941cbbaa26c4b54cb11fa
def num_live_neighbors(self, row, col): <NEW_LINE> <INDENT> res = 0 <NEW_LINE> for i, j in self.NEIGHBOURS: <NEW_LINE> <INDENT> new_row = row + i <NEW_LINE> new_col = col + j <NEW_LINE> if 0 <= new_row < self.num_rows() and 0 <= new_col < self.num_cols(): <NEW_LINE> <INDENT> res += self.is_live_cell(new_row, new_col) <...
Returns the number of live neighbors for the given cell. :param row: row of the cell. :param col: column of the cell. :return:
625941cbb7558d58953c4fef
def close(self): <NEW_LINE> <INDENT> if self.response is not None: <NEW_LINE> <INDENT> if hasattr(self.response, 'raw'): <NEW_LINE> <INDENT> if hasattr(self.response.raw, 'release_conn'): <NEW_LINE> <INDENT> getattr(self.response, 'raw').release_conn() <NEW_LINE> <DEDENT> <DEDENT> del self.response
Releases the underlying urllib connection and then deletes the response
625941cb6e29344779a626ec
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> length = len(self.ActionVec) <NEW_LINE> buff.write(_struct_I.pack(length)) <NEW_LINE> for val1 in self.ActionVec: <NEW_LINE> <INDENT> buff.write(_struct_i.pack(val1.name)) <NEW_LINE> _v1 = val1.actor <NEW_LINE> length = len(_v1.targetPoseVec) <NEW_...
serialize message into buffer :param buff: buffer, ``StringIO``
625941cb07d97122c4178965
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SharedAutomatedTellerMachinesCompanies): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941cbd99f1b3c44c67669
def isValid(self): <NEW_LINE> <INDENT> flattened = self.flatten() <NEW_LINE> for i in range(0, len(flattened) - 1): <NEW_LINE> <INDENT> if not flattened[i] < flattened[i + 1]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
is the tree a valid binary search tree?
625941cb7b25080760e39533
def _get_dracut_vlan_argument_from_connection(nm_client, connection, iface): <NEW_LINE> <INDENT> argument = "" <NEW_LINE> parent_con = None <NEW_LINE> if connection.get_connection_type() == NM_CONNECTION_TYPE_VLAN: <NEW_LINE> <INDENT> setting_vlan = connection.get_setting_vlan() <NEW_LINE> parent_spec = setting_vlan.ge...
Get dracut vlan configuration for given interface and NM connection. Returns also parent vlan connection. :param nm_client: instance of NetworkManager client :type nm_client: NM.Client :param connection: NetworkManager connection :type connection: NM.RemoteConnection :param iface: network interface to be used :type i...
625941cb6fece00bbac2d818
def get(self, id: int) -> dict: <NEW_LINE> <INDENT> tag = Tag.query.filter_by(id=id).one_or_none() <NEW_LINE> if not tag: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> return NestedResponse(schema=TagSchema).dump(tag)
Returns data about a requested tag. :param id: id of a requested tag :returns: a single object
625941cb187af65679ca51f9
@pimms.calc('files') <NEW_LINE> def accumulate_files(surface_files, volume_files): <NEW_LINE> <INDENT> return {'files': (tuple(surface_files) + tuple(volume_files))}
accumulate_files is a calculator that just accumulates the exported files into a single tuple, files.
625941cb6fb2d068a760f177
def is_valid(s): <NEW_LINE> <INDENT> in_str = False <NEW_LINE> bb = 0 <NEW_LINE> for c in s: <NEW_LINE> <INDENT> if c == '(' and not in_str: <NEW_LINE> <INDENT> bb += 1 <NEW_LINE> <DEDENT> elif c == ')' and not in_str: <NEW_LINE> <INDENT> bb -= 1 <NEW_LINE> if bb < 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT...
Return True if s is a valid S-Expression.
625941cbfff4ab517eb2f516
@functools.partial(jax.jit, static_argnums=(1,)) <NEW_LINE> def get_multi_env_inputs(env_batches, input_key='inputs'): <NEW_LINE> <INDENT> return jnp.array( list( map(functools.partial(get_inputs, input_key=input_key), env_batches)))
List(Batches) --> List(Batches[input_key]). Args: env_batches: list(dict); List of batches, where each batch is a dictionary. input_key: str; Key for the input (inputs == batch[input_key]). Returns:
625941cb1f037a2d8b9462d8
def exp(q): <NEW_LINE> <INDENT> q = np.asarray(q) <NEW_LINE> expo = np.empty(q.shape) <NEW_LINE> norms = np.linalg.norm(q[..., 1:], axis=-1) <NEW_LINE> e = np.exp(q[..., 0]) <NEW_LINE> expo[..., 0] = e * np.cos(norms) <NEW_LINE> norm_zero = np.isclose(norms, 0) <NEW_LINE> not_zero = np.logical_not(norm_zero) <NEW_LINE>...
Compute the natural exponential function :math:`e^q`. The exponential of a quaternion in terms of its scalar and vector parts :math:`q = a + \boldsymbol{v}` is defined by exponential power series: formula :math:`e^x = \sum_{k=0}^{\infty} \frac{x^k}{k!}` as follows: .. math:: \begin{align} e^q &= e^{a+v} \...
625941cb5f7d997b87174b72
@task(alias='reg') <NEW_LINE> def pypi_register(): <NEW_LINE> <INDENT> args = ["python", "setup.py"] <NEW_LINE> args += ["register"] <NEW_LINE> local(' '.join(args))
See :cmd:`fab reg`.
625941cbd164cc6175782e28
def default_get(self, cr, uid, fields_list=None, context=None): <NEW_LINE> <INDENT> defaults = super(base_setup_company, self) .default_get(cr, uid, fields_list=fields_list, context=context) <NEW_LINE> companies = self.pool.get('res.company') <NEW_LINE> company_id = companies.search(cr, uid, [], limit=1, o...
get default company if any, and the various other fields from the company's fields
625941cbd18da76e235325b0
def register(package_name: str) -> _theme.Theme: <NEW_LINE> <INDENT> global _default <NEW_LINE> if package_name in _fallback_theme_name: <NEW_LINE> <INDENT> raise _error.ThemeAlreadyRegistered(package_name) <NEW_LINE> <DEDENT> theme = _theme.Theme(package_name) <NEW_LINE> if not _default or theme.package_name == reg.ge...
Register a theme
625941cba8ecb033257d31a7
def _group_percentile(self, clusters, adj_list, counts): <NEW_LINE> <INDENT> retained_umis = self._get_best_percentile(clusters, counts) <NEW_LINE> groups = [[x] for x in retained_umis] <NEW_LINE> return groups
Return "groups" for the the percentile method. Note that grouping isn't really compatible with the percentile method. This just returns the retained UMIs in a structure similar to other methods
625941cbe64d504609d7491a
def take_input(): <NEW_LINE> <INDENT> i=open("input2.txt","r") <NEW_LINE> global size <NEW_LINE> size=int(i.readline().rstrip()) <NEW_LINE> global police <NEW_LINE> police=int(i.readline().rstrip()) <NEW_LINE> police=2 <NEW_LINE> global scooter <NEW_LINE> scooter=int(i.readline().rstrip()) <NEW_LINE> occur=[0]*size <NE...
Accepts the size of the chess board
625941cb0a50d4780f666f6c
def select_proper_columns(query_table, column_names): <NEW_LINE> <INDENT> result_table = {} <NEW_LINE> for name in column_names: <NEW_LINE> <INDENT> result_table[name] = query_table.get_column_content(name) <NEW_LINE> <DEDENT> return Table(result_table)
selects rows specified in query :param query_table: table with data :param column_names: specified columns in query :return: result table
625941cb6aa9bd52df036e7f
@lookup.command() <NEW_LINE> @prefix_argument <NEW_LINE> @verbose_option <NEW_LINE> @force_option <NEW_LINE> @click.option("-i", "--identifier") <NEW_LINE> def alts(prefix: str, identifier: Optional[str], force: bool): <NEW_LINE> <INDENT> id_to_alts = get_id_to_alts(prefix, force=force) <NEW_LINE> if identifier is None...
Page through alt ids in a namespace.
625941cbcc40096d61595a2b
def send_transaction( self, operator: str, tx_params: Optional[TxParams] = None ) -> Union[HexBytes, bytes]: <NEW_LINE> <INDENT> (operator) = self.validate_and_normalize_inputs(operator) <NEW_LINE> tx_params = super().normalize_tx_params(tx_params) <NEW_LINE> return self._underlying_method(operator).transact(tx_params....
Execute underlying contract method via eth_sendTransaction. :param tx_params: transaction parameters
625941cbb830903b967e99e6
def keyword_search(self, keyword, apply=None): <NEW_LINE> <INDENT> self.open(self.SEARCH_BY_KEYWORD_URL) <NEW_LINE> self.getControl('keywords').displayValue = [keyword] <NEW_LINE> self.getControl('Search').click() <NEW_LINE> if apply: <NEW_LINE> <INDENT> self.getControl('Apply on selected persons').displayValue = [appl...
Search for a keyword via keyword-search. If `apply` is not `None` select the value from the dropdown and submit the search result handler.
625941cb30dc7b7665901a41
def handle_blue_down_1(button_state, robot, dc): <NEW_LINE> <INDENT> if button_state: <NEW_LINE> <INDENT> print("Blue down channel 1 is pressed") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Blue down channel 1 was released")
Handle IR / button event.
625941cb5510c4643540f4bf
def __init__(self,w,h): <NEW_LINE> <INDENT> self.width = w <NEW_LINE> self.height = h <NEW_LINE> self.clear()
Initialised with light-blocking walls.
625941cb66673b3332b9216b
def t_ident(self, s, m, parent): <NEW_LINE> <INDENT> parent.addIdent(s)
[a-zA-Z\$_][a-zA-Z\$_\d.]*
625941cba219f33f34628a44
def post(request, pk, slug=None): <NEW_LINE> <INDENT> post = get_object_or_404(Post, pk=pk) <NEW_LINE> comments = Comment.objects.filter(post=post) <NEW_LINE> d = dict(post=post, comments=comments, form=CommentForm(), user=request.user) <NEW_LINE> d.update(csrf(request)) <NEW_LINE> return render_to_response("post.html"...
Single post with comments and a comment form.
625941cbf7d966606f6aa0de
def initConfig(self): <NEW_LINE> <INDENT> configFileName = self._config_file_path + str(self._config_set) + self._config_file_suffix <NEW_LINE> if os.path.exists(configFileName) == True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._cf = ConfigParser.ConfigParser() <NEW_LINE> self._cf.read(configFileName) <NEW_LIN...
get config data secs = cf.sections() print secs; opts = cf.options('redis') print opts kvs = cf.items('redis') print kvs value = cf.get(opts, item)
625941cb4428ac0f6e5ba8cd
def __virtual__(): <NEW_LINE> <INDENT> return 'mysql_grants' if 'mysql.grant_exists' in __salt__ else False
Only load if the mysql module is available
625941cb1b99ca400220ab8c
def set_Repo(self, value): <NEW_LINE> <INDENT> super(GetCommitInputSet, self)._set_input('Repo', value)
Set the value of the Repo input for this Choreo. ((required, string) The name of the repository.)
625941cb56b00c62f0f14734
def _validity_checking(self): <NEW_LINE> <INDENT> if PSBT_GLOBAL_UNSIGNED_TX not in self.maps['global']: <NEW_LINE> <INDENT> raise ValueError('Invalid PSBT, missing unsigned transaction') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tx_obj = Tx.parse(BytesIO(self.maps['global'][PSBT_GLOBAL_UNSIGNED_TX])) <NEW_LINE> <D...
A variety of tests to ensure this PSBT is valid
625941cb462c4b4f79d1d7ab
def list_keys( self, resource_group_name, namespace_name, topic_name, authorization_rule_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map',...
Gets the primary and secondary connection strings for the topic. :param resource_group_name: Name of the Resource group within the Azure subscription. :type resource_group_name: str :param namespace_name: The namespace name. :type namespace_name: str :param topic_name: The topic name. :type topic_name: str :param auth...
625941cb596a897236089b9b
def levelOrder(root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> res = [] <NEW_LINE> queue = [] <NEW_LINE> queue.append(root) <NEW_LINE> while queue: <NEW_LINE> <INDENT> level_size = len(queue) <NEW_LINE> current_level = [] <NEW_LINE> for _ in range(level_size): <NEW_LINE> <INDEN...
二叉树的层次遍历,使用宽度优先遍历实现 :param root: :return:
625941cb60cbc95b062c661e
def _map_columns(self, maps, body): <NEW_LINE> <INDENT> return {maps.get(k, k): v for (k, v) in body.iteritems()}
将body中与数据库字段不一致的key转换成数据库字段 :param maps: 字段映射表,只需要提供不一致的映射列表即可 :type maps: dict :param body: 需要转换的内容 :type body: dict :rtype: 转换后的body
625941cba05bb46b383ec8fc
def _complete_setup(self): <NEW_LINE> <INDENT> self.setup_server() <NEW_LINE> self.init_new_state() <NEW_LINE> self.setup_socket() <NEW_LINE> self.start_new_run() <NEW_LINE> self._load_model()
Complete necessary setup items.
625941cb379a373c97cfac1f
@then("click '{placeholder}' field") <NEW_LINE> def step(context, placeholder): <NEW_LINE> <INDENT> xpath = '//*[@placeholder="%s"]' % placeholder <NEW_LINE> context.clickActions = ClickActions(context) <NEW_LINE> context.clickActions.click_on_xpath(xpath)
Then click '{placeholder}' field
625941cb627d3e7fe0d68f2a
def create_acer_input(deck, dat, tapeENDFIn, tapePENDFIn, tapeACEROutStart, tapeXSDIROutStart, tapeIndex): <NEW_LINE> <INDENT> tapeACEROut = tapeACEROutStart + tapeIndex <NEW_LINE> tapeXSDIROut = tapeXSDIROutStart + tapeIndex <NEW_LINE> thermStr = '{0:g}'.format(round(dat.thermList[tapeIndex],1)) <NEW_LINE> suffixNonTh...
Create non-thermal ACE files
625941cb66656f66f7cbc285
def test_winning_seats(d = Results2018): <NEW_LINE> <INDENT> for key in (list(d.keys())): <NEW_LINE> <INDENT> assert not Electoral_Montecarlo.winning_min_seats(key,500)
This test function shows it is impossible for a simulation to provide a result in which a party gets more than 500 seats(it is impossible)
625941cb236d856c2ad448b5
def read_tabit_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 tabit.conf file from dbdir, returns dictionary of settings
625941cb442bda511e8be4f3
def get(self, key, db_type=None): <NEW_LINE> <INDENT> key = "{}{}".format(self.config['CACHE_KEY_PREFIX'], key) <NEW_LINE> if not db_type: <NEW_LINE> <INDENT> if self.config["CACHE_TYPE"] == "redis": <NEW_LINE> <INDENT> value = self.redis.get(key) <NEW_LINE> if value: <NEW_LINE> <INDENT> value = json_to_pyseq(value.dec...
获取一个cache :param key: :param db_type: 不使用系统设置的db type时指定类型mongodb或redis :return:default:获取不到时返回
625941cb090684286d50edc0
def meth(self): <NEW_LINE> <INDENT> return 'meth on %s' % self.name
doc
625941cb85dfad0860c3af36
def insert(self, val): <NEW_LINE> <INDENT> self.arr.append(val) <NEW_LINE> self.length += 1 <NEW_LINE> if not self.dic.has_key(val) or self.dic[val] == []: <NEW_LINE> <INDENT> self.dic[val] = [self.length - 1] <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.dic[val].append(self.length - 1) <NE...
Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool
625941cb57b8e32f52483576
def canFinish(self, numCourses, prerequisites): <NEW_LINE> <INDENT> indegrees = [0 for i in xrange(numCourses)] <NEW_LINE> graph = {} <NEW_LINE> for cur, prev in prerequisites: <NEW_LINE> <INDENT> if pre not in graph: <NEW_LINE> <INDENT> graph[pre] = [cur] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> graph[pre].appen...
:type numCourses: int :type prerequisites: List[List[int]] :rtype: bool
625941cb656771135c3eb949
def create_harm(melody, saturation, value, length): <NEW_LINE> <INDENT> import random <NEW_LINE> temp1 = melody[0] <NEW_LINE> for i in range(1, len(melody)): <NEW_LINE> <INDENT> temp1 = temp1 + melody[i] <NEW_LINE> <DEDENT> temp1 = temp1 * (length//2) <NEW_LINE> random.shuffle(melody) <NEW_LINE> temp2 = melody[0] <NEW_...
used to create the harmony
625941cb8da39b475bd6504f
def process(self, request, **kwargs): <NEW_LINE> <INDENT> self.method_check(request, allowed=['post']) <NEW_LINE> data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) <NEW_LINE> param_url = data.get('url', None) <NEW_LINE> if param_url: <NEW_LINE> <INDENT> try: <NE...
Got request with param 'url' or 'hash'. If param is 'hash' - return full url, hash for url would be returned otherwise :param request: :param kwargs: :return: example: {"hash": "799001133"} or {"url": "http://123.ru"}
625941cbeab8aa0e5d26dc33
def GetText(self): <NEW_LINE> <INDENT> name = self.name <NEW_LINE> if self.isfunction: <NEW_LINE> <INDENT> return "def " + name + "(...)" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "class " + name
Return the name of the function/class to display.
625941cb8a43f66fc4b54140
def sort_dates(list_dates): <NEW_LINE> <INDENT> less = [] <NEW_LINE> equal = [] <NEW_LINE> greater = [] <NEW_LINE> if len(list_dates) > 1: <NEW_LINE> <INDENT> pivot = int(list_dates[0].replace("-", "")) <NEW_LINE> for p in list_dates: <NEW_LINE> <INDENT> x = int(p.replace("-", "")) <NEW_LINE> if x < pivot: <NEW_LINE> <...
Implementation of quicksort. Formats dates to integers and sort the integers to get chronological order. Args: list_dates: List of dates strings Returns: Returns sorted dates list
625941cb5166f23b2e1a5234
def get_clss(db,teacher_name): <NEW_LINE> <INDENT> teacher = get_teacher(db, name=teacher_name) <NEW_LINE> return db.query(table.LeadTheClass).filter_by(teacher_id=teacher.teacher_id).all()
查询老师所负责的班级 :param db: :param teacher_name: :return:
625941cbfb3f5b602dac376e
def on_chunk_load(self, event): <NEW_LINE> <INDENT> chunk = event.chunk <NEW_LINE> n = self.noise(int(chunk.pos.x), int(chunk.pos.y)) <NEW_LINE> if n > self.server.config.ruins.threshold: <NEW_LINE> <INDENT> index = n % len(self.model_loaders) <NEW_LINE> model = self.model_loaders[index].load_model() <NEW_LINE> lower_x...
Called when a chunk has finished loading. This is a CuBolt event. Keyword arguments: event -- The event.
625941cb9f2886367277a968
def check_object_in_list(self, instance): <NEW_LINE> <INDENT> if not self._validate_type(instance): <NEW_LINE> <INDENT> raise Exception( "Object data type is not present in the entity list") <NEW_LINE> <DEDENT> return instance.id in [entity.id for entity in self._entities]
We check whether the instance is already in the list :param instance: Object that is to be added to the list
625941cb2eb69b55b151c98a
def calculate_broad_support(pid, state): <NEW_LINE> <INDENT> return _broad_support( state.get_votes_by_pid_clustered(pid), state)
Used by state to keep the cached DB value up-to-date.
625941cb7c178a314d6ef53b
def __init__(self, relations, distanceorweighs=True, symmetric=True, input_='indices', output='indices', _data=None, data_in=None, input_type=None, store=None): <NEW_LINE> <INDENT> self._initialization() <NEW_LINE> self.relations = relations <NEW_LINE> self._format_relations(relations, _data) <NEW_LINE> self._format_da...
Instantiation of the regionmetrics. It stores and manage the information of precomputed spatial relations. Parameters ---------- relations: scipy.sparse or nx.Graph or np.ndarray the precomputed spatial relations. distanceorweighs: boolean (default=True) if it is distance True, if it is weight False. symmetric...
625941cb796e427e537b06a1
@asyncio.coroutine <NEW_LINE> def search_for_userid(username, timeout=10, be_specific=False): <NEW_LINE> <INDENT> if username in userid_cache: <NEW_LINE> <INDENT> return userid_cache[username] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if be_specific: <NEW_LINE> <INDENT> uid = yield from get_user_id(username, timeou...
Searches for a steamid based on a username, not using vanity URLs Args: username (str): the username of the user you're searching for timeout (int, optional): the amount of time before aiohttp throws a timeout error Returns: A steamid (str)
625941cb8c0ade5d55d3ea96
def parse_file( self, file_or_filename: Union[str, Path, TextIO], encoding: str = "utf-8", parse_all: bool = False, *, parseAll: bool = False, ) -> ParseResults: <NEW_LINE> <INDENT> parseAll = parseAll or parse_all <NEW_LINE> try: <NEW_LINE> <INDENT> file_contents = file_or_filename.read() <NEW_LINE> <DEDENT> except At...
Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing.
625941cb91af0d3eaac9baf4
def generalised_dice_loss(prediction, ground_truth, weight_map=None, type_weight='Square'): <NEW_LINE> <INDENT> ground_truth = tf.to_int64(ground_truth) <NEW_LINE> n_voxels = ground_truth.shape[0].value <NEW_LINE> n_classes = prediction.shape[1].value <NEW_LINE> ids = tf.constant(np.arange(n_voxels), dtype=tf.int64) <N...
Function to calculate the Generalised Dice Loss defined in Sudre, C. et. al. (2017) Generalised Dice overlap as a deep learning loss function for highly unbalanced segmentations. DLMIA 2017 :param prediction: the logits :param ground_truth: the segmentation ground truth :param weight_map: :param type_weight: t...
625941cbac7a0e7691ed41a8
def on_day(self, day: date) -> "ValidityRangeRelatedQuerySet": <NEW_LINE> <INDENT> return self.within_dates(day, day)
Filter for all objects on a certain day.
625941cb627d3e7fe0d68f2b
def _skip_whitespaces(self): <NEW_LINE> <INDENT> while self.current_token.type in [STRING, NEWLINE] and not self.current_token.value.strip(): <NEW_LINE> <INDENT> self._consume(self.current_token.type)
Skip whitespaces and newline
625941cb3317a56b86939d34
def convert_number_to_linked_list(self, val): <NEW_LINE> <INDENT> digits = [int(x) for x in str(val)][::-1] <NEW_LINE> digit_first = digits[0] <NEW_LINE> result = add_two_numbers.ListNode(digit_first) <NEW_LINE> current = result <NEW_LINE> for digit in digits[1:]: <NEW_LINE> <INDENT> next = add_two_numbers.ListNode(dig...
convert a numerical value to a reverse linked list representation
625941cb50812a4eaa59c3fd
def resize_svg(self, src, dst, max_size, bigger_panoramas): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if src.endswith('.svgz'): <NEW_LINE> <INDENT> with gzip.GzipFile(src, 'rb') as op: <NEW_LINE> <INDENT> xml = op.read() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> with open(src, 'rb') as op: <NEW_LINE> <I...
Make a copy of an svg at the requested size.
625941cb004d5f362079a40e
def nds_coord(x, y, width, height): <NEW_LINE> <INDENT> return (2 * x - width) / width, (height - 2 * y) / height
Convert SCS to NDS.
625941cbe76e3b2f99f3a8e7
def validate_observer_result( sql_result: pd.DataFrame, alert_id: int, alert_label: str ) -> Optional[str]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if sql_result.empty: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> rows = sql_result.to_records() <NEW_LINE> assert ( len(rows) == 1 ), f"Observer for alert <{al...
Verifies if a DataFrame SQL query result to see if it contains a valid value for a SQLObservation. Returns an error message if the result is invalid.
625941cbbf627c535bc132aa
def _check_Subscript_expr(subs, t, env): <NEW_LINE> <INDENT> assert subs.__class__ is ast.Subscript <NEW_LINE> c = subs.value <NEW_LINE> s = subs.slice <NEW_LINE> c_t = infer_expr(c, env) <NEW_LINE> if not c_t: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if s.__class__ is ast.Index: <NEW_LINE> <INDENT> e = s.v...
Subscription.
625941cb4c3428357757c403