code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def visitall(item): <NEW_LINE> <INDENT> yield from _visitall(item, '')
Visit entity recursively including links. It does not follow links. This is a generator yielding (relative path, object) for visited items. :param item: The item to visit.
625941e59c8ee82313fbbba3
def from_now(self): <NEW_LINE> <INDENT> return self.render("fromNow()")
Use fromNow method of momentjs library :return Markup: return markup string
625941e52eb69b55b151cce2
@app.route("/api/<isbn>", methods=["GET"]) <NEW_LINE> def api(isbn): <NEW_LINE> <INDENT> if isbn == "": <NEW_LINE> <INDENT> return render_template("error.html", error_message="ISBN not found") <NEW_LINE> <DEDENT> if isbn: <NEW_LINE> <INDENT> books_object = db.execute("SELECT * FROM books WHERE isbn = '%s'" % isbn).fetc...
API route for users
625941e5462c4b4f79d1dafc
def offset_increment(self): <NEW_LINE> <INDENT> return self._offset_increment
Returns a vector that should be added to the offset vector to accommodate the constraint. Parameters ---------- exog : array-like The exogeneous data for the model.
625941e523849d37ff7b34b9
def listAllowedFormats(content=None, content_type=None): <NEW_LINE> <INDENT> pass
List the allowed values of the 'Format' DCMI element. o These items should be usable as HTTP 'Content-type' values. o Return only values appropriate for content's type, or all values if both 'content' and 'content_type' are None.
625941e5090684286d50f119
def testIteration(self): <NEW_LINE> <INDENT> dw = DetectorWrapper() <NEW_LINE> ampList = [amp for amp in dw.detector] <NEW_LINE> self.assertEqual(len(ampList), len(dw.ampInfo)) <NEW_LINE> for i, amp in enumerate(ampList): <NEW_LINE> <INDENT> self.assertEqual(amp.getName(), dw.detector[i].getName()) <NEW_LINE> self.asse...
Test iteration over amplifiers and __getitem__
625941e58c3a8732951587ed
def update_certificate_operation( self, vault_base_url, certificate_name, cancellation_requested, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> certificate_operation = models.CertificateOperationUpdateParameter(cancellation_requested=cancellation_requested) <NEW_LINE> url = self.update_certif...
Updates a certificate operation. Updates a certificate creation operation that is already in progress. This operation requires the certificates/update permission. :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. :type vault_base_url: str :param certificate_name: The name of the cer...
625941e5cb5e8a47e48b7ed1
@jitted <NEW_LINE> def surf96(t, d, a, b, rho, mode=0, itype=0, ifunc=2, dc=0.005, dt=0.025): <NEW_LINE> <INDENT> nt = len(t) <NEW_LINE> t1 = np.empty(nt, dtype=np.float64) <NEW_LINE> if itype == 1: <NEW_LINE> <INDENT> fac = 1.0 + dt <NEW_LINE> for i in range(nt): <NEW_LINE> <INDENT> t1[i] = t[i] / fac <NEW_LINE> <DEDE...
Get phase or group velocity dispersion curve. Parameters ---------- t : array_like Periods (in s). d : array_like Layer thickness (in km). a : array_like Layer P-wave velocity (in km/s). b : array_like Layer S-wave velocity (in km/s). rho : array_like Layer density (in g/cm3). mode : int, optional,...
625941e5293b9510aa2c36bf
def use_different_pieces(*groups): <NEW_LINE> <INDENT> pieces = [piece for group in groups for piece in group.pieces] <NEW_LINE> for piece in pieces: <NEW_LINE> <INDENT> if pieces.count(piece) > 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Compares multiple groups to make sure they don't have any pieces in common. Returns True if valid.
625941e566656f66f7cbc5da
def get_version(): <NEW_LINE> <INDENT> return "v0.2.00"
Returns the version currently in development. :return: (str) Version string :since: v0.1.00
625941e5d53ae8145f87a695
def get_paginated_response(self, data): <NEW_LINE> <INDENT> context = OrderedDict([ ('page_total', self.page.paginator.num_pages), ('page_size', self.page_size), ('page_number', self.page.number), ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', d...
重写该方法, 自定义response数据 1、获取更全的分页数据, 如总页数等 2、提供一种再response前, 扩展response数据的方法
625941e596565a6dacc8faf7
def _get_te_default_metric(self): <NEW_LINE> <INDENT> return self.__te_default_metric
Getter method for te_default_metric, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/isis_neighbor_attribute/neighbors/neighbor/subTLVs/subTLVs/te_default_metric/state/te_default_metric (uint32) YANG Description: This metric is...
625941e5a4f1c619b28b045d
def worker_loop(dataset, key_queue, data_queue, batchify_fn): <NEW_LINE> <INDENT> _recursive_fork_recordio(dataset, 0, 1000) <NEW_LINE> while True: <NEW_LINE> <INDENT> idx, samples = key_queue.get() <NEW_LINE> if idx is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> batch = batchify_fn([dataset[i] for i in samples...
Worker loop for multiprocessing DataLoader.
625941e5d4950a0f3b08c776
def testPackX86RomOutside(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError) as e: <NEW_LINE> <INDENT> self._DoTestFile('28_pack_4gb_outside.dts') <NEW_LINE> <DEDENT> self.assertIn("Node '/binman/u-boot': Position 0x0 (0) is outside " "the image starting at 0xffffffe0 (4294967264)", str(e.exception))
Test that the end-at-4gb property checks for position boundaries
625941e57d43ff24873a30d1
def get_img_paths_by_idx(mri_dir: str) -> dict: <NEW_LINE> <INDENT> img_paths_by_idx: dict = {} <NEW_LINE> for mri_idx in range(MIN_SEQ_LEN): <NEW_LINE> <INDENT> img_paths: list = MRIDataset(mri_idx=mri_idx, mri_dir=mri_dir).img_paths <NEW_LINE> img_paths_by_idx[mri_idx] = img_paths <NEW_LINE> <DEDENT> return img_paths...
Gets the paths to all the MRIs, organized by splice index
625941e556ac1b37e62645f5
def __init__(self, batch_size=100, ini_learning_rate=0.001, max_epochs=100, patience=10, y_tensor_type=T.ivector, L2=1e-4, objective=mean_categorical_crossentropy, adapt_learn_rate=get_constant(), update_function=get_update_adam(), valid_batch_iter=get_batch_iterator(), train_batch_iter=get_batch_iterator(), use_weight...
Constructor
625941e53539df3088e2e778
def test_vec3_square_length2(self): <NEW_LINE> <INDENT> given = (0, 0, 0) <NEW_LINE> v = vec3.Vec3(given) <NEW_LINE> expect = given[0]**2 + given[1]**2 + given[2]**2 <NEW_LINE> len_v = v.square_length <NEW_LINE> msg = "len(v) should be %.*f, got %.*f" % (Places, expect, Places, len_v) <NEW_LINE> self.assertAlmostEqual(...
Check square_length() function on Vec3.
625941e5c432627299f05076
def newton(self, p, d1, d2, x=np.ones(18), k_max=30, tol=1.e-10): <NEW_LINE> <INDENT> for k in range(k_max): <NEW_LINE> <INDENT> J = self.jacobian(p, d1, d2, x) <NEW_LINE> func = self.problem_function(p, d1, d2, x) <NEW_LINE> if npl.norm(func) < tol: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT...
Computes the solution of the system of equations at a bifurcation using Newton's method. Arguments --------- p : Artery Parent artery in the bifurcation d1 : Artery First daughter artery in the bifurcation d2 : Artery Second daughter artery in the bifurcation x : numpy.array Current solution k_max: int...
625941e58e71fb1e9831dbd5
@app.route('/') <NEW_LINE> def default(): <NEW_LINE> <INDENT> template_values = { 'username': users.get_current_user(), 'validuser': is_valid_user(), 'login_url': users.create_login_url('/'), 'logout_url': users.create_logout_url('/') } <NEW_LINE> template = JINJA_ENVIRONMENT.get_template('main.html') <NEW_LINE> return...
Render the main page.
625941e5377c676e912725d4
def add(self, item, key): <NEW_LINE> <INDENT> self._nodes.append([item, key]) <NEW_LINE> self._fix_heap_up(len(self._nodes)-1)
Add the item with the given key to the binary heap. Efficiency: O(log n) where n = number of nodes in heap. >>> h = BinaryHeap() >>> h.add("A", 3) >>> h.add("B", 1) >>> h.add("C", 4) >>> h._nodes[0] == ["B", 1] True >>> h.add("D", 0) >>> h._nodes[0] == ["D", 0] True
625941e576e4537e8c351aa3
def epoch_secs_to_local_datetime(epoch_secs) -> datetime: <NEW_LINE> <INDENT> return datetime.fromtimestamp(epoch_secs)
Get a string of local time representation from integer epoch in seconds
625941e59c8ee82313fbbba4
def run_command_exception_on_stderr(cmd, shell=False, use_pipes=True): <NEW_LINE> <INDENT> out, err = run_command(cmd, shell=shell, use_pipes=use_pipes) <NEW_LINE> if err: <NEW_LINE> <INDENT> raise CommandOutputError(err) <NEW_LINE> <DEDENT> return out
Runs a shell command, raised exception if stderr :param cmd: The command that needs to be run. :param shell: Default False: Whether to run raw shell commands with '|' and redirections :param use_pipes: Default True: If true, then pipes are used for communication :return: Command output and err :raises subprocess.Called...
625941e5fb3f5b602dac3ac5
def _add_timeout(self, future, timeout): <NEW_LINE> <INDENT> def future_timeout(): <NEW_LINE> <INDENT> if future.done(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> future.set_exception(_zmq.Again()) <NEW_LINE> <DEDENT> return self._call_later(timeout, future_timeout)
Add a timeout for a send or recv Future
625941e59f2886367277acb7
def SCardGetAttribTest(hcontextTest, hcardTest, readerName): <NEW_LINE> <INDENT> global unblocked <NEW_LINE> testFunctionName = sys._getframe().f_code.co_name <NEW_LINE> print("Test thread for %s" % testFunctionName) <NEW_LINE> before = time.time() <NEW_LINE> hresult, attrib = SCardGetAttrib(hcardTest, SCARD_ATTR_DEVIC...
SCardGetAttribTest
625941e58c0ade5d55d3edec
def count_phonetics(): <NEW_LINE> <INDENT> checks = 7 <NEW_LINE> errors = 0 <NEW_LINE> if encode(13) == encode(30): <NEW_LINE> <INDENT> errors += 1 <NEW_LINE> <DEDENT> if encode(14) == encode(40): <NEW_LINE> <INDENT> errors += 1 <NEW_LINE> <DEDENT> if encode(15) == encode(50): <NEW_LINE> <INDENT> errors += 1 <NEW_LINE>...
Count the fraction of phonetic errors missed.
625941e5de87d2750b8601c4
def set_scale(self, value): <NEW_LINE> <INDENT> self.user_embdding.set_scale(value) <NEW_LINE> if self.single: <NEW_LINE> <INDENT> self.img_encoder.set_scale(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for encoder in self.img_encoder: <NEW_LINE> <INDENT> encoder.set_scale(value)
Set scale tahn.
625941e50a366e3fb873ec4c
def __init__(self, annotation_file=None): <NEW_LINE> <INDENT> self.dataset, self.anns, self.imgs = dict(), dict(), dict() <NEW_LINE> self.imgToAnns = defaultdict(list) <NEW_LINE> if annotation_file: <NEW_LINE> <INDENT> print('loading annotations into memory...') <NEW_LINE> tic = time.time() <NEW_LINE> dataset = json.lo...
Constructor of Microsoft COCO helper class for reading and visualizing annotations. :param annotation_file (str): location of annotation file :param image_folder (str): location to the folder that hosts images. :return:
625941e5d164cc617578317d
def logdbmanager(msg): <NEW_LINE> <INDENT> with open('{0}{1}log_dbmanager.log'.format(LOG_FOLDER), 'a') as flog: <NEW_LINE> <INDENT> flog.writelines('{0}: {1}\n'.format(datetime.today().strftime('%d/%m/%Y %H:%M:%S'), msg))
Registra o log do dbmanager msg = mensagem do log
625941e563d6d428bbe4491e
def init_threads(poll_interval_ms=50): <NEW_LINE> <INDENT> _get_interp().init_threads(poll_interval_ms)
Allow using teek from other threads than the main thread. This is implemented with a queue. This function starts an :ref:`after callback <after-cb>` that checks for new messages in the queue every 50 milliseconds (that is, 20 times per second), and when another thread calls a teek function that does a :ref:`Tcl call <...
625941e5046cf37aa974d171
def _checkdir(directory): <NEW_LINE> <INDENT> directory = path.Path(directory) <NEW_LINE> if not directory.exists(): <NEW_LINE> <INDENT> print('Creating new directory', directory) <NEW_LINE> directory.mkdir(parents=True) <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True
Checks if directory exists, if not creates directory. Parameters ---------- directory : str Directory to check. Returns ------- isdir : bool True if directory exists, False if directory didn't exist when function was called.
625941e58a349b6b435e85a0
def pop(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise EmptyStack("Stack is empty") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> returnvalue = self._list[self._end - 1] <NEW_LINE> self._list[self._end - 1] = None <NEW_LINE> self._end = self._change_location_variable(self._end, -1) <NEW_LINE> ...
Pop the element at the top of the stack. This returns the value and removes it from the stack. :return: The element currently at the top of the stack.
625941e5442bda511e8be840
def test_write(tmpdir): <NEW_LINE> <INDENT> class TestWrite(util.TestScript): <NEW_LINE> <INDENT> @experiment(data_param='data') <NEW_LINE> def exp(self, data, param): <NEW_LINE> <INDENT> return np.power(data, param) <NEW_LINE> <DEDENT> <DEDENT> script = TestWrite(tmpdir) <NEW_LINE> pval = 4 <NEW_LINE> result_filename ...
@experiment-decorated methods should write their results to disk.
625941e57c178a314d6ef894
def load_dataset(args, corpus_type, shuffle): <NEW_LINE> <INDENT> assert corpus_type in ["train", "valid", "test"] <NEW_LINE> def _lazy_dataset_loader(pt_file, corpus_type): <NEW_LINE> <INDENT> dataset = torch.load(pt_file) <NEW_LINE> logger.info('Loading %s dataset from %s, number of examples: %d' % (corpus_type, pt_f...
Dataset generator. Don't do extra stuff here, like printing, because they will be postponed to the first loading time. Args: corpus_type: 'train' or 'valid' Returns: A list of dataset, the dataset(s) are lazily loaded.
625941e557b8e32f524838cb
def run(test, params, env): <NEW_LINE> <INDENT> block_test = BlockdevCommitHotunplug(test, params, env) <NEW_LINE> block_test.run_test()
Hotunplug during block commit 1. boot guest with data disk 2. do live commit 3. hotunplug data disk and check disk status 3. check block job status 4. check if the block job is completed
625941e58a43f66fc4b5448f
def makeIntOrDie(InputString): <NEW_LINE> <INDENT> TempFloat = float(InputString) <NEW_LINE> OutputInt = int(TempFloat) <NEW_LINE> if TempFloat == OutputInt: <NEW_LINE> <INDENT> return(OutputInt) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Float bitwise operand: " + InputString + ".")
Returns integer or raises exception.
625941e5d99f1b3c44c679b5
def number_of_subscribers(subreddit): <NEW_LINE> <INDENT> url = 'https://www.reddit.com' <NEW_LINE> query = '/r/' + subreddit + '/about.json' <NEW_LINE> res = requests.get(url+query, headers={'User-agent': 'your bot 0.1'}) <NEW_LINE> if res.status_code != 200: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return res...
return total subscribers
625941e53eb6a72ae02ec916
def qsub_del(self, id): <NEW_LINE> <INDENT> runCmd(["qdel", id]) <NEW_LINE> return 0
If -sync t option not available for our version of qsub, we need to manually delete the jobs from the qsub queue :returns: 0. Called for side effect of terminating jobs
625941e5711fe17d82542790
def decreasing_exclamation_marks(m, n): <NEW_LINE> <INDENT> pass
Prints exclamation marks: m on the first row, m-1 on the next row, m-2 on the next, etc, until n on the last row. For example, when m = 5 and n = 2: !!!!! !!!! !!! !! Precondition: m and n are positive integers with m >= n.
625941e557b8e32f524838cc
def actor(self, batch): <NEW_LINE> <INDENT> if self.verbose: print("In Evaluator[%s]::actor" % self.name) <NEW_LINE> m = self.mi[self.actor_name] <NEW_LINE> m.set_volatile(True) <NEW_LINE> state_curr = m.forward(batch.hist(0)) <NEW_LINE> m.set_volatile(False) <NEW_LINE> if self.sampler is not None: <NEW_LINE> <INDENT> ...
Actor. Get the model, forward the batch and get a distribution. Sample from it and act. Reply the message to game engine. Args: batch(dict): batch data Returns: reply_msg(dict): ``pi``: policy, ``a``: action, ``V``: value, `rv`: reply version, signatured by step
625941e58e71fb1e9831dbd6
@superState('gameControllerResponder') <NEW_LINE> def gameReady(player): <NEW_LINE> <INDENT> if player.firstFrame(): <NEW_LINE> <INDENT> player.inKickingState = False <NEW_LINE> player.brain.fallController.enabled = True <NEW_LINE> player.brain.nav.stand() <NEW_LINE> player.brain.tracker.repeatBasicPan() <NEW_LINE> pla...
Stand up, and pan for localization, and walk to kicking off positions.
625941e524f1403a92600f91
def detect_text(path): <NEW_LINE> <INDENT> with io.open(path,'rb') as image_file: <NEW_LINE> <INDENT> content = image_file.read() <NEW_LINE> <DEDENT> image = vision_client.image(content=content) <NEW_LINE> texts = image.detect_text() <NEW_LINE> print('\nThe writings on it say:') <NEW_LINE> for text in texts: <NEW_LINE>...
Detects text in the file.
625941e5097d151d1a223286
def pack_ushort_to_hn(val): <NEW_LINE> <INDENT> return ((val & 0xff) << 8) | ((val & 0xff00) >> 8) & 0xffff
Pack unsigned short to network order unsigned short
625941e530c21e258bdfa8cf
def do_set_collection_text_mining_xml(crossref_config): <NEW_LINE> <INDENT> if ( crossref_config.get("text_mining_xml_pattern") and crossref_config.get("text_mining_pdf_pattern") != "" ): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
decide whether to text mining xml resource
625941e53617ad0b5ed68325
@app.route('/api/v1/conference/', methods=['POST']) <NEW_LINE> def conference_api(): <NEW_LINE> <INDENT> conference_name = 'p%s' % (make_id(8)) <NEW_LINE> app_id = create_plivo_application(conference_name) <NEW_LINE> endpoint_username = create_plivo_endpoint(conference_name, app_id) <NEW_LINE> inbound_did = attach_inbo...
1. Create a conference name 2. Create an endpoint and store in redis with conference name 3. Attach the above application to it 4. Return endpoint username/password to template
625941e530bbd722463cc1f6
def get_swem_mean(train: pd.DataFrame, test: pd.DataFrame, col_definition: dict, option: dict): <NEW_LINE> <INDENT> n_train = len(train) <NEW_LINE> train = pd.concat([train, test], sort=False).reset_index(drop=True) <NEW_LINE> vectorizer = make_pipeline( make_union( TruncatedSVD(n_components=option['n_components'], ran...
col_definition: text_col option: n_components, lang={'ja', 'en'}
625941e51b99ca400220aee1
def setConnection(self, cellX, cellY, numNeigh): <NEW_LINE> <INDENT> [connX, connY] = self._cell2connCoord(cellX, cellY, numNeigh) <NEW_LINE> self.connectionMatrix[connX, connY]=1
open a connection, i.e., we can go straight from cellX,cellY to its neighbour number numNeigh
625941e55fdd1c0f98dc0663
def resize_image(source: ImageModel, width: int, height: int) -> None: <NEW_LINE> <INDENT> if width is None: <NEW_LINE> <INDENT> width = height <NEW_LINE> <DEDENT> if height is None: <NEW_LINE> <INDENT> height = width <NEW_LINE> <DEDENT> output_io_stream = BytesIO() <NEW_LINE> image = Image.open(source.original_image) ...
Изменяет размер исходного изображения
625941e5d18da76e23532909
def landingFlaps(self): <NEW_LINE> <INDENT> sflaps = self.getString('flaps').split(',') <NEW_LINE> land_flap = [] <NEW_LINE> regex = r"\d+" <NEW_LINE> for f in sflaps: <NEW_LINE> <INDENT> if 'L' in f: <NEW_LINE> <INDENT> m = re.search(regex, f) <NEW_LINE> land_flap.append(int(f[m.start():m.end()])) <NEW_LINE> <DEDENT> ...
'flaps' keyword in aircrafts.cfg must have a 'T' or an 'L' for takeoff and landing flap setting. Example in aircraft.cfg: flaps = 0, 1, 2, 5T, 10T, 15TL, 25L, 30L, 40L
625941e5379a373c97cfaf75
def __add_adj_list(self, edges=None): <NEW_LINE> <INDENT> if edges is None: <NEW_LINE> <INDENT> if len(self.adj_list) > 0: <NEW_LINE> <INDENT> raise ValueError('Please delete all edges from adjacency list before adding all edges') <NEW_LINE> <DEDENT> edges = self.exp_weight_sorted <NEW_LINE> <DEDENT> for edge in edges:...
Update adjacency list with specified additional edges (larger subgraph). If edges not specified, update adjacency list with all edges (entire graph) :param edges list: list of edges to update adjacency list with
625941e5bf627c535bc135fe
def is_BST(root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> stack = [] <NEW_LINE> pre = None <NEW_LINE> while root and stack: <NEW_LINE> <INDENT> while root: <NEW_LINE> <INDENT> stack.append(root) <NEW_LINE> root = root.left <NEW_LINE> <DEDENT> root = stack.pop() <NEW_LINE> if...
:type root: TreeNode :rtype: bool
625941e5a8ecb033257d34fa
def getUDPSocket(ttl): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> socketObj = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) <NEW_LINE> socketObj.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl) <NEW_LINE> <DEDENT> except socket.error as e: <NEW_LINE> <INDENT> if e.errno in ErrorDescriptions: <NEW_...
Get UDP socket instance Returns: socketObj
625941e5046cf37aa974d172
def calculate_statistic(statistic, N, M, sigma, Y): <NEW_LINE> <INDENT> noise_list = [white_noise(sigma, M-1, seed) for seed in range(N)] <NEW_LINE> walk_list = [random_walk(Y, noise) for noise in noise_list] <NEW_LINE> statistic_array = np.array([statistic(series) for series in walk_list]) <NEW_LINE> return statistic_...
Генерирование N случайных блужданий длины M с дисперсией белого шума sigma и начальным условием Y и подсчёт по ним статистики statistic
625941e591af0d3eaac9be4b
def my_hook(hook_dict): <NEW_LINE> <INDENT> if hook_dict['status'] == 'finished': <NEW_LINE> <INDENT> print('my_hook: finished') <NEW_LINE> print("filename: {}".format(hook_dict["filename"])) <NEW_LINE> <DEDENT> if hook_dict['status'] == 'downloading': <NEW_LINE> <INDENT> print("my_hook: downloading") <NEW_LINE> <DEDEN...
Actions to be launched on various YoutubeDL events can be specified here
625941e523849d37ff7b34ba
def __init__(self, maximum=None): <NEW_LINE> <INDENT> super(PoolManager, self).__init__() <NEW_LINE> self.maximum = maximum <NEW_LINE> self._all = [] <NEW_LINE> self._available = []
Create pool manager. :param maximum: Maximum number of items to create :type maximum: int or None
625941e56fece00bbac2db72
def testSetDefaultCVSTagType( self ): <NEW_LINE> <INDENT> self.assertRaises( BIFException, self.bif.setDefaultCVSTagType, 'bad_type' )
BadDataTestCase::setDefaultCVSTagType - invalid cvs tag type
625941e599cbb53fe6793013
def playerRange(ran): <NEW_LINE> <INDENT> for char in cv.character_list: <NEW_LINE> <INDENT> if ran in char.range: <NEW_LINE> <INDENT> char.points += 1
Every character with the respective ranges gets one point, chars can have more than one range
625941e5283ffb24f3c55d2b
def get_NameString2(self): <NEW_LINE> <INDENT> return super(IAGSServerObjectName2, self).get_NameString2()
Method IAGSServerObjectName2.get_NameString2 OUTPUT ns : BSTR*
625941e599cbb53fe6793014
def log_time(self, losses, step_duration, fetch_time, model_update_time): <NEW_LINE> <INDENT> samples_per_sec = self.opt.batch_size / step_duration <NEW_LINE> time_so_far = time() - self.start_time <NEW_LINE> training_time_left = ( self.config['n_iterations'] / self.global_step - 1.0) * time_so_far if self.global_step ...
Print a logging statement to the terminal
625941e5099cdd3c635f1087
def load_parser(grammar_url, trace=0, parser=None, chart_class=None, beam_size=0, **load_args): <NEW_LINE> <INDENT> grammar = load(grammar_url, **load_args) <NEW_LINE> if not isinstance(grammar, ContextFreeGrammar): <NEW_LINE> <INDENT> raise ValueError("The grammar must be a ContextFreeGrammar, " "or a subclass thereof...
Load a grammar from a file, and build a parser based on that grammar. The parser depends on the grammar format, and might also depend on properties of the grammar itself. The following grammar formats are currently supported: - ``'cfg'`` (CFGs: ``ContextFreeGrammar``) - ``'pcfg'`` (probabilistic CFGs: ``WeightedG...
625941e5e5267d203edce0c6
def __nonzero__(self): <NEW_LINE> <INDENT> if self._vertex: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
False if no elements.
625941e53cc13d1c6d3c77a6
def make_module_view( slot_by_module_id: Optional[Dict[str, DeckSlotName]] = None, hardware_module_by_slot: Optional[Dict[DeckSlotName, HardwareModule]] = None, virtualize_modules: bool = False, ) -> ModuleView: <NEW_LINE> <INDENT> state = ModuleState( slot_by_module_id=slot_by_module_id or {}, hardware_module_by_slot=...
Get a module view test subject with the specified state.
625941e54e4d5625662d4800
def test_0004(self): <NEW_LINE> <INDENT> ts = datetime.utcnow() <NEW_LINE> messages = [ {'message_description':'TIMESTAMP test\nPLUGINS_REMOVED\nPATH_PLUGINS_REMOVED', 'message_title': 'Test 1', 'creation_time': ts, 'additional_info': { 'plugins_removed': [ '/etc/ossim/plugin1.cfg', '/etc/ossim/plugin2.cfg', '/etc/ossi...
Plugin changed
625941e5cc0a2c11143dd2c1
def print_solution(self): <NEW_LINE> <INDENT> solutions = [] <NEW_LINE> term = ord('a') <NEW_LINE> pivots = self.get_first_nonzero_indexes() <NEW_LINE> for row, dim in enumerate(pivots): <NEW_LINE> <INDENT> if dim > -1: <NEW_LINE> <INDENT> plane = self.planes[row] <NEW_LINE> solutions.append('{} = {}'.format( chr(term)...
Print out the equation in the form of A = K1, B = K2 etc
625941e567a9b606de4a82e6
def add_video_device(video_model, domain_xml, is_primary=None, status_error=False, **kwargs): <NEW_LINE> <INDENT> video_dev = Video() <NEW_LINE> video_dev.model_type = video_model <NEW_LINE> if is_primary: <NEW_LINE> <INDENT> video_dev.primary = "yes" <NEW_LINE> <DEDENT> for key, value in list(iteritems(kwargs)): <NEW_...
add the video device xml snippet, then sync the guest xml
625941e5009cb60464c637dd
def update(self, request, id, body=None): <NEW_LINE> <INDENT> payload = body.copy() <NEW_LINE> payload['id'] = id <NEW_LINE> notifier_api.notify(request.context, self._publisher_id, self._resource + '.update.start', notifier_api.INFO, payload) <NEW_LINE> body = Controller.prepare_request_body(request.context, body, Fal...
Updates the specified entity's attributes
625941e5dc8b845886cb5966
@register_ibs_method <NEW_LINE> @accessor_decors.getter_1to1 <NEW_LINE> @register_api('/api/species/uuid/', methods=['GET'], __api_plural_check__=False) <NEW_LINE> def get_species_uuids(ibs, species_rowid_list): <NEW_LINE> <INDENT> uuids_list = ibs.db.get(const.SPECIES_TABLE, (SPECIES_UUID,), species_rowid_list) <NEW_L...
Returns: list_ (list): uuids_list - species uuids RESTful: Method: GET URL: /api/species/uuid/
625941e5435de62698dfe07c
def __init__(self, suppress_notifications=None, ignore_teams_from_payload=None, ignore_recipients_from_payload=None, recipients=None, is_advanced=None, feature_type=None, allow_configuration_access=None, allow_write_access=None): <NEW_LINE> <INDENT> self._suppress_notifications = None <NEW_LINE> self._ignore_teams_from...
PingdomV2Integration - a model defined in Swagger
625941e58e7ae83300e4b3fd
def test_strictleftonly(self): <NEW_LINE> <INDENT> s = "1(2(3(4(5(6)))))" <NEW_LINE> root = mfs(s, BTN) <NEW_LINE> root.fixsize() <NEW_LINE> self.assertEqual( root.find_kth_node(1).val, 6) <NEW_LINE> self.assertEqual( root.find_kth_node(3).val, 4) <NEW_LINE> self.assertEqual( root.find_kth_node(5).val, 2)
Test a tree with only left children.
625941e550812a4eaa59c74c
def gmBottomRowRebars(sectionGeom,fiberMatName, nRebars, areaRebar, depth, width, cover): <NEW_LINE> <INDENT> return gmHorizRowRebars(sectionGeom, fiberMatName, nRebars, areaRebar, depth, width, cover, cover-depth/2)
Horizontal row of reinforcement bars in the bottom face
625941e5d164cc617578317e
def transform(self, target_contexts): <NEW_LINE> <INDENT> token_contexts = [] <NEW_LINE> for target_span_contexts in target_contexts: <NEW_LINE> <INDENT> token_span_contexts = [] <NEW_LINE> for span_context in target_span_contexts: <NEW_LINE> <INDENT> tokens = self.tokeniser(span_context) <NEW_LINE> if self.lower: <NEW...
Given a list of String lists where each String represents a context per target span it returns those Strings as a list of Strings (tokens). :param target_contexts: A list of String lists e.g. [['It was nice this morning', 'It was nice this morning but not yesterday morning'], ['another day']] where eac...
625941e5b545ff76a8914244
def _LUdecompositionFF(M): <NEW_LINE> <INDENT> from sympy.matrices import SparseMatrix <NEW_LINE> zeros = SparseMatrix.zeros <NEW_LINE> eye = SparseMatrix.eye <NEW_LINE> n, m = M.rows, M.cols <NEW_LINE> U, L, P = M.as_mutable(), eye(n), eye(n) <NEW_LINE> DD = zeros(n, n) <NEW_LINE> oldpivot = 1 <NEW_...
Compute a fraction-free LU decomposition. Returns 4 matrices P, L, D, U such that PA = L D**-1 U. If the elements of the matrix belong to some integral domain I, then all elements of L, D and U are guaranteed to belong to I. See Also ======== LUdecomposition LUdecomposition_Simple LUsolve References ========== .. ...
625941e531939e2706e4d293
def get_loopy_callables(): <NEW_LINE> <INDENT> known_callables = { "make_tuple": MakeTupleCallable(name="make_tuple"), "indexof": IndexOfCallable(name="indexof"), "indexof_vec": IndexOfCallable(name="indexof_vec"), } <NEW_LINE> return known_callables
Returns a mapping from function ids to corresponding :class:`loopy.kernel.function_interface.InKernelCallable` for functions whose interface is provided by :mod:`loopy`. Callables that fall in this category are -- - reductions leading to function calls like ``argmin``, ``argmax``. - callables that have a predefined me...
625941e57cff6e4e81117db4
def __init__(self, mdl=None): <NEW_LINE> <INDENT> super(FznReader, self).__init__() <NEW_LINE> self.source_file = None <NEW_LINE> self.tokenizer = None <NEW_LINE> self.token = None <NEW_LINE> self.var_map = {} <NEW_LINE> self.parameters = [] <NEW_LINE> self.variables = [] <NEW_LINE> self.constraints = [] <NEW_LINE> sel...
Create a new FZN reader
625941e5287bf620b61d3e90
def notify(self, commits): <NEW_LINE> <INDENT> for commit in commits: <NEW_LINE> <INDENT> cmd = ['buildbot', 'sendchange'] <NEW_LINE> def add_option(prefix, value): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> cmd.append('='.join([prefix, value])) <NEW_LINE> <DEDENT> <DEDENT> def add_property(name, val...
Notify the buildmaster of the specified commits
625941e56aa9bd52df0371d6
def _check_obj(self, other): <NEW_LINE> <INDENT> supported_types = [int, float, int, complex, np.float64, np.float32] <NEW_LINE> if is_reflfunction(other): <NEW_LINE> <INDENT> if self.id != other.id: <NEW_LINE> <INDENT> raise TypeError("Two ReflFunction objects must have identical id's to conduct arithmetic operations"...
Checks the object other so that it fulfills the demands for arithmetic operations.
625941e57b180e01f3dc4c24
@then("push link in navigation menu '{button}'") <NEW_LINE> def step(context, button): <NEW_LINE> <INDENT> context.clickActions = ClickActions(context) <NEW_LINE> context.clickActions.click_header_nav_menu(button)
Then push link in navigation menu 'button'
625941e5a05bb46b383ecc4d
def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkComplexToImaginaryImageFilterICF3IF3.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj
New() -> itkComplexToImaginaryImageFilterICF3IF3 Create a new object of the class itkComplexToImaginaryImageFilterICF3IF3 and set the input and the parameters if some named or non-named arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects - the first ...
625941e53eb6a72ae02ec917
def get_tlm_dict_raw_json(self): <NEW_LINE> <INDENT> return json.dumps(self._aitTlmDict.toJSON())
Returns the AIT-formatted dictionary
625941e54d74a7450ccd45f3
def compare_texts(x, y, ngram_length=3, preserve_order=True, remove_stopwords=True, remove_punctuation=True): <NEW_LINE> <INDENT> x_tokens, y_tokens = prep_texts(x, y, remove_stopwords, remove_punctuation) <NEW_LINE> x_ngrams = [i for i in find_ngrams(x_tokens, ngram_length)] <NEW_LINE> y_ngrams = [i for i in find_ngra...
Function to compare the similarity of two texts. Output is a similarity score based on Jaccard similarity, where a score of 1 indicates exact texts and a score of 0 indicates no commonality between the texts :param x: Text 1 :param y: Text 2 :param ngram_length: Option for considering bigrams, trigrams, etc. :param pre...
625941e530bbd722463cc1f7
@testreadonly <NEW_LINE> def changeUidWithDialog(page, application): <NEW_LINE> <INDENT> global _ <NEW_LINE> _ = get_() <NEW_LINE> if page is None or page.parent is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if page.readonly: <NEW_LINE> <INDENT> raise ReadonlyException <NEW_LINE> <DEDENT> title = _(u"Change p...
Show dialog to change page UID
625941e52eb69b55b151cce4
def gradbfun(self, gradbfunout, gradbfunpar, redjacmat): <NEW_LINE> <INDENT> for r in range(gradbfunout.shape[0]): <NEW_LINE> <INDENT> gradbfunout[r, 0] = gradbfunpar[r, 0] / redjacmat[0, 0]
Compute the gradient of the basis functions with the respect to the "reduced" spatial coordinates. :param gradbfunpars: matrix of gradients with respect to parametric coordinates, one per row :param redjacmat: reduced Jacobian matrix redJ=Rm'*J :param gradbfunout: the results will be placed in this matrix :return: Not...
625941e550812a4eaa59c74d
def colourCut(mag): <NEW_LINE> <INDENT> return 0.15 - 0.03*mag
Return g-r colour cut corresponding to r-band absolute mag
625941e5a4f1c619b28b045f
def pass_test(): <NEW_LINE> <INDENT> pass
파이썬은 함수내용을 적지않으면 오류가남 나중에 추가할 거면 pass로 일단 해놔야됨
625941e5eab8aa0e5d26df89
def cP2cSt(cP, SG): <NEW_LINE> <INDENT> cSt = cP/SG <NEW_LINE> return cSt
Parameters ---------- cP : dynamic viscosity in centiPoise(cP) SG : Specific Gravity Returns ------- cSt : kinematic viscosity in centiStokes (cSt)
625941e5379a373c97cfaf76
def on_batch_begin(self, net, **kwargs): <NEW_LINE> <INDENT> pass
Called at the beginning of each batch.
625941e5627d3e7fe0d69281
def item(self): <NEW_LINE> <INDENT> warnings.warn( "`item` has been deprecated and will be removed in a future version", FutureWarning, stacklevel=2, ) <NEW_LINE> return self.values.item()
Return the first element of the underlying data as a python scalar. .. deprecated:: 0.25.0 Returns ------- scalar The first element of %(klass)s.
625941e54e696a04525c987d
def _add_partition(self, connection, partition): <NEW_LINE> <INDENT> logger.debug('Creating virtual table for partition.\n partition: {}'.format(partition.name)) <NEW_LINE> sqlite_med.add_partition(connection, partition.datafile, partition.vid+'_vt')
Creates sqlite virtual table for mpr file of the given partition. Args: connection: connection to the sqlite db who stores mpr data. partition (orm.Partition):
625941e5d7e4931a7ee9e34e
def __init__(self, wf_spec, name, transforms=None, **kwargs): <NEW_LINE> <INDENT> assert wf_spec is not None <NEW_LINE> assert name is not None <NEW_LINE> TaskSpec.__init__(self, wf_spec, name, **kwargs) <NEW_LINE> self.transforms = transforms
Constructor. :type wf_spec: WorkflowSpec :param wf_spec: A reference to the workflow specification. :type name: str :param name: The name of the task spec. :type transforms: list :param transforms: The commands that this task will execute to transform data. The commands will be executed using the ...
625941e50a50d4780f6672c5
def test_gemv2(): <NEW_LINE> <INDENT> v1 = theano.shared( numpy.array(numpy.random.rand(5) , dtype='float32')) <NEW_LINE> v2 = theano.shared( numpy.array(numpy.random.rand(2) , dtype='float32')) <NEW_LINE> m = theano.shared( numpy.array(numpy.random.rand(5,2), dtype='float32')) <NEW_LINE> no_gpu_f = theano.function(...
test vector1+dot(vector2,matrix)
625941e50c0af96317bb8617
def get_balances(self, cryptocurrency: Cryptocurrency = None) -> Union[List[Account], Account]: <NEW_LINE> <INDENT> balances = self.client.get_balances(cryptocurrency)['data'] <NEW_LINE> if len(balances) > 1: <NEW_LINE> <INDENT> result = [] <NEW_LINE> for balance in balances: <NEW_LINE> <INDENT> result.append(Account.f...
Retrieve supported cryptocurrencies account balance(s) Args: cryptocurrency: A Cryptocurrency enum representing the cryptocurrency to query. Returns: An array of Account or a single Account object. An array of Accounts is returned when no cryptocurrency is specified Raises: BuycoinsException: An error ...
625941e599fddb7c1c9de7be
def correct_rectangle(rect, img_size=(10000, 10000)): <NEW_LINE> <INDENT> (x, y, wx, wy) = rect <NEW_LINE> (x, y, wx, wy) = (int(round(x)), int(round(y)), int(round(wx)), int(round(wy))) <NEW_LINE> (w, h) = img_size <NEW_LINE> if x >= w or y >= h:return None <NEW_LINE> if (x < 0): <NEW_LINE> <INDENT> wx += x <NEW_LINE>...
Check if rectangle fits into img and correct it accordingly @param rect: (x,y,wx,wy) - start point and width and height @param img_size: maximum coordinates of rectangle
625941e58c0ade5d55d3edee
def custom_remove(input_list, value): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for item in input_list: <NEW_LINE> <INDENT> if item == value: <NEW_LINE> <INDENT> del input_list[count] <NEW_LINE> return <NEW_LINE> <DEDENT> count += 1 <NEW_LINE> <DEDENT> return
like input_list.remove(value), should remove the first item of the value specified and return nothing For example: >>> notes = ['Do', 'Re', 'Mi', 'Fa', 'So', 'La', 'Ti', 'Do'] >>> custom_remove(notes, 'Do') >>> notes == ['Re', 'Mi', 'Fa', 'So', 'La', 'Ti', 'Do'] True
625941e529b78933be1e5ad6
def ProcessKeyPreview(self, *args): <NEW_LINE> <INDENT> pass
ProcessKeyPreview(self: Form, m: Message) -> (bool, Message) m: A System.Windows.Forms.Message, passed by reference, that represents the window message to process. Returns: true if the message was processed by the control; otherwise, false.
625941e5cad5886f8bd27408
def _fit(self, X, y, sample_weight=None, **kwargs): <NEW_LINE> <INDENT> if sample_weight is None: <NEW_LINE> <INDENT> self.clf.fit(self._get_train_features(X), y, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.clf.fit(self._get_train_features(X), y, sample_weight=sample_weight, **kwargs) <NEW_LINE> <DEDEN...
Train the classifier :param pandas.DataFrame X: data shape [n_samples, n_features] :param y: labels of events - array-like of shape [n_samples] :param sample_weight: weight of events, array-like of shape [n_samples] or None if all weights are equal :return: self .. note:: if sklearn classifier doesn't support...
625941e5167d2b6e31218fc4
def listen(self, topic, timeout=1, limit=1): <NEW_LINE> <INDENT> timer_start = time.time() <NEW_LINE> while time.time() < timer_start + self._loop_timeout: <NEW_LINE> <INDENT> if self._subscribed: <NEW_LINE> <INDENT> break; <NEW_LINE> <DEDENT> time.sleep(1) <NEW_LINE> <DEDENT> if not self._subscribed: <NEW_LINE> <INDEN...
Listen to a topic and return a list of message payloads received within the specified time. Requires an async Subscribe to have been called previously. `topic` topic to listen to `timeout` duration to listen `limit` the max number of payloads that will be returned. Specify 0 for no limit Examples: Listen a...
625941e56e29344779a62a40
def remove(self, key): <NEW_LINE> <INDENT> i = key % self.num <NEW_LINE> x,y = self.data[i] <NEW_LINE> try: <NEW_LINE> <INDENT> index = x.index(key) <NEW_LINE> del x[index],y[index] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass
Removes the mapping of the specified value key if this map contains a mapping for the key :type key: int :rtype: None
625941e55fcc89381b1e1af1
def build_codebook(huff_tree): <NEW_LINE> <INDENT> default_leaf_prefix = '0' <NEW_LINE> code_book = {} <NEW_LINE> def binary_value_finder(node, prefix=""): <NEW_LINE> <INDENT> if type(node) == tuple and len(node) == 2: <NEW_LINE> <INDENT> binary_value_finder(node[0], prefix + '0') <NEW_LINE> binary_value_finder(node[1]...
Takes the tuppled sorted huffman tree- runs on it recursively till it gets to the leaf of and inserts the value to the code book. while going for the leaf it counts the branches past(0 for left, 1 for right) ( subtrees) to find binary representation (according to it's number of occurences). inserts a value for each sym...
625941e5bd1bec0571d90a5e
def setUp(self): <NEW_LINE> <INDENT> cb_tarball = self.params.get('cb_tarball', default='compilebench-0.6.tar.bz2') <NEW_LINE> tarball_path = self.get_data_path(cb_tarball) <NEW_LINE> archive.extract(tarball_path, self.srcdir) <NEW_LINE> cb_version = cb_tarball.split('.tar.')[0] <NEW_LINE> self.srcdir = os.path.join(se...
Extract compilebench Source: https://oss.oracle.com/~mason/compilebench/compilebench-0.6.tar.bz2
625941e507d97122c4178cc5
def test_median_3(self): <NEW_LINE> <INDENT> x = np.array([1.0, 1.0, 1.0]) <NEW_LINE> label = [list(range(x.size))] <NEW_LINE> t = larry(x, label) <NEW_LINE> p = self.l.median(1) <NEW_LINE> msg = printfail(t.x, p.x, 'x') <NEW_LINE> self.assertTrue((abs(p.x - t.x) < self.tol).all(), msg) <NEW_LINE> msg = printfail(t.lab...
larry.median_3
625941e5f8510a7c17cf9b2f
def _fit_calibrator(clf, predictions, y, classes, method, sample_weight=None): <NEW_LINE> <INDENT> Y = label_binarize(y, classes=classes) <NEW_LINE> label_encoder = LabelEncoder().fit(classes) <NEW_LINE> pos_class_indices = label_encoder.transform(clf.classes_) <NEW_LINE> calibrators = [] <NEW_LINE> for class_idx, this...
Fit calibrator(s) and return a `_CalibratedClassifier` instance. `n_classes` (i.e. `len(clf.classes_)`) calibrators are fitted. However, if `n_classes` equals 2, one calibrator is fitted. Parameters ---------- clf : estimator instance Fitted classifier. predictions : array-like, shape (n_samples, n_classes) or (...
625941e5377c676e912725d7