code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def judge_is_multilayer(devices): <NEW_LINE> <INDENT> logger.debug('devices type:%s' % (type(devices))) <NEW_LINE> if not devices: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for dev in devices: <NEW_LINE> <INDENT> if dev.get('firstLayer'): <NEW_LINE> <INDENT> logger.debug('juge_is_mu... | according device info, judge is multilayer or not
Args:
devices: [
{
"firstLayer": true,
"host": "*",
"name": "*",
"port": 21108,
"serialNumber": "28088713TA",
"status": "SUSPEND",
“type”:”HPCC”
},
{
"firstLayer": true,
"host": "*",... | 625941e015baa723493c42e9 |
def download_from_web(q): <NEW_LINE> <INDENT> data = [11, 22, 33, 44] <NEW_LINE> for temp in data: <NEW_LINE> <INDENT> print("---下载完数据 %d----" % temp) <NEW_LINE> q.put(temp) <NEW_LINE> time.sleep(1) | 下载数据 | 625941e0d10714528d600058 |
def parse_querylist(querylist): <NEW_LINE> <INDENT> maximum = len(querylist) <NEW_LINE> torrentslist = [] <NEW_LINE> for query in querylist[:maximum]: <NEW_LINE> <INDENT> temp = [] <NEW_LINE> for td in query.find_all('td'): <NEW_LINE> <INDENT> if td.find_all('a'): <NEW_LINE> <INDENT> for link in td.find_all('a'): <NEW_... | querylist: <table tr> from SearchTorrent
#Stolen from NyaaPy | 625941e067a9b606de4a8228 |
def unitary_test(): <NEW_LINE> <INDENT> pass | Unitary test for solver.py script.
| 625941e03317a56b86939fc1 |
def add_element(self, item): <NEW_LINE> <INDENT> checkelts = self.complete_registry() <NEW_LINE> if isinstance(item, Entity): <NEW_LINE> <INDENT> if item.uid == self.uid: <NEW_LINE> <INDENT> raise HyperNetXError( f"Error: Self reference in submitted elements." f" Entity {self.uid} may not contain itself. " ) <NEW_LINE>... | Adds item to entity elements and adds entity to item.memberships.
Parameters
----------
item : hashable or Entity
If hashable, will be replaced with empty Entity using hashable as uid
Returns
-------
self : Entity
Notes
-----
If item is in entity elements, no new element is added but properties
will be updated.
... | 625941e0091ae356686672c9 |
def addLegend(self, offset=(30, 30), **kwargs): <NEW_LINE> <INDENT> if self._legend is None: <NEW_LINE> <INDENT> self._legend = pg.LegendItem(offset=offset, pen='k', **kwargs) <NEW_LINE> self._legend.setParentItem(self._vb) <NEW_LINE> for item in chain(self._plot_items, self._plot_items2): <NEW_LINE> <INDENT> name = it... | Add a LegendItem if it does not exist. | 625941e03d592f4c4ed1d3d5 |
def get_secret(secret_name, secret_present): <NEW_LINE> <INDENT> result = try_env_variable(secret_name) <NEW_LINE> if result is None: <NEW_LINE> <INDENT> return None, False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return result, secret_present | Get the environment variable and return success | 625941e099fddb7c1c9de700 |
def vp_start_gui(): <NEW_LINE> <INDENT> global val, w, root <NEW_LINE> root1 = Tk() <NEW_LINE> root1.withdraw() <NEW_LINE> root = Toplevel(root1) <NEW_LINE> top = Enrich__App (root) <NEW_LINE> init(root, top) <NEW_LINE> root.mainloop() <NEW_LINE> root.destroy() | Starting point when module is the main routine. | 625941e050812a4eaa59c68f |
def test_permission_remove_user_from_orgs_team_unauthenticated(self): <NEW_LINE> <INDENT> org = SeedOrganization.objects.create() <NEW_LINE> team = SeedTeam.objects.create(organization=org) <NEW_LINE> user = User.objects.create_user('test user') <NEW_LINE> response = self.client.delete(reverse( 'seedorganization-teams-... | Unauthenticated users should not be allowed to remove users from
teams. | 625941e0442bda511e8be784 |
def add_unicode_name(dst_dict: Dict[str, Any], ldh_name: str) -> None: <NEW_LINE> <INDENT> unicode_name = ldh_name.encode("idna").decode("idna") <NEW_LINE> if unicode_name != ldh_name: <NEW_LINE> <INDENT> dst_dict["unicodeName"] = unicode_name | Add optional unicodeName key to dictionary if contains non-ascii characters. | 625941e03d592f4c4ed1d3d6 |
def get_next_balanceRecords_all(self): <NEW_LINE> <INDENT> accountBalanceTable = self.accountBalanceTable <NEW_LINE> domain_org = ('org', '=', self.org) <NEW_LINE> domain_account = ('account', '=', self.account) <NEW_LINE> domain_item = ('items', '=', self.items) <NEW_LINE> balanceRecords = accountBalanceTable.search( ... | 获得相同科目余额后期记录集合,不排除期初那条 | 625941e00c0af96317bb8559 |
def check_plate_block_shear(self, load_data): <NEW_LINE> <INDENT> block_shear = float(load_data[4]) <NEW_LINE> shear_gross_area = self.tg * self.H <NEW_LINE> shear_net_area = self.tg * (self.H - self.ev - (self.nos - 1) * (self.dia + 1 / 16) - 0.5 * (self.dia + 1 / 16)) <NEW_LINE> tension_net_area = self.tg * (self.ev ... | Check the block shear strength of the plate | 625941e08e7ae83300e4b33e |
def add_entry(data, format): <NEW_LINE> <INDENT> data.insert(format['index'], format) | adds a name to the list
:param name: the name to be added.
:param data: the list to add the name to.
:return: - | 625941e0b7558d58953c527f |
def send_message(self, chat_id, text, parse_mode=None, disable_web_page_preview=False, disable_notification=False, reply_to_message_id=None, reply_markup=None): <NEW_LINE> <INDENT> from pytgbot.api_types.sendable.reply_markup import ForceReply <NEW_LINE> from pytgbot.api_types.sendable.reply_markup import InlineKeyboar... | Use this method to send text messages. On success, the sent Message is returned.
https://core.telegram.org/bots/api#sendmessage
Parameters:
:param chat_id: Unique identifier for the target chat or username of the target channel
(in the format @channelusername)
:type chat_id: int | str
:param text:... | 625941e0097d151d1a2231c8 |
@my_decorator_0 <NEW_LINE> def example_0(): <NEW_LINE> <INDENT> print('call example_0') | This is Docstring example_0 | 625941e02ae34c7f2600d4a2 |
def enableDebugLogging(self, enabled): <NEW_LINE> <INDENT> pass | Control whether the framework's internal fragment manager debugging
logs are turned on. | 625941e076d4e153a657eea3 |
def gradAscent(dataMatIn, classLabels): <NEW_LINE> <INDENT> dataMatrix = mat(dataMatIn) <NEW_LINE> labelMat = mat(classLabels).transpose() <NEW_LINE> m, n = shape(dataMatrix) <NEW_LINE> alpha = 0.001 <NEW_LINE> maxCycles = 500 <NEW_LINE> weights = ones((n, 1)) <NEW_LINE> for k in range(maxCycles): <NEW_LINE> <INDENT> h... | 梯度上升 | 625941e0d486a94d0b98e4b8 |
def test_uppercase_f_shortchut_char_mode(vim_bot): <NEW_LINE> <INDENT> main, editor_stack, editor, vim, qtbot = vim_bot <NEW_LINE> editor.stdkey_backspace() <NEW_LINE> editor.go_to_line(3) <NEW_LINE> editor.moveCursor(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) <NEW_LINE> cmd_line = vim.get_focus_widget() <NEW_LIN... | Cursor moves to the previous ocurrence of a character. | 625941e0097d151d1a2231c9 |
def build(self, input_image, topmost=None, padding=None, name="vgg19"): <NEW_LINE> <INDENT> layers = OrderedDict() <NEW_LINE> with tf.name_scope(name): <NEW_LINE> <INDENT> input_image_scaled = input_image * 255. <NEW_LINE> if self.is_rgb_input: <NEW_LINE> <INDENT> input_image = input_image_scaled - VGG_MEAN_RGB <NEW_LI... | Load variable from npy to build the VGG19 feature extractor
Parameters
----------
input_image : tf.Tensor
input image [batch, height, width, 3] values scaled [0, 1] | 625941e03317a56b86939fc2 |
def ancestors_orequal(kb, edge, node_or_list): <NEW_LINE> <INDENT> target = set([kb.normalize_page(k) for k in ensure_list(node_or_list)]) <NEW_LINE> olen = 0 <NEW_LINE> while olen!=len(target): <NEW_LINE> <INDENT> olen = len(target) <NEW_LINE> target = target.union( [kb.normalize_page(k) for (k,v) in kb.items() if not... | ancestors(kb, edge, node) + node itself | 625941e082261d6c526ab815 |
def call_plugin(self, plugin_function, event): <NEW_LINE> <INDENT> log.debug("Calling function {0} with event data {1}".format( plugin_function, event )) <NEW_LINE> try: <NEW_LINE> <INDENT> response = plugin_function(event) <NEW_LINE> assert type(response) == dict <NEW_LINE> <DEDENT> except Exception as call_exception:... | Call a plugin
:param plugin_function:
:param event:
:return: a response object | 625941e0d99f1b3c44c678fa |
def _check_left_mouse(self, mouse_pos): <NEW_LINE> <INDENT> if self.stats["state"] == 0: <NEW_LINE> <INDENT> for row in self.cells: <NEW_LINE> <INDENT> for cell in row: <NEW_LINE> <INDENT> cell_clicked = cell.rect.collidepoint(mouse_pos) <NEW_LINE> if cell_clicked and cell.state == 1: <NEW_LINE> <INDENT> cell.open_cell... | Check for left mouse button presses and respond to them. | 625941e056b00c62f0f149cd |
def list_(self, endpoint: str) -> Dict: <NEW_LINE> <INDENT> return self._http.get(endpoint) | List realms (full path version).
:param endpoint: Endpoint for realms.
:return: A Nexus results list with the Nexus payloads of the realms. | 625941e057b8e32f5248380f |
def test_overwrite_png(self, client): <NEW_LINE> <INDENT> filepath = client.download_png('2020/01/01', 2.4, "[SOHO,MDI,continuum,1,100]", overwrite=False) <NEW_LINE> filepath_2 = client.download_png('2020/01/01', 2.4, "[SOHO,MDI,continuum,1,100]", overwrite=False) <NEW_LINE> assert filepath_2 is not filepath <NEW_LINE>... | Tests for that overwrites, overwrites png edition. | 625941e001c39578d7e751ad |
def test_set_zfcp_multipath_new(self): <NEW_LINE> <INDENT> modprobe = 'modprobe dm-multipath' <NEW_LINE> conf_file = '#blacklist {\n' <NEW_LINE> conf_file += '#\tdevnode \\"*\\"\n' <NEW_LINE> conf_file += '#}\n' <NEW_LINE> cmd_conf = 'echo -e "%s" > /etc/multipath.conf' % conf_file <NEW_LINE> cmd_mpathconf = 'mpathconf... | RHEL7 | 625941e0fff4ab517eb2f7af |
def _delete_luncopy(self, luncopyid): <NEW_LINE> <INDENT> url = self.url + "/LUNCOPY/%s" % luncopyid <NEW_LINE> result = self.call(url, None, "DELETE") <NEW_LINE> self._assert_rest_result(result, 'Delete lun copy error.') | Delete a LUNcopy. | 625941e0187af65679ca5491 |
def get_email_meta_data(to_=True, from_=True, subject_=True, date_=True): <NEW_LINE> <INDENT> def decorator(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> global CURRENT_EMAIL_NAME, EMAIL_DICT <NEW_LINE> f = func(*args, **kwargs) <NEW_LINE> metadata = [] <NEW_LINE> ... | Extract email metadata | 625941e0a8370b7717052c0f |
def __init__(self, section: lief.MachO.Section, **kwargs): <NEW_LINE> <INDENT> super(MachOSectionObject, self).__init__('macho-section', **kwargs) <NEW_LINE> self.__section = section <NEW_LINE> self.__data = bytes(self.__section.content) <NEW_LINE> self.generate_attributes() | Creates an MachO Section object. Object generated by MachOObject. | 625941e066656f66f7cbc51e |
@cli.command() <NEW_LINE> @click.option('--count', default=8000, type=click.IntRange(1, 100000), help='The number of items to process.') <NEW_LINE> def progress(count): <NEW_LINE> <INDENT> items = range_type(count) <NEW_LINE> def process_slowly(item): <NEW_LINE> <INDENT> time.sleep(0.002 * random.random()) <NEW_LINE> <... | Demonstrates the progress bar. | 625941e091f36d47f21ac867 |
def _section_titles(self): <NEW_LINE> <INDENT> return self.q(css=self.SECTION_TITLES_SELECTOR).map(lambda el: el.text.strip()).results | Return a list of all section titles on the page. | 625941e00383005118ecf953 |
def build_mla(X: pd.DataFrame, y: pd.Series) -> List[Tuple[str, base.BaseEstimator]]: <NEW_LINE> <INDENT> algorithms = [ ensemble.AdaBoostClassifier(), ensemble.BaggingClassifier(), ensemble.ExtraTreesClassifier(), ensemble.GradientBoostingClassifier(), ensemble.RandomForestClassifier(), gaussian_process.GaussianProces... | Returns fit default estimators.
This will give us a good baseline for ensembling. | 625941e091af0d3eaac9bd8d |
def create_email_change(self, user, new_email, send_email=True): <NEW_LINE> <INDENT> salt = sha.new(str(random.random())).hexdigest()[:5] <NEW_LINE> activation_key = sha.new(salt+user.email).hexdigest() <NEW_LINE> user.email_new = new_email <NEW_LINE> user.save() <NEW_LINE> record, created = self.get_or_create(user=use... | Create ActionRecord for email change and mails link
with activation key to user's email.
Pass ``send_email=False`` to disable sending the email. | 625941e08da39b475bd652e9 |
def main(argv=None): <NEW_LINE> <INDENT> if argv is None: <NEW_LINE> <INDENT> argv = sys.argv <NEW_LINE> <DEDENT> root_path = FdepConfig.find_root_path() or os.getcwd() <NEW_LINE> env = os.environ.get('ENV', 'development') <NEW_LINE> config = FdepConfig.load(os.path.join(root_path, 'fdep.yml')) <NEW_LINE> runner = Fdep... | Implement the entry point of fdep. | 625941e0379a373c97cfaeb8 |
def testDestinyHistoricalStatsDestinyPostGameCarnageReportEntry(self): <NEW_LINE> <INDENT> pass | Test DestinyHistoricalStatsDestinyPostGameCarnageReportEntry | 625941e0cc40096d61595cc1 |
def extract_mvr_Yloadings(self, mvr_model_I, ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r_statement = ('pls::Yloadings(%s)' %(mvr_model_I)); <NEW_LINE> ans = robjects.r(r_statement); <NEW_LINE> loadings_y = np.array(ans); <NEW_LINE> return loadings_y; <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> ... | extract out mvr scores
INPUT:
mvr_model_I = name of the R mvr model workspace variable
OUTPUT:
data_scores
data_loadings | 625941e05510c4643540f74e |
def init(self): <NEW_LINE> <INDENT> assert self.configurable or not self.settings_form, 'Non-configurable plugin cannot have a settings form' <NEW_LINE> self.alembic_versions_path = os.path.join(self.root_path, 'migrations') <NEW_LINE> self.connect(signals.plugin.get_blueprints, lambda app: self.get_blueprints()) <NEW_... | Called when the plugin is being loaded/initialized.
If you want to run custom initialization code, this is the
method to override. Make sure to call the base method or
the other overridable methods in this class will not be
called anymore. | 625941e00a366e3fb873eb8f |
def p_list_instruction_val(p): <NEW_LINE> <INDENT> value1 = p[1] <NEW_LINE> p[0] = [value1] | list_instruction : instruction | 625941e0aad79263cf390db8 |
def test_kubernetes_rbdmap_cluster(conn: dict, id: str, rbdid: str) -> dict: <NEW_LINE> <INDENT> data = {} <NEW_LINE> return private._test_kubernetes_rbdmap_cluster(conn, id, rbdid, data) | Test Kubernetes RBD Map Cluster
[Args]
(dict) conn: Connection dictionary obtained after logging in
(str) id: id (path)
(str) rbdid: rbdid (path)
[Returns]
(dict) Response: Add Kubernetes response (includes any errors) | 625941e08e05c05ec3eea6e9 |
def mis_record(self, net, dloader, w_num, savemis): <NEW_LINE> <INDENT> total = 0 <NEW_LINE> correct = 0 <NEW_LINE> net.eval() <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> for data in dloader: <NEW_LINE> <INDENT> images, labels, timg_1, timg_2 = data <NEW_LINE> images, labels = images.to(self.device), labels.to... | mismatch record
:param dloader: testloader
:param w_num: writer cross valid number: 0-5
:return: | 625941e0e64d504609d74bb2 |
@pytest.mark.parametrize("width,depth", itertools.product([0, 2], [1, 2])) <NEW_LINE> def test_format_list_width_synthetic(width, depth, dummy_list_of_lists): <NEW_LINE> <INDENT> tab = (" " * width) * depth <NEW_LINE> assert format_list(dummy_list_of_lists, depth=depth, width=width).split("\n")[0] == tab + "[" | Test list of lists formatting with different combination of widths and depth for one line | 625941e0956e5f7376d711de |
def healpy_rejection_sampler(m, nsamples, jitter=False, ret_idx=False): <NEW_LINE> <INDENT> if hp.maptype(m) != 0: <NEW_LINE> <INDENT> raise ValueError( "Given map is no healpy map (-1) or a series of maps (>0) : " + "{}.".format(hp.maptype(m))) <NEW_LINE> <DEDENT> m = norm_healpy_map(m) <NEW_LINE> weights = m / np.sum... | Sampler to sample positions from given skymaps that are treated as PDFs.
Pixel indices are drawn according to the pixel weight defined by the map.
If 'jitter' is True, positions are sampled with a gaussian with width of
the pixel resolution, to escape from the healpix grid.
Paramters
---------
m : array-like
Vali... | 625941e099cbb53fe6792f58 |
def _createEmptySUFileObject(self): <NEW_LINE> <INDENT> self.traces = [] | Creates an empty SUFile object. | 625941e076d4e153a657eea4 |
def pullback(b, c, d, b_d, c_d): <NEW_LINE> <INDENT> a = NXGraph() <NEW_LINE> check_homomorphism(b, d, b_d) <NEW_LINE> check_homomorphism(c, d, c_d) <NEW_LINE> a_b = {} <NEW_LINE> a_c = {} <NEW_LINE> f = b_d <NEW_LINE> g = c_d <NEW_LINE> for n1 in b.nodes(): <NEW_LINE> <INDENT> for n2 in c.nodes(): <NEW_LINE> <INDENT> ... | Find the pullback from b -> d <- c.
Given h1 : B -> D; h2 : C -> D returns A, rh1, rh2
with rh1 : A -> B; rh2 : A -> C and A the pullback. | 625941e0ec188e330fd5ab0b |
def buildSegment( self, segmentNode, context, nesting=0 ): <NEW_LINE> <INDENT> assert segmentNode.nodeType == DOM.Node.ELEMENT_NODE and segmentNode.nodeName == "segment" <NEW_LINE> segXid= segmentNode.getAttribute('xid') <NEW_LINE> name= self.getChildTextValue( segmentNode, "name" ) <NEW_LINE> usage= self.getChildTextV... | Segment contains Elements and Composites.
:param segmentNode: a :mod:`xml.dom` Element with a name of :samp:`segment`
:param context: The Loop which contains this Segment.
:param nesting: The current nesting level used to indent the log messages. | 625941e0d58c6744b4257fd0 |
def get_edges_between(uri, args): <NEW_LINE> <INDENT> if args['start'] and args['end'] and not uri: <NEW_LINE> <INDENT> json = get_edges_between_helper([], add_slash(args['start']), add_slash(args['end'])) <NEW_LINE> <DEDENT> elif args['nodes'] and not uri: <NEW_LINE> <INDENT> nodes = args['nodes'][1:-1].split(',') <NE... | This function finds all edges between two nodes and returns them in a list | 625941e0d53ae8145f87a5dc |
def set_T(T): <NEW_LINE> <INDENT> E=caget('XF:11IDA-OP{Mono:DCM-Ax:Energy}Mtr.RBV') <NEW_LINE> tol=0.5 <NEW_LINE> empty_pos=-18.5 <NEW_LINE> [pos_att,bestT]=calc_T(T,E) <NEW_LINE> target_pos=empty_pos+pos_att <NEW_LINE> print('moving foil_x to target_pos') <NEW_LINE> caput('XF:11IDB-OP{Mon:Foil-Ax:X}Mtr.VAL',target_pos... | call: set_T(T)
function calls calc_T(T)
required arument:
T: commanded tranmission (e.g. 1e-3)
optional arguments:
E='auto': get beamline energy from PV (currently: DCM) | E=7894: manual overwrite of energy parameter
function moves Si absorbers in monitor chamber according to calculation by calc_T()
function reads back... | 625941e0bde94217f3683160 |
def generate_jwks() -> Tuple[dict, dict]: <NEW_LINE> <INDENT> print("Generating keys.") <NEW_LINE> private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) <NEW_LINE> public_key = private_key.public_key().public_bytes(encoding=serialization.Encoding.PEM, format=serializati... | Generate JWK set. | 625941e032920d7e50b28545 |
def on_closing(): <NEW_LINE> <INDENT> root.destroy() | if messagebox.askokcancel(PROGRAM_NAME_SHORT, "Do you want to quit?"):
try:
#messagebox.showinfo(PROGRAM_NAME_SHORT, "debug")
''
except Exception as e: logError(e,"")
root.destroy() | 625941e007d97122c4178c05 |
def add_next(self, next): <NEW_LINE> <INDENT> self._total_cnt += 1 <NEW_LINE> self._wrd[next] += 1 | Add new edge or adjust weights | 625941e030c21e258bdfa812 |
def test_wrong_cert(self): <NEW_LINE> <INDENT> certfile = os.path.join(os.path.dirname(__file__) or os.curdir, "wrongcert.pem") <NEW_LINE> server = ThreadedEchoServer(CERTFILE, certreqs=ssl.CERT_REQUIRED, cacerts=CERTFILE, chatty=False, connectionchatty=False) <NEW_LINE> with server, socket.socket() ... | Connecting when the server rejects the client's certificate
Launch a server with CERT_REQUIRED, and check that trying to
connect to it with a wrong client certificate fails. | 625941e029b78933be1e5a1a |
def get_particle(s: str) -> Tuple[str, Optional[str]]: <NEW_LINE> <INDENT> particle = None <NEW_LINE> ix = s.rfind("*") <NEW_LINE> if ix >= 0: <NEW_LINE> <INDENT> particle = s[ix:].strip() <NEW_LINE> s = s[:ix].strip() <NEW_LINE> if not particle: <NEW_LINE> <INDENT> raise ConfigError("Particle should be at least one le... | Process particles, should only be one in each line | 625941e0d18da76e2353284c |
def listCommands(self): <NEW_LINE> <INDENT> return [x.key for x in self.commands] | Returns list of commands used in entry | 625941e0d58c6744b4257fd1 |
def test_debug_mode(self): <NEW_LINE> <INDENT> from App.config import getConfiguration <NEW_LINE> from plone.api.env import debug_mode <NEW_LINE> getConfiguration().debug_mode = True <NEW_LINE> self.assertEqual(debug_mode(), True) <NEW_LINE> getConfiguration().debug_mode = False <NEW_LINE> self.assertEqual(debug_mode()... | Tests that the retured value is the same as
getConfiguration.debug_mode. | 625941e08a349b6b435e84e5 |
def Append(self, itemText, parent=None, clientData=None): <NEW_LINE> <INDENT> if parent is None: <NEW_LINE> <INDENT> parent = self._tree.GetRootItem() <NEW_LINE> <DEDENT> item = self._tree.AppendItem(parent, itemText, data=clientData) <NEW_LINE> if self._sort: <NEW_LINE> <INDENT> self._tree.SortChildren(parent) <NEW_LI... | Adds the itemText to the control, associating the given clientData
with the item if not None. If parent is None, itemText is added
as a root item, else itemText is added as a child item of
parent. The return value is the :class:`TreeItemId` of the newly added
item.
:param string `itemText`: text to add to the control
... | 625941e0656771135c3ebbe5 |
def comoving_los_depth(self, bw, redshift, action=None): <NEW_LINE> <INDENT> drz_los = (FCNST.c/1e3) * bw * (1+redshift)**2 / CNST.rest_freq_HI / self.cosmo.H0.value / self.cosmo.efunc(redshift) <NEW_LINE> if action is None: <NEW_LINE> <INDENT> self.z = redshift <NEW_LINE> self.drz_los = drz_los <NEW_LINE> return <NEW_... | ------------------------------------------------------------------------
Compute comoving line-of-sight depth (Mpc/h) corresponding to specified
redshift and bandwidth for redshifted 21 cm line
Inputs:
bw [scalar] bandwidth in Hz
redshift [scalar] redshift
action [string] If set to None (default), the c... | 625941e0596a897236089e2f |
def set_hostname(hostname): <NEW_LINE> <INDENT> curr_hostname = get_hostname() <NEW_LINE> cmd = "wmic computersystem where name='{0}' call rename name='{1}'".format(curr_hostname, hostname) <NEW_LINE> ret = __salt__['cmd.run'](cmd=cmd) <NEW_LINE> return "successful" in ret | .. versionadded:: 2016.3.0
Set the hostname of the windows minion, requires a restart before this
will be updated.
:param str hostname:
The hostname to set
CLI Example:
.. code-block:: bash
salt 'minion-id' system.set_hostname newhostname | 625941e0f7d966606f6aa37b |
def construct_l2_loss(gt, pred, normalize_gt=False): <NEW_LINE> <INDENT> if normalize_gt: <NEW_LINE> <INDENT> gt = gt / 255.0 <NEW_LINE> <DEDENT> if cfg.DATASET == "MOVINGMNIST": <NEW_LINE> <INDENT> return mx.sym.MakeLoss( mx.sym.mean(mx.sym.square(gt - pred)), grad_scale=cfg.MODEL.L2_LAMBDA, name="mse") <NEW_LINE> <DE... | Construct symbol of L2 loss.
Used variables:
gt: ground truth
pred: prediction (or real data during training)
Args:
gt: ground truth variable
pred: prediction (or real data during training) variable
normalize_gt: if True divide gt by 255.0 | 625941e031939e2706e4d1d8 |
def elapseTime(self, gameState): <NEW_LINE> <INDENT> newParticles = [] <NEW_LINE> visitedPositions = [] <NEW_LINE> newPosDists = {} <NEW_LINE> for particle in self.particles: <NEW_LINE> <INDENT> if particle not in visitedPositions: <NEW_LINE> <INDENT> visitedPositions.append(particle) <NEW_LINE> newPosDists[particle] =... | Update beliefs for a time step elapsing.
As in the elapseTime method of ExactInference, you should use:
newPosDist = self.getPositionDistribution(self.setGhostPosition(gameState, oldPos))
to obtain the distribution over new positions for the ghost, given its
previous position (oldPos) as well as Pacman's current p... | 625941e07b180e01f3dc4b69 |
def get_csrf_token(self, request): <NEW_LINE> <INDENT> csrf_token = request.get_claims.get('jti', None) <NEW_LINE> if not csrf_token: <NEW_LINE> <INDENT> return self.new_csrf_token(request) <NEW_LINE> <DEDENT> return csrf_token | Returns currently active CSRF token by checking cookie,
generating a new one if needed. | 625941e094891a1f4081be1d |
def popup_get_yes_no(win_title, default='YES'): <NEW_LINE> <INDENT> return popup_get_multiple_choice(win_title, ['YES', 'NO'], default) | Lets user choose between 'YES' and 'NO', tabbing to highlight and select each choice.
For example, choice = popup_get_yes_no('Continue?')
The default default choice is 'YES'.
Returns the string of the choice the user selected.
:param str win_title: the title of the window - helpful if it asks the user the yes/no ques... | 625941e0507cdc57c6307055 |
def test_untag_simple(self): <NEW_LINE> <INDENT> fields_to_test = { '$view': '/views/base.html', '$view@ja': '/views/base-ja.html', 'qaz': 'qux', 'qaz@ja': 'qux-ja', 'qaz@de': 'qux-de', 'foo': 'bar-base', 'foo@en': 'bar-en', 'foo@de': 'bar-de', 'foo@ja': 'bar-ja', } <NEW_LINE> fields = copy.deepcopy(fields_to_test) <NE... | Untag field values by locale with nested fields. | 625941e056ac1b37e626453c |
def lambert_azimuthal(coordinate_tripples, longitude_offset = pi/8, latitude_offset = pi/8): <NEW_LINE> <INDENT> x = coordinate_tripples[0] <NEW_LINE> y = coordinate_tripples[1] <NEW_LINE> z = coordinate_tripples[2] <NEW_LINE> rho = np.sqrt(x**2) + np.sqrt(y**2) + np.sqrt(z**2) <NEW_LINE> azimuth = np.arctan2(y,x) <NEW... | An area-preserving projection from geophysical coordinates to the
plane.
Required Arguments
-------------------
* coordinate_tripples : 3-column, N row tripples of sphere
coordinates.
Optional Arguments
-------------------
* longitude_offset : offset in radians from Greenwich, England.
Negative moves towards New ... | 625941e00c0af96317bb855a |
def mousePressEvent(self, event): <NEW_LINE> <INDENT> if event.modifiers() & QtCore.Qt.ShiftModifier: <NEW_LINE> <INDENT> self.editor.startArc(self) <NEW_LINE> <DEDENT> QtGui.QGraphicsRectItem.mousePressEvent(self, event) | Prevents the movement of this item, when connections are drawn.
:param event: `QtGui.mousePressEvent` | 625941e024f1403a92600ed6 |
def storeActivities(self): <NEW_LINE> <INDENT> f = open(self.activitiesFile, "w+") <NEW_LINE> pickle.dump(self.activities, f) <NEW_LINE> f.close() | Store activities into file to make them persistent | 625941e094891a1f4081be1e |
def get_database_uri(self): <NEW_LINE> <INDENT> database_uri = self._get_attribute( attribute='database_uri' ) <NEW_LINE> if not database_uri: <NEW_LINE> <INDENT> raise MashConfigException( 'database_uri is required in MASH configuration file.' ) <NEW_LINE> <DEDENT> return database_uri | Return the database uri.
:rtype: string | 625941e0711fe17d825426d6 |
def add(self, item): <NEW_LINE> <INDENT> self.items.append(item) | Add an item to this Group, e.g. a Dataset or another Group. | 625941e03eb6a72ae02ec858 |
def _save(self, name, content, max_length=None): <NEW_LINE> <INDENT> client = Fdfs_client(self.client_conf) <NEW_LINE> ret = client.upload_by_buffer(content.read()) <NEW_LINE> if ret.get("Status") != "Upload successed.": <NEW_LINE> <INDENT> raise Exception("upload file failed") <NEW_LINE> <DEDENT> file_name = ret.get("... | 在FastDFS中保存文件
:param name: 传入的文件名
:param content: 文件对象
:return: 保存到数据库中的FastDFS的文件名 | 625941e0b7558d58953c5280 |
def setParams(self, *args): <NEW_LINE> <INDENT> return _MontePython_cxx.LiqHe4QForceNum_setParams(self, *args) | setParams(LiqHe4QForceNum self, QickArray & params_) | 625941e0adb09d7d5db6cb00 |
def touch(self): <NEW_LINE> <INDENT> influenced = copy(self.__influences) <NEW_LINE> pending = copy(influenced) <NEW_LINE> while len(pending): <NEW_LINE> <INDENT> item = pending.pop() <NEW_LINE> new = item.__influences - influenced <NEW_LINE> influenced.update(new) <NEW_LINE> pending.update(new) <NEW_LINE> <DEDENT> for... | Raises events on influenced Bool-s.
Crashes badly on Python 3.4. | 625941e0d486a94d0b98e4b9 |
def action_dims(self): <NEW_LINE> <INDENT> act_space = self.gym_env.action_space <NEW_LINE> if isinstance(act_space, gym.spaces.Discrete): <NEW_LINE> <INDENT> return {self.action_key: act_space.n} <NEW_LINE> <DEDENT> return {self.action_key: act_space.shape[0]} | Gym has a single action. | 625941e0f8510a7c17cf9a72 |
def addMovie(self, newMovie, channel): <NEW_LINE> <INDENT> if newMovie.data[Movie.RAWTITLE] in self.skip: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for movie in self.movies: <NEW_LINE> <INDENT> if movie.data[Movie.RAWTITLE] == newMovie.data[Movie.RAWTITLE]: <NEW_LINE> <INDENT> movie.data[Movie.CHANNELS].append(cha... | Add a new movie to the list.
If the movie is already in the list, append the channel to it.
Skip the movie if no information about it can be found. | 625941e00a50d4780f667208 |
def test_rename_folder(self): <NEW_LINE> <INDENT> from frostmark import db_base, user_data <NEW_LINE> from frostmark.db import get_session <NEW_LINE> from frostmark.models import Folder <NEW_LINE> from frostmark.editor import Editor <NEW_LINE> data = dirname(abspath(user_data.__file__)) <NEW_LINE> self.assertNotIn(db_b... | Test renaming a Folder item. | 625941e0498bea3a759b9e21 |
def mode(alist): <NEW_LINE> <INDENT> mode = [] <NEW_LINE> counts = {} <NEW_LINE> for i in range(count(alist)): <NEW_LINE> <INDENT> if alist[i] in counts: <NEW_LINE> <INDENT> counts[alist[i]] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> counts[alist[i]] = 1 <NEW_LINE> <DEDENT> <DEDENT> max_not = None <NEW_LINE> fo... | :param alist: list of data that will be used to find mode
:return: mode_val as an integer if more than one mode returns as tuple | 625941e066656f66f7cbc51f |
def fin(): <NEW_LINE> <INDENT> print("Sleeping for 15 seconds to avoid VirusTotal 403 rate quota limits...") <NEW_LINE> sleep(15) | Helper function which sleeps for 15 seconds between each test. This is to avoid VirusTotal 403 rate quota limits. | 625941e050812a4eaa59c691 |
def pick_alien(self): <NEW_LINE> <INDENT> col_num = random.randint(0, len(self._aliens[0])) <NEW_LINE> picked_col = [] <NEW_LINE> for _ in self._aliens: <NEW_LINE> <INDENT> picked_col.append(_[col_num - 1]) <NEW_LINE> <DEDENT> for _ in picked_col: <NEW_LINE> <INDENT> if not _ is None: <NEW_LINE> <INDENT> return _ | Randomly selects a column of aliens and returns the first alien in that
column that is not None. If all aliens in the column are None, it returns
None. | 625941e0d6c5a102081443c0 |
def get_access_policy(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.get_access_policy_with_http_info(id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.get_access_policy_with_http_info(id, **k... | Get access policy
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_access_policy(id, callback=callback_func... | 625941e0bf627c535bc13542 |
def save_npz_dict(save_list=None, name='model.npz', sess=None): <NEW_LINE> <INDENT> if sess is None: <NEW_LINE> <INDENT> raise ValueError("session is None.") <NEW_LINE> <DEDENT> if save_list is None: <NEW_LINE> <INDENT> save_list = [] <NEW_LINE> <DEDENT> save_list_names = [tensor.name for tensor in save_list] <NEW_LINE... | Input parameters and the file name, save parameters as a dictionary into .npz file.
Use ``tl.files.load_and_assign_npz_dict()`` to restore.
Parameters
----------
save_list : list of parameters
A list of parameters (tensor) to be saved.
name : str
The name of the `.npz` file.
sess : Session
TensorFlow Sess... | 625941e08da39b475bd652ea |
def split_lines(body): <NEW_LINE> <INDENT> binary = isinstance(body, bytes) <NEW_LINE> pattern = b"(\n|\r\n)" <NEW_LINE> if not binary: <NEW_LINE> <INDENT> pattern = pattern.decode("utf-8") <NEW_LINE> <DEDENT> return re.split(pattern, body) | Split a string on line separators, and keep line endings.
This method behaves the same as `str.splitlines(True)`, but only splits on POSIX
and DOS style line endings.
Args:
body: An arbitrary string.
Returns:
A list of strings consisting of lines and line separators.
Example:
... | 625941e00c0af96317bb855b |
@pytest.mark.skipif(not(has_off_toolkit), reason="Test requires OFF toolkit") <NEW_LINE> def test_smirnoff99Frosst_data_is_not_loadable(): <NEW_LINE> <INDENT> from openforcefield.typing.engines.smirnoff import ForceField <NEW_LINE> with pytest.raises(TypeError) as excinfo: <NEW_LINE> <INDENT> ForceField('smirnoff99Fros... | Test that the openforcefield toolkit does raise an Exception if
a nonexistent FF isn't found. | 625941e038b623060ff0b160 |
def set_speed(self, speed): <NEW_LINE> <INDENT> self.speed = speed <NEW_LINE> if speed > MAX_SPEED: <NEW_LINE> <INDENT> speed -= MAX_SPEED <NEW_LINE> speed *= -1 <NEW_LINE> <DEDENT> pwm_speed = speed * (CENTER_PWM_RANGE) / MAX_SPEED + CENTER_PWM_VALUE <NEW_LINE> self.pi.set_servo_pulsewidth(self.pin, pwm_speed) | Sets the speed of the motor.
speed: double value specifying the speed that the motor should be set to. | 625941e0a05bb46b383ecb92 |
def isWrap(wrap): <NEW_LINE> <INDENT> if not cmds.objExists(wrap): return False <NEW_LINE> if not cmds.objectType(wrap) == 'wrap': return False <NEW_LINE> return True | Check if specified node is a wrap deformer
@param wrap: Node to check as wrap deformer
@type wrap: str | 625941e07c178a314d6ef7d8 |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(KillTurtlePairRequest, self).__init__(*args, **kwds) <NEW_LINE> if self.id is None: <NEW_LINE> <INDENT> self.id = uuid_msgs.msg.UniqueID() <NEW_LINE> <DEDENT> if self.request is None: <NEW_LINE> <INDENT> self.request = con... | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
id,request
:param args: complete ... | 625941e0e5267d203edce00c |
def get_app_name(self, appid): <NEW_LINE> <INDENT> if self.applist is None: <NEW_LINE> <INDENT> print('Call get_app_list first!') <NEW_LINE> return None <NEW_LINE> <DEDENT> if self._is_id_valid(appid): <NEW_LINE> <INDENT> app_index = self._loc_app_id(appid) <NEW_LINE> app_name = str(app_index.values[0]) <NEW_LINE> retu... | Return appname from appid
Call example:
AppList().populate_app_list().get_app_name(500)
Returns:
App_name (str) is found
None otherwise | 625941e07b25080760e397ca |
@pytest.fixture <NEW_LINE> def local_service(database, tmpdir): <NEW_LINE> <INDENT> env = Config().basedir(tmpdir).volume(FStore(basedir=str(tmpdir))).auth() <NEW_LINE> return LocalAPIFactory(env=env, db=database, engine=StateEngine()) | Create a local API factory for test purposes. | 625941e0442bda511e8be787 |
def savefig(filename, *args, **kwargs): <NEW_LINE> <INDENT> pylab.savefig(globaldata.directory + filename, *args, **kwargs) | Like pylab.savefig but appends the Results directory | 625941e0956e5f7376d711df |
def processExperimentNode(self, experimentNode): <NEW_LINE> <INDENT> openBISCollectionIdentifier = experimentNode.attrib.get("openBISCollectionIdentifier") <NEW_LINE> openBISIdentifier = experimentNode.attrib.get("openBISIdentifier") <NEW_LINE> expName = experimentNode.attrib.get("name") <NEW_LINE> description = experi... | Register a MICROSCOPY_EXPERIMENT sample based on the Experiment XML node.
@param experimentNode An XML node corresponding to a MICROSCOPY_EXPERIMENT (sample)
@return ISample Sample of type MICROSCOPY_EXPERIMENT | 625941e0e76e3b2f99f3ab79 |
def yearly(self, end_date=None, areas=[]): <NEW_LINE> <INDENT> return self.fetch(self.YEARLY, end_date, areas) | Helper to fetch yearly data, see Prices.fetch() | 625941e03617ad0b5ed68269 |
def test_merge_strategy_merge_state_top_saltenv_base(dunder_opts): <NEW_LINE> <INDENT> ret = show_top( dunder_opts, top_file_merging_strategy="merge", state_top_saltenv="base" ) <NEW_LINE> assert ret == { "base": ["base_base"], "foo": ["base_foo"], "bar": ["base_bar"], "baz": ["base_baz"], } | This tests with state_top_saltenv=base, which should pull states *only*
from the base saltenv. | 625941e001c39578d7e751ae |
def get_id_from_link(self, url: str) -> str: <NEW_LINE> <INDENT> return url.split('=')[1] | Returns forum thread identifier from full thread URL.
:param url: | 625941e04c3428357757c699 |
def sendCommand(socket, command, _tag=None, **kwargs): <NEW_LINE> <INDENT> parts = [b'', _tag or command, command] <NEW_LINE> for (key, value) in kwargs.items(): <NEW_LINE> <INDENT> parts.extend((key.encode(), json.dumps(value).encode())) <NEW_LINE> <DEDENT> logging.debug("Sending command: %r", parts) <NEW_LINE> try: <... | Send command to the backend application using the bridge protocol
Keyword Arguments:
socket -- the socket used for sending the command
command -- (bytes) the command to be sent (also used as tag unless _tag is given)
_tag -- (bytes) the tag to be sent (overrides the default)
**kwargs -- The arguments of the com... | 625941e0009cb60464c63722 |
def set_from_dict(self, data, source=None, merge=False): <NEW_LINE> <INDENT> if data is not None: <NEW_LINE> <INDENT> if merge: <NEW_LINE> <INDENT> merged = self.to_dict() <NEW_LINE> merged.update(data) <NEW_LINE> data = merged <NEW_LINE> <DEDENT> self._meta.set_from_dict(self, data, source=source) | Args:
data (dict): Raw data, coming for example from a json file
source (str | None): Optional, description of source where 'data' came from
merge (bool): If True, add `data` to existing fields | 625941e0283ffb24f3c55c71 |
def test_dog(test_dog_url): <NEW_LINE> <INDENT> response = requests.request('GET', test_dog_url) <NEW_LINE> assert response.status_code == 200 | Checking https://dog.ceo/dog-api/ availability. Should be 200 | 625941e02c8b7c6e89b35b32 |
def move_mino(self, mino, offset): <NEW_LINE> <INDENT> cells = mino.move_cells(offset) <NEW_LINE> if self.vacant(cells): <NEW_LINE> <INDENT> mino.update(cells, offset) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False | Try move given polyomino, return true if moved. | 625941e0ac7a0e7691ed4439 |
def on_DownloadStart(self, num_files, num_bytes): <NEW_LINE> <INDENT> values = (num_files, num_bytes) <NEW_LINE> self.add_signal("DownloadStart", repr(values)) | Starting a new parallel download batch | 625941e0d164cc61757830c2 |
def test_clear_by_name_err(self): <NEW_LINE> <INDENT> cred_out = StringIO() <NEW_LINE> get_url = get_server_location() + CREDENTIAL_URI + '?name=credential1' <NEW_LINE> delete_url = get_server_location() + CREDENTIAL_URI + '1/' <NEW_LINE> credential_entry = {'id': 1, 'name': 'credential1', 'username': 'root', 'password... | Testing the clear credential command successfully with stubbed data.
When specifying a name with an error response | 625941e03317a56b86939fc4 |
def make_image_label(self, id_str, filename): <NEW_LINE> <INDENT> fix_dict = { 'PROFILE': 'Profile', 'FRONT': 'Front', 'HEAD': 'Head', 'BACK': 'Back', 'BOTTOM': 'Bottom', 'DETAIL': 'Detail', 'TOP': 'Top', 'EDGE': 'Edge', 'INSCRIPTION': 'Inscription', 'BASE': 'Base', } <NEW_LINE> id_num = id_str.replace('PC ', '') <NEW_... | makes the label for an image | 625941e09c8ee82313fbbae9 |
def get_weekday(year=YEAR, month=MONTH, day=DAY): <NEW_LINE> <INDENT> WEEKDAY = ['월', '화', '수', '목', '금', '토', '일'] <NEW_LINE> DATE = date(year, month, day) <NEW_LINE> return WEEKDAY[DATE.weekday()] | Use datetime.today to get weekday in Korean. | 625941e04f6381625f114daf |
def get_status(my): <NEW_LINE> <INDENT> return my.status | get the current status of this handler | 625941e007f4c71912b117f8 |
def onPMMessage(self, pm, author, message): <NEW_LINE> <INDENT> msg = '[PM] {}: {}'.format(author.name, message) <NEW_LINE> self.buffer.append(msg) <NEW_LINE> self.message_handler(author, message) | Called when the bot receives a private message. Message is logged and handled.
:param pm: The room the message was sent in.
:param author: The author of the message.
:param message: The message received. | 625941e0596a897236089e30 |
def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> features = self.featExtractor.getFeatures(state, action) <NEW_LINE> difference = (reward + self.discount * self.getValue(nextState)) - self.getQValue(state, action) <NEW_LINE> for feature in features: <NEW_LINE> <INDENT> self.weights[feature] = sel... | Should update your weights based on transition | 625941e085dfad0860c3b1cf |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.