code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def mutate(self) -> None: <NEW_LINE> <INDENT> mutable_nodes = [] <NEW_LINE> for node in self.nodes: <NEW_LINE> <INDENT> if not node.input_nodes: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> mutable_nodes.append(node) <NEW_LINE> <DEDENT> node = random.choice(mutable_nodes) <NEW_LINE> num_inputs = node.num_inputs <NEW_LINE> input_numbers = random.sample(range(node.index), num_inputs) <NEW_LINE> node.input_nodes = [] <NEW_LINE> for num in input_numbers: <NEW_LINE> <INDENT> node.input_nodes.append(self.nodes[num]) <NEW_LINE> <DEDENT> return
Mutate the bot.
625941c2e5267d203edcdc31
def items_equal(left, right): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return sorted(left) == sorted(right) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return False
Returns `True` if items in `left` list are equal to items in `right` list.
625941c291af0d3eaac9b9a8
def get_integration_specific_email(provider): <NEW_LINE> <INDENT> return getattr(provider, 'integration_specific_email', None) or constants.DEFAULT_CONTACT_EMAIL
Return the edX contact email to use for a particular provider.
625941c27c178a314d6ef3ee
def parsePair(self, fA, fB): <NEW_LINE> <INDENT> currFileA = list(csv.reader(open(fA, 'rb'), delimiter='\t')) <NEW_LINE> currFileB = list(csv.reader(open(fB, 'rb'), delimiter='\t')) <NEW_LINE> if self.areVersions(currFileA, currFileB): <NEW_LINE> <INDENT> self.addVersion(fA, fB) <NEW_LINE> self.addVersion(fB, fA)
Parses a pair of files in the stats dir
625941c266656f66f7cbc13c
def test_section_rubric_valid(self): <NEW_LINE> <INDENT> rI = baker.make("RubricItem") <NEW_LINE> rI2 = baker.make("RubricItem") <NEW_LINE> f = SectionRubricForm({ 'rI'+str(rI.pk): RUBRIC_GRADES_CHOICES[0][0], 'rI'+str(rI2.pk): RUBRIC_GRADES_CHOICES[1][0], 'section_comment':"You did a good job examining ways to improve." },rubricItems= RubricItem.objects.all()) <NEW_LINE> self.assertTrue(f.is_valid())
Tests that SectionRubricForm accepts valid data
625941c29c8ee82313fbb706
def response_for_user_customer(user_customer): <NEW_LINE> <INDENT> return make_response(jsonify({ 'status': 'success', 'customer': user_customer }))
Return the response for when a single customer when requested by the user. :param user_customer: :return:
625941c28e7ae83300e4af5e
def access_group_initiator_delete(self, access_group, init_id, init_type, flags=0): <NEW_LINE> <INDENT> raise LsmError(ErrorNumber.NO_SUPPORT, "Not supported")
Deletes an initiator from an access group, Raises LsmError on error
625941c26fb2d068a760f02d
def test_real_command(self): <NEW_LINE> <INDENT> exit_code = man.run_command([], ['cd']) <NEW_LINE> self.assertEqual(exit_code, 0)
man cd
625941c24428ac0f6e5ba783
def test_submit_results_for_run(self): <NEW_LINE> <INDENT> user = self.F.UserFactory.create( username="foo", permissions=["execution.execute"], ) <NEW_LINE> apikey = self.F.ApiKeyFactory.create(owner=user) <NEW_LINE> envs = self.F.EnvironmentFactory.create_full_set( {"OS": ["OS X", "Linux"]}) <NEW_LINE> pv = self.F.ProductVersionFactory.create(environments=envs) <NEW_LINE> r1 = self.F.RunFactory.create(name="RunA", productversion=pv) <NEW_LINE> c_p = self.F.CaseVersionFactory.create( case__product=pv.product, productversion = pv, name="PassCase", ) <NEW_LINE> c_i = self.F.CaseVersionFactory.create( case__product=pv.product, productversion = pv, name="InvalidCase", ) <NEW_LINE> c_f = self.F.CaseVersionFactory.create( case__product=pv.product, productversion = pv, name="FailCase", ) <NEW_LINE> self.F.CaseStepFactory(caseversion=c_f) <NEW_LINE> self.factory.create(caseversion=c_p, run=r1, environments=envs) <NEW_LINE> self.factory.create(caseversion=c_i, run=r1, environments=envs) <NEW_LINE> self.factory.create(caseversion=c_f, run=r1, environments=envs) <NEW_LINE> params = {"username": user.username, "api_key": apikey.key} <NEW_LINE> payload = { "objects": [ { "case": c_p.case.id, "environment": envs[0].id, "run_id": r1.id, "status": "passed" }, { "case": c_i.case.id, "comment": "why u no make sense??", "environment": envs[0].id, "run_id": r1.id, "status": "invalidated" }, { "bug": "http://www.deathvalleydogs.com", "case": c_f.case.id, "comment": "why u no pass?", "environment": envs[0].id, "run_id": r1.id, "status": "failed", "stepnumber": 1 } ] } <NEW_LINE> res = self.patch( self.get_list_url(self.resource_name), params=params, payload=payload, ) <NEW_LINE> result = self.model.Result.objects.get(runcaseversion__caseversion=c_p) <NEW_LINE> self.assertEqual(result.status, "passed") <NEW_LINE> self.assertEqual(result.environment, envs[0]) <NEW_LINE> result = self.model.Result.objects.get(runcaseversion__caseversion=c_f) <NEW_LINE> self.assertEqual(result.status, "failed") <NEW_LINE> self.assertEqual(result.comment, "why u no pass?") <NEW_LINE> self.assertEqual(set(result.bug_urls()), set(["http://www.deathvalleydogs.com"])) <NEW_LINE> self.assertEqual(result.environment, envs[0]) <NEW_LINE> result = self.model.Result.objects.get(runcaseversion__caseversion=c_i) <NEW_LINE> self.assertEqual(result.status, "invalidated") <NEW_LINE> self.assertEqual(result.environment, envs[0]) <NEW_LINE> self.assertEqual(result.comment, "why u no make sense??")
Submit results for an existing test run.
625941c28a349b6b435e8105
def __init__(self, base_preprocessor): <NEW_LINE> <INDENT> super(MAMLPreprocessorV2, self).__init__() <NEW_LINE> self._base_preprocessor = base_preprocessor
Construct a Meta-learning feature/label Preprocessor. Used in conjunction with MetaInputGenerator. Takes a normal preprocessor's expected inputs and wraps its outputs into meta TensorSpecs for meta-learning algorithms. Args: base_preprocessor: An instance of the base preprocessor class to convert into TrainValPairs.
625941c226238365f5f0edfd
def threeSumClosest(self, nums, target): <NEW_LINE> <INDENT> ans = float('inf') <NEW_LINE> nums = sorted( nums ) <NEW_LINE> for i in range(len(nums) - 2): <NEW_LINE> <INDENT> p, q = i+1, len(nums) - 1 <NEW_LINE> while p < q: <NEW_LINE> <INDENT> temp = nums[i] + nums[p] + nums[q] <NEW_LINE> if abs( temp - target ) < abs( ans - target ): <NEW_LINE> <INDENT> ans = temp <NEW_LINE> <DEDENT> if temp == target: <NEW_LINE> <INDENT> return temp <NEW_LINE> <DEDENT> if temp < target: <NEW_LINE> <INDENT> p += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> q -= 1 <NEW_LINE> <DEDENT> <DEDENT> if nums[i] > target and ans != float('inf'): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return ans
:type nums: List[int] :type target: int :rtype: int
625941c2aad79263cf3909d0
def reset(): <NEW_LINE> <INDENT> global _SUCCESSORS <NEW_LINE> _INCACHE.clear() <NEW_LINE> _MERGED.clear() <NEW_LINE> _SUCCESSORS = weakref.WeakKeyDictionary() <NEW_LINE> _FSUCC.clear() <NEW_LINE> _MATCHED_FINDINGS.clear()
Deletes the content of all the global data structures of the module, allowing a fresh restart of every reasoning operations.
625941c285dfad0860c3adec
def convert_assets(assets, args, srcdir=None): <NEW_LINE> <INDENT> if srcdir is None: <NEW_LINE> <INDENT> srcdir = acquire_conversion_source_dir() <NEW_LINE> <DEDENT> testfile = 'data/empires2_x1_p1.dat' <NEW_LINE> if not srcdir.joinpath(testfile).is_file(): <NEW_LINE> <INDENT> print("file not found: " + testfile) <NEW_LINE> return False <NEW_LINE> <DEDENT> srcdir = mount_drs_archives(srcdir) <NEW_LINE> converted_path = assets.joinpath("converted") <NEW_LINE> converted_path.mkdirs() <NEW_LINE> targetdir = DirectoryCreator(converted_path).root <NEW_LINE> args.srcdir = FSLikeObjSynchronizer(srcdir).root <NEW_LINE> args.targetdir = FSLikeObjSynchronizer(targetdir).root <NEW_LINE> def flag(name): <NEW_LINE> <INDENT> return getattr(args, name, False) <NEW_LINE> <DEDENT> args.flag = flag <NEW_LINE> from .driver import convert <NEW_LINE> converted_count = 0 <NEW_LINE> total_count = None <NEW_LINE> for current_item in convert(args): <NEW_LINE> <INDENT> if isinstance(current_item, int): <NEW_LINE> <INDENT> total_count = current_item + converted_count <NEW_LINE> continue <NEW_LINE> <DEDENT> if total_count is None: <NEW_LINE> <INDENT> info("[%s] %s" % (converted_count, current_item)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> info("[%s] %s" % ( format_progress(converted_count, total_count), current_item )) <NEW_LINE> <DEDENT> converted_count += 1 <NEW_LINE> <DEDENT> del args.srcdir <NEW_LINE> del args.targetdir <NEW_LINE> return True
Perform asset conversion. Requires original assets and stores them in usable and free formats. assets must be a filesystem-like object pointing at the game's asset dir. sourceidr must be None, or point at some source directory. If gen_extra_files is True, some more files, mostly for debugging purposes, are created. This method prepares srcdir and targetdir to allow a pleasant, unified conversion experience, then passes them to .driver.convert().
625941c2fb3f5b602dac3623
def compute_gradient_error(x, x_shape, y, y_shape, x_init_value=None, delta=1e-3, init_targets=None): <NEW_LINE> <INDENT> grad = compute_gradient(x, x_shape, y, y_shape, x_init_value, delta, init_targets) <NEW_LINE> if isinstance(grad, tuple): <NEW_LINE> <INDENT> grad = [grad] <NEW_LINE> <DEDENT> return max(np.fabs(j_t - j_n).max() for j_t, j_n in grad)
Computes the gradient error. Computes the maximum error for dy/dx between the computed Jacobian and the numerically estimated Jacobian. This function will modify the tensors passed in as it adds more operations and hence changing the consumers of the operations of the input tensors. This function adds operations to the current session. To compute the error using a particular device, such as a GPU, use the standard methods for setting a device (e.g. using with sess.graph.device() or setting a device function in the session constructor). Args: x: a tensor or list of tensors x_shape: the dimensions of x as a tuple or an array of ints. If x is a list, then this is the list of shapes. y: a tensor y_shape: the dimensions of y as a tuple or an array of ints. x_init_value: (optional) a numpy array of the same shape as "x" representing the initial value of x. If x is a list, this should be a list of numpy arrays. If this is none, the function will pick a random tensor as the initial value. delta: (optional) the amount of perturbation. init_targets: list of targets to run to initialize model params. TODO(mrry): Remove this argument. Returns: The maximum error in between the two Jacobians.
625941c2a4f1c619b28affd0
def test_future_question(self): <NEW_LINE> <INDENT> future_question = create_question(question_text='Future question.', days=5) <NEW_LINE> url = reverse('polls:detail', args=(future_question.id,)) <NEW_LINE> response = self.client.get(url) <NEW_LINE> self.assertEqual(response.status_code, 404)
Questions with a pub_date in the future aren't displayed on the index page.
625941c24527f215b584c3ec
def test_get_log_info(self): <NEW_LINE> <INDENT> self.classifier._entity_log_sources.append('unit_test_simple_log') <NEW_LINE> logs = self.classifier.get_log_info_for_source() <NEW_LINE> assert_list_equal(logs.keys(), ['unit_test_simple_log'])
StreamClassifier - Load Log Info for Source
625941c28e05c05ec3eea305
def set_is_entanglement(self, entanglement): <NEW_LINE> <INDENT> self._is_entanglement = entanglement
Makes tile to be or not in entanglement
625941c2099cdd3c635f0bee
def __init__(self, ssh_host: ConnectionParts = None, ssh_gateway: ConnectionParts = None, autoconnect: bool = False): <NEW_LINE> <INDENT> self._connection = None <NEW_LINE> self._localhost_name = gethostname() <NEW_LINE> self._ssh_host = None <NEW_LINE> self._ssh_gateway = None <NEW_LINE> self.logger = _LOGGER <NEW_LINE> self._created_dirs = set() <NEW_LINE> self.apply(ssh_host, ssh_gateway) <NEW_LINE> if autoconnect: <NEW_LINE> <INDENT> self.connect(ssh_host, ssh_gateway)
Apply argued ssh connection arguments. Setup connection if specified. Keyword Arguments: ssh_host -- the ssh_host connection info ssh_gateway -- the ssh_gateway connection info autoconnect -- If True, try to connect to the remote host
625941c27b180e01f3dc4793
def add_attachments(self,url,attachments,descriptions=None): <NEW_LINE> <INDENT> page = self.wiki_page_from_url(url) <NEW_LINE> if isinstance(attachments,basestring): <NEW_LINE> <INDENT> attachments = [attachments] <NEW_LINE> <DEDENT> default_desc='automated upload' <NEW_LINE> if descriptions is None: <NEW_LINE> <INDENT> descriptions = len(attachments)*[default_desc] <NEW_LINE> <DEDENT> elif isinstance(descriptions,basestring): <NEW_LINE> <INDENT> descriptions = [descriptions] <NEW_LINE> <DEDENT> uploads = [] <NEW_LINE> for a,d in zip(attachments,descriptions): <NEW_LINE> <INDENT> uploads += [dict(path=a,filename=os.path.basename(a),description=d)] <NEW_LINE> <DEDENT> fields = dict( resource_id=page.internal_id, project_id=page.manager.params.get('project_id',0), text = page.text, uploads = uploads, ) <NEW_LINE> logging.info("Attaching files:\n"+"\n".join(attachments)) <NEW_LINE> return self.wiki_page.update(**fields)
Attach files to wiki page at the given url.
625941c2498bea3a759b9a42
def __init__(self, hass, values, invert_buttons): <NEW_LINE> <INDENT> ZWaveDeviceEntity.__init__(self, values, DOMAIN) <NEW_LINE> self._network = hass.data[zwave.ZWAVE_NETWORK] <NEW_LINE> self._open_id = None <NEW_LINE> self._close_id = None <NEW_LINE> self._current_position = None <NEW_LINE> self._invert_buttons = invert_buttons <NEW_LINE> self._workaround = workaround.get_device_mapping(values.primary) <NEW_LINE> if self._workaround: <NEW_LINE> <INDENT> _LOGGER.debug("Using workaround %s", self._workaround) <NEW_LINE> <DEDENT> self.update_properties()
Initialize the zwave rollershutter.
625941c27b180e01f3dc4794
def hist(a, bins): <NEW_LINE> <INDENT> n = searchsorted(sort(a), bins) <NEW_LINE> n = concatenate([n, [len(a)]]) <NEW_LINE> n = array(list(map(float, n))) <NEW_LINE> return n[1:] - n[:-1]
Histogram of 'a' defined on the bin grid 'bins' Usage: h=hist(p,xp)
625941c207f4c71912b11413
def terminal_length(self, n='0'): <NEW_LINE> <INDENT> if self._terminal_length_value: <NEW_LINE> <INDENT> if self._terminal_length_value != int(n): <NEW_LINE> <INDENT> self._terminal_length_value = int(n) <NEW_LINE> return self._terminal_length(n) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._terminal_length_value = int(n) <NEW_LINE> return self._terminal_length(n)
Sets terminal length of shell
625941c2566aa707497f44fe
def test_locate_on_shard(self): <NEW_LINE> <INDENT> nb_obj_to_add = 10 <NEW_LINE> self._create(self.cname) <NEW_LINE> self._add_objects(self.cname, nb_obj_to_add) <NEW_LINE> obj_id_s1 = random.randrange(nb_obj_to_add // 2) <NEW_LINE> obj_name_s1 = 'content_' + str(obj_id_s1) <NEW_LINE> _, chunks_s1 = self.storage.object_locate(self.account, self.cname, obj_name_s1) <NEW_LINE> obj_id_s2 = random.randrange(nb_obj_to_add // 2, nb_obj_to_add) <NEW_LINE> obj_name_s2 = 'content_' + str(obj_id_s2) <NEW_LINE> _, chunks_s2 = self.storage.object_locate(self.account, self.cname, obj_name_s2) <NEW_LINE> params = {"partition": "50,50", "threshold": 1} <NEW_LINE> shards = self.container_sharding.find_shards( self.account, self.cname, strategy="shard-with-partition", strategy_params=params) <NEW_LINE> modified = self.container_sharding.replace_shard( self.account, self.cname, shards, enable=True) <NEW_LINE> self.assertTrue(modified) <NEW_LINE> self._test_locate_on_shard(chunks_s1, obj_name_s1, 0) <NEW_LINE> self._test_locate_on_shard(chunks_s2, obj_name_s2, 1)
Check the locate command directly on the shard (with account and cname of the shard).
625941c28a43f66fc4b53ff9
def rbegin(self) -> "std::vector< double >::reverse_iterator": <NEW_LINE> <INDENT> return _moduleconnectorwrapper.DoubleVector_rbegin(self)
rbegin(DoubleVector self) -> std::vector< double >::reverse_iterator
625941c27cff6e4e81117918
def _print_rg_cov(rghat, fh, log): <NEW_LINE> <INDENT> _print_cov(rghat.hsq1, fh + '.hsq1.cov', log) <NEW_LINE> _print_cov(rghat.hsq2, fh + '.hsq2.cov', log) <NEW_LINE> _print_cov(rghat.gencov, fh + '.gencov.cov', log)
Print covariance matrix of estimates.
625941c23539df3088e2e2dd
def prepare_data(self): <NEW_LINE> <INDENT> self.data = np.load(self.name) <NEW_LINE> self.x, self.y = self.data['x'], self.data['y'] <NEW_LINE> self.x_uncal = self.data['x_uncal'] <NEW_LINE> self.nfo = self.data['info'].tolist() <NEW_LINE> self.tstart = self.data['starttime'] <NEW_LINE> self.tstop = self.tstart + self.data['totaltime'] <NEW_LINE> self.livetime = float(self.data["livetime"]) <NEW_LINE> self.livefraction = float(self.data['livetime'])/float(self.data['totaltime'])
Loads the data from the npz file into np.arrays This initialized: self.data, self.x, self.y, self.nfo self.tstart, self.tstop, and self.deadtime
625941c29b70327d1c4e0d66
def createTree(nodeList, node): <NEW_LINE> <INDENT> if len(nodeList) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if nodeList[0] == '!': <NEW_LINE> <INDENT> return nodeList[1:] <NEW_LINE> <DEDENT> splitAtt, splitVal, value = nodeList[0].strip().split('-') <NEW_LINE> nodeList = nodeList[1:] <NEW_LINE> if splitAtt == splitVal == '$': <NEW_LINE> <INDENT> node.setSplit("Base case") <NEW_LINE> node.setValue(value) <NEW_LINE> return nodeList[2:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node.setSplit((splitAtt, splitVal)) <NEW_LINE> <DEDENT> leftChild = Tree() <NEW_LINE> node.setLesser(leftChild) <NEW_LINE> nodeList = createTree(nodeList, leftChild) <NEW_LINE> rightChild = Tree() <NEW_LINE> node.setGreater(rightChild) <NEW_LINE> nodeList = createTree(nodeList, rightChild) <NEW_LINE> return nodeList
Given the csv file containing the tree in DFS traversal, it returns it as a list. :param nodeList: list of nodes in the tree in DFS traversal order :param node: Root node of the tree :return: remaining nodes in list of nodes in the tree in DFS traversal order
625941c29b70327d1c4e0d67
def test_sysan_sanitization(self): <NEW_LINE> <INDENT> a = models.Test(str(uuid.uuid4())) <NEW_LINE> with self.g.session_scope() as s: <NEW_LINE> <INDENT> a = s.merge(a) <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> a.sysan["foo"] = {"bar": "baz"}
It shouldn't be possible to set system annotations keys to anything but primitive values.
625941c2fbf16365ca6f6152
def get_df_from_table(self, table_name, **kwargs): <NEW_LINE> <INDENT> with self.engine.connect() as conn: <NEW_LINE> <INDENT> return pd.read_sql_table(table_name, conn, **kwargs)
Return a pandas DataFrame of the DB table
625941c229b78933be1e5642
def test_html_output(self): <NEW_LINE> <INDENT> output = hbcal("hbcal -ih -o hebrew -fhtml --molad 1 2 5775") <NEW_LINE> self.assertEqual('&#1497;&#1493;&#1501; ' + '&#1512;&#1488;&#1513;&#1493;&#1503; 30 ' + '&#1504;&#1497;&#1505;&#1503; 5775 07:27 &#1493;4 ' + '&#1495;&#1500;&#1511;&#1497;&#1501;', output[0])
Test --molad option
625941c207d97122c417881a
def p_primary_expression_4(p): <NEW_LINE> <INDENT> p[0] = ast.StringLitExp(p[1], line_no=str(p.lineno(1) + __start_line_no - 1))
primary_expression : SCONST_D
625941c2796e427e537b0556
def can_receive(self, hostname, filename): <NEW_LINE> <INDENT> return self.socket_mgr.can_receive(hostname=hostname, filename=filename)
Determine if the load is not too much to allow receiving from another client
625941c21b99ca400220aa43
def df_traverse(tree, clique_ix=None, func=yield_id): <NEW_LINE> <INDENT> stack = [tree] <NEW_LINE> while stack: <NEW_LINE> <INDENT> tree = stack.pop() <NEW_LINE> yield from func(tree) <NEW_LINE> if tree[0] == clique_ix: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> stack.extend([child for child in reversed(tree[1:])])
Depth-first traversal with optional early termination :param tree: tree structure in list format :param clique_ix: clique id used to terminate traversal :param func: function controlling component of tree output Output: Depends on func argument. Default is list of clique ids [id1, ..., idN] (or [id1, ..., cid])
625941c22eb69b55b151c83f
def diff(self, n=1): <NEW_LINE> <INDENT> def func(value): <NEW_LINE> <INDENT> value = value.astype('float') <NEW_LINE> shifted_value = np.roll(value, n) <NEW_LINE> value = value - shifted_value <NEW_LINE> if n>=0: <NEW_LINE> <INDENT> value[:n]=np.nan <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value[n:]=np.nan <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> return self._non_agg(func)
Take the difference between the current value and the nth value above it. Parameters ---------- n: int Returns ------- A DataFrame
625941c2090684286d50ec76
def test_get_license(): <NEW_LINE> <INDENT> licenses = pyslurm.licenses().get() <NEW_LINE> assert_true(isinstance(licenses, dict))
License: Test licenses().get() return type
625941c2566aa707497f44ff
def get_element(self, elementinfo, waittime=1): <NEW_LINE> <INDENT> time.sleep(waittime) <NEW_LINE> try: <NEW_LINE> <INDENT> element = self.driver.find_element(elementinfo["type"], elementinfo["value"]) <NEW_LINE> if element == None: <NEW_LINE> <INDENT> self.lg.info("定位元素失败:%s" % elementinfo["desc"]) <NEW_LINE> self.driver.quit() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return element <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.lg.error(e) <NEW_LINE> self.lg.error("未定位到元素:%s" % elementinfo["desc"]) <NEW_LINE> self.get_screenshot()
获取元素对象,传入元素信息返回元素 :param elementinfo: :param waittime: :return:
625941c250812a4eaa59c2b6
def __manglePrivateMemberName(self, privateMemberName, skipCheck=False): <NEW_LINE> <INDENT> assert privateMemberName.startswith("__"), "%r doesn't start with __" % privateMemberName <NEW_LINE> assert not privateMemberName.startswith("___"), "%r starts with ___" % privateMemberName <NEW_LINE> assert not privateMemberName.endswith("__"), "%r ends with more than one underscore" % privateMemberName <NEW_LINE> realName = "_" + (self.__myClassName).lstrip("_") + privateMemberName <NEW_LINE> if not skipCheck: <NEW_LINE> <INDENT> value = getattr(self, realName) <NEW_LINE> <DEDENT> return realName
Mangles the given mangled (private) member name; a mangled member name is one whose name begins with two or more underscores and ends with one or zero underscores. privateMemberName: The private member name (e.g., "__logger") skipCheck: Pass True to skip test for presence of the demangled member in our instance. Returns: The demangled member name (e.g., "_CLAModel__logger")
625941c2d8ef3951e32434d0
def upload(): <NEW_LINE> <INDENT> rsync_project(remote_dir=env.project_path, local_dir='./', delete=True, exclude=['.git', '*.pyc', 'dist', 'build', '.scrapy'])
TODO: allow to upload via git
625941c2d4950a0f3b08c2e3
def test_receiveUnimplemented(self): <NEW_LINE> <INDENT> self.proto.dispatchMessage(transport.MSG_UNIMPLEMENTED, '\x00\x00\x00\xff') <NEW_LINE> self.assertEqual(self.proto.unimplementeds, [255])
Test that unimplemented messages are received correctly. See test_sendUnimplemented.
625941c2d18da76e23532466
def send_idle_acknowledgement(self): <NEW_LINE> <INDENT> with open(self.__stepdown_files.idle_ack, "w"): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> os.remove(self.__stepdown_files.permitted)
Signal to the running test that stepdown thread won't continue to run stepdowns.
625941c2711fe17d82542302
def highlight(self): <NEW_LINE> <INDENT> self.highlighted_sprites.append(self)
placeholder method controlling highlight behaviour
625941c22eb69b55b151c840
def number_of_nodes(graph, level): <NEW_LINE> <INDENT> pass
Calculates the number of nodes at given level :param level: :param graph: The graph :return: Total number of nodes at given level
625941c21d351010ab855aaf
def average_edge(pollster_edges, pollster_errors): <NEW_LINE> <INDENT> edges = [] <NEW_LINE> weights = [] <NEW_LINE> for pollster in pollster_edges: <NEW_LINE> <INDENT> weight = pollster_to_weight(pollster, pollster_errors) <NEW_LINE> edges.append(pollster_edges[pollster]) <NEW_LINE> weights.append(weight) <NEW_LINE> <DEDENT> return weighted_average(edges, weights)
Given *PollsterEdges* and *PollsterErrors*, returns the average of these *Edge*s weighted by their respective *PollsterErrors*.
625941c2d58c6744b4257bf3
def ntp_request(host: str) -> Union[None, NTPResponse]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> socket.getaddrinfo(host, "ntp") <NEW_LINE> <DEDENT> except socket.gaierror as error: <NEW_LINE> <INDENT> sys.stderr.write("Cannot resolve host '{}': {}\n".format(host, error)) <NEW_LINE> sys.stderr.flush() <NEW_LINE> return None <NEW_LINE> <DEDENT> client = ntplib.NTPClient() <NEW_LINE> attrs = {} <NEW_LINE> try: <NEW_LINE> <INDENT> response = client.request(host) <NEW_LINE> for attr in [ "offset", "delay", "root_delay", "leap", "version", "stratum", "mode", "ref_id", ]: <NEW_LINE> <INDENT> attrs[attr] = getattr(response, attr) <NEW_LINE> <DEDENT> attrs["ref_id"] = ref_id_to_text(attrs["ref_id"], attrs["stratum"]) <NEW_LINE> <DEDENT> except NTPException as error: <NEW_LINE> <INDENT> sys.stderr.write("Cannot convert reference: {}\n".format(error)) <NEW_LINE> sys.stderr.flush() <NEW_LINE> return None <NEW_LINE> <DEDENT> return NTPResponse(host, **attrs)
Request NTP server host to retrieve attributes
625941c24e4d5625662d436d
def get_gen_val(f_map, in_val): <NEW_LINE> <INDENT> if in_val == '': <NEW_LINE> <INDENT> return f_map[''][0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ind = int(in_val) <NEW_LINE> return f_map[ind][0]
Return the generalized value from the map. If the value read in is other than the empty string, the value is cast to an integer. :param f_map: The generalization map to be used :param in_val: The value to be generalized; this will always come in as a string but will be cast to an integer if it is non-empty :return: the generalized value
625941c2a05bb46b383ec7b6
def vector_matches_position_vector(self, vector): <NEW_LINE> <INDENT> matches = True <NEW_LINE> for hyperplane_index, orientation in vector: <NEW_LINE> <INDENT> if self.position_vector[hyperplane_index] == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif self.position_vector[hyperplane_index] != orientation: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return matches
tests if input pos vector matches vertex position vector. For input vector not all position have to be specified. :param vector: list of tuples (hyperplane_index, orientation) :return: matches: Boolean that indicates if self.position_vector matches position vector match.
625941c216aa5153ce36240b
def __repr__(self,*args): <NEW_LINE> <INDENT> pass
__repr__(self: object) -> str Returns the code representation of the object. The default implementation returns a string which consists of the type and a unique numerical identifier.
625941c2fff4ab517eb2f3ce
def get_single_valued_metadata(self): <NEW_LINE> <INDENT> return list()
Return a list of metadata attaining only one value for this type.
625941c276d4e153a657eac3
def iter_switches(self): <NEW_LINE> <INDENT> return <NEW_LINE> yield None
Iterate or generate switches for the <switch> tags under the <switchlist> tag in VPR's architecture description XML and the <switches> tag under the <switches> tag in VPR's routing resource graph XML. Each element in the returned iterator/generator should be a `dict` satisfying the JSON schema 'schema/switch.schema.json'.
625941c299cbb53fe6792b7a
def si_crystal_test(): <NEW_LINE> <INDENT> jobs=[] <NEW_LINE> cwriter=CrystalWriter({ 'xml_name':'../../BFD_Library.xml', 'cutoff':0.2, 'kmesh':(3,3,3), 'spin_polarized':False }) <NEW_LINE> cwriter.set_struct_fromcif(open('structures/si.cif','r').read(),primitive=True) <NEW_LINE> cman=CrystalManager( name='crys', path='test_si_crys', writer=cwriter, runner=RunnerPBS( queue='secondary', nn=1,np=16, walltime='0:10:00' ) ) <NEW_LINE> jobs.append(cman) <NEW_LINE> var=QWalkManager( name='var', path=cman.path, writer=VarianceWriter(), reader=VarianceReader(), runner=RunnerPBS( nn=1,np=16,queue='secondary',walltime='0:10:00' ), trialfunc=SlaterJastrow(cman,kpoint=0) ) <NEW_LINE> jobs.append(var) <NEW_LINE> lin=QWalkManager( name='linear', path=cman.path, writer=LinearWriter(), reader=LinearReader(), runner=RunnerPBS( nn=1,np=16,queue='secondary',walltime='1:00:00' ), trialfunc=SlaterJastrow(slatman=cman,jastman=var,kpoint=0) ) <NEW_LINE> jobs.append(lin) <NEW_LINE> for kidx in cman.qwfiles['kpoints']: <NEW_LINE> <INDENT> kpt=cman.qwfiles['kpoints'][kidx] <NEW_LINE> dmc=QWalkManager( name='dmc_%d'%kidx, path=cman.path, writer=DMCWriter(), reader=DMCReader(), runner=RunnerPBS( nn=1,np=16,queue='secondary',walltime='1:00:00', ), trialfunc=SlaterJastrow(slatman=cman,jastman=lin,kpoint=kidx) ) <NEW_LINE> jobs.append(dmc) <NEW_LINE> <DEDENT> return jobs
Simple tests that check PBC is working Crystal, and that QMC can be performed on the result.
625941c260cbc95b062c64d6
def nb_100(data, deveui): <NEW_LINE> <INDENT> output = {} <NEW_LINE> temperature_humidity_parsed = temperature_humidity(data[deveui + "-1"]) <NEW_LINE> output.update(temperature_humidity_parsed) <NEW_LINE> output["pressure"] = round(float(data[deveui + "-2"]["pressure"]) / (1*10**5), 3) <NEW_LINE> output["rssi"] = float(data[deveui + "-3"]["Signal strength"]) <NEW_LINE> output["battery"] = float(data[deveui + "-4"]["battery"]) / (1*10**3) <NEW_LINE> return output
reformat nb_100 data
625941c2c4546d3d9de729c5
def __init__( self, field, specification, optional=False, spec_filter=None, immediate_rebind=True, ): <NEW_LINE> <INDENT> super(RequiresBest, self).__init__( field, specification, False, optional, spec_filter, immediate_rebind )
:param field: The injected field :param specification: The injected service specification :param optional: If True, this injection is optional :param spec_filter: An LDAP query to filter injected services upon their properties :param immediate_rebind: If True, the component won't be invalidated then re-validated if a matching service is available when the injected dependency is unbound :raise TypeError: A parameter has an invalid type :raise ValueError: An error occurred while parsing the filter or an argument is incorrect
625941c2d18da76e23532467
def add_osd_perf_query(self, query: Dict[str, Any]) -> Optional[int]: <NEW_LINE> <INDENT> return self._ceph_add_osd_perf_query(query)
Register an OSD perf query. Argument is a dict of the query parameters, in this form: :: { 'key_descriptor': [ {'type': subkey_type, 'regex': regex_pattern}, ... ], 'performance_counter_descriptors': [ list, of, descriptor, types ], 'limit': {'order_by': performance_counter_type, 'max_count': n}, } Valid subkey types: 'client_id', 'client_address', 'pool_id', 'namespace', 'osd_id', 'pg_id', 'object_name', 'snap_id' Valid performance counter types: 'ops', 'write_ops', 'read_ops', 'bytes', 'write_bytes', 'read_bytes', 'latency', 'write_latency', 'read_latency' :param object query: query :rtype: int (query id)
625941c2046cf37aa974ccdd
def revoke_security_group(self, group_name, src_security_group_name=None, src_security_group_owner_id=None, ip_protocol=None, from_port=None, to_port=None, cidr_ip=None): <NEW_LINE> <INDENT> if src_security_group_name: <NEW_LINE> <INDENT> if from_port is None and to_port is None and ip_protocol is None: <NEW_LINE> <INDENT> return self._revoke_deprecated(group_name, src_security_group_name, src_security_group_owner_id) <NEW_LINE> <DEDENT> <DEDENT> params = {'GroupName':group_name} <NEW_LINE> if src_security_group_name: <NEW_LINE> <INDENT> params['IpPermissions.1.Groups.1.GroupName'] = src_security_group_name <NEW_LINE> <DEDENT> if src_security_group_owner_id: <NEW_LINE> <INDENT> params['IpPermissions.1.Groups.1.UserId'] = src_security_group_owner_id <NEW_LINE> <DEDENT> if ip_protocol: <NEW_LINE> <INDENT> params['IpPermissions.1.IpProtocol'] = ip_protocol <NEW_LINE> <DEDENT> if from_port: <NEW_LINE> <INDENT> params['IpPermissions.1.FromPort'] = from_port <NEW_LINE> <DEDENT> if to_port: <NEW_LINE> <INDENT> params['IpPermissions.1.ToPort'] = to_port <NEW_LINE> <DEDENT> if cidr_ip: <NEW_LINE> <INDENT> params['IpPermissions.1.IpRanges.1.CidrIp'] = cidr_ip <NEW_LINE> <DEDENT> return self.get_status('RevokeSecurityGroupIngress', params, verb='POST')
Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are revoking another group or you are revoking some ip-based rule. :type group_name: string :param group_name: The name of the security group you are removing the rule from. :type src_security_group_name: string :param src_security_group_name: The name of the security group you are revoking access to. :type src_security_group_owner_id: string :param src_security_group_owner_id: The ID of the owner of the security group you are revoking access to. :type ip_protocol: string :param ip_protocol: Either tcp | udp | icmp :type from_port: int :param from_port: The beginning port number you are disabling :type to_port: int :param to_port: The ending port number you are disabling :type cidr_ip: string :param cidr_ip: The CIDR block you are revoking access to. See http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing :rtype: bool :return: True if successful.
625941c26fece00bbac2d6d0
def Solve(dData): <NEW_LINE> <INDENT> m = dData.A.shape[0] <NEW_LINE> n = dData.A.shape[1] <NEW_LINE> dInit = INIT(np.zeros(m), np.ones(n), np.ones(n)) <NEW_LINE> dCone = CONE(gHc, n) <NEW_LINE> return NSSolve(dData, dInit, dCone)
Solve the linear program using non-symmetric cone alg. Note: This isnt optimal for LP, but used for tests...
625941c250812a4eaa59c2b7
def get(self, key, default=None): <NEW_LINE> <INDENT> with self.__lock: <NEW_LINE> <INDENT> return copy.deepcopy(self.__values.get(key, default))
Return thread safe copy of value.
625941c2925a0f43d2549e08
def start(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.subscribe() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> self.start()
启动接收
625941c28e05c05ec3eea306
def remove_file(self, path): <NEW_LINE> <INDENT> Logger.info('RemoteConection.remove_file: Removing {}'.format(path)) <NEW_LINE> self.sftp.unlink(path) <NEW_LINE> Logger.info('RemoteConection.remove_file: Removed.')
Unlink a remote file. Does not work with directories.
625941c263b5f9789fde7078
def spatial_batchnorm_backward(dout, cache): <NEW_LINE> <INDENT> dx, dgamma, dbeta = None, None, None <NEW_LINE> pass <NEW_LINE> return dx, dgamma, dbeta
Computes the backward pass for spatial batch normalization. Inputs: - dout: Upstream derivatives, of shape (N, k, H, W) - cache: Values from the forward pass Returns a tuple of: - dx: Gradient with respect to inputs, of shape (N, k, H, W) - dgamma: Gradient with respect to scale parameter, of shape (k,) - dbeta: Gradient with respect to shift parameter, of shape (k,)
625941c2435de62698dfdbdf
def _set_list_tuple_only_structure(self, key): <NEW_LINE> <INDENT> self.set_neighs([e[0] for e in key]) <NEW_LINE> self.set_sp_rel_pos([e[1] for e in key])
Set the neighbourhood information in a form of list tuple only structure. Parameters ---------- neighs_info: tuple the neighborhood information for each element `i` and perturbations `k`. The standards to set that information are: * [(neighs{any form}, sp_relative_pos{any form})]
625941c20c0af96317bb817b
def generate(self, module): <NEW_LINE> <INDENT> if self.module_backend.needs_regeneration(): <NEW_LINE> <INDENT> if not self.check_mode: <NEW_LINE> <INDENT> if self.backup: <NEW_LINE> <INDENT> self.backup_file = module.backup_local(self.path) <NEW_LINE> <DEDENT> self.module_backend.generate_private_key() <NEW_LINE> privatekey_data = self.module_backend.get_private_key_data() <NEW_LINE> if self.return_content: <NEW_LINE> <INDENT> self.privatekey_bytes = privatekey_data <NEW_LINE> <DEDENT> write_file(module, privatekey_data, 0o600) <NEW_LINE> <DEDENT> self.changed = True <NEW_LINE> <DEDENT> elif self.module_backend.needs_conversion(): <NEW_LINE> <INDENT> if not self.check_mode: <NEW_LINE> <INDENT> if self.backup: <NEW_LINE> <INDENT> self.backup_file = module.backup_local(self.path) <NEW_LINE> <DEDENT> self.module_backend.convert_private_key() <NEW_LINE> privatekey_data = self.module_backend.get_private_key_data() <NEW_LINE> if self.return_content: <NEW_LINE> <INDENT> self.privatekey_bytes = privatekey_data <NEW_LINE> <DEDENT> write_file(module, privatekey_data, 0o600) <NEW_LINE> <DEDENT> self.changed = True <NEW_LINE> <DEDENT> file_args = module.load_file_common_arguments(module.params) <NEW_LINE> if module.check_file_absent_if_check_mode(file_args['path']): <NEW_LINE> <INDENT> self.changed = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.changed = module.set_fs_attributes_if_different(file_args, self.changed)
Generate a keypair.
625941c2498bea3a759b9a43
@view_config(route_name='api_v1_key_action', request_method='DELETE', renderer='json') <NEW_LINE> def delete_key(request): <NEW_LINE> <INDENT> auth_context = auth_context_from_request(request) <NEW_LINE> key_id = request.matchdict.get('key') <NEW_LINE> if not key_id: <NEW_LINE> <INDENT> raise KeyParameterMissingError() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> key = Key.objects.get(owner=auth_context.owner, id=key_id, deleted=None) <NEW_LINE> <DEDENT> except me.DoesNotExist: <NEW_LINE> <INDENT> raise NotFoundError('Key id does not exist') <NEW_LINE> <DEDENT> auth_context.check_perm('key', 'remove', key.id) <NEW_LINE> m_delete_key(auth_context.owner, key_id) <NEW_LINE> return list_keys(request)
Delete key Delete key. When a key gets deleted, it takes its associations with it so just need to remove from the server too. If the default key gets deleted, it sets the next one as default, provided that at least another key exists. It returns the list of all keys after the deletion, excluding the private keys (check also list_keys). REMOVE permission required on key. --- key: in: path required: true type: string
625941c221a7993f00bc7c80
def setUpPloneSite(self, portal): <NEW_LINE> <INDENT> self.applyProfile(portal, 'pmr2.flatmap:default')
Apply the default pmr2.flatmap profile and ensure that the settings have the tmpdir applied in.
625941c21f037a2d8b946192
def router(paramstring): <NEW_LINE> <INDENT> params = dict(parse_qsl(paramstring)) <NEW_LINE> if params: <NEW_LINE> <INDENT> if params['action'] == 'list_category': <NEW_LINE> <INDENT> list_movies(params['category']) <NEW_LINE> <DEDENT> elif params['action'] == 'list_movie': <NEW_LINE> <INDENT> list_videos(params['movie'],params['thumb']) <NEW_LINE> <DEDENT> elif params['action'] == 'play': <NEW_LINE> <INDENT> play_video(params['video']) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> list_categories()
Router function that calls other functions depending on the provided paramstring :param paramstring:
625941c2090684286d50ec77
def keyword_param_f(name="name", gender=None): <NEW_LINE> <INDENT> print("keyword params: name={}, gender={}".format(name, gender))
Keyword parameter is defined by giving it a default value. Python interpreter won't care order of keyword parameters. You can omit some parameter ( Then default value will be used).
625941c238b623060ff0ad81
def generate_salt(length=8): <NEW_LINE> <INDENT> chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890./" <NEW_LINE> salt = [random.choice(chars) for i in range(0, length)] <NEW_LINE> return "".join(salt)
Generate a random salt for password hashing :return: A random salt of the requested length
625941c28e71fb1e9831d73e
def eval(self, y_pred, y_true, metadata): <NEW_LINE> <INDENT> raise NotImplementedError
Args: - y_pred (Tensor): Predicted targets - y_true (Tensor): True targets - metadata (Tensor): Metadata Output: - results (dict): Dictionary of results - results_str (str): Pretty print version of the results
625941c25fc7496912cc3911
def sent2vec(model, s): <NEW_LINE> <INDENT> words = s.lower() <NEW_LINE> words = word_tokenize(words) <NEW_LINE> stop_words = stopwords.words('english') <NEW_LINE> words = [w for w in words if not w in stop_words] <NEW_LINE> words = [w for w in words if w.isalpha()] <NEW_LINE> M = [] <NEW_LINE> for w in words: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> M.append(model[w]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> M = np.array(M) <NEW_LINE> v = M.sum(axis=0) <NEW_LINE> return v / np.sqrt((v ** 2).sum())
Sentence to Vector by summing the embeddings
625941c23617ad0b5ed67e8c
def is_valid_interfaces(meta): <NEW_LINE> <INDENT> interfaces = meta['input_port_mapping'] <NEW_LINE> for intf in interfaces: <NEW_LINE> <INDENT> if not is_valid(intf): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
:param meta: :return: boolean
625941c2cc40096d615958e5
def __init__(self, entity: str, location: List[int], value: str, *, confidence: float = None, metadata: dict = None, groups: List['CaptureGroup'] = None, interpretation: 'RuntimeEntityInterpretation' = None, alternatives: List['RuntimeEntityAlternative'] = None, role: 'RuntimeEntityRole' = None) -> None: <NEW_LINE> <INDENT> self.entity = entity <NEW_LINE> self.location = location <NEW_LINE> self.value = value <NEW_LINE> self.confidence = confidence <NEW_LINE> self.metadata = metadata <NEW_LINE> self.groups = groups <NEW_LINE> self.interpretation = interpretation <NEW_LINE> self.alternatives = alternatives <NEW_LINE> self.role = role
Initialize a RuntimeEntity object. :param str entity: An entity detected in the input. :param List[int] location: An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. :param str value: The entity value that was recognized in the user input. :param float confidence: (optional) A decimal percentage that represents Watson's confidence in the recognized entity. :param dict metadata: (optional) Any metadata for the entity. :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :param RuntimeEntityInterpretation interpretation: (optional) An object containing detailed information about the entity recognized in the user input. For more information about how system entities are interpreted, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-system-entities). :param List[RuntimeEntityAlternative] alternatives: (optional) An array of possible alternative values that the user might have intended instead of the value returned in the **value** property. This property is returned only for `@sys-time` and `@sys-date` entities when the user's input is ambiguous. This property is included only if the new system entities are enabled for the workspace. :param RuntimeEntityRole role: (optional) An object describing the role played by a system entity that is specifies the beginning or end of a range recognized in the user input. This property is included only if the new system entities are enabled for the workspace.
625941c2cc0a2c11143dce24
def __init__(self, sampler=None, *args, **kwargs): <NEW_LINE> <INDENT> super(TransitionBatchUpdate, self).__init__(*args, **kwargs) <NEW_LINE> if sampler is None: <NEW_LINE> <INDENT> sampler = TransitionSampler(playback.MapPlayback(1000), 32, 4) <NEW_LINE> <DEDENT> self._sampler = sampler <NEW_LINE> self._n_update = 0
:param sampler: :type sampler: TransitionSampler :param args: :param kwargs:
625941c2293b9510aa2c322b
def userReg(self, code, name, password): <NEW_LINE> <INDENT> code = code.strip() <NEW_LINE> try: <NEW_LINE> <INDENT> data = self.config.get(code, "name") <NEW_LINE> return False, "用户{code}已存在".format(code=code) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> name = name.strip() <NEW_LINE> if not len(name) > 0: <NEW_LINE> <INDENT> return False, "用户名{name}无效".format(name=name) <NEW_LINE> <DEDENT> path = "{root}\\{code}".format(root=self.rootPath, code=code) <NEW_LINE> if os.path.exists(path): <NEW_LINE> <INDENT> return False, "用户{code}已存在".format(code=code) <NEW_LINE> <DEDENT> os.mkdir(path) <NEW_LINE> self.config.add_section(code) <NEW_LINE> self.config.set(code, "name", name) <NEW_LINE> self.config.set(code, "password", password) <NEW_LINE> self.config.set(code, "storageSize", self.initSize) <NEW_LINE> self.config.set(code, "storaged", "0M") <NEW_LINE> self.config.write(open(self.configfile, "w", encoding="utf-8")) <NEW_LINE> return True, "用户[{code}]{name}注册成功".format(code=code, name=name)
注册用户 :param name: :param password: :return:
625941c244b2445a3393202b
def find_first(word, letter): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> while index < len(word): <NEW_LINE> <INDENT> if word[index] == letter: <NEW_LINE> <INDENT> return index <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> index += 1 <NEW_LINE> <DEDENT> <DEDENT> return -1
find a character in a string :param word: :param letter: :return: the index if found or -1 if not
625941c2925a0f43d2549e09
def parse_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') <NEW_LINE> parser.add_argument('--gpu', dest='gpu_id', help='GPU id to use', default=0, type=int) <NEW_LINE> parser.add_argument('--def', dest='prototxt', help='prototxt file defining the network', default=None, type=str) <NEW_LINE> parser.add_argument('--solver', dest='solver', help='solver prototxt', default=None, type=str) <NEW_LINE> parser.add_argument('--net', dest='caffemodel', help='model to test', default=None, type=str) <NEW_LINE> parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) <NEW_LINE> parser.add_argument('--imdb', dest='imdb_name', help='dataset to test', default='voc_2007_test', type=str) <NEW_LINE> parser.add_argument('--wait', dest='wait', help='wait until net file exists', default=True, type=bool) <NEW_LINE> parser.add_argument('--comp', dest='comp_mode', help='competition mode', action='store_true') <NEW_LINE> parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) <NEW_LINE> parser.add_argument('--task', dest='task_name', help='set task name', default='sds', type=str) <NEW_LINE> if len(sys.argv) == 1: <NEW_LINE> <INDENT> parser.print_help() <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> return parser.parse_args()
Parse input arguments
625941c23cc13d1c6d3c730f
def eval_object(context, obj, expected_type): <NEW_LINE> <INDENT> result = expected_type.default_value() <NEW_LINE> for name, val in six.iteritems(obj.props): <NEW_LINE> <INDENT> subtype = expected_type[name] <NEW_LINE> ctx.set_property(result, name, eval_rhs(context, val, subtype)) <NEW_LINE> <DEDENT> return result
Evaluate the provided object :type context: ctx.EvaluationContext :param context: Evaluation context. :type obj: ast.JsonObj :param obj: The expression to evaluate :type expected_type: type_util.IsType :param expected_type: The expected type of this computation. :return: Returns the computed value
625941c2a8370b7717052834
def is_noun(self, word): <NEW_LINE> <INDENT> return self.tagger.is_noun(word)
is noun word
625941c2b57a9660fec33816
def modify_polling_status_line(self, status_line): <NEW_LINE> <INDENT> return status_line
Hook to modify the status line that is printed during polling.
625941c2656771135c3eb800
def InitializeBongardLTM(ltm): <NEW_LINE> <INDENT> for i in range(10): <NEW_LINE> <INDENT> ltm.GetNode(content=PlatonicInteger(magnitude=i)) <NEW_LINE> <DEDENT> for i in (0, 4, 9): <NEW_LINE> <INDENT> ltm.AddEdge(PlatonicInteger(magnitude=i), Square(), edge_type_set={LTMEdge.LTM_EDGE_TYPE_ISA})
Called if ltm was empty (had no nodes).
625941c2e76e3b2f99f3a7a2
def onResidual(**bvalues): <NEW_LINE> <INDENT> pass
function (target) { if (!target.hasType('Rock')) this.damage(target.baseMaxhp / 6, target); }
625941c2293b9510aa2c322c
def on_notify(self, notification): <NEW_LINE> <INDENT> if notification.get('record', False) and self.running: <NEW_LINE> <INDENT> if 'timestamp' not in notification: <NEW_LINE> <INDENT> logger.error("Notification without timestamp will not be saved.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data['notifications'].append(notification) <NEW_LINE> <DEDENT> <DEDENT> elif notification['subject'] == 'recording.must_start': <NEW_LINE> <INDENT> if self.running: <NEW_LINE> <INDENT> logger.info('Recording already running!') <NEW_LINE> <DEDENT> elif not self.g_pool.capture.online: <NEW_LINE> <INDENT> logger.error("Current world capture is offline. Please reconnect or switch to fake capture") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if notification.get("session_name", ""): <NEW_LINE> <INDENT> self.set_session_name(notification["session_name"]) <NEW_LINE> <DEDENT> self.start() <NEW_LINE> <DEDENT> <DEDENT> elif notification['subject'] == 'recording.must_stop': <NEW_LINE> <INDENT> if self.running: <NEW_LINE> <INDENT> self.stop() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.info('Recording already stopped!')
Handles recorder notifications Reacts to notifications: ``recording.should_start``: Starts a new recording session. fields: 'session_name' change session name use `/` to att dirs. start with `/` to ingore the rec base dir and start from root instead. ``recording.should_stop``: Stops current recording session Emits notifications: ``recording.started``: New recording session started ``recording.stopped``: Current recording session stopped Args: notification (dictionary): Notification dictionary
625941c24f6381625f1149d0
def set_own_cert(self, cert, key, passwd=None): <NEW_LINE> <INDENT> cert_char = pynng.nng.to_char(cert) <NEW_LINE> key_char = pynng.nng.to_char(key) <NEW_LINE> passwd_char = pynng.nng.to_char(passwd) if passwd is not None else pynng.ffi.NULL <NEW_LINE> err = pynng.lib.nng_tls_config_own_cert(self._tls_config, cert_char, key_char, passwd_char) <NEW_LINE> pynng.check_err(err)
Configure own certificate and key.
625941c271ff763f4b54961c
def find(self, node, f): <NEW_LINE> <INDENT> if node in self._mancache: <NEW_LINE> <INDENT> mapping = self._mancache[node][0] <NEW_LINE> return mapping.get(f), mapping.flags(f) <NEW_LINE> <DEDENT> text = self.revision(node) <NEW_LINE> start, end = self._search(text, f) <NEW_LINE> if start == end: <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> l = text[start:end] <NEW_LINE> f, n = l.split('\0') <NEW_LINE> return revlog.bin(n[:40]), n[40:-1]
look up entry for a single file efficiently. return (node, flags) pair if found, (None, None) if not.
625941c263b5f9789fde7079
def run(self) -> None: <NEW_LINE> <INDENT> logging.info("%s", self._name) <NEW_LINE> team_urls = ScrapeFunctions.get_team_list( self.BASE_URL, self._year, self.TEAM_IDS ) <NEW_LINE> logging.info("Found %d teams to scrape", len(team_urls)) <NEW_LINE> for team in team_urls: <NEW_LINE> <INDENT> logging.info("Fetching %s", team.team) <NEW_LINE> url = f"{self.BASE_URL}{self._year}/{team.url}" <NEW_LINE> teamSoup = ScrapeFunctions.get_soup(url) <NEW_LINE> logging.info("Looking for game log table") <NEW_LINE> df = self._scrape(teamSoup) <NEW_LINE> logging.info("Cleaning scraped data") <NEW_LINE> df = self._clean(df, team.team) <NEW_LINE> self._data = pd.concat([self._data, df], ignore_index=True) <NEW_LINE> <DEDENT> self._runnable = False
Run the scraper
625941c266656f66f7cbc13e
def setEquipments(self,newEquipments): <NEW_LINE> <INDENT> if isinstance(newEquipments, Equipments) or newEquipments is None: <NEW_LINE> <INDENT> self._equipments = newEquipments <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('"equipments" attribute for a Game object must be a list')
Set the Equipments object of the current game Args: self: the Game object newEquipments: An Equipments object that represent all the private equipments of this player Returns: The Equipments object Raises: TypeError: Raise a TypeError if "newEquipments" is not an Equipments object
625941c25fc7496912cc3912
def test_process_pool_join_futures_timeout(self): <NEW_LINE> <INDENT> pool = ProcessPool(max_workers=1, context=mp_context) <NEW_LINE> for _ in range(2): <NEW_LINE> <INDENT> pool.schedule(long_function) <NEW_LINE> <DEDENT> pool.close() <NEW_LINE> self.assertRaises(TimeoutError, pool.join, 0.4) <NEW_LINE> pool.stop() <NEW_LINE> pool.join()
Process Pool Spawn TimeoutError is raised if join on long tasks.
625941c28e7ae83300e4af60
def __click_context_action_button(self, button_name): <NEW_LINE> <INDENT> logger.debug('click %s in context-action' %button_name) <NEW_LINE> buttons = self.find_elements(*self.__context_action_buttons_loc) <NEW_LINE> if len(buttons): <NEW_LINE> <INDENT> for button in buttons: <NEW_LINE> <INDENT> if button_name == button.text: <NEW_LINE> <INDENT> button.click() <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> raise NoSuchElementException('The button is failed to be located')
Click the button in context-action <div> by the provided name. It is for the row operation on report page :param button_name: str: button name :return:
625941c2e8904600ed9f1ebf
def lddmm_matching( I, J, m=None, lddmm_steps=1000, lddmm_integration_steps=10, reg_weight=1e-1, learning_rate_pose = 2e-2, fluid_params=[1.0,.1,.01], progress_bar=True ): <NEW_LINE> <INDENT> if m is None: <NEW_LINE> <INDENT> defsh = [I.shape[0], 3] + list(I.shape[2:]) <NEW_LINE> m = torch.zeros(defsh, dtype=I.dtype).to(I.device) <NEW_LINE> <DEDENT> do_regridding = m.shape[2:] != I.shape[2:] <NEW_LINE> J = J.to(I.device) <NEW_LINE> matchterms = [] <NEW_LINE> regterms = [] <NEW_LINE> losses = [] <NEW_LINE> metric = lm.FluidMetric(fluid_params) <NEW_LINE> m.requires_grad_() <NEW_LINE> pb = range(lddmm_steps) <NEW_LINE> if progress_bar: pb = tqdm(pb) <NEW_LINE> for mit in pb: <NEW_LINE> <INDENT> if m.grad is not None: <NEW_LINE> <INDENT> m.grad.detach_() <NEW_LINE> m.grad.zero_() <NEW_LINE> <DEDENT> m.requires_grad_() <NEW_LINE> h = lm.expmap(metric, m, num_steps=lddmm_integration_steps) <NEW_LINE> if do_regridding is not None: <NEW_LINE> <INDENT> h = lm.regrid(h, shape=I.shape[2:], displacement=True) <NEW_LINE> <DEDENT> Idef = lm.interp(I, h) <NEW_LINE> regterm = (metric.sharp(m)*m).mean() <NEW_LINE> matchterm = mse_loss(Idef, J) <NEW_LINE> matchterms.append(matchterm.detach().item()) <NEW_LINE> regterms.append(regterm.detach().item()) <NEW_LINE> loss = matchterm + reg_weight*regterm <NEW_LINE> loss.backward() <NEW_LINE> loss.detach_() <NEW_LINE> with torch.no_grad(): <NEW_LINE> <INDENT> losses.append(loss.detach()) <NEW_LINE> p = metric.flat(m.grad).detach() <NEW_LINE> if torch.isnan(losses[-1]).item(): <NEW_LINE> <INDENT> print(f"loss is NaN at iter {mit}") <NEW_LINE> break <NEW_LINE> <DEDENT> m.add_(-learning_rate_pose, p) <NEW_LINE> <DEDENT> <DEDENT> return m.detach(), [l.item() for l in losses], matchterms, regterms
Matching image I to J via LDDMM
625941c28a349b6b435e8107
def test_evangelical_church_day(self): <NEW_LINE> <INDENT> all_sessions = self.calendar.all_sessions <NEW_LINE> self.assertNotIn(pd.Timestamp('2019-10-31', tz=UTC), all_sessions) <NEW_LINE> self.assertNotIn(pd.Timestamp('2018-11-02', tz=UTC), all_sessions) <NEW_LINE> self.assertNotIn(pd.Timestamp('2017-10-27', tz=UTC), all_sessions) <NEW_LINE> self.assertNotIn(pd.Timestamp('2016-10-31', tz=UTC), all_sessions) <NEW_LINE> self.assertNotIn(pd.Timestamp('2014-10-31', tz=UTC), all_sessions)
Evangelical Church Day (also known as Halloween) adheres to the following rule: If October 31st falls on a Tuesday, it is observed the preceding Friday. If it falls on a Wednesday, it is observed the next Friday. If it falls on Thu, Fri, Sat, Sun, or Mon then the holiday is acknowledged that day.
625941c226238365f5f0ee00
def appendTail(self, value): <NEW_LINE> <INDENT> self.in_stack.append(value)
:type value: int :rtype: None
625941c2fb3f5b602dac3625
def get_rich_menu(self, rich_menu_id, timeout=None): <NEW_LINE> <INDENT> response = self._get( '/v2/bot/richmenu/{rich_menu_id}'.format(rich_menu_id=rich_menu_id), timeout=timeout ) <NEW_LINE> return RichMenuResponse.new_from_json_dict(response.json)
Call get rich menu API. https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu Get rich menu object through a given rich_menu_id :param str rich_menu_id: ID of the rich menu :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) float tuple. Default is self.http_client.timeout :type timeout: float | tuple(float, float) :return: RichMenuResponse instance :type RichMenuResponse: T <= :py:class:`linebot.models.reponse.RichMenuResponse`
625941c285dfad0860c3adee
def compute_cphase_exponents_for_fsim_decomposition( fsim_gate: 'cirq.FSimGate', ) -> Sequence[Tuple[float, float]]: <NEW_LINE> <INDENT> def nonempty_intervals( intervals: Sequence[Tuple[float, float]] ) -> Sequence[Tuple[float, float]]: <NEW_LINE> <INDENT> return tuple((a, b) for a, b in intervals if a < b) <NEW_LINE> <DEDENT> bound1 = abs(_asinsin(fsim_gate.theta)) <NEW_LINE> bound2 = abs(_asinsin(fsim_gate.phi / 2)) <NEW_LINE> min_exponent_1 = 4 * min(bound1, bound2) / np.pi <NEW_LINE> max_exponent_1 = 4 * max(bound1, bound2) / np.pi <NEW_LINE> assert min_exponent_1 <= max_exponent_1 <NEW_LINE> min_exponent_2 = 2 - max_exponent_1 <NEW_LINE> max_exponent_2 = 2 - min_exponent_1 <NEW_LINE> assert min_exponent_2 <= max_exponent_2 <NEW_LINE> if max_exponent_1 < min_exponent_2: <NEW_LINE> <INDENT> return nonempty_intervals( [(min_exponent_1, max_exponent_1), (min_exponent_2, max_exponent_2)] ) <NEW_LINE> <DEDENT> if max_exponent_2 < min_exponent_1: <NEW_LINE> <INDENT> return nonempty_intervals( [(min_exponent_2, max_exponent_2), (min_exponent_1, max_exponent_1)] ) <NEW_LINE> <DEDENT> min_exponent = min(min_exponent_1, min_exponent_2) <NEW_LINE> max_exponent = max(max_exponent_1, max_exponent_2) <NEW_LINE> return nonempty_intervals([(min_exponent, max_exponent)])
Returns intervals of CZPowGate exponents valid for FSim decomposition. Ideal intervals associated with the constraints are closed, but due to numerical error the caller should not assume the endpoints themselves are valid for the decomposition. See `decompose_cphase_into_two_fsim` for details on how FSimGate parameters constrain the phase angle of CZPowGate. Args: fsim_gate: FSimGate into which CZPowGate would be decomposed. Returns: Sequence of 2-tuples each consisting of the minimum and maximum value of the exponent for which CZPowGate can be decomposed into two FSimGates. The intervals are cropped to [0, 2]. The function returns zero, one or two intervals.
625941c28e05c05ec3eea307
def addArg(self, x, args): <NEW_LINE> <INDENT> from QGL.Channels import Qubit <NEW_LINE> if hasattr(x, "__iter__") and not isinstance(x, str) and not isinstance(x, QRegister): <NEW_LINE> <INDENT> for xx in x: <NEW_LINE> <INDENT> self.addArg(xx, args) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(x, QRegister): <NEW_LINE> <INDENT> for q in x.qubits: <NEW_LINE> <INDENT> if q not in self.qubits: <NEW_LINE> <INDENT> self.qubits.append(q) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif isinstance(x, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> idx = int(x[1:]) <NEW_LINE> <DEDENT> except ValueError as ve: <NEW_LINE> <INDENT> raise ValueError(f"QRegister names must be of the form q<int>: '{x}' (from args {args})") <NEW_LINE> <DEDENT> if idx not in self.qubits: <NEW_LINE> <INDENT> self.qubits.append(idx) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(x, Qubit): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> idx = int(x.label[1:]) <NEW_LINE> <DEDENT> except ValueError as ve: <NEW_LINE> <INDENT> raise ValueError(f"QRegister names must be of the form q<int>: '{x}' (from args {args})") <NEW_LINE> <DEDENT> if idx not in self.qubits: <NEW_LINE> <INDENT> self.qubits.append(idx) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(x, QReference): <NEW_LINE> <INDENT> self.addArg(x.ref.qubits[x.idx], args) <NEW_LINE> <DEDENT> elif isinstance(x, int): <NEW_LINE> <INDENT> if x not in self.qubits: <NEW_LINE> <INDENT> self.qubits.append(x) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise NameError(f"Invalid QRegister constructor 'QRegister({args})'; arg {x} unknown.")
Parse one argument to the QRegister constructor. A recursive function.
625941c23346ee7daa2b2cff
def test_is_valid_request(self): <NEW_LINE> <INDENT> primitive = C_MOVE() <NEW_LINE> assert not primitive.is_valid_request <NEW_LINE> primitive.MessageID = 1 <NEW_LINE> assert not primitive.is_valid_request <NEW_LINE> primitive.AffectedSOPClassUID = '1.2' <NEW_LINE> assert not primitive.is_valid_request <NEW_LINE> primitive.Priority = 2 <NEW_LINE> assert not primitive.is_valid_request <NEW_LINE> primitive.MoveDestination = b'1234567890123456' <NEW_LINE> assert not primitive.is_valid_request <NEW_LINE> primitive.Identifier = BytesIO() <NEW_LINE> assert primitive.is_valid_request
Test C_MOVE.is_valid_request
625941c24527f215b584c3ee
def get_object(self, **kwargs): <NEW_LINE> <INDENT> return StudentAchievement.objects.get(id=self.kwargs['pk'])
Return object for user
625941c2498bea3a759b9a44
def listcomponents(module_location): <NEW_LINE> <INDENT> components = [] <NEW_LINE> counter = 0 <NEW_LINE> LOGGER.info("Searching for components in %s." % module_location) <NEW_LINE> for posloc in os.listdir(module_location): <NEW_LINE> <INDENT> if os.path.isdir(os.path.join(module_location, posloc)) and posloc.startswith("ncm-"): <NEW_LINE> <INDENT> components.append(posloc) <NEW_LINE> LOGGER.debug("Adding %s to component list." % posloc) <NEW_LINE> counter += 1 <NEW_LINE> <DEDENT> <DEDENT> LOGGER.info("Found %s components." % counter) <NEW_LINE> return components
return a list of components in module_location.
625941c2cb5e8a47e48b7a41
def add_submenu(submenu, title): <NEW_LINE> <INDENT> __GUI_CONTROLLER.menu = dict(submenu=submenu.menu, title=title)
Menu setter. Provides access to set the private property `__GUI_CONTROLLER.menu`. Note: See `__GUI_CONTROLLER.menu` for more information.
625941c28a43f66fc4b53ffb
def base_delete_one(self, p_id): <NEW_LINE> <INDENT> result = self._resource.id(p_id).delete({}) <NEW_LINE> self.print_res(result) <NEW_LINE> assert 0 == result.code <NEW_LINE> assert result.data <NEW_LINE> return result
:param p_id: :return:
625941c2d6c5a10208143fdd
def _get_dtype(self, dtype): <NEW_LINE> <INDENT> if dtype not in (np.float32, np.float64, np.complex64, np.complex128): <NEW_LINE> <INDENT> raise TypeError('Array is of an unsupported dtype.') <NEW_LINE> <DEDENT> self.dtype = dtype <NEW_LINE> cuda_dict = {np.float32: 'float', np.float64: 'double', np.complex64: 'pycuda::complex<float>', np.complex128: 'pycuda::complex<double>'} <NEW_LINE> self.cuda_type = cuda_dict[self.dtype]
Certify that the dtype is valid, and find the cuda datatype.
625941c291f36d47f21ac485
def test_no_url(self): <NEW_LINE> <INDENT> self.disp.push(events.COMMAND, "pepe", "canal", "foto", "pepe") <NEW_LINE> self.assertEqual(self.answer[0][1], u"pepe: doesn't have configured URL") <NEW_LINE> self.disp.push(events.PRIVATE_MESSAGE, "pepe", "foto pepe") <NEW_LINE> self.assertEqual(self.answer[0][1], u"pepe: doesn't have configured URL")
No url configured.
625941c29b70327d1c4e0d69
def encode(hrp, witver, witprog): <NEW_LINE> <INDENT> spec = Encoding.BECH32 if witver == 0 else Encoding.BECH32M <NEW_LINE> ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5), spec) <NEW_LINE> if decode(hrp, ret) == (None, None): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return ret
Encode a segwit address.
625941c2cdde0d52a9e52fc5