code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def cut_xy(self, w, xc, width=20): <NEW_LINE> <INDENT> x_left = self.x[0] if ( xc - width*w/2) < self.x[0] else (xc - width*w/2) <NEW_LINE> x_right = (xc + width*w/2) if (xc + width * w/2) < self.x[-1] else self.x[-1] <NEW_LINE> p_left = int((x_left - self.x[0])//(self.x[1]-self.x[0])) <NEW_LINE> p_right = int((x_right...
裁剪出x在xc附近的部分 x是等差的
625941dcbde94217f36830f8
@app.route('/project') <NEW_LINE> def get_project_info(): <NEW_LINE> <INDENT> title = request.args.get('title') <NEW_LINE> description, max_grade = hackbright.get_project_by_title(title) <NEW_LINE> student_grades_list = hackbright.get_students_and_grades(title) <NEW_LINE> return render_template('project-info.html', tit...
List information about a project.
625941dc4f6381625f114d46
def longestConsecutive(self, nums): <NEW_LINE> <INDENT> visited = set() <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> visited.add(num) <NEW_LINE> <DEDENT> max_len = 0 <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> if num - 1 not in visited: <NEW_LINE> <INDENT> curr = 0 <NEW_LINE> item = num <NEW_LINE> while item in ...
:type nums: List[int] :rtype: int
625941dc8c0ade5d55d3ecc7
def get_hash(self): <NEW_LINE> <INDENT> import hashlib <NEW_LINE> m = hashlib.sha1() <NEW_LINE> def hashadd(v): <NEW_LINE> <INDENT> m.update(("/%s" % str(v)).encode("utf8")) <NEW_LINE> <DEDENT> m.update(KeyboardConfigBase.get_hash(self)) <NEW_LINE> for x in (self.xkbmap_print, self.xkbmap_query, self.xkbmap_raw, ...
This hash will be different whenever the keyboard configuration changes.
625941dc0a50d4780f66719f
def guess_type(self, url, strict=True): <NEW_LINE> <INDENT> def splittype(url): <NEW_LINE> <INDENT> import ure <NEW_LINE> _typeprog = ure.compile('^([^/:]+):') <NEW_LINE> match = _typeprog.match(url) <NEW_LINE> if match: <NEW_LINE> <INDENT> scheme = match.group(1) <NEW_LINE> return scheme.lower(), url[len(scheme) + 1:]...
Guess the type of a file based on its URL. Return value is a tuple (type, encoding) where type is None if the type can't be guessed (no or unknown suffix) or a string of the form type/subtype, usable for a MIME Content-type header; and encoding is None for no encoding or the name of the program used to encode (e.g. co...
625941dc3c8af77a43ae3aad
def set_game_controller(self, game_controller): <NEW_LINE> <INDENT> self.__game_controller = game_controller <NEW_LINE> self.__gamefield_screen.set_game_controller(game_controller)
set a game_controller to get all viewing objects from :param game_controller: :return: None
625941dc4428ac0f6e5baafe
def git(self, command): <NEW_LINE> <INDENT> cmd = '%s' % command <NEW_LINE> return GitRepo.execute_git_cmd(cmd, cwd=self.path, env=self.env)
Executes a command in the repository context
625941dc21bff66bcd684c5a
def test_profile_loading(self): <NEW_LINE> <INDENT> self.click('empty_profile') <NEW_LINE> self.find('no_plugins_enabled') <NEW_LINE> self.click('owasp_top_10') <NEW_LINE> self.find('audit_plugins_enabled') <NEW_LINE> self.click('empty_profile') <NEW_LINE> self.find('no_plugins_enabled')
Tests that it is possible to change from one profile to the next and w3af doesn't break.
625941dc6aa9bd52df0370af
def run(self, epochs: Tuple[int, int], callbacks: Optional[Callbacks] = None, show_progress: Optional[bool] = True) -> None: <NEW_LINE> <INDENT> outter_epochs, inner_epochs = epochs <NEW_LINE> with tf.compat.v1.Session(graph=self.compiler.graph) as sess: <NEW_LINE> <INDENT> writer = tf.compat.v1.summary.FileWriter(self...
Runs the policy optimizer for a given number of `epochs`. Optionally, it executes `callbacks` to extend planning behavior during training. Args: epochs (int): The number of training epochs. callbacks (Optional[Dict[str, List[Callback]]]): Mapping from events to lists of callables.
625941dc94891a1f4081bdb5
def lagrange(subsolver, start_point=10, ncpus=1): <NEW_LINE> <INDENT> def lagrange_solver(mat, degrees=[], infolevel=0): <NEW_LINE> <INDENT> return _lagrange(subsolver, start_point, ncpus, mat, degrees, infolevel) <NEW_LINE> <DEDENT> return lagrange_solver
Creates a solver for matrices of univariate polynomials or rational functions over some field `K`, based on a given solver for matrices over `K`, using evaluation+interpolation. INPUT: - ``subsolver`` -- a solver for matrices over `K` - ``start_point`` -- first evaluation point to be used - ``ncpus`` -- maximum numbe...
625941dc8c3a8732951586c8
def authenticate_user(self, id_, password): <NEW_LINE> <INDENT> self.db.run_query('SELECT * FROM UserInfo WHERE id=? AND password=?', id_, password) <NEW_LINE> row_match = self.db.fetch_one() <NEW_LINE> if row_match is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True
Match both id and password -> Allows the user to sign in.
625941dc23849d37ff7b3398
def hash_function(size): <NEW_LINE> <INDENT> key = secrets.token_bytes(size//8) <NEW_LINE> if size == 224: <NEW_LINE> <INDENT> condensat = hashlib.sha3_224(key).digest() <NEW_LINE> <DEDENT> if size == 256: <NEW_LINE> <INDENT> condensat = hashlib.sha3_256(key).digest() <NEW_LINE> <DEDENT> if size == 384: <NEW_LINE> <IND...
function hash(size)
625941dcbe383301e01b578b
def test_past_as_initlatch_4(self): <NEW_LINE> <INDENT> moddict = ModDict() <NEW_LINE> moddict.parse(inputs.TEST_MODULE_4) <NEW_LINE> printer = Printer(moddict, indent_size=2) <NEW_LINE> initlatch = printer['InitLatch'] <NEW_LINE> self.assertEqual('\n' + initlatch, TEST_MODULE_4_REF)
Test past as initlatch with TEST_MODULE_4
625941dc6e29344779a6291a
def intlog2(x): <NEW_LINE> <INDENT> ilog = 0 <NEW_LINE> while 2**ilog < x: <NEW_LINE> <INDENT> ilog += 1 <NEW_LINE> <DEDENT> return ilog
Compute the ceiling of the log2(x)
625941dc56b00c62f0f14965
def query_many(self, key, testmsg, dictkeys=[], dictkeyvals={}, retry=10): <NEW_LINE> <INDENT> self._keys = {} <NEW_LINE> self._listens = {} <NEW_LINE> self._result = None <NEW_LINE> left = retry <NEW_LINE> res = False <NEW_LINE> while ((left >= 0) and (res != True)): <NEW_LINE> <INDENT> res = self.query(key, testmsg, ...
Send a command and wait for response from the plugin. :param key: a key to look for :type key: str :param testmsg: The message to send :param testmsg: XPLMessage :param dictkeys: The keys that must exist in the returning message :type dictkeys: set() :param dictkeyvals: The key:val pairs that mus exist ine the returni...
625941dc71ff763f4b54999b
def _extract_zip_file_object(fileobj, filename): <NEW_LINE> <INDENT> zip_file = zipfile.ZipFile(fileobj) <NEW_LINE> file_data = zip_file.read(filename) <NEW_LINE> file_data_string = file_data.decode() <NEW_LINE> return io.StringIO(file_data_string)
Return an uncompressed file-like string object.
625941dc10dbd63aa1bd2ead
def make_str_from_row(board, row_index): <NEW_LINE> <INDENT> if(row_index<len(board)): <NEW_LINE> <INDENT> selected=board[row_index] <NEW_LINE> result = '' <NEW_LINE> for letter in selected: <NEW_LINE> <INDENT> result += letter <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> return ''
(list of list of str, int) -> str Return the characters from the row of the board with index row_index as a single string. >>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0) 'ANTT'
625941dce1aae11d1e749fc5
def GetMetadata(self, url_path, recursive=False): <NEW_LINE> <INDENT> base_url = 'http://metadata/computeMetadata/v1/' <NEW_LINE> suffix = '' <NEW_LINE> if recursive: <NEW_LINE> <INDENT> suffix = '?recursive=true' <NEW_LINE> <DEDENT> url = '{0}{1}{2}'.format(base_url, url_path, suffix) <NEW_LINE> request = urllib2.Requ...
Retrieves instance metadata. Args: url_path: The path of the metadata url after the api version. http://metadata/computeMetadata/v1/url_path recursive: If set, returns the tree of metadata starting at url_path as a json string. Returns: The metadata returned based on the url path.
625941dc91f36d47f21ac800
def diff_3(a, b, delta): <NEW_LINE> <INDENT> return (a - b)/float(2*delta)
Three point differentiantion formula [f(x+dx) - f(x-dx)]/2dx
625941dc099cdd3c635f0f65
def read_json(fname): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(fname, 'r') as f: <NEW_LINE> <INDENT> data = json.load(f) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> ZenException(f"Check that {fname} exists and it is a proper json file") <NEW_LINE> <DEDENT> return data
Read a json file and return content Parameters ---------- fname : str Json filename Returns ------- data : json object The file content as a json object
625941dc24f1403a92600e6e
@register.simple_tag <NEW_LINE> def print_mailboxes( tree, selected=None, withunseen=False, selectonly=False, hdelimiter='.'): <NEW_LINE> <INDENT> result = "" <NEW_LINE> for mbox in tree: <NEW_LINE> <INDENT> cssclass = "" <NEW_LINE> name = mbox["path"] if "sub" in mbox else mbox["name"] <NEW_LINE> label = ( mbox["label...
Display a tree of mailboxes and sub-mailboxes. :param tree: the mailboxes to display
625941dcd7e4931a7ee9e229
def test_genshi_relative_filename_cwd(self): <NEW_LINE> <INDENT> with directory(self._tests_rel_dir): <NEW_LINE> <INDENT> twc.Widget(template='genshi:./test.html').display()
Issue #30 take 2 -- http://bit.ly/LT4rBP
625941dc5e10d32532c5f231
def test_esmtpClientTlsModeDeprecationGet(self): <NEW_LINE> <INDENT> val = self.clientProtocol.tlsMode <NEW_LINE> del val <NEW_LINE> warningsShown = self.flushWarnings( offendingFunctions=[self.test_esmtpClientTlsModeDeprecationGet] ) <NEW_LINE> self.assertEqual(len(warningsShown), 1) <NEW_LINE> self.assertIdentical(wa...
L{smtp.ESMTPClient.tlsMode} is deprecated.
625941dc99cbb53fe6792ef1
def _new_label_pair(self, name, start='start', end='end'): <NEW_LINE> <INDENT> label = self._new_label(name) <NEW_LINE> return f'{label}_{start}', f'{label}_{end}'
Get a pair of related labels.
625941dc5510c4643540f6e8
def ordersinfo(self,symbol,orderId='',tradeType=0): <NEW_LINE> <INDENT> ORDERS_INFO_RESOURCE = "/api/v1/orders_info.do" <NEW_LINE> params = { 'api_key':self.__apikey, 'symbol':symbol, 'order_id':orderId, 'type':tradeType } <NEW_LINE> params['sign'] = buildMySign(params,self.__secretkey) <NEW_LINE> return httpPost(self....
|api_key|String|是|用户申请的apiKey| |type|Integer|是|查询类型 0:未完成的订单 1:已经完成的订单| |symbol|String|是|币对如ltc_btc| |order_id|String|是|订单ID(多个订单ID中间以","分隔,一次最多允许查询50个订单)| |sign|String|是|请求参数的签名|
625941dc0a366e3fb873eb27
def test_sensor_sb_1_5(self, sensors): <NEW_LINE> <INDENT> for val, change, sens in sensors: <NEW_LINE> <INDENT> assert sens.path is None <NEW_LINE> assert sens.extract_value(SB_1_5) is change <NEW_LINE> assert sens.value == val <NEW_LINE> assert sens.path == JMESPATH_VAL_IDX.format("1", sens.key_idx) <NEW_LINE> assert...
Test extract value.
625941dc6fb2d068a760f3ac
def write_macros_to_output(tests, executable, reg_dir, output=None): <NEW_LINE> <INDENT> lines = [] <NEW_LINE> for test in tests: <NEW_LINE> <INDENT> lines.append("ADD_TEST(" + test + " " + executable + " " + "--gtest_filter=" + test + ")") <NEW_LINE> <DEDENT> lines.append("ADD_TEST(RegressionTe...
writes a list of test names as ADD_TEST cmake macros to an output file Arguments tests -- a list of all test names to be added as ADD_TEST macros to the output file exectuable -- the name of the test executable output -- the output file to write to, if output is not specified, the list of ADD_TEST macros will be wr...
625941dcd18da76e235327e4
def test_Ridge(*data): <NEW_LINE> <INDENT> X_train,X_test,y_train,y_test=data <NEW_LINE> regr = linear_model.Ridge() <NEW_LINE> regr.fit(X_train, y_train) <NEW_LINE> print('Coefficients:%s, intercept %.2f'%(regr.coef_,regr.intercept_)) <NEW_LINE> print("Residual sum of squares: %.2f"% np.mean((regr.predict(X_test) - y_...
测试 Ridge 的用法
625941dca79ad161976cc450
def set_rotation_values(self, values): <NEW_LINE> <INDENT> self.__rotation_values = values
Set possible rotation values ex. => (-0.26, 0.26) => rotate by (a value from -0.26, 0.26) radians
625941dc091ae35668667264
def sort_and_cut(counter: Counter, limit: int) -> List[str]: <NEW_LINE> <INDENT> tokens_and_frequencies = sorted(counter.items(), key=lambda tup: tup[0]) <NEW_LINE> tokens_and_frequencies.sort(key=lambda tup: tup[1], reverse=True) <NEW_LINE> vocab_tokens = [i[0] for i in tokens_and_frequencies[:limit]] <NEW_LINE> retur...
This function returns an list of the most-frequent tokens in descending order with given limit :param counter: Counter object to retrieve item and frequency from :param limit: Number of tokens to be included :return: List of the most-used tokens
625941dc82261d6c526ab7ae
def generate_pwd_hash(password: bytes) -> bytes: <NEW_LINE> <INDENT> hashed = bcrypt.hashpw(password, bcrypt.gensalt()) <NEW_LINE> return hashed
generate password hash value : password must be encoded before hashing.
625941dcac7a0e7691ed43d2
def updateTypeMaps(opts): <NEW_LINE> <INDENT> namespace = opts.namespace <NEW_LINE> global CURRENT_LANG <NEW_LINE> global PRIMITIVE_TYPE_MAP <NEW_LINE> global TYPE_MAP <NEW_LINE> global BASE_TYPE_MAP <NEW_LINE> CURRENT_LANG = opts.lang <NEW_LINE> PRIMITIVE_TYPE_MAP = { 'PositiveInt': 'PositiveInteger', 'NonNegativeInt'...
Updates the type maps with a new namespace. **Must** be executed at least once, **before** node class file generation.
625941dcd58c6744b4257f69
def crossing_turn_right(self): <NEW_LINE> <INDENT> if not Settings.disable_driving: <NEW_LINE> <INDENT> RobotStatusController.is_at_crossing = True <NEW_LINE> self.stop_autonomous_behavior() <NEW_LINE> drive_action = self.robot.drive_straight(util.distance_mm(Settings.crossing_approach_distance), util.speed_mmps(RobotS...
Run all behavior associated with turning right at a crossing
625941dc3617ad0b5ed68201
def _report_exception(message, e, stack): <NEW_LINE> <INDENT> name = 'crash report' if e else 'report' <NEW_LINE> sys.stderr.write('Sending the %s ...' % name) <NEW_LINE> message = (message or '').rstrip() <NEW_LINE> if e: <NEW_LINE> <INDENT> if message: <NEW_LINE> <INDENT> message += '\n' <NEW_LINE> <DEDENT> message +...
Sends the stack trace to the breakpad server.
625941dc5fc7496912cc3c89
def get_runtime_config(self, namespace=None): <NEW_LINE> <INDENT> for item in super().get_runtime_config(namespace): <NEW_LINE> <INDENT> yield item <NEW_LINE> <DEDENT> for item in self.conn.get_runtime_config(namespace): <NEW_LINE> <INDENT> yield item
Return generator for items in runtime configuration.
625941dc66656f66f7cbc4b8
def fuzzy_and(args): <NEW_LINE> <INDENT> rv = True <NEW_LINE> for ai in args: <NEW_LINE> <INDENT> ai = fuzzy_bool(ai) <NEW_LINE> if ai is False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if rv: <NEW_LINE> <INDENT> rv = ai <NEW_LINE> <DEDENT> <DEDENT> return rv
Return True (all True), False (any False) or None. >>> from sympy.core.logic import fuzzy_and >>> from sympy import Dummy If you had a list of objects to test the commutivity of and you want the fuzzy_and logic applied, passing an iterator will allow the commutativity to only be computed as many times as necessary. W...
625941dceab8aa0e5d26de64
def _begin_of_line(self, data: str, index: int, filename: str = 'unknown') -> int: <NEW_LINE> <INDENT> space_counter = 0 <NEW_LINE> counter = 1 <NEW_LINE> while index - counter > 0: <NEW_LINE> <INDENT> if data[index - counter] == ';': <NEW_LINE> <INDENT> return self._check_bof_value(index - counter + space_counter + 1,...
After the log event matches, find the beginning of the line, e.g.: .info(...); --> log.info(...); It then returns the index :param data: Log file (as string) :param index: Given index of a log line :param filename: (optional) A filename for logging purposes :return: The index of the line start
625941dc63b5f9789fde73f1
def predict(self, X): <NEW_LINE> <INDENT> if self.fit_intercept: <NEW_LINE> <INDENT> X = np.c_[np.ones(X.shape[0]), X] <NEW_LINE> <DEDENT> return sigmoid(np.dot(X, self.beta))
Use the trained model to generate prediction probabilities on a new collection of data points. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(Z, M)` A dataset consisting of `Z` new examples, each of dimension `M`. Returns ------- y_pred : :py:class:`ndarray <numpy.ndarray>` of shape `(Z,...
625941dcfbf16365ca6f64d4
def critical(message, label=""): <NEW_LINE> <INDENT> return colored(label + message, fg='white', bg='red', style='bright')
Return a colored CRITICAL message
625941dc30c21e258bdfa7aa
def start(self, in_queue, out_queue): <NEW_LINE> <INDENT> active_time = datetime.timedelta() <NEW_LINE> batch_count = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> reads = in_queue.get() <NEW_LINE> timer_started = datetime.datetime.now() <NEW_LINE> if reads is None: <NEW_LINE> <INDENT> batch_tim...
Starts processing reads from in_queue. The number of reads processed are put into the out_queue for counting purpose. The worker will stop when the it gets a None from the in_queue. Args: in_queue: A queue holding list of reads to be processed. Each item in the in_queue is a list reads so that the frequen...
625941dc0383005118ecf8ed
def __le__(self, card): <NEW_LINE> <INDENT> return self.value() <= card.value()
Less-than, or equal, operator :return: True if self has a lesser or equal value than card
625941dc3c8af77a43ae3aae
def p_tuple(p): <NEW_LINE> <INDENT> p[0] = p[1]
tuple : tuple0 | tuple_many | tuple1
625941dc26238365f5f0f17d
def getConfusion(self, frame): <NEW_LINE> <INDENT> return self.confusion[frame]
Returns the confusion matrix of a specific frame.
625941dc8a349b6b435e847f
def monitor(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> lastmtime = os.path.getmtime(self.logFile) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logDirectory = self.logFile.replace('log.json', '') <NEW_LINE> self.create(logDirectory) <NEW_LINE> lastmtime = os.path.getmtime(self.logFile) <NEW_LINE> <DEDENT> wh...
monitors changes
625941dc85dfad0860c3b167
def sendCommand2Gummi(self, seg, start_positions, positions, velocities, duration): <NEW_LINE> <INDENT> self.cmd_number_of_slices = int(floor(duration*self.update_command_rate)) <NEW_LINE> if self.cmd_number_of_slices < 1: self.cmd_number_of_slices = 1 <NEW_LINE> msg = JointState() <NEW_LINE> msg.name = self.joint_name...
gummi_interface/gummi.py will read and execute the commands sent from here
625941dc1d351010ab855e27
def put(self, bucket, filepath): <NEW_LINE> <INDENT> with cloudstorage.open('/%s/%s' % (bucket, filepath), 'w') as f: <NEW_LINE> <INDENT> f.write(self.request.body)
Stores a file in a mocked GS.
625941dc5fdd1c0f98dc0540
def test_capture(self) -> None: <NEW_LINE> <INDENT> foo = object() <NEW_LINE> with capturedLogs() as captured: <NEW_LINE> <INDENT> self.log.debug("Capture this, please", foo=foo) <NEW_LINE> self.log.info("Capture this too, please", foo=foo) <NEW_LINE> <DEDENT> self.assertTrue(len(captured) == 2) <NEW_LINE> self.assertE...
Events logged within context are captured.
625941dc85dfad0860c3b168
def get(self, id_: str, hda_ldda: str = 'hda'): <NEW_LINE> <INDENT> res = self.gi.datasets.show_dataset(id_, hda_ldda=hda_ldda) <NEW_LINE> ds_dict = self._get_dict('show_dataset', res) <NEW_LINE> if hda_ldda == 'hda': <NEW_LINE> <INDENT> hist = self.obj_gi.histories.get(ds_dict['history_id']) <NEW_LINE> return wrappers...
Retrieve the dataset corresponding to the given id. :type hda_ldda: str :param hda_ldda: Whether to show a history dataset ('hda' - the default) or library dataset ('ldda') :rtype: :class:`~.wrappers.HistoryDatasetAssociation` or :class:`~.wrappers.LibraryDatasetDatasetAssociation` :return: the history or library d...
625941dcd8ef3951e3243849
def jse_grad(x, p_ij, dot_p_ij_log_p_ij, w_cf, N, n_components): <NEW_LINE> <INDENT> X = np.reshape(a=x, newshape=(N, n_components)) <NEW_LINE> q_ij, log_q_ij = sne_lds_similarities_fast(dsm_lds=pairwise_dist(X=X, metric='sqeuclidean', tomatrix=True), arr_den_s_i=2*np.ones(shape=N, dtype=np.float64), compute_log=True) ...
Computes the value of the gradient of the objective function of JSE. In: - x: numpy one-dimensional array with N*n_components elements, containing the current values of the low dimensional coordinates. np.reshape(a=x, newshape=(N, n_components)) should yield a two-dimensional array with one example per row and one LDS ...
625941dc63d6d428bbe447fc
def from_url(str_or_uri, rsa_private_key): <NEW_LINE> <INDENT> token_and_scopes = auth_sub_string_from_url(str_or_uri) <NEW_LINE> return SecureAuthSubToken(token_and_scopes[0], rsa_private_key, token_and_scopes[1])
Creates a new SecureAuthSubToken using information in the URL. Uses auth_sub_string_from_url. Args: str_or_uri: The current page's URL (as a str or externals.atom.http_core.Uri) which should contain a token query parameter since the Google auth server redirected the user's browser to this URL. rsa_pri...
625941dc293b9510aa2c359e
def addAtTail(self, val: int) -> None: <NEW_LINE> <INDENT> if self.tail == None: <NEW_LINE> <INDENT> self.head = ListNode(val) <NEW_LINE> self.tail = self.head <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node = ListNode(val) <NEW_LINE> self.tail.next = node <NEW_LINE> self.tail = node <NEW_LINE> <DEDENT> self.num += ...
Append a node of value val to the last element of the linked list.
625941dcbaa26c4b54cb1429
def test_06_visualization_api( self ): <NEW_LINE> <INDENT> self.run_js_script( 'api-visualizations-tests.js' )
Test API for visualizations.
625941dc5e10d32532c5f232
def generate_dice_value(self): <NEW_LINE> <INDENT> self.dice = (random.randint(1, 6), random.randint(1, 6))
generates the dice value for a go
625941dc30c21e258bdfa7ab
def get_column_by_name(self, name): <NEW_LINE> <INDENT> for column in self._columns: <NEW_LINE> <INDENT> if column.attribute == name: <NEW_LINE> <INDENT> return column <NEW_LINE> <DEDENT> <DEDENT> raise LookupError("There is no column called %s" % name)
Returns the name of a column
625941dc97e22403b379d2a7
def check_naming_conventions(self, ds): <NEW_LINE> <INDENT> ret_val = [] <NEW_LINE> variable_naming = TestCtx(BaseCheck.MEDIUM, '§2.3 Naming Conventions for variables') <NEW_LINE> dimension_naming = TestCtx(BaseCheck.MEDIUM, '§2.3 Naming Conventions for dimensions') <NEW_LINE> attribute_naming = TestCtx(BaseCheck.MEDIU...
Checks the variable names to ensure they are valid CF variable names under CF. CF §2.3 Variable, dimension and attribute names should begin with a letter and be composed of letters, digits, and underscores. :param netCDF4.Dataset ds: An open netCDF dataset :rtype: compliance_checker.base.Result
625941dc2eb69b55b151cbbf
def fill_walk(self): <NEW_LINE> <INDENT> while len(self.x_values) < self.num_pionts: <NEW_LINE> <INDENT> x_step = self.get_step() <NEW_LINE> y_step = self.get_step() <NEW_LINE> if x_step == 0 and y_step == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> next_x = self.x_values[-1] + x_step <NEW_LINE> next_y = self.y...
Calculate all the points in the walk
625941dc32920d7e50b284de
def change_variable(self,var): <NEW_LINE> <INDENT> assert self.dim > 1, "Available for q^r, r>1" <NEW_LINE> assert type(var) == str, "Choose a variable name (a string)" <NEW_LINE> self.variable = var
Changes the variable in which to display the generator of the finite field.
625941dc45492302aab5e5d3
def InsertArg(self, string="", **_): <NEW_LINE> <INDENT> logging.debug("Storing Argument %s", string) <NEW_LINE> if self.state == "LIST_ARG": <NEW_LINE> <INDENT> self.list_args.append(string) <NEW_LINE> <DEDENT> elif self.current_expression.AddArg(string): <NEW_LINE> <INDENT> self.stack.append(self.current_expression) ...
Insert an arg to the current expression.
625941dc15baa723493c4284
def __init__(self, phi, anc_probs=[1/4, 1/4, 1/2]): <NEW_LINE> <INDENT> prob_norm = sum(anc_probs) <NEW_LINE> n_probs = [prob/prob_norm for prob in anc_probs] <NEW_LINE> y_plus_prob = (2*np.sin(phi + np.pi/2)**2 + 1)/4 <NEW_LINE> x_plus_prob = (np.cos(phi)**2 + 1)/2 <NEW_LINE> self.probs = [n_probs[0]*x_plus_prob/2, n_...
Constructor :param phi: The strength of the interaction :param anc_probs: Probabilities of performing x, y, and z measurements on the ancilla (meter) :param p: List giving the probabilities of performing a :math:`\sigma_x`, :math:`\sigma_y`, or ...
625941dca8ecb033257d33d8
def str_to_card(str_card): <NEW_LINE> <INDENT> if str_card.startswith('!'): <NEW_LINE> <INDENT> str_card = str_card[1:] <NEW_LINE> <DEDENT> return Card(int(str_card[-1]), str_card[:-1])
Return a Card obj from a string representation. >>> str_to_card('102') 10♡ >>> str_to_card('!102') 10♡
625941dc498bea3a759b9dbb
def isPalindrome(self, x): <NEW_LINE> <INDENT> temp_val = x <NEW_LINE> if x >= 0: <NEW_LINE> <INDENT> answer = "" <NEW_LINE> while temp_val >= 10: <NEW_LINE> <INDENT> answer += str(temp_val%10) <NEW_LINE> temp_val /= 10 <NEW_LINE> <DEDENT> answer += str(temp_val) <NEW_LINE> if int(answer) == x: <NEW_LINE> <INDENT> retu...
:type x: int :rtype: bool
625941dc07d97122c4178b9e
def prepare_stream_for_storage(self, stream): <NEW_LINE> <INDENT> if 'address' not in stream: <NEW_LINE> <INDENT> return stream, {} <NEW_LINE> <DEDENT> return stream, {'address': stream['address']}
Performs any necessary conversions on the stream properties so that it can be inserted into a stream manager hierarchy.
625941dc3346ee7daa2b307a
def get_name(self): <NEW_LINE> <INDENT> return self.name
чтение имени устройства
625941dc7cff6e4e81117c92
def get_stock_info(stock_name): <NEW_LINE> <INDENT> endpoint = 'https://stooq.com/q/l/?s={}.us&f=sd2t2ohlcv&h&e=csv'.format(stock_name.lower()) <NEW_LINE> response = requests.get(endpoint) <NEW_LINE> decoded_content = response.content.decode('utf-8') <NEW_LINE> cr = list(csv.reader(decoded_content.splitlines(), delimit...
Fetch stock information from endpoint. Creates string response. :param stock_name: String :return: String
625941dcbe7bc26dc91cd907
def plusOne(self, digits): <NEW_LINE> <INDENT> tag=1 <NEW_LINE> for i in range(1,len(digits)+1): <NEW_LINE> <INDENT> digits[-i]+=tag <NEW_LINE> tag=0 <NEW_LINE> if digits[-i]<=9: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> digits[-i]%=10 <NEW_LINE> tag+=1 <NEW_LINE> <DEDENT> if tag==1: <NEW_LINE> <INDENT> digits.inse...
:type digits: List[int] :rtype: List[int]
625941dc4f6381625f114d48
def runTest(self): <NEW_LINE> <INDENT> self.setUp() <NEW_LINE> self.test_RunPipeline1()
Run as few or as many tests as needed here.
625941dc7d847024c06be5cb
def get_current_position(self, node_id, node_speed, node_coordinates): <NEW_LINE> <INDENT> if self._destinations[node_id]['pause time'] is not None: <NEW_LINE> <INDENT> if self._pause(node_id, node_coordinates) is None: <NEW_LINE> <INDENT> self._assign_new_destination(node_id, node_speed) <NEW_LINE> <DEDENT> return nod...
Calculates and returns a node's position at the current simulation step in accordance with the Random Waypoint mobility model. A distance of the route traveled by the node, between the current and previous simulation steps, is calculated as the product of the current node's speed and the *simulation period* (see: :mod...
625941dc8c0ade5d55d3ecc9
def load_file(filename): <NEW_LINE> <INDENT> if filename in ['-', 'stdin']: <NEW_LINE> <INDENT> filehandle = sys.stdin <NEW_LINE> <DEDENT> elif filename.split('.')[-1] == 'gz': <NEW_LINE> <INDENT> filehandle = gzip.open(filename) <NEW_LINE> <DEDENT> elif filename.split('.')[-1] == 'bz2': <NEW_LINE> <INDENT> filehandle ...
LOADING FILES
625941dccad5886f8bd272e5
def FDSN_station_query(station, service): <NEW_LINE> <INDENT> query = service + 'query?station=' + station <NEW_LINE> queryresult = curl(query) <NEW_LINE> root = ET.fromstring(queryresult.decode('utf-8')) <NEW_LINE> latitude = float(root[4][3][2].text) <NEW_LINE> longitude = float(root[4][3][3].text) <NEW_LINE> depth =...
Use pycurl to query station details via FDSN. :param station: station site code :return: station latitude (dec. deg.), longitude (dec. deg.), and depth (+ve direction is down, in m)
625941dcc432627299f04f54
def _tokenizer(sentence): <NEW_LINE> <INDENT> words = [] <NEW_LINE> for space_separated_fragment in sentence.lower().strip().split(): <NEW_LINE> <INDENT> words.extend(re.split(_WORD_SPLIT, space_separated_fragment)) <NEW_LINE> <DEDENT> return [w for w in words if w]
Very basic tokenizer: split the sentence into a list of tokens + lower().
625941dcf8510a7c17cf9a0b
def cal(self, k): <NEW_LINE> <INDENT> t = self.n - k <NEW_LINE> return self.factt(self.n)/(self.factt(t) * self.factt(k))
cal function
625941dce5267d203edcdfa6
def partial_threshold_tanimoto_search_symmetric(results, arena, threshold=0.7, query_start=0, query_end=None, target_start=0, target_end=None): <NEW_LINE> <INDENT> assert arena.popcount_indices <NEW_LINE> N = len(arena) <NEW_LINE> if query_end is None: <NEW_LINE> <INDENT> query_end = N <NEW_LINE> <DEDENT> elif query_en...
Compute a portion of the symmetric Tanimoto search results For most cases, use threshold_tanimoto_arena_symmetric instead of this function! This function is only useful for thread-pool implementations. In that case, set the number of OpenMP threads to 1. `results` is a SearchResults instance which is at least as lar...
625941dc29b78933be1e59b4
def current_date(self, date_format='%Y-%m-%d'): <NEW_LINE> <INDENT> date = datetime.now().strftime(date_format) <NEW_LINE> return date
Get current date in year-month-day format(default)
625941dcc4546d3d9de72d43
def fin_cita(inicio, duracion): <NEW_LINE> <INDENT> return inicio + duracion
Calcula el final de una cita segun su inicio y duracion.
625941dc004d5f362079a63e
def process_file_upload_batch_parameters(namespace): <NEW_LINE> <INDENT> if not os.path.exists(namespace.source): <NEW_LINE> <INDENT> raise ValueError('incorrect usage: source {} does not exist'.format(namespace.source)) <NEW_LINE> <DEDENT> if not os.path.isdir(namespace.source): <NEW_LINE> <INDENT> raise ValueError('i...
Process the parameters of storage file batch upload command
625941dc56b00c62f0f14967
def layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes): <NEW_LINE> <INDENT> vgg_layer7_out = tf.stop_gradient(vgg_layer7_out) <NEW_LINE> vgg_layer4_out = tf.stop_gradient(vgg_layer4_out) <NEW_LINE> vgg_layer3_out = tf.stop_gradient(vgg_layer3_out) <NEW_LINE> score_layer7 = tf.layers.conv2d( vgg_layer7_...
Create the layers for a fully convolutional network. Build skip-layers using the vgg layers. :param vgg_layer3_out: TF Tensor for VGG Layer 3 output :param vgg_layer4_out: TF Tensor for VGG Layer 4 output :param vgg_layer7_out: TF Tensor for VGG Layer 7 output :param num_classes: Number of classes to classify :retu...
625941dcb830903b967e9c15
def maxShear(diaphragm): <NEW_LINE> <INDENT> return diaphragm.Syt / 2.0
Returns maximum shear stress from yield strength of material. Using maximum shear stress theory
625941dc1f037a2d8b94650a
def GetStringWidth(self,first:'Any') -> 'Any': <NEW_LINE> <INDENT> pass
Gets the necessary column width to fully display this text in a column. Args: first(Any):String that contains the text whose width is to be determined.CommentsDoesn't take the size of an included Image in account, only the size of the text is determined. Returns: Any
625941dc8e71fb1e9831dab5
def lengthOfLIS(self, nums): <NEW_LINE> <INDENT> if len(nums) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> length = [1]*len(nums) <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> for j in range(i): <NEW_LINE> <INDENT> if nums[i] > nums[j]: <NEW_LINE> <INDENT> length[i] = max(length[j]+1, length[i]) <...
:type nums: List[int] :rtype: int
625941dc30bbd722463cc0d5
def canConstruct(self, ransomNote, magazine): <NEW_LINE> <INDENT> r = {} <NEW_LINE> m = {} <NEW_LINE> for i in ransomNote: <NEW_LINE> <INDENT> if i in r: <NEW_LINE> <INDENT> r[i] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r[i] = 1 <NEW_LINE> <DEDENT> <DEDENT> for i in magazine: <NEW_LINE> <INDENT> if i in m: <N...
:type ransomNote: str :type magazine: str :rtype: bool
625941dcb5575c28eb68e30f
def __setattr__(self, key, value): <NEW_LINE> <INDENT> if hasattr(self, key): <NEW_LINE> <INDENT> raise AttributeError("{} attributes can be added but not modified." "Attribute {!r} already exists with value {!r}".format( self.__class__.__name__, key, getattr(self, key))) <NEW_LINE> <DEDENT> self.__dict__[key] = value
redefine __setattr__
625941dc8e7ae83300e4b2da
def _find_v1_settings(self, settings): <NEW_LINE> <INDENT> if 'module_name' in settings: <NEW_LINE> <INDENT> modname = settings['module_name'] <NEW_LINE> <DEDENT> if 'modules' not in settings or len(settings['modules']) == 0: <NEW_LINE> <INDENT> raise DataError("No modules defined in module_settings.json file") <NEW_LI...
Parse a v1 module_settings.json file. V1 is the older file format that requires a modules dictionary with a module_name and modules key that could in theory hold information on multiple modules in a single directory.
625941dc24f1403a92600e70
def sumRange(self, i, j): <NEW_LINE> <INDENT> if self.lazy: <NEW_LINE> <INDENT> self.lazy = False <NEW_LINE> self.passLazy(self.left, self.val // self.length) <NEW_LINE> self.passLazy(self.right, self.val // self.length) <NEW_LINE> <DEDENT> if i == self.start and j == self.end: <NEW_LINE> <INDENT> return self.val <NEW_...
sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int
625941dc379a373c97cfae53
def is_regressor(estimator): <NEW_LINE> <INDENT> return isinstance(estimator, RegressionMixin)
Return True if the given estimator is a regressor. Parameters ---------- estimator : object Estimator object to test. Returns ------- out : bool True if estimator is a regressor and False otherwise.
625941dc24f1403a92600e71
def __eq__(self, other_wcs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> comparisons = self.make_comparisons(other_wcs) <NEW_LINE> return sequences.all_true(comparisons) <NEW_LINE> <DEDENT> except AttributeError as e: <NEW_LINE> <INDENT> log.warning("Problem occurred while comparing coordinate systems:") <NEW_LINE> pr...
This function ... :param other_wcs: :return:
625941dc5fdd1c0f98dc0541
def move_units(self, individual): <NEW_LINE> <INDENT> individual.world.randomly_spawn_fruit() <NEW_LINE> self.update_game_state(individual) <NEW_LINE> for pacman_index, pacman_cont in enumerate(individual.pacman_conts): <NEW_LINE> <INDENT> individual.world.move_pacmen(pacman_cont.get_move(individual.game_state, pacman_...
Moves all units in individual.world based on the unit controller moves. Before units are moved, a fruit probabilistically spawns and the game state is updated. After units are moved, game variables are updated.
625941dcde87d2750b8600a2
def _config_integer(param, value, configfile, lineno, radix=10): <NEW_LINE> <INDENT> if not check_definition(param, configfile, lineno): <NEW_LINE> <INDENT> return (1, 0) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> n = int(value, radix) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> stderr('%s:%d: invalid ...
get numeric integer value
625941dce64d504609d74b4d
def add_docs_from(self, obj, *args, **kwargs): <NEW_LINE> <INDENT> if obj.__doc__ is not None: <NEW_LINE> <INDENT> self.add_docs(obj.__doc__, *args, **kwargs)
Parameters ---------- obj : object the object from which the `__doctring__` property should be parsed section : str the optional name of the initial section keep_only : list of str a list of sections that should be kept. All other section are discarded translate : dict str: str a dictionary of from_seti...
625941dcf7d966606f6aa315
def print_tree(self): <NEW_LINE> <INDENT> if self.left: <NEW_LINE> <INDENT> self.left.print_tree() <NEW_LINE> <DEDENT> print(self.data) <NEW_LINE> if self.right: <NEW_LINE> <INDENT> self.right.print_tree()
按顺序打印数的内容
625941dc2ae34c7f2600d43e
def edistw_to_finish(point, fline, walls): <NEW_LINE> <INDENT> (x, y) = point <NEW_LINE> ((x1, y1), (x2, y2)) = fline <NEW_LINE> if x1 == x2: <NEW_LINE> <INDENT> ds = [math.sqrt((x1 - x) ** 2 + (y3 - y) ** 2) for y3 in range(min(y1, y2), max(y1, y2) + 1) if not rt.crash(((x, y), (x1, y3)), wal...
straight-line distance from (x,y) to the finish line ((x1,y1),(x2,y2)). Return infinity if there's no way to do it without intersecting a wall
625941dca934411ee37519a1
def _inch_calculate(self, val): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return "%.4f" % val * 0.3937 <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return "Err"
Calculate inch value from given val in cm
625941dc4527f215b584c761
def CreateContext(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
This initializes the worker, informing it about the other workers in the cluster and exchanging authentication tokens which will be used in all other RPCs to detect whether the worker has restarted.
625941dc31939e2706e4d173
def test_incompatible_higher_rank_partial_outputs_raises(self): <NEW_LINE> <INDENT> input_graph = self._get_shaped_input_graph() <NEW_LINE> edge_model_fn, node_model_fn, global_model_fn = self._get_shaped_model_fns() <NEW_LINE> edge_model_fn_2 = functools.partial( snt.Conv2D, output_channels=10, kernel_shape=[3, 3], st...
A error should be raised if partial outputs have incompatible shapes.
625941dcbde94217f36830fb
def calculate_all_attentions(self, xs_pad, ilens, ys_pad): <NEW_LINE> <INDENT> self.eval() <NEW_LINE> if "custom" not in self.etype and "custom" not in self.dtype: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with torch.no_grad(): <NEW_LINE> <INDENT> self.forward(xs_pad, ilens, ys_pad) <N...
E2E attention calculation. Args: xs_pad (torch.Tensor): batch of padded input sequences (B, Tmax, idim) ilens (torch.Tensor): batch of lengths of input sequences (B) ys_pad (torch.Tensor): batch of padded character id sequence tensor (B, Lmax) Returns: ret (ndarray): attention weights with the...
625941dcd18da76e235327e6
def catch_exception(func, *args, **kwargs): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return jsonify({"message" : f"INVALID_PARAMETER_{e}"}), 400 <NEW_...
parameter 유효성 검사하는 데코레이터의 exception을 잡아줍니다. Args: func: parameter 유효성 검사하는 function Returns: 400 {"message" : "INVALID_PARAMETER_"} : parameter 유효성 검사 통과 못함 Author: tnwjd060124@gmail.com (손수정) History: 2020-08-29 (tnwjd060124@gmail.com) : 초기 생성
625941dc30bbd722463cc0d6
def set_vml_num_threads(nthreads): <NEW_LINE> <INDENT> if use_vml: <NEW_LINE> <INDENT> _set_vml_num_threads(nthreads) <NEW_LINE> <DEDENT> pass
Suggests a maximum number of threads to be used in VML operations. This function is equivalent to the call `mkl_domain_set_num_threads(nthreads, MKL_DOMAIN_VML)` in the MKL library. See: http://www.intel.com/software/products/mkl/docs/webhelp/support/functn_mkl_domain_set_num_threads.html for more info about it.
625941dc71ff763f4b54999e
def partition_with_profiler(model: nn.Module, sample_batch: Tensors, kwargs: Optional[Dict] = None, nparts=4, max_depth=100, basic_blocks: Optional[List[nn.Module]] = None, weighting_function: Optional[Callable[[Any], int]] = None) -> Graph: <NEW_LINE> <INDENT> graph = graph_builder(model, sample_batch, kwargs=kwargs, ...
return a graph representing the partitioned model with the weights given by the profiler this method does not distribute the model accross devices Parameters: model: the network we wish to model sample_batch: a sample input to use for tracing nparts: the number of partitions max_depth: how far down we ...
625941dc283ffb24f3c55c0b
def asp_grammar(): <NEW_LINE> <INDENT> def ident(): return ap.RegExMatch(r'[a-z][a-zA-Z0-9_]*') <NEW_LINE> def number(): return ap.RegExMatch(r'-?[0-9]+'), <NEW_LINE> def text(): return '"', ap.RegExMatch(r'((\\")|([^"]))*'), '"' <NEW_LINE> def variable(): return ap.RegExMatch(r'(([A-Z][a-zA-Z0...
Implement the Answer Set Programming grammar.
625941dcd6c5a1020814435a
def transform_scalars(dataset, size=2): <NEW_LINE> <INDENT> from tomviz import utils <NEW_LINE> import scipy.ndimage <NEW_LINE> import numpy as np <NEW_LINE> array = utils.get_array(dataset) <NEW_LINE> result = np.empty_like(array) <NEW_LINE> scipy.ndimage.filters.median_filter(array, size, output=result) <NEW_LINE> ut...
Apply a Median filter to dataset.
625941dc187af65679ca542c
def test_post_no_permission(self): <NEW_LINE> <INDENT> new_project = self._make_project( 'NewProject', PROJECT_TYPE_PROJECT, None ) <NEW_LINE> new_user = self.make_user('new_user') <NEW_LINE> self._make_assignment(new_project, new_user, self.role_owner) <NEW_LINE> with self.login(new_user): <NEW_LINE> <INDENT> response...
Test POST with no user permission on a project
625941dc7d847024c06be5cc