code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def example(): <NEW_LINE> <INDENT> pass
>>> example() 42
625941ce2ae34c7f2600d264
def order_list_api(self, page=1): <NEW_LINE> <INDENT> logging.info("订单 - 订单数页") <NEW_LINE> data = {"page": page} <NEW_LINE> logging.info(f"请求参数:{data}") <NEW_LINE> return requests.get(self.order_list_url, params=data, headers=app.headers)
订单列表 :param page: 订单数页 :return:
625941ce26238365f5f0efa1
@blueprint.app_errorhandler(400) <NEW_LINE> def bad_request(error=None): <NEW_LINE> <INDENT> message = { 'errors': { 'status': 400, 'detail': 'Bad Request: ' + error, } } <NEW_LINE> resp = jsonify(message) <NEW_LINE> resp.status_code = 400 <NEW_LINE> return resp
400 The browser (or proxy) sent a request that this server could not understand.
625941cefbf16365ca6f62f8
def collect_node_names(self): <NEW_LINE> <INDENT> def add_node_name(name): <NEW_LINE> <INDENT> node_id = self.escape_id(name) <NEW_LINE> nth, suffix = 1, '' <NEW_LINE> while node_id + suffix in self.written_ids or node_id + suffix in self.node_names: <NEW_LINE> <INDENT> nth += 1 <NEW_LINE> suffix = '<%...
Generates a unique id for each section. Assigns the attribute ``node_name`` to each section.
625941ce4f6381625f114b6e
@jit <NEW_LINE> def p_verlet(E,t0,t1,dt): <NEW_LINE> <INDENT> x_t = 0 <NEW_LINE> v_t = 0 <NEW_LINE> rescattered_t = 0 <NEW_LINE> x_ = np.zeros(timesteps) <NEW_LINE> for i in range(t0,t1): <NEW_LINE> <INDENT> x_t = x_t + dt*v_t + dt*dt/2/m*e*E[i] <NEW_LINE> v_t = v_t + dt/2/m*e*(E[i+1] + E[i]) <NEW_LINE> if i == t0: <NE...
velocity verlet algorithm input: E : electric field t0 : start of integration t1 : end of integration dt : time step output: p_t : final momentum
625941ce7d847024c06be3ef
def insert_into_db(conn, title, author, isbn, gtype, genres, mapped_genres): <NEW_LINE> <INDENT> c = conn.cursor() <NEW_LINE> isbn_key = int(isbn) <NEW_LINE> book_data = (isbn_key, title, author, gtype, str(genres), str(mapped_genres)) <NEW_LINE> c.execute("INSERT INTO books VALUES (?, ?, ?, ?, ?, ?, NULL)", book_data)...
Takes information about a book and inserts a new row into the database containing that information, updating the existing entry if the ISBN is already present. :param conn: <Connection> connection to the database to insert into :param title: <String> title of the book :param author: <String> author of the book :param ...
625941ce24f1403a92600c98
def get_variables(name, type_spec, **kwargs): <NEW_LINE> <INDENT> py_typecheck.check_type(name, six.string_types) <NEW_LINE> type_spec = computation_types.to_type(type_spec) <NEW_LINE> py_typecheck.check_type(type_spec, computation_types.Type) <NEW_LINE> if isinstance(type_spec, computation_types.TensorType): <NEW_LINE...
Creates a set of variables that matches the given `type_spec`. Args: name: The common name to use for the scope in which all of the variables are to be created. type_spec: An instance of `tff.Type` or something convertible to it. The type signature may only be composed of tensor types and named tuples, ...
625941ce4e696a04525c957e
def get_firmware(self, id_or_uri): <NEW_LINE> <INDENT> firmware_uri = self._client.build_uri(id_or_uri) + "/firmware" <NEW_LINE> return self._client.get(firmware_uri)
Gets baseline firmware information for a SAS Logical Interconnect. Args: id_or_uri: Can be either the SAS Logical Interconnect ID or URI. Returns: dict: SAS Logical Interconnect Firmware.
625941ce9c8ee82313fbb8a8
def batch_test_ss_mlp(test_count=10, su_count=1000): <NEW_LINE> <INDENT> sgd_params = {} <NEW_LINE> sgd_params['start_rate'] = 0.1 <NEW_LINE> sgd_params['decay_rate'] = 0.998 <NEW_LINE> sgd_params['wt_norm_bound'] = 3.5 <NEW_LINE> sgd_params['epochs'] = 1000 <NEW_LINE> sgd_params['batch_size'] = 100 <NEW_LINE> mlp_para...
Run multiple semisupervised learning tests.
625941ceaad79263cf390b74
def instance(): <NEW_LINE> <INDENT> if CommandHandler.__instance is None: <NEW_LINE> <INDENT> CommandHandler() <NEW_LINE> <DEDENT> return CommandHandler.__instance
Singleton instance
625941cebde94217f3682f24
def deletes(self, obj=None, header=False): <NEW_LINE> <INDENT> if header: <NEW_LINE> <INDENT> return "操作" <NEW_LINE> <DEDENT> _url = self.get_delete_url(obj) <NEW_LINE> return mark_safe("<a href='%s'>删除</a>" % _url)
删除
625941ce0a50d4780f666fc5
def link_signal_handler(self, signal) -> None: <NEW_LINE> <INDENT> link_type, target_ip, port = signal <NEW_LINE> if link_type == self.ServerTCP: <NEW_LINE> <INDENT> self.tcp_server_start(port) <NEW_LINE> <DEDENT> elif link_type == self.ClientTCP: <NEW_LINE> <INDENT> self.tcp_client_start(target_ip, port) <NEW_LINE> <D...
连接信号分用的槽函数
625941ced10714528d5ffe17
def make_monotonic(labels, classes=None, copy=False): <NEW_LINE> <INDENT> labels = rmm_cupy_ary(cp.asarray, labels, dtype=labels.dtype) <NEW_LINE> if copy: <NEW_LINE> <INDENT> labels = labels.copy() <NEW_LINE> <DEDENT> if labels.ndim != 1: <NEW_LINE> <INDENT> raise ValueError("Labels array must be 1D") <NEW_LINE> <DEDE...
Takes a set of labels that might not be drawn from the set [0, n-1] and renumbers them to be drawn that interval. Parameters ---------- labels : array-like of size (n,) labels to convert classes : array-like of size (n_classes,) the unique set of classes in the set of labels copy : boolean if true, a copy w...
625941ce26068e7796caee12
@register.simple_tag(name='cdr_details') <NEW_LINE> def cdr_details(cdr_id): <NEW_LINE> <INDENT> link = '<a href="#cdr-detail" url="/cdr_detail/%s" class="cdr-detail" data-toggle="modal" data-controls-modal="cdr-detail" title="%s"><i class="fa fa-search"></i></a>' % (cdr_id, _('cdr detail').capitalize()) <NE...
Create link to get cdr detail
625941ce7b180e01f3dc4930
def setUp(self): <NEW_LINE> <INDENT> self.input, self.output = socket.socketpair(socket.AF_UNIX)
Create a pair of UNIX sockets.
625941ce796e427e537b06f9
def list_interface_ips(ip_type, interface): <NEW_LINE> <INDENT> assert ip_type in (futils.IPV4, futils.IPV6), ( "Expected an IP type, got %s" % ip_type ) <NEW_LINE> if ip_type == futils.IPV4: <NEW_LINE> <INDENT> data = futils.check_call( ["ip", "addr", "list", "dev", interface]).stdout <NEW_LINE> regex = r'^ inet ([...
List the local IPs assigned to an interface. :param str ip_type: IP type, either futils.IPV4 or futils.IPV6 :param str interface: Interface name :returns: a set of all addresses directly assigned to the device.
625941ce046cf37aa974ce7b
def set_settings(**kwargs): <NEW_LINE> <INDENT> if 'service_fee' in kwargs: <NEW_LINE> <INDENT> ticket_service_fees = kwargs.get('service_fee') <NEW_LINE> ticket_maximum_fees = kwargs.get('maximum_fee') <NEW_LINE> from app.api.helpers.data_getter import DataGetter <NEW_LINE> from app.api.helpers.db import save_to_db <N...
Update system settings
625941ce627d3e7fe0d68f83
def write_coverage(self, prf): <NEW_LINE> <INDENT> for i, label, handler in self.coverage_selection: <NEW_LINE> <INDENT> handler(label, prf[i])
Write P/R/F1 figures.
625941ce090684286d50ee19
def read_headers(self): <NEW_LINE> <INDENT> environ = self.environ <NEW_LINE> while True: <NEW_LINE> <INDENT> line = self.rfile.readline() <NEW_LINE> if not line: <NEW_LINE> <INDENT> raise ValueError("Illegal end of headers.") <NEW_LINE> <DEDENT> if line == '\r\n': <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if line[...
Read header lines from the incoming stream.
625941ce73bcbd0ca4b2c1a9
def __init__(self): <NEW_LINE> <INDENT> self.item_list = [] <NEW_LINE> self.playlist = []
Playlist constructor.
625941ce21a7993f00bc7e23
def admin_group_check(user): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> admin_group = Group.objects.get(name='StuCampus') <NEW_LINE> <DEDENT> except Group.DoesNotExist: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return (admin_group in user.groups.all())
Admin group check function for user_passes_test.
625941ce5166f23b2e1a528c
def get_wagtail_image(self, url): <NEW_LINE> <INDENT> filename = self._filename_from_url(url) <NEW_LINE> try: <NEW_LINE> <INDENT> return WagtailImage.objects.get(title=filename) <NEW_LINE> <DEDENT> except WagtailImage.DoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> print(f"Downloading {url}") <NEW_LINE> resp...
Looks for an existing image with the same name, otherwise downloads and saves the image.
625941ce4428ac0f6e5ba926
def gene2go(filename, experimental=False, tax_id=9606, **kwds): <NEW_LINE> <INDENT> defaults = {'comment': '#', 'names': GENE2GO_COLUMNS, 'low_memory' : False} <NEW_LINE> defaults.update(kwds) <NEW_LINE> result = pd.read_table(filename, **defaults) <NEW_LINE> retain_mask = result.tax_id == tax_id <NEW_LINE> result.drop...
read go-annotation file :param filename: protein or gene identifier column :param experimental: use only experimentally validated annotations :param tax_id: filter according to taxon
625941cedc8b845886cb5668
def test_past_question(self): <NEW_LINE> <INDENT> pass
Questions with a pub_date in the past are displayed on the index page.
625941ce566aa707497f469b
def create_invalid_cfg ( self ): <NEW_LINE> <INDENT> new_cfg = self.create_cfg ( image_save_dir="/mantosh_downloaded", url_timeout=-1, max_dl_attempt=-1, sys_proxy=(), log_dir="/mantosh_logs", log_lvl="invalid" ) <NEW_LINE> return new_cfg
Create a new cfg.APP_CFG with valid values. Please look into cfg.py for details. :return: A new invalid cfg.APP_CFG
625941ce4f88993c3716c19b
@app.route("/api/heartbeat") <NEW_LINE> def api_heartbeat(): <NEW_LINE> <INDENT> result = { "ok": True, "error": "" } <NEW_LINE> return jsonify(result)
Health check for the API
625941ce0a366e3fb873e94e
def restart_target(self, target=None, fuzz_data_logger=None, session=None): <NEW_LINE> <INDENT> return self.__method_missing("restart_target")
This method is forwarded to the RPC daemon.
625941ce1d351010ab855c4f
def get_maxcount(self): <NEW_LINE> <INDENT> return max(tag.post_count for tag in self) if self.count() else 0
Return the most used tag's number of associations. This is needed for the calculation of the tag cloud
625941ced164cc6175782e81
def contains_each_unit(container): <NEW_LINE> <INDENT> units = nt.get_all_units(container) <NEW_LINE> sts = nt.get_all_spiketrains(container) <NEW_LINE> return [spk for spk in filter(lambda st: st.unit in units, sts)]
Each `neo.core.SpikeTrain` object of given input has a link to each `neo.core.Unit`. Parameters ---------- container : list, tuple, iterable, dict, neo container The container for the neo objects. Returns ------- sts : list of neo.core.SpikeTrain objects List of `neo.core.SpikeTrain` objects with a link to ea...
625941ce293b9510aa2c33ca
def test_summary(self): <NEW_LINE> <INDENT> data = self.iris <NEW_LINE> input_sum = self.widget.info.set_input_summary = Mock() <NEW_LINE> output_sum = self.widget.info.set_output_summary = Mock() <NEW_LINE> self.send_signal(self.widget.Inputs.data, data) <NEW_LINE> input_sum.assert_called_with(len(data), format_summar...
Check if status bar is updated when data is received
625941ce55399d3f055887e8
def on_release(self, button): <NEW_LINE> <INDENT> self.pressed = False <NEW_LINE> if self._on_release: <NEW_LINE> <INDENT> self._on_release(button)
Set the `pressed` variable `False` and call the underlying desired `_on_release` method if any :param button: :return:
625941ce596a897236089bf4
def action_edit(self): <NEW_LINE> <INDENT> _buffer = self.editor.current_buffer <NEW_LINE> filename = self.input.prompt_bar('Open file:') <NEW_LINE> _buffer.open_file(filename) <NEW_LINE> self.editor.command_stack = [] <NEW_LINE> self.editor.undo_stack = []
Open new file to for edit
625941ce5f7d997b87174bcb
def testShallowTag(self): <NEW_LINE> <INDENT> self.init_submodules() <NEW_LINE> self.tag_release("--shallow", self.new_version) <NEW_LINE> self.assertTrue(self.has_new_prefixed_tag(self.sandbox)) <NEW_LINE> for submodule in self.sandbox.submodules: <NEW_LINE> <INDENT> self.assertFalse(self.has_new_prefixed_tag(submodul...
Test shallow tagging on repository with submodules
625941ce097d151d1a222f8d
def send_json_handler(request, response, content): <NEW_LINE> <INDENT> if content: <NEW_LINE> <INDENT> response["content"] = json.dumps(content) <NEW_LINE> response["Content-type"] = "application/json" <NEW_LINE> return ok_200_handler(request, response) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return err_404_handl...
send_json handler Add JSON content to response
625941ce377c676e912722dc
def conv_forward_naive(x, w, b, conv_param): <NEW_LINE> <INDENT> out = None <NEW_LINE> N, C, H, W = x.shape <NEW_LINE> F, C, HH, WW = w.shape <NEW_LINE> stride = conv_param['stride'] <NEW_LINE> pad = conv_param['pad'] <NEW_LINE> x_pad = np.pad(x, ((0,), (0,), (pad,), (pad,)), mode='constant') <NEW_LINE> out_h = (H + 2*...
A naive implementation of the forward pass for a convolutional layer. The input consists of N data points, each with C channels, height H and width W. We convolve each input with F different filters, where each filter spans all C channels and has height HH and width HH. Input: - x: Input data of shape (N, C, H, W) - ...
625941ce0fa83653e46570ee
def play_resume(playqueue, xml, stack): <NEW_LINE> <INDENT> result = Playback_Successful() <NEW_LINE> listitem = PKC_ListItem() <NEW_LINE> stack_item = stack.pop(0) <NEW_LINE> api = API(xml[0]) <NEW_LINE> item = PL.playlist_item_from_xml(playqueue, xml[0], kodi_id=stack_item['kodi_id'], kodi_type=stack_item['kodi_type'...
If there exists a resume point, Kodi will ask the user whether to continue playback. We thus need to use setResolvedUrl "correctly". Mind that there might be several parts!
625941ce30c21e258bdfa5d1
def draw(self, painter): <NEW_LINE> <INDENT> self.draw_circle(painter) <NEW_LINE> self.draw_debug(painter)
draw the individual
625941ceac7a0e7691ed4200
def _maybe_convert_i8(self, key): <NEW_LINE> <INDENT> original = key <NEW_LINE> if is_list_like(key): <NEW_LINE> <INDENT> key = ensure_index(key) <NEW_LINE> <DEDENT> if not self._needs_i8_conversion(key): <NEW_LINE> <INDENT> return original <NEW_LINE> <DEDENT> scalar = is_scalar(key) <NEW_LINE> if is_interval_dtype(key...
Maybe convert a given key to its equivalent i8 value(s). Used as a preprocessing step prior to IntervalTree queries (self._engine), which expects numeric data. Parameters ---------- key : scalar or list-like The key that should maybe be converted to i8. Returns ------- scalar or list-like The original key if ...
625941ce63d6d428bbe44623
def add_data_stage01_rnasequencing_softwareParameters(self,table_I,data_I): <NEW_LINE> <INDENT> if data_I: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> model_I = self.convert_tableString2SqlalchemyModel(table_I); <NEW_LINE> queryinsert = sbaas_base_query_insert(session_I=self.session,engine_I=self.engine,settings_I=sel...
add rows of data_stage01_rnasequencing_softwareParameters
625941ce85dfad0860c3af8f
def inline_vector_mult(vectorA, vectorB): <NEW_LINE> <INDENT> return Vector([i * j for i, j in zip(vectorA, vectorB)])
Multiply each index of two vectors by each other, so [vectorA[0] * vectorB[0], ...]
625941cead47b63b2c50a0b3
def cartesian(self,s): <NEW_LINE> <INDENT> p = [] <NEW_LINE> for i in self.list(): <NEW_LINE> <INDENT> for j in s.list(): <NEW_LINE> <INDENT> p.append((i,j)) <NEW_LINE> <DEDENT> <DEDENT> return HashSet(p)
Returns the Cartesian product of this set and s.
625941ce956e5f7376d70fa0
def __eq__(self, other): <NEW_LINE> <INDENT> if not self.str or not other: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> hashed = str(self.str) <NEW_LINE> other = bcrypt.hashpw(other, hashed) <NEW_LINE> if len(hashed) != len(other): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> result = 0 <NEW_LINE> for x...
Returns ``True`` if the passwords match. The other password is hashed before comparing. The time taken is independent of the number of characters that match.
625941ce8c3a8732951584ee
def setup_master_chainconsumer(source, master_version, epoch_versions, n_steps, discard, n_walkers=1000, epoch_discard=None, epoch_n_steps=None, epoch_n_walkers=None, cap=None, sigmas=None, cloud=None, compressed=False, fontsize=16, alt_params=True, unit_labels=True): <NEW_LINE> <INDENT> if epoch_discard is None: <NEW_...
Setup multiple MCMC chains, including multi-epoch and single-epochs alt_params : bool Replace parameters with forms used in paper
625941ce627d3e7fe0d68f84
def test_column_names(self): <NEW_LINE> <INDENT> bad_column_msg = 'Wrong columns for year={}' <NEW_LINE> expected_2015_cols = {'date', 'KITT', 'KITT_err', 'P014', 'P014_err', 'SA46', 'SA46_err', 'SA48', 'SA48_err', 'AZAM', 'AZAM_err'} <NEW_LINE> expected_2012_cols = expected_2015_cols - {'KITT', 'KITT_err'} <NEW_LINE> ...
Check the downloaded data for the correct column names The set of correct column names is determined by manually checking the SuomiNet website.
625941ce63b5f9789fde7219
def setPermanence(self, columnIndex, permanence): <NEW_LINE> <INDENT> assert(columnIndex < self._numColumns) <NEW_LINE> self._updatePermanencesForColumn(permanence, columnIndex, raisePerm=False)
Sets the permanence values for a given column. ``permanence`` size must match the number of inputs. :param columnIndex: (int) column index to set permanence for. :param permanence: (list) value to set.
625941ce851cf427c661a642
def isDescriptorOf_entity(self, entity, identifier=None): <NEW_LINE> <INDENT> return self._bundle.description(entity, self, identifier)
Creates a new relation between an entity and this entity description. :param entity: The entity described by this entity description. :param identifier: Identifier for new isDescribedBy relation record (default: None).
625941ce26238365f5f0efa2
def print_tuple(*name): <NEW_LINE> <INDENT> name_len = len(name) <NEW_LINE> print('参数个数:', name_len) <NEW_LINE> print('*name的类型', type(name)) <NEW_LINE> print('*name的值:', name) <NEW_LINE> n = 0 <NEW_LINE> for i_name in name: <NEW_LINE> <INDENT> print('第{n}个名字:{value}'.format(n=n, value=i_name)) <NEW_LINE> n += 1
以元组的方式传入参数
625941ce23849d37ff7b31c3
def main(): <NEW_LINE> <INDENT> header = ['SepalL', 'SepalW', 'PetalL', 'PetalW', 'Class'] <NEW_LINE> df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None, names=['SepalL','SepalW','PetalL','PetalW','Class']) <NEW_LINE> lst = df.values.tolist() <NEW_LINE> t = build_tr...
dataset = d_sets.load_iris() df = pd.DataFrame(data = np.c_[dataset['data'], dataset['target']], columns = dataset['feature_names'] + ['class']) #df = pd.read_csv(dataset.data, header=None, names=names) lst = df.values.tolist() header = dataset['feature_names'] + ['class']
625941ce30bbd722463cbef9
def as_batched_service(batch_size, max_delay, max_queued=0, start=True): <NEW_LINE> <INDENT> def wrap(batch_process_func): <NEW_LINE> <INDENT> service = BatchedService(batch_process_func, batch_size, max_delay, max_queued=max_queued, start=start) <NEW_LINE> return service <NEW_LINE> <DEDENT> return wrap
decorator version of BatchedService. See BatchedService itself for docs Example: >>> @as_batched_service(batch_size=3, max_delay=0.1) >>> def square(batch_xs): >>> print("processing...", batch_xs) >>> return [x_i ** 2 for x_i in batch_xs] >>> futures = square.submit_many(range(10)) >>> print([f.result() for f i...
625941ce23e79379d52ee698
def stop(name): <NEW_LINE> <INDENT> cmd = 'net stop "{0}"'.format(name) <NEW_LINE> return not __salt__['cmd.retcode'](cmd)
Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name>
625941ce099cdd3c635f0d8f
def to_alpha(new_color, alpha: int = None) -> QtGui.QColor: <NEW_LINE> <INDENT> new_color = QtGui.QColor(new_color) <NEW_LINE> if not new_color.isValid(): <NEW_LINE> <INDENT> raise ValueError(str(new_color) + " is not a valid color!") <NEW_LINE> <DEDENT> new_color.setAlpha(alpha) <NEW_LINE> return new_color
Get new color based on the given color and alpha. :param new_color: the base color :param alpha: new color's alpha :return: new color with base color and the given alpha value
625941ce0c0af96317bb831c
def _perform_request(self): <NEW_LINE> <INDENT> self.error_type = False <NEW_LINE> server_payload = self._prepare_iap_payload() <NEW_LINE> reveal_account = self.env['iap.account'].get('reveal') <NEW_LINE> dbuuid = self.env['ir.config_parameter'].sudo().get_param('database.uuid') <NEW_LINE> params = { 'account_token': r...
This will perform the request and create the corresponding leads. The user will be notified if he hasn't enough credits.
625941ce5166f23b2e1a528d
def getRequestData(self, reqId): <NEW_LINE> <INDENT> if not self.data[reqId]["complete"]: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.data[reqId].pop("complete", None) <NEW_LINE> return self.data[reqId]
Retreive Response Data from and ID
625941ce3617ad0b5ed6802b
def attach(self, obj): <NEW_LINE> <INDENT> self.set_properties(obj) <NEW_LINE> super(PointArray, self).attach(obj)
Set up the properties when the object is attached.
625941ced164cc6175782e82
def replot(self): <NEW_LINE> <INDENT> self.__scanwdgt.clear() <NEW_LINE> selection = [int(index.row()) for index in list(self.__scanlist.selectedIndexes())] <NEW_LINE> self.info("Plotting selection %s" % selection) <NEW_LINE> for index in selection: <NEW_LINE> <INDENT> berror = False <NEW_LINE> scan = self.__storage.ge...
Function taking care for replotting on appropritate signal - channels checked, scans selected :return:
625941ceff9c53063f47c327
def add_path_segment(self, value): <NEW_LINE> <INDENT> segments = self.path_segments() + (to_unicode(value),) <NEW_LINE> return self.path_segments(segments)
Add a new path segment to the end of the current string :param string value: the new path segment to use Example:: >>> u = URL('http://example.com/foo/') >>> u.add_path_segment('bar').as_string() u'http://example.com/foo/bar'
625941ce167d2b6e31218cca
def listreceivedbyaddress(self, minconf=1, includeempty=False): <NEW_LINE> <INDENT> return [AddressInfo(**x) for x in self.proxy.listreceivedbyaddress(minconf, includeempty)]
Returns a list of addresses. Each address is represented with a :class:`~shieldrpc.data.AddressInfo` object. Arguments: - *minconf* -- Minimum number of confirmations before payments are included. - *includeempty* -- Whether to include addresses that haven't received any payments.
625941ce6e29344779a62746
def test_html(self): <NEW_LINE> <INDENT> self.assertContains(self.resp, u'Título da palestra', 2) <NEW_LINE> self.assertContains(self.resp, u'/palestras/1/') <NEW_LINE> self.assertContains(self.resp, u'/palestras/2/') <NEW_LINE> self.assertContains(self.resp, u'/palestrantes/marcio-ramos-correa/', 2) <NEW_LINE> self.as...
Html should list talks.
625941ced486a94d0b98e27a
def _FindNameMatches(self, query): <NEW_LINE> <INDENT> matches = models.CommonName.objects.filter(name__icontains=query) <NEW_LINE> return matches[:self._max_results]
Override matching.
625941cee1aae11d1e749deb
def run(self, input_files, metadata, output_files, output_metadata): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logger.debug("Initialise the Dorothea") <NEW_LINE> tt_handle = RUNNER(self.configuration) <NEW_LINE> tt_files, tt_meta = tt_handle.run(input_files, metadata, output_files, output_metadata) <NEW_LINE> return...
Main run function for processing a test file. :param input_files: Dictionary of file locations. :type input_files: dict :param metadata: Required meta data. :type metadata: dict :param output_files: Locations of the output files to be returned by the pipeline. :type output_files: dict :param output_metadata: :type out...
625941cefb3f5b602dac37c7
def _recognise_speech() -> None: <NEW_LINE> <INDENT> recogniser: Recogniser = SpeechRecogniser( JackRobot( SpeechEngine( ) ) ) <NEW_LINE> while True: <NEW_LINE> <INDENT> recogniser.run()
Main speech recogniser program to run.
625941ce45492302aab5e3f8
def _set_local_id(self, v, load=False): <NEW_LINE> <INDENT> if hasattr(v, "_utype"): <NEW_LINE> <INDENT> v = v._utype(v) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> t = YANGDynClass( v, base=six.text_type, is_leaf=True, yang_name="local-id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, regi...
Setter method for local_id, mapped from YANG variable /network_instances/network_instance/segment_routing/srgbs/srgb/state/local_id (string) If this variable is read-only (config: false) in the source YANG file, then _set_local_id is considered as a private method. Backends looking to populate this vari...
625941ce71ff763f4b5497c0
def bgr2ycbcr(img, y_only=False): <NEW_LINE> <INDENT> img_type = img.dtype <NEW_LINE> img = _convert_input_type_range(img) <NEW_LINE> if y_only: <NEW_LINE> <INDENT> out_img = np.dot(img, [24.966, 128.553, 65.481]) + 16.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out_img = np.matmul( img, [[24.966, 112.0, -18.214], ...
Convert a BGR image to YCbCr image. The bgr version of rgb2ycbcr. It implements the ITU-R BT.601 conversion for standard-definition television. See more details in https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion. It differs from a similar function in cv2.cvtColor: `BGR <-> YCrCb`. In OpenCV, it implements...
625941ced6c5a1020814417f
def pinyin(hans, style=TONE, heteronym=False, errors='default'): <NEW_LINE> <INDENT> if isinstance(hans, unicode): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import jieba <NEW_LINE> hans = jieba.cut(hans) <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> pys = [] <NEW_LINE>...
将汉字转换为拼音. :param hans: 汉字字符串( ``u'你好吗'`` )或列表( ``[u'你好', u'吗']`` ). 如果用户安装了 ``jieba`` , 将使用 ``jieba`` 对字符串进行 分词处理。 也可以使用自己喜爱的分词模块对字符串进行分词处理, 只需将经过分词处理的字符串列表传进来就可以了。 :type hans: unicode 字符串或字符串列表 :param style: 指定拼音风格 :param errors: 指定如何处理没有拼音的字符 * ``...
625941ce5fcc89381b1e17f4
def scan_file(location, file_type=""): <NEW_LINE> <INDENT> xmlDict = {} <NEW_LINE> path = location <NEW_LINE> f_list = os.listdir(path) <NEW_LINE> for i in f_list: <NEW_LINE> <INDENT> k = i.find(".") <NEW_LINE> if(k != -1): <NEW_LINE> <INDENT> if(file_type == ""): <NEW_LINE> <INDENT> xmlDict[i[:k]] = path + i <NEW_LINE...
传入想要扫描的文件夹路径 与 文件扩展名(后缀,点后面那几个字母, 不包括那个点)返回扫描到的文件。
625941ce8a349b6b435e82a8
def predict_labels(self, indices, k=1): <NEW_LINE> <INDENT> N, M = np.shape(self.y_train) <NEW_LINE> num_test = indices.shape[0] <NEW_LINE> y_pred = np.zeros((M,num_test)) <NEW_LINE> dist_dice =indices[:,0:k] <NEW_LINE> for i in xrange(num_test): <NEW_LINE> <INDENT> dice_i = dist_dice[i,:] <NEW_LINE> dice_i = list(dice...
Given a matrix of distances between test points and training points, predict a label for each test point. Inputs: - dists: A numpy array of shape (num_test, num_train) where dists[i, j] gives the distance betwen the ith test point and the jth training point. Returns: - y: A numpy array of shape (num_test,) containi...
625941cee64d504609d74974
def check_transport_auth_anonymous(config): <NEW_LINE> <INDENT> if 'type' not in config: <NEW_LINE> <INDENT> raise InvalidConfigException("missing mandatory attribute 'type' in WAMP-Anonymous configuration") <NEW_LINE> <DEDENT> if config['type'] not in ['static', 'dynamic', 'function']: <NEW_LINE> <INDENT> raise Invali...
Check a WAMP-Anonymous configuration item. http://crossbar.io/docs/Anonymous-Authentication https://github.com/crossbario/crossbar/blob/master/docs/pages/administration/auth/Anonymous-Authentication.md
625941cecdde0d52a9e53168
def _edge_detection(self): <NEW_LINE> <INDENT> edge_detection(self.model)
Detect the image edge.
625941ce8c0ade5d55d3eaf0
def CreateLocalGateway(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("CreateLocalGateway", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.CreateLocalGatewayRespo...
该接口用于创建用于CDC的本地网关。 :param request: Request instance for CreateLocalGateway. :type request: :class:`tencentcloud.vpc.v20170312.models.CreateLocalGatewayRequest` :rtype: :class:`tencentcloud.vpc.v20170312.models.CreateLocalGatewayResponse`
625941ceec188e330fd5a8d3
def test_GET_fail(self): <NEW_LINE> <INDENT> c = Client() <NEW_LINE> response = c.get(self.url) <NEW_LINE> self.assertStatusCodeEquals(response, 302) <NEW_LINE> self.assertEquals(response['Location'], 'http://%s%s' % ( self.site_location.site.domain, reverse('localtv_submit_video')))
If the URL isn't present in the GET request, the view should redirect back to the localtv_submit_video view.
625941cea8ecb033257d3201
def predict_for_user(self, user_id, item_ids, rank_training_last=True, sort=True, combine_original_order=False): <NEW_LINE> <INDENT> user_id = str(user_id) <NEW_LINE> item_ids = np.array(item_ids).astype(str) <NEW_LINE> df = pd.DataFrame() <NEW_LINE> df[self._item_col] = item_ids <NEW_LINE> df[self._user_col] = user_id...
method for predicting for one user for a small subset of items. optimized for minimal latency for use in real-time ranking will return -np.inf for combinations of unknown user / unknown items :param user_id: a single user ID, may be an unknown users (all predictions will be None) :param item_ids: a subset of item IDs,...
625941ce99cbb53fe6792d1b
def run_server(config_file=None, *args, **kwargs): <NEW_LINE> <INDENT> app = make_app(config_file=config_file, *args, **kwargs) <NEW_LINE> if config_file is None: <NEW_LINE> <INDENT> config = get_config() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> config = get_config(config_file) <NEW_LINE> <DEDENT> config.update(kw...
Same as make_app, but also runs the app
625941ce6aa9bd52df036ed9
def test_opening_dash_desaturates_icons(self): <NEW_LINE> <INDENT> self.unity.dash.ensure_visible() <NEW_LINE> current_monitor = self.unity.dash.monitor <NEW_LINE> self.addCleanup(self.unity.dash.ensure_hidden) <NEW_LINE> for icon in self.unity.launcher.model.get_launcher_icons(): <NEW_LINE> <INDENT> if isinstance(icon...
Opening the dash must desaturate all the launcher icons.
625941cebe383301e01b55ba
def get_version(self): <NEW_LINE> <INDENT> self.facts['version'] = None <NEW_LINE> import ibmsecurity.qradar.firmware <NEW_LINE> ret_obj = ibmsecurity.qradar.firmware.get(self) <NEW_LINE> for partition in ret_obj['data']: <NEW_LINE> <INDENT> if partition['active'] is True: <NEW_LINE> <INDENT> ver = partition['firmware_...
Get appliance version (active partition) When firmware are installed or partition are changed, then this value is updated
625941ce6fece00bbac2d873
@login_required <NEW_LINE> def clientKioskList(request, client_id): <NEW_LINE> <INDENT> assert isinstance(request, HttpRequest) <NEW_LINE> clientQuery = ClientKiosk.objects.filter(client=client_id).prefetch_related('client', 'kiosk_type') <NEW_LINE> contactQuery = ClientContact.objects.filter(client=client_id) <NEW_LIN...
Renders the Kiosk List page from the Client List page
625941ced8ef3951e3243672
def backup_files(valid_level): <NEW_LINE> <INDENT> with open("bak/time", "w") as time_file: <NEW_LINE> <INDENT> time_file.write(datetime.now().strftime("%Y-%m-%d %H:%M:%S")+"\n") <NEW_LINE> <DEDENT> for level in valid_level: <NEW_LINE> <INDENT> shutil.copy(str(level)+".txt", "bak/")
Backup files in "bak" directory Record the timestamp in a file Args: valid_level: [str] List of number of levels
625941ce97e22403b379d0ce
def add_task(task, priority=False): <NEW_LINE> <INDENT> deferred = Deferred() <NEW_LINE> gen = task() <NEW_LINE> with _executor.context as ctx: <NEW_LINE> <INDENT> gen_task = (deferred, gen) <NEW_LINE> if priority: <NEW_LINE> <INDENT> ctx.task_queue.appendleft(gen_task) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ctx...
Add a task to the list. The task is a coroutine who performs IO-bound tasks. It can performs in many "steps", separated by external calls using Promise yielded. The first yielded result who is not a thenable (see promise.is_thenable()) is used to resolve the returning promise. Each call to the generator is guaranteed...
625941ced6c5a10208144180
def test_nosetup(self): <NEW_LINE> <INDENT> print('no setup for this test, just a sleep') <NEW_LINE> print('this is the test {}'.format(self.test)) <NEW_LINE> time.sleep(1)
This test should take more than 1 second and print 0
625941cee76e3b2f99f3a93f
def breadthFirstSearch(problem): <NEW_LINE> <INDENT> visited = [] <NEW_LINE> stateQueue = util.Queue() <NEW_LINE> stateQueue.push([(problem.getStartState(), "Stop", 0)]) <NEW_LINE> while not stateQueue.isEmpty(): <NEW_LINE> <INDENT> pacway = stateQueue.pop() <NEW_LINE> curr = pacway[len(pacway)-1] <NEW_LINE> curr = cur...
Search the shallowest nodes in the search tree first. print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) "*** YOUR CODE HERE ***"
625941ce097d151d1a222f8e
def encodeValue(self, value): <NEW_LINE> <INDENT> return value.encode(utils.ENCODING)[:self.length].ljust(self.length)
Return raw data string encoded from a ``value``.
625941cef7d966606f6aa139
def G ( x , y , z , u , v , w ) : <NEW_LINE> <INDENT> result = 0.0 <NEW_LINE> result += x * x * y + x * y * y <NEW_LINE> result += z * z * u + z * u * u <NEW_LINE> result += v * v * w + v * w * w <NEW_LINE> result += x * z * w + x * u * v <NEW_LINE> result += y * z * v + y * u * w <NEW_LINE> result -= x * y * ( z + u ...
Universal four-particle kinematical function, aka ``tetrahedron-function'' - see E.Byckling, K.Kajantie, ``Particle kinematics'' , John Wiley & Sons, London, New York, Sydney, Toronto, 1973, p.89, eq. (5.23) - see https://userweb.jlab.org/~rafopar/Book/byckling_kajantie.pdf E.g. physical range for 2->2 sca...
625941ceaad79263cf390b76
def predict_risk(self, x): <NEW_LINE> <INDENT> self.lstm.reset_state() <NEW_LINE> for t in range(len(x)): <NEW_LINE> <INDENT> v = Variable(self.xp.array(x[t], dtype=self.xp.float32)) <NEW_LINE> h = self(v) <NEW_LINE> <DEDENT> return F.sigmoid(self.ho(h))
Risk prediction Args: x (a list of feature array): a feature array list Returns: r (a Variable of float): a risk value
625941ce4e696a04525c9580
def create_tamper_proof_string( name, value, key, duration=None, hmac=HMAC, hasher=sha384 ): <NEW_LINE> <INDENT> if not isinstance(name, str): <NEW_LINE> <INDENT> raise ValueError("You can only tamper-proof str name/values.") <NEW_LINE> <DEDENT> if not isinstance(value, str): <NEW_LINE> <INDENT> raise ValueError("You c...
Return a tamper proof version of the passed in string value.
625941ce4f6381625f114b70
def get_run_info(instrument, ipts, run_number): <NEW_LINE> <INDENT> run_info = {} <NEW_LINE> try: <NEW_LINE> <INDENT> conn = httplib.HTTPConnection(ICAT_DOMAIN, ICAT_PORT, timeout=2.0) <NEW_LINE> url = '/icat-rest-ws/dataset/SNS/%s/%s' % (instrument.upper(), run_number) <NEW_LINE> conn.request('GET', url) <NEW_LINE> r ...
Get ICAT info for the specified run
625941cebe7bc26dc91cd734
def sub_start(self, sub): <NEW_LINE> <INDENT> start = self.timestamp_start - timedelta(minutes=sub) <NEW_LINE> if start > self.timestamp_end: <NEW_LINE> <INDENT> return Timestamp(self.timestamp_end, start, self.span, self.quarter) <NEW_LINE> <DEDENT> return Timestamp(start, self.timestamp_end, self.span, self.quarter)
Subtracts minutes from the timestamp_start. **Span and Quarter will to not be recalculate** :param sub: minutes to substract :return: timestamp
625941cef9cc0f698b140730
def testMatchDraw(self): <NEW_LINE> <INDENT> self.bot.replies = ['lose+'] <NEW_LINE> self.game.interface.flags = 256 <NEW_LINE> self.assertEqual(('dice', 3), self.game.gipf_check('Dice', ('cards', 'dice')))
Test drawing the gipf challenge with match play.
625941ce0383005118ecf717
def _dict_from_element(element): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return element.getValueAsString() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> if element.numValues() > 1: <NEW_LINE> <INDENT> results = [] <NEW_LINE> for i in range(0, element.numValues()): <NEW_LINE> <INDENT> subelement = element.getV...
Used for e.g. dividends
625941cecc40096d61595a85
def get_count_A_C_G_and_T_in_string(dna_string): <NEW_LINE> <INDENT> dna_string = dna_string.upper() <NEW_LINE> As = 0 <NEW_LINE> Cs = 0 <NEW_LINE> Gs = 0 <NEW_LINE> Ts = 0 <NEW_LINE> for ch in dna_string: <NEW_LINE> <INDENT> if ch == 'A': <NEW_LINE> <INDENT> As += 1 <NEW_LINE> <DEDENT> elif ch == 'C': <NEW_LINE> <INDE...
Create a function named get_count_A_C_G_and_T_in_string with a parameter named dna_string. :param dna_string: a DNA string :return: the count of As, Cs, Gs, and Ts in the dna_string
625941ce50812a4eaa59c456
def test_duplicate_email(self): <NEW_LINE> <INDENT> get_user_model().objects.create_user( username=self.username, email=self.email, password=self.password ) <NEW_LINE> try: <NEW_LINE> <INDENT> with transaction.atomic(): <NEW_LINE> <INDENT> get_user_model().objects.create_user( username='AnotherRandom', email=self.email...
Test that a user won't be created with a duplicated email
625941cebde94217f3682f26
def get_stdev(data, dt_start=None, dt_end=None): <NEW_LINE> <INDENT> stdev = data[dt_start:dt_end].std() <NEW_LINE> return stdev[stdev.notnull()]
Returns a dict with the standard deviation of numeric columns over the given time period. Args: data (dataframe): The panadas dataframe containing at least a debit and a credit column. dt_start (str): The start date (specific if given '2012-11-11' or the month '2012-11') from were the standard deviatio...
625941ce44b2445a339321ca
def softmax_cross_entropy_with_logits(sentinel=None, labels=None, logits=None, dim=-1): <NEW_LINE> <INDENT> if sentinel is not None: <NEW_LINE> <INDENT> name = "softmax_cross_entropy_with_logits" <NEW_LINE> raise ValueError("Only call `%s` with named arguments (labels=..., logits=..., ...)" % name) <NEW_LINE> <DEDENT> ...
Wrapper around tf.nn.softmax_cross_entropy_with_logits_v2 to handle deprecated warning
625941ce8a43f66fc4b5419a
def _call_with_validation(self, method, exception_class, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> func = getattr(self, method) <NEW_LINE> output = func(*args, **kwargs) <NEW_LINE> if callable(self.validate): <NEW_LINE> <INDENT> if not self.validate(output): <NEW_LINE> <INDENT> msg = 'Validator {0}...
Utility method to invoke ``method`` and validate the output. Call ``self.validate`` when appropriate, and raise ``exception_class`` if a validation error occurs. :param str method: Name of the method to call. :param Exception exception_class: Type of exception to raise when an error occurs. :param args: Positional arg...
625941ce56ac1b37e6264303
def __is_valid_agency_prefix(agency_prefix): <NEW_LINE> <INDENT> return agency_prefix in agencies_by_prefix
Given a two-digit prefix a la the Federal Audit Clearinghouse, return True if it's one of the prefixes that the FAC lists as a "federal agency prefix." Implementing this as a dict lookup instead of a range check because not every two-digit combination between 00 and 99 is actually valid (i.e., listed in FAC).
625941ced10714528d5ffe19
def edit_user(self, user_id, user_dict): <NEW_LINE> <INDENT> with self.db.cursor() as sql: <NEW_LINE> <INDENT> user = User(None, user_dict['role'], user_dict['username'], user_dict['email'], user_dict['label'], None, None) <NEW_LINE> if 'new_password' in user_dict: <NEW_LINE> <INDENT> user.set_password(user_dict['new_p...
Edit a user with values from the given user dictionary. Raises a KeyError if necessary values are missing from the user_dict. Returns None if a user with given id does not exist.
625941ce91f36d47f21ac628
def save_training_meta_data(cfg,net): <NEW_LINE> <INDENT> meta_fid = open(os.path.join(cfg.META_SAVE_DIR, cfg.MODEL_BASE_SAVE_NAME + '.txt'),'w') <NEW_LINE> config_params = [attr for attr in dir(cfg) if not callable(getattr(cfg, attr)) and not attr.startswith("__")] <NEW_LINE> for param in config_params: <NEW_LINE> <IN...
Writes a text file that describes model and paramters. ex) save_training_meta_data(cfg,net) Input parameters: cfg: (Config) a config isntance from configs/ net: (torch Module) a pytorch network Returns: None
625941ceab23a570cc2502b8
def do_csv_stat(fname=None,**kwargs): <NEW_LINE> <INDENT> if fname is None: <NEW_LINE> <INDENT> raise ValueError("Incorrect input : please provide filename") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> df = pd.read_csv(fname, index_col=0) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError("Enable to open...
Reads a csv into a dataframe to perform the analysis cf do_dataframe_stats
625941ce8e05c05ec3eea4aa
def remove_node(self, node): <NEW_LINE> <INDENT> self.clear_path_cache() <NEW_LINE> if node.children: <NEW_LINE> <INDENT> del self.handle2node[node.handle] <NEW_LINE> node.set_handle(None) <NEW_LINE> self.__displayed -= 1 <NEW_LINE> self.__total -= 1 <NEW_LINE> <DEDENT> elif node.parent: <NEW_LINE> <INDENT> iternode = ...
Remove a node from the map.
625941ce442bda511e8be54d
def get_trim_currents_avg(self, data_set): <NEW_LINE> <INDENT> data = self._rotcoildata[data_set] <NEW_LINE> return [d.trim_coil_current_avg for d in data]
Return currents of a data set.
625941cea17c0f6771cbe185
def test_dumpdata_uses_default_manager(self): <NEW_LINE> <INDENT> management.call_command( 'loaddata', 'animal.xml', verbosity=0, commit=False, ) <NEW_LINE> management.call_command( 'loaddata', 'sequence.json', verbosity=0, commit=False, ) <NEW_LINE> animal = Animal( name='Platypus', latin_name='Ornithorhynchus anatinu...
Regression for #11286 Ensure that dumpdata honors the default manager Dump the current contents of the database as a JSON fixture
625941cef548e778e58cd6b3
def _dump_pgraph(xbox): <NEW_LINE> <INDENT> buffer = bytearray([]) <NEW_LINE> buffer.extend(xbox.read(0xFD400000, 0x200)) <NEW_LINE> buffer.extend(bytes([0] * 0x200)) <NEW_LINE> buffer.extend(xbox.read(0xFD400400, 0x2000 - 0x400)) <NEW_LINE> assert len(buffer) == 0x2000 <NEW_LINE> return bytes(buffer)
Returns the entire PGRAPH region.
625941ce85dfad0860c3af90