code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def p_proc(p): <NEW_LINE> <INDENT> p[0] = ast(p, "PROC", 1, 2) | proc : command empty
| command procout | 625941ed7c178a314d6ef9a5 |
def _write_caption(self, caption_set, caption): <NEW_LINE> <INDENT> layout_groups = self._layout_groups(caption.nodes, caption_set) <NEW_LINE> start = self._timestamp(caption.start) <NEW_LINE> end = self._timestamp(caption.end) <NEW_LINE> timespan = f'{start} --> {end}' <NEW_LINE> output = '' <NEW_LINE> cue_style_tags ... | :type caption: Caption | 625941ed55399d3f05588bf4 |
def publish_to_lms(self, access_token=None): <NEW_LINE> <INDENT> return LMSPublisher().publish(self, access_token=access_token) | Publish Course and Products to LMS. | 625941edf8510a7c17cf9c3d |
def setTransaction(self, transaction): <NEW_LINE> <INDENT> self._transaction = transaction | Associate this Installer with a given transaction. Future actions
will take place in the given transaction context, if this Checker
supports transactions. | 625941ed01c39578d7e75378 |
def provide_jar(self, version) -> str: <NEW_LINE> <INDENT> checkstyle_jar = jar_path(version) <NEW_LINE> if os.path.isfile(checkstyle_jar): <NEW_LINE> <INDENT> logger.info('Using existing jar: ' + checkstyle_jar) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.info('{} does not exists'.format(checkstyle_jar)) <NEW... | Checks if the jar is locally available. If not initiates a download.
:returns: the path to the jar
:rtype: str | 625941edf548e778e58cdabc |
def send_notification(self, rcpt_to, rcpt_cc='', rcpt_bcc='', subject='', message='', mime_type='plain'): <NEW_LINE> <INDENT> if self.get_param('SMTP_SERVER') != '': <NEW_LINE> <INDENT> host = self.get_param('SMTP_SERVER') <NEW_LINE> port = int(self.get_param('SMTP_PORT')) <NEW_LINE> rcpt_from = self.get_param('EMAIL_N... | Sends e-mail notifications.
This method has the same behavior as the application server, sending e-mail notifications only when SMTP_SERVER
parameter is set on the configuration file. If this parameter is not set, notifications are not set and no
exceptions are raised.
Parameters
----------
rcpt_to : str
Semicolo... | 625941ed009cb60464c638ea |
def plot_label(lon, lat, zone, m): <NEW_LINE> <INDENT> x, y = m(lon, lat) <NEW_LINE> plt.text(x, y, zone, fontsize=9,color='#a6a6a6',zorder=35) <NEW_LINE> return | Add generic labels to basemap | 625941ed4d74a7450ccd4702 |
def return_data(filename): <NEW_LINE> <INDENT> text2=file_handler(filename) <NEW_LINE> text2=list(text2) <NEW_LINE> if len(text2) > 88: <NEW_LINE> <INDENT> del text2[40:40+len(text2)-88] <NEW_LINE> <DEDENT> if len(text2)<88: <NEW_LINE> <INDENT> text2.insert(41,"<") <NEW_LINE> <DEDENT> Data= {'Name':None,'Passport Numbe... | img=cv2.imread(filename)
apply_ocr(filename)
df = pd.read_csv('eng.tsv',sep=' ',quoting=csv.QUOTE_NONE)
df=df[df.text != ' ']
df.dropna()
footer = df[df.block_num == df.block_num.max()]
footer_coords = [(footer.iloc[0].left-20, footer.iloc[0].top-20), (footer.iloc[-1].left+footer.iloc[-1].wid... | 625941ed73bcbd0ca4b2c5b2 |
def get_info(file_path): <NEW_LINE> <INDENT> if file_exists(file_path) == False: <NEW_LINE> <INDENT> raise IOError("Input file not found.") <NEW_LINE> <DEDENT> output = psm(file_path) <NEW_LINE> if output == "": <NEW_LINE> <INDENT> raise Exception("Can't apply OCR with Tesseract on this document.") <NEW_LINE> <DEDENT> ... | :param file_path: input file path
:return: the complete orientation and script detection information
obtained by "tesseract input_img output -psm 0" | 625941ed63f4b57ef0001646 |
@conversion <NEW_LINE> def extracted_object(item: Generated, name: str) -> None: <NEW_LINE> <INDENT> generated = item.pop(name) <NEW_LINE> item.update(generated) | Merge a child node to the parent one. | 625941ed44b2445a339325ce |
@hook.command("bing", "b") <NEW_LINE> def bing(text, bot): <NEW_LINE> <INDENT> api_key = bot.config.get("api_keys", {}).get("bing_azure") <NEW_LINE> show_nsfw = text.endswith(" nsfw") <NEW_LINE> if show_nsfw: <NEW_LINE> <INDENT> text = text[:-5].strip().lower() <NEW_LINE> <DEDENT> rating = NSFW_FILTER if show_nsfw else... | <query> - returns the first bing search result for <query> | 625941ed5166f23b2e1a5695 |
def power(self, period, duration, objective=None, method=None, oversample=10): <NEW_LINE> <INDENT> period, duration = self._validate_period_and_duration(period, duration) <NEW_LINE> try: <NEW_LINE> <INDENT> oversample = int(oversample) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> raise ValueError("oversamp... | Compute the periodogram for a set of periods
Parameters
----------
period : array-like or Quantity
The periods where the power should be computed
duration : float, array-like or Quantity
The set of durations to test
objective : {'likelihood', 'snr'}, optional
The scalar that should be optimized to find the... | 625941ed187af65679ca565c |
def get_action_permissions_for_projects(action_id: int) -> typing.Dict[int, Permissions]: <NEW_LINE> <INDENT> actions.get_action(action_id) <NEW_LINE> action_permissions = {} <NEW_LINE> for project_action_permissions in ProjectActionPermissions.query.filter_by(action_id=action_id).all(): <NEW_LINE> <INDENT> if project_... | Get permissions for a specific action for projects.
:param action_id: the ID of an existing action
:return: a dict mapping project IDs to permissions
:raise errors.ActionDoesNotExistError: if no action with the given action
ID exists | 625941ed56b00c62f0f14b99 |
def check_schedule_rules(today): <NEW_LINE> <INDENT> matches = [] <NEW_LINE> if today.weekday() == SCHEDULED_DAY_OF_WEEK: <NEW_LINE> <INDENT> matches.append('Weekly') <NEW_LINE> if (today + datetime.timedelta(days=7)).month != today.month: <NEW_LINE> <INDENT> matches.append('Monthly') <NEW_LINE> if today.month % 3 == 0... | >>> check_schedule_rules(datetime.date(2017, 2, 28))
[]
>>> check_schedule_rules(datetime.date(2017, 3, 5))
['Weekly']
>>> check_schedule_rules(datetime.date(2017, 3, 26))
['Quarterly', 'Monthly', 'Weekly'] | 625941ed2eb69b55b151cdf4 |
def test_lingo_user_port_http_user_controller_get_high_score(self): <NEW_LINE> <INDENT> headers = { 'Accept': 'application/json', 'Authorization': self.bearerToken, } <NEW_LINE> response = self.client.open( '/api/highscore', method='GET', headers=headers) <NEW_LINE> self.assert200(response, 'Response body is : ' + resp... | Test case for lingo_port_http_user_controller_get_high_score
Get users high scores | 625941eda79ad161976cc682 |
def write_conf_file(self, output_directory, extra={}): <NEW_LINE> <INDENT> trans = self.trans <NEW_LINE> request = trans.request <NEW_LINE> api_key = api_keys.ApiKeyManager( trans.app ).get_or_create_api_key( trans.user ) <NEW_LINE> conf_file = { 'history_id': self.attr.history_id, 'api_key': api_key, 'remote_host': re... | Build up a configuration file that is standard for ALL IEs.
TODO: replace hashed password with plaintext. | 625941ed7cff6e4e81117ec2 |
@app.route('/regex/<string:page>', methods=["GET"]) <NEW_LINE> @nocache <NEW_LINE> @requireAdmin <NEW_LINE> def GetRegex(page): <NEW_LINE> <INDENT> return getRegex(page) | Requires authentication | 625941ed45492302aab5e806 |
@cli.command() <NEW_LINE> def loop_cmd(cmd, args: str, sep=','): <NEW_LINE> <INDENT> for arg in tqdm(args.split(sep)): <NEW_LINE> <INDENT> magic_cmd(cmd.format(arg=arg), print_output=True) | mecli loop-cmd 'ls {arg}' ".,.. | 625941edd8ef3951e3243a7a |
def pruneTree(self, root): <NEW_LINE> <INDENT> if not root: return None <NEW_LINE> root.left = self.pruneTree(root.left) <NEW_LINE> root.right = self.pruneTree(root.right) <NEW_LINE> if not root.left and not root.right and not root.val: return None <NEW_LINE> return root | :type root: TreeNode
:rtype: TreeNode | 625941ed4428ac0f6e5bad34 |
def pattern1(level): <NEW_LINE> <INDENT> for i in range(1, level + 1): <NEW_LINE> <INDENT> print() <NEW_LINE> for j in range(i): <NEW_LINE> <INDENT> print('*', end='') | This function prints the following pattern:
*
**
***
**** | 625941edd164cc617578328c |
def test_parse_classic_otu_table_floats_in_table(self): <NEW_LINE> <INDENT> data = self.otu_table1_floats <NEW_LINE> data_f = (data.split('\n')) <NEW_LINE> obs = parse_classic_otu_table(data_f) <NEW_LINE> exp = (['Fing', 'Key', 'NA'], ['0', '1', '2', '3', '4'], array([[19111.0, 44536.0, 42.0], [1216.0, 3500.0, 6.0], [1... | parse_classic_otu_table functions using an OTU table containing floats
but cast as int....this will automatically cast into floats | 625941ed8e7ae83300e4b50b |
def diagnostic_yield(self, sample_id, exon_ids=None, query=None, level=10, threshold=100): <NEW_LINE> <INDENT> if exon_ids: <NEW_LINE> <INDENT> query = self.query().filter(Exon.exon_id.in_(exon_ids)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query = self.query() <NEW_LINE> <DEDENT> level = "completeness_{}".format(... | Calculate transcripts that aren't completely covered.
This metric only applies to one sample in isolation. Otherwise
it's hard to know what to do with exons that are covered or
not covered across multiple samples.
Args:
sample_id (str): unique sample id | 625941ed56b00c62f0f14b9a |
def test_s3_delete_url_encode(self): <NEW_LINE> <INDENT> key = self.bucket + '/a+b/foo' <NEW_LINE> tasks = [FileInfo(src=key, src_type='s3', dest_type='local', operation='delete', size=0)] <NEW_LINE> self.assertEqual(len(list_contents(self.bucket, self.session)), 1) <NEW_LINE> self.s3_handler.call(tasks) <NEW_LINE> sel... | Tests S3 deletes. The files used are the same generated from
filegenerators_test.py. This includes the create s3 file. | 625941edd53ae8145f87a7a2 |
def get_paragraph(self): <NEW_LINE> <INDENT> return ' '.join(' '.join(chunk.strip().split()) for chunk in self.chunks if chunk.strip()) | Retrieve the formatted chunks of text.
:return: the formatted text as a :class:`str`
:rtype: str | 625941eda05bb46b383ecd59 |
def walk_storage(path, topdown=True, onerror=None, followlinks=False, storage=private_storage): <NEW_LINE> <INDENT> if not topdown: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> if onerror: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> roots = [path] <NEW_LINE> while len(roots): ... | Generate the file names in a stored directory tree by walking the tree
top-down.
For each directory in the tree rooted at the directory top (including top
itself), it yields a 3-tuple (dirpath, dirnames, filenames).
This is intended for use with an implementation of the Django storage API.
You can specify something o... | 625941ed16aa5153ce3629b5 |
def grando_transform_shift_batch(batch_of_images, shift): <NEW_LINE> <INDENT> t = np.array([]) <NEW_LINE> reshape_batch_of_images = batch_of_images.reshape(len(batch_of_images), 28, 28) <NEW_LINE> for i in reshape_batch_of_images: <NEW_LINE> <INDENT> t = np.append(t, scipy.ndimage.interpolation.shift(i, float(shift))) ... | Input: batch of images; type: ndarray: size: (batch, 784); shift; type: float;
Output: batch of shifted images; type: ndarray; size: (batch, 784); | 625941ed656771135c3ebdb2 |
def get_links(): <NEW_LINE> <INDENT> links = { url_sales_ninc_eps: "Sales,NetInc,EPS", url_roic: "Roic", url_fcf: "Fcf", url_bvps: "Bvps", url_ni_ttm: "Net Inc TMM", url_pe_ttm: "PE TTM", url_rev_ttm: "Revenue TTM", } <NEW_LINE> for link, text in links.items(): <NEW_LINE> <INDENT> print(link + " =", text) <NEW_LINE> <D... | Links | 625941ed60cbc95b062c6a80 |
def test_validate_hash(self): <NEW_LINE> <INDENT> working_dir = self.workspace_dir <NEW_LINE> base_path = os.path.join( working_dir, 'test_file_md5_098f6bcd4621d373cade4e832627b4f6.txt') <NEW_LINE> with open(base_path, 'w') as base_file: <NEW_LINE> <INDENT> base_file.write('test') <NEW_LINE> <DEDENT> self.assertTrue(ec... | Test ecoshard.validate_hash. | 625941ed66673b3332b925ce |
def rpc_get_backend(self): <NEW_LINE> <INDENT> return self.backend.name | Return the name of the current backend. | 625941edc432627299f05187 |
def _hay_colision(self, personaje, destino): <NEW_LINE> <INDENT> hay_colision = False <NEW_LINE> if (not self._mapa.es_pisable(destino[0],destino[1])): <NEW_LINE> <INDENT> hay_colision = True <NEW_LINE> <DEDENT> for item in self._personajes: <NEW_LINE> <INDENT> if (item.nombre != personaje.nombre): <NEW_LINE> <INDENT> ... | Comprueba si existe colision de un personajes con otros o con el mapa | 625941edd99f1b3c44c67ac2 |
def genConfusionMatrix(recordLabels, resultData, threshold = 0.99, window = 30, windowStepSize = 5): <NEW_LINE> <INDENT> likelihoodScores = [row[2] for row in resultData] <NEW_LINE> predicted = map(lambda x: 1 if x > threshold else 0, likelihoodScores) <NEW_LINE> actual = recordLabels <NEW_LINE> if not windowStepSize: ... | Returns a confusion matrix object for the results of the
given experiment and the ground truth labels.
:param experiment: an experiment info dict
:param threshold: cutoff to be applied to Likelihood scores
:type threshold: float
:param window: Use a WindowedConfusionMatrix and calculate stats over
this ... | 625941ed004d5f362079a86c |
def background(self, where, widget): <NEW_LINE> <INDENT> if where is not None and isinstance(widget, object): <NEW_LINE> <INDENT> widget.focus(getattr(self._background, where)) | function that would provide the widget with source image. | 625941ed07d97122c4178dd5 |
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> start = end <NEW_LINE> end += 2 <NEW_LINE> (self.value,) = _get_struct_H().unpack(str[start:end]) <NEW_LINE> return self <NEW_LINE> <DEDENT> except struct.error as e: <NEW_LINE> <INDENT> raise genpy.DeserializationE... | unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module | 625941ed293b9510aa2c37cd |
def set_ListId(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ListId', value) | Set the value of the ListId input for this Choreo. ((required, string) The id of the Mailchimp list the subscribers will be added to.) | 625941ed0a50d4780f6673d4 |
def fit(model_file, data, force_compile=False, **kwargs): <NEW_LINE> <INDENT> if not force_compile and os.path.exists("cache/%s.pickle" % model_file): <NEW_LINE> <INDENT> model = pickle.load(open("cache/%s.pickle" % model_file, 'rb')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> model = pystan.StanModel(model_file) <N... | Compile the model unless cached and run the sampler. | 625941ed21bff66bcd684e8b |
def tanchu_zidan(self): <NEW_LINE> <INDENT> if self.zidan_list: <NEW_LINE> <INDENT> return self.zidan_list.pop() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | 弹出最上面的那颗子弹 | 625941ed29b78933be1e5be2 |
def _new_room(name, map_name): <NEW_LINE> <INDENT> if ROOMS.has_key(name): <NEW_LINE> <INDENT> return ERR_ROOMEXISTS <NEW_LINE> <DEDENT> map_info = res.canvas.get(map_name) <NEW_LINE> if not map_info: <NEW_LINE> <INDENT> return ERR_MAPNOTFOUND <NEW_LINE> <DEDENT> ROOMS[name] = dict(map_name=map_name, map_info=map_info,... | @return: error (like golang) | 625941ed4527f215b584c98f |
@index_bp.route('/') <NEW_LINE> @login_required <NEW_LINE> def home(): <NEW_LINE> <INDENT> return redirect(url_for('main.all_cars')) | Home Page: The main page lists all the cars that are available
:return: List of all cars
:rtype: Function | 625941ed293b9510aa2c37ce |
def _update_weights(self): <NEW_LINE> <INDENT> tmp_filename = "tmp_model_weights_save.h5" <NEW_LINE> if self._training_mongodb_id is not None and self._training.result.model is not None: <NEW_LINE> <INDENT> self._training.result.model.save(tmp_filename) <NEW_LINE> self._handle_response(update_weights( self._training_mo... | save file and update weights, remove tmp h5 file afterwards | 625941ed50812a4eaa59c859 |
def htmPredictionModelControlEnableSPLearningCb(htmPredictionModel): <NEW_LINE> <INDENT> assert isinstance(htmPredictionModel, HTMPredictionModel) <NEW_LINE> htmPredictionModel._getSPRegion().setParameter('learningMode', True) <NEW_LINE> return | Enables learning in the HTMPredictionModel's Spatial Pooler
See also htmPredictionModelControlDisableSPLearningCb.
htmPredictionModel: pointer to a HTMPredictionModel instance
Returns: nothing | 625941ed0a366e3fb873ed5c |
def setSplit(self, split): <NEW_LINE> <INDENT> self.split = split | Sets the split attribute and split value to the current node
:param split: A tuple containing the split attribute and split value
:return: None | 625941ed15fb5d323cde1055 |
def retrieve_data(self, section): <NEW_LINE> <INDENT> title = self._find_section_title(section) <NEW_LINE> sub_section = [sub_section for sub_section in section.sections if sub_section.level == section.level + 1] <NEW_LINE> if sub_section: <NEW_LINE> <INDENT> sections_titles = [self._find_section_title(ast) for ... | Recursive search to retrieve a table or list of a section,
or existing subsection.
Element from sections are stored in a dict like :
{
"section" : {
"sub section" : [RadioTable, RadioTable, ...],
"sub section" : {
"sub section" : [...],
...
},
...
},
... | 625941edaad79263cf390f86 |
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> now = timezone.now() <NEW_LINE> if self.is_approved: <NEW_LINE> <INDENT> self.is_draft = False <NEW_LINE> if self.date_publication is None and not self.is_draft: <NEW_LINE> <INDENT> self.date_publication = now <NEW_LINE> <DEDENT> if self.date_publication > now: <NEW_... | Override the default ``save`` method. | 625941ed6aa9bd52df0372e5 |
def order_log_transfer(queues, job): <NEW_LINE> <INDENT> job.stageout = 'log' <NEW_LINE> put_in_queue(job, queues.data_out) <NEW_LINE> logger.debug('job added to data_out queue') <NEW_LINE> n = 0 <NEW_LINE> nmax = 60 <NEW_LINE> while n < nmax: <NEW_LINE> <INDENT> log_transfer = job.get_status('LOG_TRANSFER') <NEW_LINE>... | Order a log transfer for a failed job.
:param queues: pilot queues object.
:param job: job object.
:return: | 625941ed1f037a2d8b94673a |
def apply_operation(self): <NEW_LINE> <INDENT> if self.operation_selected < 0 or not self.num2_typed: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> current = float(self.display.cget('text')) <NEW_LINE> if self.operation_selected == 0: <NEW_LINE> <INDENT> self.value += current <NEW_LINE> <DEDENT> if self.operation_sele... | Applies the selected operation | 625941eddc8b845886cb5a74 |
def deleteDuplicates(self, head): <NEW_LINE> <INDENT> if head is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> first = head <NEW_LINE> n = head.next <NEW_LINE> head.next = None <NEW_LINE> while n != None: <NEW_LINE> <INDENT> if first.val != n.val: <NEW_LINE> <INDENT> first.next = n <NEW_LINE> first = n <NEW... | :type head: ListNode
:rtype: ListNode | 625941edb7558d58953c5446 |
def test_update_weights_and_biases_test_negative_2(self): <NEW_LINE> <INDENT> input_maps = [ numpy.array([ (-0.14062, 0.293809, 0.905852, -0.45878, 0.740724), (-0.68267, -0.09463, 0.614261, -0.50213, 0.565014), (0.076374, -0.7649, -0.30093, 0.471437, -0.32848), (-0.38347, 0.160011, -0.30884, 0.493158, -0.28132), (-0.64... | Что делать, когда мы хотим обучить слой (обновить веса и смещения) после прямого и
обратного прохода, а входной сигнал для слоя некорректен - входных карт столько, сколько
нужно, но они не такого размера. | 625941ed30bbd722463cc307 |
@app.route('/command', methods=['POST']) <NEW_LINE> def command(): <NEW_LINE> <INDENT> global config, devices <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> name = request.form['id'] <NEW_LINE> try: <NEW_LINE> <INDENT> properties = devices[name] <NEW_LINE> ssh = pxssh() <NEW_LINE> ssh.force_password = True... | Executes a command to a given device (form field 'id') when triggered. | 625941ed29b78933be1e5be3 |
def _swap(self, x): <NEW_LINE> <INDENT> return x | swap the members of x if this is a column-oriented matrix
| 625941ed7047854f462a1941 |
def getEnthalpyOfReaction(self, T): <NEW_LINE> <INDENT> cython.declare(dHrxn=cython.double, reactant=Species, product=Species) <NEW_LINE> dHrxn = 0.0 <NEW_LINE> for reactant in self.reactants: <NEW_LINE> <INDENT> dHrxn -= reactant.thermo.getEnthalpy(T) <NEW_LINE> <DEDENT> for product in self.products: <NEW_LINE> <INDEN... | Return the enthalpy of reaction in J/mol evaluated at temperature
`T` in K. | 625941ed956e5f7376d713a9 |
def handle_url_manager_setting(self, cms_config): <NEW_LINE> <INDENT> self.url_manager_supported_models = parse_settings( cms_config, "url_manager_supported_models" ) | Check the url_manager_supported_models settings has been correctly set
and add it to the masterlist | 625941ed5f7d997b87174fda |
def convert(content): <NEW_LINE> <INDENT> those = [] <NEW_LINE> for this in content: <NEW_LINE> <INDENT> that = this.decode("GBK") <NEW_LINE> that = that.encode("utf-8") <NEW_LINE> those.append(that) <NEW_LINE> <DEDENT> return those | convert GBK to utf-8 | 625941ed55399d3f05588bf5 |
def on_enter(self, *args): <NEW_LINE> <INDENT> if self.text not in self.previous_command_list[1:]: <NEW_LINE> <INDENT> self.previous_command_list.insert(1, self.text) <NEW_LINE> <DEDENT> self.previous_command_selection_index = 0 <NEW_LINE> self.height -= self.font_size * self.line_count <NEW_LINE> self.line_count = 0 <... | Callback for the enter counter change event. The event of a changed(incremented) enter counter was triggered by
the user pressing the 'Enter' key, therefore manly signaling the main ConsoleWidget, that the command input
can now be fetched to be processed further.
The contents of this method are always executed before e... | 625941ed2c8b7c6e89b35cfa |
def init(self): <NEW_LINE> <INDENT> df = {} <NEW_LINE> for document in self.documents_list: <NEW_LINE> <INDENT> temp = {} <NEW_LINE> for word in document: <NEW_LINE> <INDENT> temp[word] = temp.get(word, 0) + 1 <NEW_LINE> <DEDENT> self.f.append(temp) <NEW_LINE> for key in temp.keys(): <NEW_LINE> <INDENT> df[key] = df.ge... | 求解文本集合中的f和idf变量 | 625941ed7d847024c06be7fe |
def test_with_diagnostics_method(mt_trans): <NEW_LINE> <INDENT> trans = mt_trans.with_diagnostics() <NEW_LINE> assert trans.create_model['debugLevel'] == 'Diagnostic' | Test method functionality of the Transaction Builder. | 625941edd7e4931a7ee9e45d |
def p_print(p): <NEW_LINE> <INDENT> p[0] = ('print', p[3]) | expression : PRINT lparen expression rparen | 625941ed32920d7e50b28712 |
def save_xls(self, result): <NEW_LINE> <INDENT> len = result.__len__() <NEW_LINE> workbook = xlwt.Workbook(encoding='utf-8') <NEW_LINE> worksheet = workbook.add_sheet('lagou') <NEW_LINE> for i in range(len): <NEW_LINE> <INDENT> worksheet.write(i, 0, label=result[i]['one']) <NEW_LINE> worksheet.write(i, 1, label=result[... | 存储到excel中 | 625941edac7a0e7691ed45ff |
def randomVectors(shape, seed=None, magnitude=1, type=Float): <NEW_LINE> <INDENT> a = randomArray(shape, seed, (-1,1), type) <NEW_LINE> Geometry.normalize(a,a) <NEW_LINE> if magnitude != 1: <NEW_LINE> <INDENT> a *= array((magnitude,), type) <NEW_LINE> <DEDENT> return a | Generates a Numeric array full of random vectors with the given magnitude | 625941ed4c3428357757c862 |
def test_tables(self): <NEW_LINE> <INDENT> tbls = self.db.get_tables_names() <NEW_LINE> for tab, tbl in zip(self.tables, tbls): <NEW_LINE> <INDENT> self.assertEqual(tab, tbl, "Names of the tables are not equal") <NEW_LINE> <DEDENT> self.db.drop_table(self.tables[0]) <NEW_LINE> tbls = self.db.get_tables_names() <NEW_LIN... | Test the names of the tables | 625941edbaa26c4b54cb1658 |
def mask(size): <NEW_LINE> <INDENT> if size == 8: <NEW_LINE> <INDENT> return 0xff <NEW_LINE> <DEDENT> elif size == 16: <NEW_LINE> <INDENT> return 0xffff <NEW_LINE> <DEDENT> elif size == 32: <NEW_LINE> <INDENT> return 0xffffffff <NEW_LINE> <DEDENT> elif size == 64: <NEW_LINE> <INDENT> return 0xffffffffffffffff <NEW_LINE... | The basic bitmask to extract the value of bit-size 'size'. | 625941ed046cf37aa974d280 |
def set_board(self, board): <NEW_LINE> <INDENT> self.board = board <NEW_LINE> self.board_height = len(self.board.grid) | Sets a board
:param board: Sets an active board to the renderer object | 625941ed7d43ff24873a31e2 |
def post(self): <NEW_LINE> <INDENT> greeting = SetGreeting(self) <NEW_LINE> q = self.request.get('q') <NEW_LINE> self.template_values = {} <NEW_LINE> rs = DoSearch(q, MAP_SIZE) <NEW_LINE> if rs is None: <NEW_LINE> <INDENT> path = os.path.join(os.path.dirname(__file__), 'bad_search.html') <NEW_LINE> self.response.out.wr... | Handles an HTTP Post to /search (does a LocalSearch for the query).
Args:
q: CGI Arg The query that was last run.
Returns:
Renders template view for a search. | 625941ed1b99ca400220aff1 |
def _validate_nullable(self, nullable, field, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> if not nullable: <NEW_LINE> <INDENT> self._error(field, errors.NOT_NULLABLE) <NEW_LINE> <DEDENT> self._drop_remaining_rules( 'allowed', 'empty', 'forbidden', 'items', 'keysrules', 'min', 'max', 'minlength', '... | {'type': 'boolean'} | 625941ed26238365f5f0f3b3 |
def print_report(conns): <NEW_LINE> <INDENT> message = list() <NEW_LINE> for url, sluice in conns.iteritems(): <NEW_LINE> <INDENT> message.append( url + '\t' + '\t'.join([str(v) for v in sluice.stats.__dict__.values()]) ) <NEW_LINE> <DEDENT> header = '\t'.join( chain(['host'], conns.values()[0].stats.__dict__.keys()) )... | Nicely print out open_sluices | 625941eddd821e528d63b6e2 |
def test_name_special_characters(self): <NEW_LINE> <INDENT> expected_errors = { "name": [ "Not a valid domain name." ] } <NEW_LINE> with self.assertRaisesMessage(ValidationError, str(expected_errors)): <NEW_LINE> <INDENT> factory.DomainFactory.create(name="example?.com").full_clean() <NEW_LINE> <DEDENT> with self.asser... | Ensure names cannot contain special characters. | 625941ed3d592f4c4ed1d59d |
def MoveHand(hand, f1=0.8, f2=0.8, spread=None, timeout=None): <NEW_LINE> <INDENT> preshape = hand.GetDOFValues() <NEW_LINE> if f1 is not None: preshape[0] = f1 <NEW_LINE> if f2 is not None: preshape[1] = f2 <NEW_LINE> if spread is not None: preshape[2] = spread <NEW_LINE> robot = hand.GetParent() <NEW_LINE> ac... | Change the hand preshape. This function blocks until trajectory execution
finishes. This can be changed by changing the timeout parameter to a
maximum number of seconds. Pass zero to return instantantly.
@param f1 finger 1 angle
@param f2 finger 2 angle
@param spread spread angle
@param timeout blocking execution timeo... | 625941ed82261d6c526ab9e5 |
def predict(self,x_test, batch_size, model_path, result_path): <NEW_LINE> <INDENT> x_test = sequence.pad_sequences(x_test, maxlen=75) <NEW_LINE> model = load_model(model_path) <NEW_LINE> y_test = model.predict(x_test, batch_size=batch_size).tolist() <NEW_LINE> file = open(result_path, 'w+') <NEW_LINE> for index in y_te... | :param x_test:
:param batch_size:
:param model_path:
:param result_path:
:return: | 625941ed9b70327d1c4e1316 |
def mapper(model, table, **options): <NEW_LINE> <INDENT> extensions = to_list(options.pop('extension', None), []) <NEW_LINE> options['extension'] = extensions <NEW_LINE> old_init = getattr(model, '__init__', lambda s: None) <NEW_LINE> def register_init(self, *args, **kwargs): <NEW_LINE> <INDENT> old_init(self, *args, *... | A mapper that hooks in standard extensions. | 625941ed8da39b475bd654b9 |
def is_satisfied(self, offer, basket): <NEW_LINE> <INDENT> value_of_matches = D('0.00') <NEW_LINE> for line in basket.all_lines(): <NEW_LINE> <INDENT> if (self.can_apply_condition(line) and line.quantity_without_offer_discount(offer) > 0): <NEW_LINE> <INDENT> price = unit_price(offer, line) <NEW_LINE> value_of_matches ... | Determine whether a given basket meets this condition | 625941ed73bcbd0ca4b2c5b3 |
def setUp(self): <NEW_LINE> <INDENT> self.test_net.reset(populations=True, projections=True) <NEW_LINE> self.test_g_exc_m.get() | basic setUp() method to reset the network after every test | 625941edd164cc617578328d |
def text2json_rawFile2rawFile_folder_level(self, input_folder, output_file): <NEW_LINE> <INDENT> input_file_list = os.listdir(input_folder) <NEW_LINE> input_file_list = [os.path.join(input_folder, input_file) for input_file in input_file_list if not os.path.isdir(input_file)] <NEW_LINE> self.text2json_file2file(input_f... | The same Function with self.text2json_rawFile2rawFile, but in folder
level. | 625941ed67a9b606de4a83f5 |
def plot_matches_features_corr(data: pd.DataFrame): <NEW_LINE> <INDENT> data = data.drop(columns=['date', 'team1', 'team2', 'team1Home', 'team2Home', 'neutralVenue', 'friendly', 'qualifier', 'finaltourn']) <NEW_LINE> corr = data.corr() <NEW_LINE> mask = np.zeros_like(corr, dtype=np.bool) <NEW_LINE> mask[np.triu_indices... | Plot matches data correlation.
Data structure.
['date', 'team1', 'team2', 'team1Home', 'team2Home', 'neutralVenue',
'friendly', 'qualifier', 'finaltourn', 'last10win_per.t1',
'last10loss_per.t1', 'last10draw_per.t1', 'last10gd_per.t1',
'last10_oppCC_per.t1', 'last30win_per.t1', 'last30loss_per.t1',
'last30draw_per.t1'... | 625941ed5e10d32532c5f463 |
def stats(self, alpha=0.05, start=0, batches=100, chain=None, quantiles=(2.5, 25, 50, 75, 97.5)): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> trace = np.squeeze( np.array( self.db.trace( self.name)( chain=chain), float))[ start:] <NEW_LINE> n = len(trace) <NEW_LINE> if not n: <NEW_LINE> <INDENT> print_( 'Cannot genera... | Generate posterior statistics for node.
:Parameters:
name : string
The name of the tallyable object.
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
Batch size for cal... | 625941ed50812a4eaa59c85a |
@register.simple_tag <NEW_LINE> def load_menu(request, module): <NEW_LINE> <INDENT> return Menus.load(request, module) | Interfáz del Método para cargar en variables los menús que se mostrará al usuario
Usage::
{% load_menu request 'MODULE_KEY' %}
Definition::
('WEB', 'Web informativa'),
('VENTAS', 'Ventas'),
('BACKEND', 'Backend Manager'),
Examples::
{% load_menu request 'BACKEND' %} | 625941ed1b99ca400220aff2 |
def precmd(self, line): <NEW_LINE> <INDENT> if line.find("!!") >= 0 or line.find("!$") >= 0 or line.find("!^") >= 0 or line.find("!*") >= 0: <NEW_LINE> <INDENT> line = self.__do_substitutions(line) <NEW_LINE> <DEDENT> parsed_line = shlex.split(line) <NEW_LINE> if ">" in parsed_line or ">>" in parsed_line: <NEW_LINE> <I... | Process a command before it executes: perform variable substitutions and
set up any output redirection. | 625941ed32920d7e50b28713 |
def load_dataset(folder): <NEW_LINE> <INDENT> sequences = [] <NEW_LINE> labels = [] <NEW_LINE> wid = [] <NEW_LINE> log('Loading traces from {}'.format(folder)) <NEW_LINE> files = [os.path.join(folder, x) for x in os.listdir(folder)] <NEW_LINE> files = [x for x in files if os.path.basename(x).find('-') != -1] <NEW_LINE>... | Creates a dataset from files of packet sequences within the
specified folder. Each file "w-n" represents the packet sequence
of n-th load of w-th webpage. A file is in the format specified in
load_packets_sequence(). Returns a list of traces and a list with
the respective labels. | 625941ed8c0ade5d55d3eefe |
def _parse_options_types(self, options): <NEW_LINE> <INDENT> self._init_types(options.kind) | Filter objects types | 625941ed99cbb53fe6793123 |
def generate_expiry_time(): <NEW_LINE> <INDENT> date_time = datetime.now() + timedelta(minutes=AUTH_TOKEN_EXPIRY) <NEW_LINE> return datetime.strftime(date_time, "%Y-%m-%dT%H:%M:%S") | Generate expiry time for Auth Token
Returns:
str: datetime in IS0 8601 string format | 625941ed009cb60464c638eb |
def test_ugrid2d(self): <NEW_LINE> <INDENT> log = get_logger(level='warning') <NEW_LINE> ugrid_filename = os.path.join(TEST_PATH, 'quad_tri.ugrid') <NEW_LINE> msg = ( '5 1 1 0 0 0 0\n' '0. 0. 0.\n' '1. 0. 0.\n' '1. 1. 0.\n' '0. 1. 0.\n' '0. 2. 0.\n' '3 4 5\n' '1 2 3 4\n' ) <NEW_LINE> with open(ugrid_filename, 'w') as... | simple UGRID2D model | 625941ed4e696a04525c998c |
def Probability(o): <NEW_LINE> <INDENT> return o / (o + 1) | Computes the probability corresponding to given odds.
Example: o=2 means 2:1 odds in favor, or 2/3 probability
o: float odds, strictly positive
Returns: float probability | 625941edcc40096d61595e8c |
def _unthreadsafe_return_connection(self, con): <NEW_LINE> <INDENT> self._unthreadsafe_add_connection(con) | Return a connection to the pool.
In this case, the connections need to be put
back into the queue after they have been used.
This is done automatically when the connection is closed
and should never be called explicitly outside of this module. | 625941ed090684286d50f22d |
def is_fund_code(s: str) -> bool: <NEW_LINE> <INDENT> return bool(re.fullmatch(r"[0-9]{6}", s)) | Check if the string represents a valid fund code | 625941ed26238365f5f0f3b4 |
def errnoToFailure(e, path): <NEW_LINE> <INDENT> if e == errno.ENOENT: <NEW_LINE> <INDENT> return defer.fail(FileNotFoundError(path)) <NEW_LINE> <DEDENT> elif e == errno.EACCES or e == errno.EPERM: <NEW_LINE> <INDENT> return defer.fail(PermissionDeniedError(path)) <NEW_LINE> <DEDENT> elif e == errno.ENOTDIR: <NEW_LINE>... | Map C{OSError} and C{IOError} to standard FTP errors. | 625941ed26068e7796caf225 |
@shared_task <NEW_LINE> def xfer_to_open_humans(oh_id, num_submit=0, logger=None, **kwargs): <NEW_LINE> <INDENT> print('Trying to copy data for {} to Open Humans'.format(oh_id)) <NEW_LINE> oh_member = OpenHumansMember.objects.get(oh_id=oh_id) <NEW_LINE> tempdir = tempfile.mkdtemp() <NEW_LINE> try: <NEW_LINE> <INDENT> a... | Transfer data to Open Humans.
num_submit is an optional parameter in case you want to resubmit failed
tasks (see comments in code). | 625941ed711fe17d8254289e |
@commands('bomb') <NEW_LINE> def start(bot, trigger): <NEW_LINE> <INDENT> if not trigger.group(2): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not trigger.sender.startswith('#') or (trigger.nick not in bot.ops[trigger.sender] and trigger.nick not in bot.halfplus[trigger.sender]): <NEW_LINE> <INDENT> return ... | Put a bomb in the specified user's pants. They will be kicked if they
don't guess the right wire fast enough. | 625941ed01c39578d7e7537a |
def load_bragg_by_filename(file_name): <NEW_LINE> <INDENT> base_file_name = os.path.basename(file_name).lower() <NEW_LINE> gss_ws_name = os.path.basename(file_name).split('.')[0] <NEW_LINE> if base_file_name.endswith('.gss') or base_file_name.endswith( '.gsa') or base_file_name.endswith('.gda'): <NEW_LINE> <INDENT> sim... | Load Bragg diffraction file (including 3-column data file, GSAS file) for Rietveld | 625941ed5fc7496912cc3ebc |
def test_should_raise_dvc_file_step_format_error(base_steps, work_dir): <NEW_LINE> <INDENT> target = join(work_dir, 'format_error.dvc') <NEW_LINE> with open(target, 'wb') as fd: <NEW_LINE> <INDENT> fd.write(b'k:v:\n\t\t-') <NEW_LINE> <DEDENT> base_steps.append(target) <NEW_LINE> with pytest.raises(MlVToolException) as ... | Test raises if dvc file step format error | 625941ed7b25080760e39994 |
def set_log_dir(self): <NEW_LINE> <INDENT> self.log_dir = os.path.join(self.root_dir, 'logs') <NEW_LINE> model_name = self.config.MODEL_NAME <NEW_LINE> now = datetime.datetime.now() <NEW_LINE> self.checkpoint_dir = os.path.join(self.log_dir, '{}_{:%Y%m%dT%H%M}'.format(model_name.lower(), now)) <NEW_LINE> self.checkpoin... | set the log_dir for the model to store checkpoint files | 625941edb7558d58953c5447 |
def dumps( self, obj: typing.Any, *args, many: typing.Optional[bool] = None, **kwargs ): <NEW_LINE> <INDENT> serialized = self.dump(obj, many=many) <NEW_LINE> return self.opts.render_module.dumps(serialized, *args, **kwargs) | Same as :meth:`dump`, except return a JSON-encoded string.
:param obj: The object to serialize.
:param many: Whether to serialize `obj` as a collection. If `None`, the value
for `self.many` is used.
:return: A ``json`` string
:rtype: str
.. versionadded:: 1.0.0
.. versionchanged:: 3.0.0b7
This method returns ... | 625941edec188e330fd5acd2 |
def test_set_object(self): <NEW_LINE> <INDENT> self.flash['message'] = 'Message' <NEW_LINE> self.storage.set(self.flash, self.request, self.response) <NEW_LINE> self.assertEqual(1, len(self.response.cookies)) | CookieStorage: should store valid objects.
| 625941edc4546d3d9de72f77 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self._class = Review <NEW_LINE> self._name = "Review" | Constructor attributes and objects to test | 625941ed0a50d4780f6673d5 |
def menu(self, menuname): <NEW_LINE> <INDENT> self.cmd("menu") <NEW_LINE> self.assertTextAt("Menu:", x=0) <NEW_LINE> self.write(menuname) <NEW_LINE> self.rtn() <NEW_LINE> self.assertTrue(self.joe.expect(lambda: len(self._readSelected(self.joe.cursor.X, self.joe.cursor.Y)) > 0)) | Brings up menuname menu | 625941ed38b623060ff0b32b |
def travel(self): <NEW_LINE> <INDENT> curr = self._head <NEW_LINE> while curr != None: <NEW_LINE> <INDENT> print(curr.item, end=' ') <NEW_LINE> curr = curr.next <NEW_LINE> <DEDENT> print() | 遍历整个链表 | 625941ed23e79379d52eea9b |
def waitForReleases(self, maxWait=None, keys=None, chars=None, mods=None, duration=None, clear=True, checkInterval=0.002): <NEW_LINE> <INDENT> return self.waitForKeys(maxWait, keys, chars, mods, duration, self.KEY_RELEASE, clear, checkInterval) | See the waitForKeys() method documentation.
This method is identical, but only returns KeyboardRelease events. | 625941ed187af65679ca565e |
def create_questionnaire_with(self, questionnaire_data): <NEW_LINE> <INDENT> questionnaire_code = fetch_(QUESTIONNAIRE_CODE, from_(questionnaire_data)) <NEW_LINE> gen_ramdom = fetch_(GEN_RANDOM, from_(questionnaire_data)) <NEW_LINE> if gen_ramdom: <NEW_LINE> <INDENT> questionnaire_code = questionnaire_code + generateId... | Function to create a questionnaire on the 'create questionnaire' page
Args:
questionnaire_data is data to fill in the different fields of the questionnaire page
Return self | 625941ed66656f66f7cbc6ec |
def DrawPageBackground(self, dc, wnd, rect): <NEW_LINE> <INDENT> dc.SetPen(wx.TRANSPARENT_PEN) <NEW_LINE> dc.SetBrush(self._tab_ctrl_background_brush) <NEW_LINE> edge = wx.Rect(*rect) <NEW_LINE> edge.width = 2 <NEW_LINE> dc.DrawRectangle(edge.x, edge.y, edge.width, edge.height) <NEW_LINE> edge.x += rect.width - 2 <NEW_... | Draw the background of a ribbon page.
:param `dc`: The device context to draw onto;
:param `wnd`: The window which is being drawn onto (which is commonly the
L{RibbonPage} whose background is being drawn, but doesn't have to be);
:param `rect`: The rectangle within which to draw.
:see: L{GetPageBackgroundRedrawArea} | 625941ed45492302aab5e807 |
def get_overall_benefit(): <NEW_LINE> <INDENT> items = Item.objects.filter(status="sold") <NEW_LINE> overall_benefit = 0 <NEW_LINE> overall_benefit_in_perctange = 0 <NEW_LINE> for item in items: <NEW_LINE> <INDENT> overall_purchase_cost_of_sold_item += item.price <NEW_LINE> overall_sold_cost_of_sold_item += item.sellin... | Calcualte the overall benefit from the sold item | 625941ed287bf620b61d3f9f |
def res_q(f, g, x): <NEW_LINE> <INDENT> m = degree(f, x) <NEW_LINE> n = degree(g, x) <NEW_LINE> if m < n: <NEW_LINE> <INDENT> return (-1)**(m*n) * res_q(g, f, x) <NEW_LINE> <DEDENT> elif n == 0: <NEW_LINE> <INDENT> return g**m <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r = rem(f, g, x) <NEW_LINE> if r == 0: <NEW_LIN... | The input polynomials f, g are in Z[x] or in Q[x].
The output is the resultant of f, g computed recursively
by polynomial divisions in Q[x], using the function rem.
See Cohen's book p. 281.
References:
===========
1. J. S. Cohen: Computer Algebra and Symbolic Computation
- Mathematical Methods. A. K. Peters, 2003. | 625941edd58c6744b425819c |
def rsa_crt_dmq1(private_exponent, q): <NEW_LINE> <INDENT> return private_exponent % (q - 1) | Compute the CRT private_exponent % (q - 1) value from the RSA
private_exponent and q. | 625941edf9cc0f698b140b35 |
def __init__(self): <NEW_LINE> <INDENT> self.Topic = None <NEW_LINE> self.Payload = None <NEW_LINE> self.StringToken = None <NEW_LINE> self.ProducerName = None <NEW_LINE> self.SendTimeout = None <NEW_LINE> self.MaxPendingMessages = None | :param Topic: 消息要发送的topic的名字, 这里尽量需要使用topic的全路径,即:tenant/namespace/topic。如果不指定,默认使用的是:public/default
:type Topic: str
:param Payload: 要发送的消息的内容
:type Payload: str
:param StringToken: Token 是用来做鉴权使用的,可以不填,系统会自动获取
:type StringToken: str
:param ProducerName: 设置 producer 的名字,要求全局唯一,用户不配置,系统会随机生成
:type ProducerName: str
:pa... | 625941edd164cc617578328e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.