code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def errmsg(self): <NEW_LINE> <INDENT> pass
Get the reason authentication failed.
625941db07f4c71912b1175f
def gaussian_elimination(A: np.ndarray, b: np.ndarray, use_pivoting: bool = True) -> (np.ndarray, np.ndarray): <NEW_LINE> <INDENT> A = A.copy() <NEW_LINE> b = b.copy() <NEW_LINE> z,s = np.shape(A) <NEW_LINE> if(z != s) : <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> n = len(b) <NEW_LINE> if(z != n) : <NEW_LI...
Gaussian Elimination of Ax=b with or without pivoting. Arguments: A : matrix, representing left side of equation system of size: (m,m) b : vector, representing right hand side of size: (m, ) use_pivoting : flag if pivoting should be used Return: A : reduced result matrix in row echelon form (type: np.ndarray, size: (...
625941db925a0f43d254a154
def __serverStop(self): <NEW_LINE> <INDENT> self.mangosd.communicate(b'server shutdown 1') <NEW_LINE> print('mangosd exited with: {}'.format(self.mangosd.wait())) <NEW_LINE> self.mangosd = None <NEW_LINE> self.realmd.send_signal(SIGINT) <NEW_LINE> print('realmd exited with: {}'.format(self.realmd.wait())) <NEW_LINE> se...
Stop both server processes
625941dbcad5886f8bd272b4
def get_context(self): <NEW_LINE> <INDENT> c = {} <NEW_LINE> if self._has_device(): <NEW_LINE> <INDENT> c.update( { 'id': str(self.device.id), 'key': self.key, 'name': self.name, 'mac_address': self.mac_address, } ) <NEW_LINE> if self.context: <NEW_LINE> <INDENT> c.update(self.context) <NEW_LINE> <DEDENT> <DEDENT> c.up...
additional context passed to netjsonconfig
625941db67a9b606de4a8192
def __repr__(self): <NEW_LINE> <INDENT> return '<Twilio.Api.V2010.ApplicationList>'
Provide a friendly representation :returns: Machine friendly representation :rtype: str
625941db55399d3f05588990
@app.route('/convert') <NEW_LINE> def convert(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> validate(request.args.to_dict(), convert_schema) <NEW_LINE> <DEDENT> except ValidationError as ve: <NEW_LINE> <INDENT> return ve.message, 400 <NEW_LINE> <DEDENT> amount = float(request.args.get('amount')) <NEW_LINE> src_curren...
Converts the pr​ovided `amount` from​ `​src_currency` to `​​dest_currency`, given the exchange rate at the `​reference_date`. Returns a json with the converted amount. An example of call: /convert?amount=10&src_currency=EUR&des​t_currency=GBP&reference_date=2019-11-28 An example of response: { “amount”: 8.518, ...
625941dbad47b63b2c50a259
def test_integerproperty(self): <NEW_LINE> <INDENT> class TestClass(object): <NEW_LINE> <INDENT> test_a = burger.IntegerProperty('_test_a') <NEW_LINE> test_b = burger.IntegerProperty('_test_b') <NEW_LINE> test_c = burger.IntegerProperty('_test_c') <NEW_LINE> test_d = burger.IntegerProperty('_test_d') <NEW_LINE> def __i...
Test burger.IntegerProperty()
625941db1d351010ab855df6
def record_component_to_daskarray(record_component): <NEW_LINE> <INDENT> if not found_dask: <NEW_LINE> <INDENT> raise ImportError("dask NOT found. Install dask for Dask DataFrame " "support.") <NEW_LINE> <DEDENT> chunks = record_component.available_chunks() <NEW_LINE> offsets_per_dim = list(map(list, zip(*[chunk.offset...
Load a RecordComponent into a Dask.array. Parameters ---------- record_component : openpmd_api.Record_Component A record component class in openPMD-api. Returns ------- dask.array A dask array. Raises ------ ImportError Raises an exception if dask is not installed See Also -------- openpmd_api.BaseRecor...
625941db23e79379d52ee83c
def create_function(self, instance, code): <NEW_LINE> <INDENT> method_dict = {} <NEW_LINE> methodName = self.get_signature_string(code) <NEW_LINE> exec(code.strip(), globals(), method_dict) <NEW_LINE> setattr(instance, methodName, method_dict[methodName]) <NEW_LINE> return instance.__dict__[methodName]
Method to create a function/method given a code in python and set it to a given instance. :param instance: object to set the code given in the parameters of this method :type instance: <type 'instance'> :param code: String containing the code to set to the object :type code: str
625941dbd18da76e235327b3
def check_squares(self): <NEW_LINE> <INDENT> for a in range(9): <NEW_LINE> <INDENT> for num in range(1, 10): <NEW_LINE> <INDENT> if num not in self.squares[a]: <NEW_LINE> <INDENT> spots = 0 <NEW_LINE> for b in range(9): <NEW_LINE> <INDENT> pos = self.pos_from_square(a, b) <NEW_LINE> if num in self.allowed[pos]: <NEW_LI...
For each 3x3 square in the game, check if any numbers only has 1 possible spot that they can go in that square
625941db8c0ade5d55d3ec98
def logger_setup(): <NEW_LINE> <INDENT> logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename='pyvmax.log', filemode='w') <NEW_LINE> console = logging.StreamHandler() <NEW_LINE> console.setLevel(logging.WARNING) <NEW_LINE> formatter = logg...
setup the style and defults of the python logger Args: Returns: Raises:
625941db3617ad0b5ed681d1
def testFindDirectories(self): <NEW_LINE> <INDENT> client_mock = action_mocks.ActionMock(searching.Find) <NEW_LINE> findspec = rdf_client.FindSpec( path_regex="bin", pathspec=rdf_paths.PathSpec( path="/", pathtype=rdf_paths.PathSpec.PathType.OS)) <NEW_LINE> for s in test_lib.TestFlowHelper( "FindFiles", client_mock, cl...
Test that the Find flow works with directories.
625941dbfff4ab517eb2f718
def _K_(self, x1, x2): <NEW_LINE> <INDENT> if self.kernel == 'linear': <NEW_LINE> <INDENT> return sum([x1[k] * x2[k] for k in range(self.n)]) <NEW_LINE> <DEDENT> if self.kernel == 'poly': <NEW_LINE> <INDENT> return (sum([x1[k] * x2[k] for k in range(self.n)])+1)**3 <NEW_LINE> <DEDENT> print ('没有定义核函数') <NEW_LINE> retur...
核函数
625941dbeab8aa0e5d26de34
def levelOrder(self, root): <NEW_LINE> <INDENT> A = [] <NEW_LINE> if root: <NEW_LINE> <INDENT> self.level(A, root, 0) <NEW_LINE> <DEDENT> return A
:type root: TreeNode :rtype: List[List[int]]
625941db26068e7796caefbd
def load_words(): <NEW_LINE> <INDENT> with open(DICTIONARY) as d: <NEW_LINE> <INDENT> words = [word for word in d.read().split() if word != ''] <NEW_LINE> <DEDENT> return words
Load dictionary into a list and return list
625941db71ff763f4b54996b
def _parse(self, soup: BeautifulSoup) -> pd.DataFrame: <NEW_LINE> <INDENT> left = soup.find('div', 'left').div <NEW_LINE> main = soup.find('div', 'main').find('div', 'rf_table') <NEW_LINE> year = main.find('div', {'id': 'Year'}) <NEW_LINE> self._year_ids = [node.attrs['id'] for node in year] <NEW_LINE> period_month = p...
Extracts and returns a pandas.DataFrame corresponding to the given parsed HTML response from financials.morningstar.com. :param soup: Parsed HTML response by BeautifulSoup. :return pandas.DataFrame corresponding to the given parsed HTML response from financials.morningstar.com.
625941db283ffb24f3c55bda
def write(self, s): <NEW_LINE> <INDENT> h = self.handle <NEW_LINE> try: <NEW_LINE> <INDENT> r = h.write(s) <NEW_LINE> h.flush() <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> r = None <NEW_LINE> <DEDENT> return r
Writes to this thread's handle. This also flushes, just to be extra sure the string was written.
625941db0fa83653e4657295
def initBannerCanvas( numChars, numLines ): <NEW_LINE> <INDENT> canvas_height = 80 * numLines <NEW_LINE> canvas_width = 80 * numChars <NEW_LINE> turtle.setup( canvas_width, canvas_height ) <NEW_LINE> height = 30 <NEW_LINE> width = 30 * numChars <NEW_LINE> margin = 5 <NEW_LINE> turtle.setworldcoordinates( -margin+1, -m...
Set up the drawing canvas to draw a banner numChars wide and numLines high. The coordinate system used assumes all characters are 20x20 and there are 10-point spaces between them. Postcondition: The turtle's starting position is at the bottom left corner of where the first character should be displayed.
625941db3d592f4c4ed1d343
def rowCount(self, parent): <NEW_LINE> <INDENT> if not parent.isValid(): <NEW_LINE> <INDENT> parentNode = self._rootNode <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parentNode = parent.internalPointer() <NEW_LINE> <DEDENT> return parentNode.childCount()
Returns the number of rows under the given /parent/. When the parent is valied it means that rowCount is returning the number of children of parent. Paramters --------- parent : view_model.TreeNode The parent node of the current node. Returns ------- row_count : int The number of children of the parent node.
625941db442bda511e8be6f0
def test_get_host_config(self): <NEW_LINE> <INDENT> request = Host.GetConfigRequest() <NEW_LINE> response = self.host_client.get_host_config(request) <NEW_LINE> assert_that(response.hostConfig.agent_id, matches_regexp("[0-9a-f-]{36}")) <NEW_LINE> datastores = response.hostConfig.datastores <NEW_LINE> assert_that(datast...
Test that the agent responds with Host configuration
625941db66673b3332b9236d
def update_file(shop, cost, datafile): <NEW_LINE> <INDENT> df = open(datafile, 'w') <NEW_LINE> df.write(shop + "," + str(cost)) <NEW_LINE> df.close()
Create or overwrite data to given file in cwd
625941db8a349b6b435e844e
def _find_summary_info(self): <NEW_LINE> <INDENT> summary = super(RegionMappingScientific, self)._find_summary_info() <NEW_LINE> summary.update({"Source Surface": self.surface.display_name, "Source Surface GID": self.surface.gid, "Connectivity GID": self.connectivity.gid, "Connectivity": self.connectivity.display_name}...
Gather scientifically interesting summary information from an instance of this datatype.
625941db2c8b7c6e89b35a9b
def log(self, name, value, step=None): <NEW_LINE> <INDENT> if name not in self._metrics: <NEW_LINE> <INDENT> self.add_metric(name) <NEW_LINE> <DEDENT> metric_to_log = self._metrics[name] <NEW_LINE> if step is None: <NEW_LINE> <INDENT> step = len(metric_to_log) - 1 <NEW_LINE> <DEDENT> metric_to_log.append((step, value))
Args: name(str): name of the metric value(float or int): value of the metric step(int): optional step
625941db0383005118ecf8bd
def biweightLocation(dataList, tuningConstant): <NEW_LINE> <INDENT> C=tuningConstant <NEW_LINE> listMedian=median(dataList) <NEW_LINE> listMAD=MAD(dataList) <NEW_LINE> if listMAD!=0: <NEW_LINE> <INDENT> uValues=[] <NEW_LINE> for item in dataList: <NEW_LINE> <INDENT> uValues.append((item-listMedian)/(C*listMAD)) <NEW_LI...
Calculates the biweight location estimator (like a robust average) of a list of numbers. @type dataList: list @param dataList: input data, must be a one dimensional list @type tuningConstant: float @param tuningConstant: 6.0 is recommended. @rtype: float @return: biweight location @note: Returns None if an error occu...
625941db56ac1b37e62644a6
def apply( self ): <NEW_LINE> <INDENT> result1Number, result2Number = self.selectVariable1.get(), self.selectVariable2.get() <NEW_LINE> cb1result = self.cb1.get() <NEW_LINE> bookResult = [None,'Current','All','OT','NT','None'] <NEW_LINE> fillResult = [None,'Versification','Version','Basic','None'] <NEW_LINE> self.resul...
Override the empty ModalDialog.apply function to process the results how we need them. Results are left in self.result
625941dba4f1c619b28b030f
def validate_rake_aggregate(dataset, lvl_locs, parent, status): <NEW_LINE> <INDENT> child = dataset.sel(location_id=lvl_locs) <NEW_LINE> par = dataset.sel(location_id=parent) <NEW_LINE> child = np.round( ((child['est'] * child['population']).sum(dim='location_id'))) <NEW_LINE> par = np.round(par['est'] * (par['populati...
Validates that population-weighted summed subnational estimates equal parent est*pop
625941db5166f23b2e1a5434
def getcwd(self): <NEW_LINE> <INDENT> host_context_path = [ (self._expand_tilde(path) if expand else path) for path, expand in self.host_context._path ] <NEW_LINE> path = os.path.normpath(os.path.join(*[ self.get_start_path() ] + host_context_path)) <NEW_LINE> assert path[0] == '/' <NEW_LINE> return path
Return current working directory as absolute path.
625941db5510c4643540f6b9
def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'mirror_proxy': 'str', 'sync_priority': 'str' } <NEW_LINE> self.attribute_map = { 'mirror_proxy': 'mirrorProxy', 'sync_priority': 'syncPriority' } <NEW_LINE> self._mirror_proxy = None <NEW_LINE> self._sync_priority = None
MirrorSyncPriorityDescriptor - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
625941db56b00c62f0f14936
def test_xux_menu(self): <NEW_LINE> <INDENT> Homes = Home(self.autoDriver, self.baseUrl) <NEW_LINE> Homes.MMLP() <NEW_LINE> Homes.FMBK() <NEW_LINE> Homes.SmallBear() <NEW_LINE> Homes.Shopping_cart() <NEW_LINE> Homes.Personal_center()
测试用例:未登录情况下,检验前端菜单栏链接是否正常 :return:
625941dbfff4ab517eb2f719
def _forward(self, data, fn=None, batchsize=16, converter=concat_examples, retain_inputs=False, preprocess_fn=None, postprocess_fn=None): <NEW_LINE> <INDENT> input_list = None <NEW_LINE> output_list = None <NEW_LINE> it = SerialIterator(data, batch_size=batchsize, repeat=False, shuffle=False) <NEW_LINE> for batch in it...
Forward data by iterating with batch Args: data: "train_x array" or "chainer dataset" fn (Callable): Main function to forward. Its input argument is either Variable, cupy.ndarray or numpy.ndarray, and returns Variable. batchsize (int): batch size converter (Callable): convert from `data...
625941dbe64d504609d74b1b
def test_basic_behaviour(self): <NEW_LINE> <INDENT> fhand = NamedTemporaryFile() <NEW_LINE> engine = sqlalchemy.create_engine('sqlite:///:memory:') <NEW_LINE> create_naming_database(engine) <NEW_LINE> add_project_to_naming_database(engine, name='my_project', code='my', description='a test project') <NEW_LINE> naming = ...
It tests that we can get names using a FileNamingSchema
625941db71ff763f4b54996c
def afterTest(self, test): <NEW_LINE> <INDENT> pass
Called after the test has been run and the result recorded (after stopTest). :param test: the test case :type test: :class:`nose.case.Test`
625941db38b623060ff0b0c9
@components.command() <NEW_LINE> @click.option(*OPTIONS_PROJECT["args"], **OPTIONS_PROJECT["kwargs"]) <NEW_LINE> @click.option( "--query", "-q", type=str, help="To filter the component versions based on this query spec.", ) <NEW_LINE> @click.option( "--sort", "-s", type=str, help="To order the component versions based ...
List component versions by project or owner/project. Examples:  $ polyaxon components ls -p=kaniko  $ polyaxon components ls -p=acme/kaniko
625941db851cf427c661a7e8
def initialize(self): <NEW_LINE> <INDENT> LOG.info("Starting OVNMechanismDriver") <NEW_LINE> self._nb_ovn = None <NEW_LINE> self._sb_ovn = None <NEW_LINE> self._plugin_property = None <NEW_LINE> self._ovn_client = None <NEW_LINE> self.sg_enabled = ovn_acl.is_sg_enabled() <NEW_LINE> if cfg.CONF.SECURITYGROUP.firewall_dr...
Perform driver initialization. Called after all drivers have been loaded and the database has been initialized. No abstract methods defined below will be called prior to this method being called.
625941db1f5feb6acb0c4e27
def add_player(self, node_id): <NEW_LINE> <INDENT> if self.__accept_player: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self._lock.acquire(timeout=self.__timeout): <NEW_LINE> <INDENT> if node_id in self.__players: <NEW_LINE> <INDENT> raise PlayerAlreadyRegisteredException(node_id) <NEW_LINE> <DEDENT> node = {} <NEW...
:param node_id: repmgr node id. In order to add a new player, set_accept_player must set to True. Otherwise, PlayerDelayedRegistrationException will raise
625941db4f6381625f114d17
def apply(self, src, effect, value, rgb, trans): <NEW_LINE> <INDENT> return QImage()
QImage KIconEffect.apply(QImage src, int effect, float value, QColor rgb, bool trans)
625941db30dc7b7665901c3f
def __init__(self, default_value='', min=0, max=10000, step=1, **kwargs): <NEW_LINE> <INDENT> super(Slider, self).__init__('range', default_value, **kwargs) <NEW_LINE> self.attributes['min'] = str(min) <NEW_LINE> self.attributes['max'] = str(max) <NEW_LINE> self.attributes['step'] = str(step) <NEW_LINE> self.attributes...
Args: default_value (str): min (int): max (int): step (int): kwargs: See Widget.__init__()
625941db7047854f462a16e2
def process_undirected(binary_file, output_fp, ontology, logfile_fp, counts): <NEW_LINE> <INDENT> input_fp = open(binary_file, 'rU') <NEW_LINE> scanner = parse_mitab_file(input_fp, full_mitab_iterator) <NEW_LINE> offsets_map = _consume_undirected_offsets_only(scanner) <NEW_LINE> sorted_keys = sorted(offsets_map.iterkey...
Process all 'other' interactions - undirected physical interactions. Write consolidated interactions to output_fp.
625941dbe76e3b2f99f3aae3
def test_has_outdated_cache_raises_error_for_bad_source(empty_cache): <NEW_LINE> <INDENT> with pytest.raises(TypeError): <NEW_LINE> <INDENT> empty_cache.has_outdated_cache('http://t.co/')
Test has_outdated_cache raises TypeError for non MangaSource source.
625941dbadb09d7d5db6ca6a
def file_save(self, remove_existing=False, write_empty=False, dry_run=False): <NEW_LINE> <INDENT> raise NotImplementedError
saves file tags from tag dictionary (dict_meta) to AudioFile. Args: remove_existing (bool): if true clear all tags before writing. Defaults to False. write_empty (bool): if true write tags with Empty Value, if false, the tag will not be created and a existing tag will be deleted. Be...
625941db566aa707497f4841
def decompress(file_name): <NEW_LINE> <INDENT> if not os.path.isfile(file_name): <NEW_LINE> <INDENT> raise ValueError("Can not find file '{}'".format(file_name)) <NEW_LINE> <DEDENT> _, ext = os.path.splitext(file_name) <NEW_LINE> _open = None <NEW_LINE> if ext == ".tab": <NEW_LINE> <INDENT> _open = open <NEW_LINE> <DED...
Compression-agnostic iterator. Iterate over files on the archive and return a tuple of file name, line count and file descriptor. Supported file formats are .tab, .gz and .zip.
625941db187af65679ca53fb
def extractSegmentByDirAndStartPoint(self, walkingDir=0.0, startPoint=(1.2, 1.7)): <NEW_LINE> <INDENT> normalWalkDir = angleNormalize(walkingDir) <NEW_LINE> startX = startPoint[0] <NEW_LINE> startY = startPoint[1] <NEW_LINE> candidateList = [] <NEW_LINE> for id, attr in self.nodesDict.iteritems(): <NEW_LINE> <INDENT> f...
[startX, startY, endX, endY, ['s1', 's2', ..., 'sk'], probLastTime, probCurrent, pLastSegment, extendStatus] :param walkingDir: base direction to select segments candidate :return: segments candidate, the pLastProb is set to minProb firstly, and the extend status is set to zero, (0, 1, ..., possible counter num in a st...
625941db7c178a314d6ef73f
def iNexpo2(prob, means): <NEW_LINE> <INDENT> _assertprob(prob, 'iNexpo2') <NEW_LINE> if len(means) == 1: <NEW_LINE> <INDENT> x = iexpo(prob, means[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> def _fifi2fid(x): <NEW_LINE> <INDENT> x = kept_within(0.0, x) <NEW_LINE> cdf = cNexpo2(means, x) <NEW_LINE> pdf ...
A distribution of a sum of exponential random variables. NB No two means are allowed to be equal!!!!
625941dbd486a94d0b98e423
def parse_date(datestring, yeardigits=4, expanded=False): <NEW_LINE> <INDENT> if yeardigits != 4: <NEW_LINE> <INDENT> expanded = True <NEW_LINE> <DEDENT> isodates = build_date_regexps(yeardigits, expanded) <NEW_LINE> for pattern in isodates: <NEW_LINE> <INDENT> match = pattern.match(datestring) <NEW_LINE> if match: <NE...
Parse an ISO 8601 date string into a datetime.date object. As the datetime.date implementation is limited to dates starting from 0001-01-01, negative dates (BC) and year 0 can not be parsed by this method. For incomplete dates, this method chooses the first day for it. For instance if only a century is given, this me...
625941db8a43f66fc4b5433e
def test_example_post_force(self): <NEW_LINE> <INDENT> blog_entry_uri, blog_entry = self.tastyfactory['entry'].create() <NEW_LINE> post_data = self.tastyfactory['comment'].create_post_data( entry=blog_entry) <NEW_LINE> self.assertInstanceOf(dict, post_data) <NEW_LINE> self.assertEquals(blog_entry_uri, post_data['entry'...
When creating mockup test data, foreign rels can be forced.
625941db29b78933be1e5983
def capture_function(func, *args, **kwargs): <NEW_LINE> <INDENT> pipes = {} <NEW_LINE> for i in ("stdin", "stdout", "stderr", "return_value"): <NEW_LINE> <INDENT> read_end, write_end = os.pipe() <NEW_LINE> pipes[i] = (os.fdopen(read_end, "r"), os.fdopen(write_end, "w")) <NEW_LINE> <DEDENT> child_pid = os.fork() <NEW_LI...
Executes a function and captures anything it prints to standard output or standard error, along with capturing its return value. :param func: The function to execute and capture. :param \*args,\*\*kwargs: The arguments to pass to the function. :returns: An instance of :class:`CapturedFunction`. >>> def foo(x, c = 3):...
625941db5166f23b2e1a5435
def contains_object(object_element, search_from_element): <NEW_LINE> <INDENT> key_identifier_value = next( iter_elements(object_element, 'objectIdentifierValue') ) <NEW_LINE> identifiers = iter_elements(search_from_element, 'objectIdentifierValue') <NEW_LINE> for identifier_value in identifiers: <NEW_LINE> <INDENT> if ...
Return True if `search_from_element` contains the `object_element` object or objectIdentifier. :object_element: PREMIS object or identifier :search_from_element: PREMIS object to search from :returns: Boolean
625941db23849d37ff7b3369
def minCost(self, houses, cost, m, n, target): <NEW_LINE> <INDENT> dp = [[[float('inf')]*(n+1) for _ in xrange(target+1)] for _ in xrange(m+1)] <NEW_LINE> for i in xrange(n+1): dp[0][0][i] = 0 <NEW_LINE> for i in xrange(1, m+1): <NEW_LINE> <INDENT> for j in xrange(1, target+1): <NEW_LINE> <INDENT> if houses[i-1] == 0: ...
:type houses: List[int] :type cost: List[List[int]] :type m: int :type n: int :type target: int :rtype: int
625941db8a349b6b435e844f
def timestamp_index_to_seconds(self, index): <NEW_LINE> <INDENT> return math.floor(self.video_length * index / self.timestamp_num)
Converts a timestamp index to its corresponding time in the video in seconds :param index: integer representing the timestamp index :return: integer representing the seconds in the video specified by the timestamp index
625941db5fc7496912cc3c5a
def LocateElement(self, data): <NEW_LINE> <INDENT> i = self.link[0].next <NEW_LINE> while i and self.link[i] != data: <NEW_LINE> <INDENT> i = self.link[i].next <NEW_LINE> <DEDENT> return i
定位第一个与data值相同的节点,并返回该节点的下标
625941db8e05c05ec3eea652
def test_filter_dataframe(): <NEW_LINE> <INDENT> df = DataFrame(DataFrame({'a': [1, 2, 1], 'b': [2, 3, 2], 'c': [0, 1, 2]})) <NEW_LINE> result = filter_dataframe(df, {'a': 1, 'b': 2}) <NEW_LINE> assert len(result) == 2 <NEW_LINE> assert all(result['a'] == 1) <NEW_LINE> assert all(result['b'] == 2) <NEW_LINE> result = f...
Test `filter_dataframe()` function.
625941db3317a56b86939f2e
@app.route('/images', methods=['GET']) <NEW_LINE> def images_index(): <NEW_LINE> <INDENT> output = docker('image', 'ls') <NEW_LINE> resp = json.dumps(docker_images_to_array(output)) <NEW_LINE> return Response(response=resp, mimetype="application/json")
List all images Complete the code below generating a valid response.
625941db2eb69b55b151cb8e
def get_gradient(self): <NEW_LINE> <INDENT> return self.gradient
获取当前的梯度
625941db4d74a7450ccd449f
def estimate_incumbent(self, startpoints=None): <NEW_LINE> <INDENT> best = np.argmin(self.model.Y) <NEW_LINE> incumbent = self.model.X[best] <NEW_LINE> incumbent_value = self.model.Y[best] <NEW_LINE> return incumbent[np.newaxis, :], incumbent_value[:, np.newaxis]
Estimates the current incumbent. Note: this is just a lookup of the observation that has been made so far and thus do not need any startpoints. Parameters ---------- startpoints : (N, D) numpy array In the case of local search, we start form each point a separated local search procedure Returns ------- np.nda...
625941dbd7e4931a7ee9e1fa
def _EnsureCorrectGanetiVersion(cmd): <NEW_LINE> <INDENT> logging.debug("Ensure correct Ganeti version: %s", cmd) <NEW_LINE> version = constants.DIR_VERSION <NEW_LINE> all_cmds = [["test", "-d", os.path.join(pathutils.PKGLIBDIR, version)]] <NEW_LINE> if constants.HAS_GNU_LN: <NEW_LINE> <INDENT> all_cmds.extend([["ln", ...
Ensured the correct Ganeti version before running a command via SSH. Before a command is run on a node via SSH, it makes sense in some situations to ensure that this node is indeed running the correct version of Ganeti like the rest of the cluster. @type cmd: string @param cmd: string @rtype: list of strings @return:...
625941db63d6d428bbe447cc
@login_required <NEW_LINE> def create_team(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> form = TeamForm(request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> new_team = form.save() <NEW_LINE> Membership.objects.create(user=request.user, team=new_team, role=Membership.ADMIN) ...
Page for the creation of a new Team. A new Membership object will be created for the User creating the Team with role ADMIN.
625941db4d74a7450ccd44a0
def lists_to_flat_list(list_of_lists): <NEW_LINE> <INDENT> assert isinstance(list_of_lists, list) <NEW_LINE> for _list in list_of_lists: <NEW_LINE> <INDENT> assert isinstance(_list, list) <NEW_LINE> <DEDENT> return [item for sublist in list_of_lists for item in sublist]
Transforms list of lists into one list.
625941db8e05c05ec3eea653
def Delete(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Delete') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params)
Requests deletion of a Folder. The Folder is moved into the. [DELETE_REQUESTED] state immediately, and is deleted approximately 30 days later. This method may only be called on an empty Folder in the [ACTIVE] state, where a Folder is empty if it doesn't contain any Folders or Projects in the [ACTIVE] state. The caller ...
625941db32920d7e50b284ae
def load_image(name, colorkey=None): <NEW_LINE> <INDENT> fullname = os.path.join('data', name) <NEW_LINE> if not os.path.isfile(fullname): <NEW_LINE> <INDENT> print(f"Файл с изображением '{fullname}' не найден") <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> image = pygame.image.load(fullname) <NEW_LINE> if colorkey is not ...
загрузка изображений
625941dbfb3f5b602dac3972
def to_cpu(self): <NEW_LINE> <INDENT> if self.data is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._data = [cuda.to_cpu(self.data)] <NEW_LINE> node = self._node <NEW_LINE> if node._data is not None: <NEW_LINE> <INDENT> node.retain_data() <NEW_LINE> <DEDENT> if node._grad is not None: <NEW_LINE> <INDENT> no...
Copies the data and gradient arrays to CPU.
625941db56b00c62f0f14937
def get_module_docs_archive_path(self, module_name): <NEW_LINE> <INDENT> docs_path = os.path.join(config.MODULES_SRC, module_name, 'docs') <NEW_LINE> if not os.path.exists(docs_path): <NEW_LINE> <INDENT> self.logger.error('Docs directory for module "%s" does not exist' % (module_name)) <NEW_LINE> return False <NEW_LINE...
Display module docs archive path if exists
625941db30dc7b7665901c40
def time_vis(func): <NEW_LINE> <INDENT> N = 1000 <NEW_LINE> n = list(range(N)) <NEW_LINE> t = [] <NEW_LINE> for i in range(N): <NEW_LINE> <INDENT> data = list(range(3 * n[i] )) <NEW_LINE> data = random.sample(data, k = 3 * n[i]) <NEW_LINE> time_start = time.time() <NEW_LINE> func(data) <NEW_LINE> time_end = time.time()...
将不同规模下所需要的排序时间绘制为散点图 @func:输入进来的函数;格式为func(input_array)
625941dba8ecb033257d33a8
def set_xyz(self, x: float, y: float, z: float) -> None: <NEW_LINE> <INDENT> self.coord[0] = x <NEW_LINE> self.coord[1] = y <NEW_LINE> self.coord[2] = z
This method re-sets all x, y and z coordinates of the atom. :param x: Sets the cartesion x-coordinate of the atom to x. :param y: Sets the cartesion y-coordinate of the atom to y. :param z: Sets the cartesion x-coordinate of the atom to z. :return: None
625941db167d2b6e31218e71
def local(self): <NEW_LINE> <INDENT> flags = 0 <NEW_LINE> error = self.client.device_local(self.link, flags, self.lock_timeout, self.io_timeout) <NEW_LINE> if error: <NEW_LINE> <INDENT> raise Vxi11Error("error local: %d" % error)
Send local command
625941dbbd1bec0571d9090b
def Complete8Rows(self): <NEW_LINE> <INDENT> aRowFilled = False <NEW_LINE> rowNum = 0 <NEW_LINE> for row in self.tiles: <NEW_LINE> <INDENT> if list(row).count(0) == 1: <NEW_LINE> <INDENT> colNum = 0 <NEW_LINE> for i in row: <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> self.SetValue(45 - sum(row), rowNum, colNum) ...
Complete rows of 8 with last missing number return True if at least 1 value added
625941dbbe383301e01b575d
def ajouter_commandes(self): <NEW_LINE> <INDENT> self.commandes = [ commandes.acheter.CmdAcheter(), commandes.info.CmdInfo(), commandes.lister.CmdLister(), commandes.questeur.CmdQuesteur(), commandes.vendre.CmdVendre(), ] <NEW_LINE> for cmd in self.commandes: <NEW_LINE> <INDENT> importeur.interpreteur.ajouter_commande(...
Ajout des commandes
625941db94891a1f4081bd87
def test_keep_only_empty(self): <NEW_LINE> <INDENT> with open('keep_only_empty.txt', encoding="utf-8", errors="ignore") as skip_file: <NEW_LINE> <INDENT> skip_handler = skiplist_handler.SkipListHandler(skip_file.read()) <NEW_LINE> <DEDENT> with open('x.plist', 'rb') as plist_data: <NEW_LINE> <INDENT> data = remove_repo...
Test skipping all files except empty.
625941db6aa9bd52df037081
def write(self): <NEW_LINE> <INDENT> ext = os.path.splitext(self.file_handle)[1] <NEW_LINE> writer = self.supported_extensions.get(ext, None) <NEW_LINE> if writer is None: <NEW_LINE> <INDENT> msg = (f'Writing files of extension type {ext} is not supported') <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> writer()
Write spline curve information to a file
625941db8c3a873295158699
def poisson_percentile(mu, x, y, yval): <NEW_LINE> <INDENT> x = np.asarray(x, dtype=np.int) <NEW_LINE> y = np.asarray(y, dtype=np.float) <NEW_LINE> w = poisson_weight(x, mu) <NEW_LINE> m = y > yval <NEW_LINE> u = np.sum(w[m], dtype=np.float) <NEW_LINE> err = np.sqrt(np.sum(w[m]**2)) / np.sum(w) <NEW_LINE> if u == 0.: <...
Calculate upper percentile using a Poissonian distribution. Parameters ---------- mu : float Mean value of Poissonian distribution x : array-like, dtype int Trials of variable that is expected to be poissonian distributed y : array-like Observed variable connected to poissonian variable *x* yval : float...
625941db0a50d4780f667171
def is_submodule(path): <NEW_LINE> <INDENT> if not os.path.isdir(path): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> contents = os.listdir(path) <NEW_LINE> if contents: <NEW_LINE> <INDENT> dot_git = os.path.join(path, ".git") <NEW_LINE> if os.path.isdir(dot_git): <NEW_LINE> <INDENT> return False <NEW_LINE> <DED...
Tell if the given path is a submodule
625941db4c3428357757c603
def get_pv_type_info(self, pv): <NEW_LINE> <INDENT> r = self.get("/getPVTypeInfo", params={"pv": pv}) <NEW_LINE> return self._return_json(r)
Get the type info for a given PV. In the AA terminology, the PVTypeInfo contains the various archiving parameters for a PV. :param pv: The name of the pv. :return: a dict with details (hostname, RTYP, ...) about the PV
625941db15baa723493c4254
def first_false_index(iterable, pred=None, default=None): <NEW_LINE> <INDENT> if pred is None: <NEW_LINE> <INDENT> func = lambda x: not x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> func = lambda x: not pred(x) <NEW_LINE> <DEDENT> return first_true_index(iterable, func, default)
find the first index position for the which the callable pred returns False
625941dbf8510a7c17cf99da
def ada_moto_rev(chan, duty): <NEW_LINE> <INDENT> m = ADA_MOTO_PWM_MAP[chan] <NEW_LINE> PCA9685_logic_chan(m[HB_IN1], False) <NEW_LINE> PCA9685_logic_chan(m[HB_IN2], True) <NEW_LINE> PCA9685_duty_chan(m[HB_PWM], duty * 41)
Drive reverse (CCW) with 0-100% duty cycle
625941dbdc8b845886cb5813
def modify_sg_slo(self, sg_name, new_slo): <NEW_LINE> <INDENT> payload = {'editStorageGroupActionParam': {'editStorageGroupSLOParam': {'sloId': new_slo} } } <NEW_LINE> storage_group = self.get_storage_group(sg_name) <NEW_LINE> LOG.info('Modifying the SG SLO to {0} '.format(new_slo)) <NEW_LINE> if ('slo' in storage_grou...
Modify service level of the Storage Group
625941db435de62698dfdf29
def composed_Q(self): <NEW_LINE> <INDENT> query_dict = {self.composed_query_string(): self.parameter} <NEW_LINE> return Q(**query_dict)
Return a Q object formatted for Django's ORM.
625941db435de62698dfdf2a
def return_index(self, index): <NEW_LINE> <INDENT> return self._elements[index]
Returns element at a concrete position in the list.
625941db4527f215b584c731
def init_route(api, api_version): <NEW_LINE> <INDENT> for model in models: <NEW_LINE> <INDENT> func = route_init_func.get(model, None) <NEW_LINE> if func is None: <NEW_LINE> <INDENT> print('failed to get model function') <NEW_LINE> continue <NEW_LINE> <DEDENT> model_func_map.append([model, func]) <NEW_LINE> <DEDENT> fo...
model = "exam_standard", 写在service.conf中 route_init_func = {"exam_standard": exam_standard_route} func = ["exam_standard", exam_standard_route] 运行的时候: exam_standard_route(api, api_version, "exam_standard")
625941db091ae35668667236
def send_receive(self, data, wait = True): <NEW_LINE> <INDENT> rx_data = self.spi.transfer(data) <NEW_LINE> if wait == True: <NEW_LINE> <INDENT> self.check_device_ready() <NEW_LINE> <DEDENT> return rx_data
Transmit and receive full duplex data over SPI If requested to wait, wait for device to become ready before return.
625941db2ae34c7f2600d40d
def _get_devices(self): <NEW_LINE> <INDENT> scalers = [] <NEW_LINE> timers = [] <NEW_LINE> motors = [] <NEW_LINE> detectors = [] <NEW_LINE> for r in self.mx_database.get_all_records(): <NEW_LINE> <INDENT> mx_class = r.get_field('mx_class') <NEW_LINE> if mx_class == 'scaler': <NEW_LINE> <INDENT> scalers.append(r.name) <...
Gets a list of all of the relevant devices and returns them to populate the scan GUI. :param list scaler_fields: A list of the scaler record types to return. Defined in the mxmap_config file. :param list det_fields: A list of the detector record types to return. Defined in the mxmap_config file.
625941dbe1aae11d1e749f96
def y_from_equation(x,equation): <NEW_LINE> <INDENT> if equation[0] != float('inf'): <NEW_LINE> <INDENT> y = equation[0] * x + equation[1] <NEW_LINE> <DEDENT> elif equation[0] == float('inf'): <NEW_LINE> <INDENT> y = 'Undefined' <NEW_LINE> <DEDENT> return(y)
Given an equation representing a line (slope,intercept) and an x-coordinate, returns the corresponding y-value. Args: x: The x-coordinate, an int or float equation: A tuple or list of form (slope,intercept). The intercept is assumed to be a y-intercept. Returns: An int or float representing the y-coordina...
625941db63f4b57ef00013ef
def get_nonzero(self): <NEW_LINE> <INDENT> return zip(*np.nonzero(self.map))
Retrieve the indices of the map where there is an object. An object has a nonzero value stored in the map index. Returns a list of tuple indices.
625941dbfb3f5b602dac3973
def url_for_version(self, version): <NEW_LINE> <INDENT> if not isinstance(version, Version): <NEW_LINE> <INDENT> version = Version(version) <NEW_LINE> <DEDENT> cls = self.__class__ <NEW_LINE> if not (hasattr(cls, 'url') or self.version_urls()): <NEW_LINE> <INDENT> raise NoURLError(cls) <NEW_LINE> <DEDENT> version_urls ...
Returns a URL from which the specified version of this package may be downloaded. version: class Version The version for which a URL is sought. See Class Version (version.py)
625941db99cbb53fe6792ec3
def test_default_car_name(self): <NEW_LINE> <INDENT> car_name = Car() <NEW_LINE> self.assertEqual('General', car_name.name, msg='The car should be called `General`,'+ ' if no name was passed as an argument')
Test default car name attribute
625941db21a7993f00bc7fd1
def graph_scatter_plot(self): <NEW_LINE> <INDENT> plot.scatter( self.times, self.displacements, marker=".", label=f"{self.car_weight} pno" )
Creates a graph of just the individual position-time points
625941db6aa9bd52df037082
def setUp(self): <NEW_LINE> <INDENT> self.mock_logger = mock.MagicMock() <NEW_LINE> self.modules = { "logger": self.mock_logger, } <NEW_LINE> self.module_patcher = mock.patch.dict('sys.modules', self.modules) <NEW_LINE> self.module_patcher.start() <NEW_LINE> self.logger_patcher = None
Set a mock logger package in modules
625941db23e79379d52ee83d
def _createStubPage(report, node): <NEW_LINE> <INDENT> filename = node['_md_path'] <NEW_LINE> if isinstance(node, moosesyntax.ObjectNodeBase): <NEW_LINE> <INDENT> filename = os.path.join(report.working_dir, node['_md_path']) <NEW_LINE> <DEDENT> elif isinstance(node, moosesyntax.SyntaxNode): <NEW_LINE> <INDENT> action =...
Copy template content to expected document location.
625941db91af0d3eaac9bcf8
def testController(self): <NEW_LINE> <INDENT> module = install_bundle(self.framework) <NEW_LINE> context = self.framework.get_bundle_context() <NEW_LINE> assert isinstance(context, BundleContext) <NEW_LINE> self.assertIsNone(context.get_service_reference(IEchoService), "Service is already registered") <NEW_LINE> self.a...
Tests the service controller
625941db1d351010ab855df8
def parse_configuration_file(config): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(config, 'r') as stream: <NEW_LINE> <INDENT> conf_data = yaml.load(stream, Loader=yaml.FullLoader) <NEW_LINE> <DEDENT> <DEDENT> except (OSError, IOError) as error: <NEW_LINE> <INDENT> logger.error("Failed when opening config fil...
Parses the configuration file. Returns: dictionary containing the configuration file data
625941db23e79379d52ee83e
def key_value_to_str_if_not_none(key, value, separator=' ', suffix='\n'): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> return "{}{}{}{}".format(key, separator, value, suffix) <NEW_LINE> <DEDENT> return ""
Helper method that, given a key, value, separator and suffix, it will return the string '<key><separator><value><suffix>' if value is not None, otherwise it will return the empty string '' :param key: key :param value: value :param separator: character to use as separator, default ' ' :param suf...
625941dbd18da76e235327b5
def is_fully_within_image(self, image): <NEW_LINE> <INDENT> if isinstance(image, tuple): <NEW_LINE> <INDENT> shape = image <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shape = image.shape <NEW_LINE> <DEDENT> height, width = shape[0:2] <NEW_LINE> return self.x1 >= 0 and self.x2 < width and self.y1 >= 0 and self.y2 < he...
Estimate whether the bounding box is fully inside the image area. Parameters ---------- image : (H,W,...) ndarray or tuple of int Image dimensions to use. If an ndarray, its shape will be used. If a tuple, it is assumed to represent the image shape and must contain at least two integers. Returns -----...
625941db8c0ade5d55d3ec9a
def addFeatureSA(self, callback, default=None, name=None): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> featureName = callback.__name__ <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> featureName = name <NEW_LINE> <DEDENT> featureValues = callback(self) <NEW_LINE> setattr(self, "_%s_values" % featureName, fea...
Add a feature to the suffix array. The callback must return a sequence such that the feature at position i is attached to the suffix referenced by self.SA[i]. It is called with one argument: the instance of SuffixArray self. The callback may traverse self.SA in any fashion. The default behavior is to name the new fea...
625941db57b8e32f52483779
def retrieve_short_url_destination(shorturl_key): <NEW_LINE> <INDENT> return shorturls_table.get_item(shorturl_key=shorturl_key)['destination_url']
Retrieves destination URL from database :raises: ItemNotFound if key doesn't exist :return: Destination URL String
625941db57b8e32f5248377a
def has_ships(self): <NEW_LINE> <INDENT> return bool(self._ships)
Check if current player as active ships :rtype: `bool`
625941db38b623060ff0b0ca
def _findPoliciesToCombine(self, singlePolicyRes): <NEW_LINE> <INDENT> policiesConfiguration = RssConfiguration.getPolicies() <NEW_LINE> if not policiesConfiguration['OK']: <NEW_LINE> <INDENT> return policiesConfiguration <NEW_LINE> <DEDENT> policiesConfiguration = policiesConfiguration['Value'] <NEW_LINE> def combineP...
method that iterates over the single policy results and checks the CS configuration of the policies looking for the option 'doNotCombine'. If it is present, that single policy result is discarded. :Parameters: **singlePolicyRes** - `list( dict )` list with every single policy result to be combined ( see _runPoli...
625941dbfbf16365ca6f64a5
def startOfChunk(prevTag, tag, prevType, type_): <NEW_LINE> <INDENT> chunkStart = ((prevTag == "B" and tag == "B") or (prevTag == "B" and tag == "B") or (prevTag == "I" and tag == "B") or (prevTag == "O" and tag == "B") or (prevTag == "O" and tag == "I") or (prevTag == "E" and tag == "E") or (prevTag == "E" and tag == ...
checks if a chunk started between the previous and current word; arguments: previous and current chunk tags, previous and current types
625941db091ae35668667237
def readme(): <NEW_LINE> <INDENT> with open("README.md") as file: <NEW_LINE> <INDENT> return file.read()
Opens readme file and returns content
625941db283ffb24f3c55bdc
def injection(self, queries): <NEW_LINE> <INDENT> default_page = self.scan.page(self.page) <NEW_LINE> data = {} <NEW_LINE> for query in queries: <NEW_LINE> <INDENT> data[query] = self.parse.html_diff(default_page, self.scan.page(queries[query])) <NEW_LINE> <DEDENT> if len(queries) == 1: <NEW_LINE> <INDENT> return data[...
Takes page to fuzz for injections and params to check for. :queries: List??? need to check it is always a list. :returns: List if queries has only one query. Dict of lists otherwise. Keys are injected strings, values are results.
625941db167d2b6e31218e72
def coords(self, qind, qdep=[], coneqs=[]): <NEW_LINE> <INDENT> if not isinstance(qind, (list, tuple)): <NEW_LINE> <INDENT> raise TypeError('Generalized coords. must be supplied in a list.') <NEW_LINE> <DEDENT> self._q = qind + qdep <NEW_LINE> self._qdot = [diff(i, dynamicsymbols._t) for i in self._q] <NEW_LINE> if not...
Supply all the generalized coordiantes in a list. If some coordinates are dependent, supply them as part of qdep. Their dependent nature will only show up in the linearization process though. Parameters ========== qind : list A list of independent generalized coords qdep : list List of dependent coordinates ...
625941dbbd1bec0571d9090c
def _http_request(self, url, method, **kwargs): <NEW_LINE> <INDENT> kwargs['headers'] = copy.deepcopy(kwargs.get('headers', {})) <NEW_LINE> kwargs['headers'].setdefault('User-Agent', USER_AGENT) <NEW_LINE> if self.auth_token: <NEW_LINE> <INDENT> kwargs['headers'].setdefault('X-Auth-Token', self.auth_token) <NEW_LINE> <...
Send an http request with the specified characteristics. Wrapper around httplib.HTTP(S)Connection.request to handle tasks such as setting headers and error handling.
625941dbd4950a0f3b08c629
def increment(self, value): <NEW_LINE> <INDENT> self.shift_on_clock_changes() <NEW_LINE> self._values[-1] += value
Increment this number by `value`, will increment the last element by `` value``.
625941db4a966d76dd5512ef