code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def plot_msd(msd, h_exp): <NEW_LINE> <INDENT> fig, ax = plt.subplots(1, 2, figsize = (10, 10)) <NEW_LINE> av_msd = np.mean(msd, axis = 0) <NEW_LINE> for p in np.arange(0, msd.shape[0], step = 1): <NEW_LINE> <INDENT> for t in np.arange(0, msd.shape[1], step = 1): <NEW_LINE> <INDENT> ax[0].plot(t, msd[p, t], 'bx') <NEW_L... | Plots the MSD of particle(s). Both the individual MSDs and an average MSD are plotted.
A label specifying the Hurst exponent is also needed.
Parameters
----------
msd : ndarray
First number to be subtracted.
h_exp : float
Hurst exponent of the simulated particle(s). | 625941db63d6d428bbe447d7 |
def request_configuration( host, mac, name, customize, config, hass, add_devices): <NEW_LINE> <INDENT> configurator = get_component('configurator') <NEW_LINE> if host in _CONFIGURING: <NEW_LINE> <INDENT> configurator.notify_errors( _CONFIGURING[host], 'Failed to pair, please try again.') <NEW_LINE> return <NEW_LINE> <D... | Request configuration steps from the user. | 625941db92d797404e304473 |
def arduino_comports(): <NEW_LINE> <INDENT> from serial.tools.list_ports_posix import comports <NEW_LINE> arduino_manufacturer_regex = re.compile(r'arduino', re.IGNORECASE) <NEW_LINE> for comport in comports(): <NEW_LINE> <INDENT> if comport.manufacturer: <NEW_LINE> <INDENT> match = arduino_manufacturer_regex.search(co... | List of serial comports serial numbers of Arduino boards connected to this machine
:return: generator of comports connected to arduino | 625941db82261d6c526ab78b |
def run(self): <NEW_LINE> <INDENT> while self.attempts < self.max_attempts: <NEW_LINE> <INDENT> self.attempts += 1 <NEW_LINE> if self.stdin: <NEW_LINE> <INDENT> stdin_fd = subprocess.PIPE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stdin_fd = None <NEW_LINE> <DEDENT> self.process = subprocess.Popen(self.commands, std... | Runs the command, called by threading library. | 625941db8e05c05ec3eea65e |
def getTokensForText(self, body, POStags=None): <NEW_LINE> <INDENT> return self._text.getTokensForText(self._retina, body, POStags) | Get tokenized input text
Args:
body, str: The text to be tokenized (required)
POStags, str: Specify desired POS types (optional)
Returns:
list of str
Raises:
CorticalioException: if the request was not successful | 625941db2eb69b55b151cb9a |
def markFinal(self, testName, result, resultMessage): <NEW_LINE> <INDENT> self.setResult(result, resultMessage) <NEW_LINE> if "FAIL" in self.resultList: <NEW_LINE> <INDENT> self.log.error(testName + " TEST FAILED") <NEW_LINE> self.resultList.clear() <NEW_LINE> assert True == False <NEW_LINE> <DEDENT> else: <NEW_LINE> <... | Mark the final result of the verification point in a test case
This needs to be called at least once in a test case
This should be final test status of the test case | 625941db94891a1f4081bd92 |
def test_send_notification_ignored_when_disabled(self): <NEW_LINE> <INDENT> self.notification_switch.disable_notifications() <NEW_LINE> args = (aggregator.UBUNTUONE_TITLE, "hello", None, False) <NEW_LINE> self.toggleable.send_notification(*args) <NEW_LINE> self.assertNotShown(args) | The send_notification method is ignored when disabled. | 625941db4d74a7450ccd44ab |
def __init__(self, addresses, frequency, window, leftover): <NEW_LINE> <INDENT> super(SampleAnalysis, self).__init__(addresses=addresses, type=peers.ANALYSIS) <NEW_LINE> self.eog_analyser = EogAnalyser(frequency, 0) <NEW_LINE> high_pass = HighpassFilter(frequency, 0.1) <NEW_LINE> self.data_loader = DataLo... | Initialization - super() and ready() calls are required... | 625941db9b70327d1c4e10be |
def _set_ref_locs(self, labels=None, do_refs=False): <NEW_LINE> <INDENT> if labels is None: <NEW_LINE> <INDENT> labels = self.items <NEW_LINE> <DEDENT> is_unique = labels.is_unique <NEW_LINE> if is_unique and not do_refs: <NEW_LINE> <INDENT> if not self.items.is_unique: <NEW_LINE> <INDENT> self._ref_locs = None <NEW_LI... | if we have a non-unique index on this axis, set the indexers
we need to set an absolute indexer for the blocks
return the indexer if we are not unique
labels : the (new) labels for this manager
ref : boolean, whether to set the labels (one a 1-1 mapping) | 625941dba79ad161976cc42e |
def test_render_heading(): <NEW_LINE> <INDENT> for level in xrange(1, 7): <NEW_LINE> <INDENT> cell = { 'cell_type': 'heading', 'level' : level, 'source' : ['Test for heading type H{0}'.format(level)] } <NEW_LINE> cell_nb = nbformat.NotebookNode(cell) <NEW_LINE> if type(cell_nb.source) is list: <NEW_LINE> <INDENT>... | Unit test for cell type "heading" | 625941db15fb5d323cde0dfb |
def read_stylesheet_vars(self ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.stylesheetVarsFileName, 'rb') as h: <NEW_LINE> <INDENT> self.varsDict = pickle.loads(h.read()) <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> self.set_missing_styles... | Read all the variables from saved file into our dict | 625941db293b9510aa2c357b |
def connect(self, receiver, *args, **kwargs): <NEW_LINE> <INDENT> self._dispatcher.connect(receiver, *args, **kwargs) | Connect the receiver to listen for signals/events.
:param signal:
:param sender:
:return: | 625941db32920d7e50b284ba |
def reject_unedited_merge_commit(commit): <NEW_LINE> <INDENT> if git_config("hooks.disable-merge-commit-checks"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> RH_PATTERN = "Merge branch '.*'" <NEW_LINE> for line in commit.raw_revlog_lines: <NEW_LINE> <INDENT> if re.match(RH_PATTERN, line): <NEW_LINE> <INDENT> info = ... | Raise InvalidUpdate if the commit looks like an unedited merge commit.
More precisely, we are trying to catch the cases where a merge
was performed without the user being aware of it. This can
happen for instance if the user typed "git pull" instead of
"git pull --rebase".
We implement a very crude identification me... | 625941dbdd821e528d63b48f |
def get_state(self, graph): <NEW_LINE> <INDENT> return graph | Transforms the graph object at a given simulator time-step into the data-structure describing the state of
the simulator, then passed to `store_state`. Default behaviour is to simply return the graph object itself.
Overwrite this method to alter the data-structure that gets passed to `store_state`.
Args:
graph: (N... | 625941db3cc13d1c6d3c7661 |
def test_dfs_with_connected_graph_contains_all_nodes(self): <NEW_LINE> <INDENT> graph = utility_functions.build_biconnected_test_graph() <NEW_LINE> all_nodes = graph.get_all_node_ids() <NEW_LINE> ordering = depth_first_search(graph, 1) <NEW_LINE> self.assertEqual(len(all_nodes), len(ordering)) <NEW_LINE> for n in all_n... | Does the ''depth_first_search'' function return all the nodes for a connected graph? | 625941db21a7993f00bc7fdc |
def game_over(self): <NEW_LINE> <INDENT> for i in range(0, self.__GRID_LEN__): <NEW_LINE> <INDENT> x_count = 0 <NEW_LINE> o_count = 0 <NEW_LINE> for j in range(0, self.__GRID_LEN__): <NEW_LINE> <INDENT> if self.GRID[i][j] == self.X: <NEW_LINE> <INDENT> x_count += 1 <NEW_LINE> <DEDENT> elif self.GRID[i][j] == self.O: <N... | Check if the game is over (a straight line with same symbols)
:return: Winning mark ('x' or 'o', None otherwise) | 625941db7c178a314d6ef74c |
def change_USE_SUBTITLES(use_subtitles): <NEW_LINE> <INDENT> use_subtitles = checkbox_to_value(use_subtitles) <NEW_LINE> if app.USE_SUBTITLES == use_subtitles: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> app.USE_SUBTITLES = use_subtitles <NEW_LINE> if app.USE_SUBTITLES: <NEW_LINE> <INDENT> if not app.subtitlesFinder... | Enable/Disable subtitle searcher
TODO: Make this return true/false on success/failure
:param use_subtitles: New desired state | 625941db5f7d997b87174d82 |
def get_first_edge(self): <NEW_LINE> <INDENT> return self.edges[0] | "
Get first edge in the triangle:
:return edges[0] : edge 1. | 625941db2eb69b55b151cb9b |
def retrieve_chapter(chapterurl, chapterdir): <NEW_LINE> <INDENT> chapterfile = chapterdir + "chapter.html" <NEW_LINE> get_file(chapterfile, chapterurl) <NEW_LINE> maxpages = 0 <NEW_LINE> with open(chapterfile, "r") as chap: <NEW_LINE> <INDENT> for line in chap: <NEW_LINE> <INDENT> line = str(line) <NEW_LINE> if "<opti... | Function to download Volumes | 625941db5f7d997b87174d83 |
def _get_tdp_power(cpu): <NEW_LINE> <INDENT> powercap_cpu_base = os.path.join( BASE_POWERCAP_PATH, "intel-rapl:{}".format(cpu.node_id)) <NEW_LINE> try: <NEW_LINE> <INDENT> path = os.path.join(powercap_cpu_base, "constraint_0_max_power_uw") <NEW_LINE> tdp = int(_read_sysfs(path)) <NEW_LINE> tdp /= MICRO_CONV <NEW_LINE> ... | Get the TDP limit of package | 625941db4c3428357757c60f |
def daemonize(): <NEW_LINE> <INDENT> pid = os.fork() <NEW_LINE> if pid > 0: <NEW_LINE> <INDENT> sys.exit(0) <NEW_LINE> <DEDENT> os.setsid() <NEW_LINE> pid = os.fork() <NEW_LINE> if pid > 0: <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> os.chdir('/') <NEW_LINE> os.umask(0) <NEW_LINE> stdin = file('/dev/null', 'r') ... | Detach from the parent process and run as a daemon | 625941db3539df3088e2e633 |
def poisson_cdf_inv ( cdf, lam, maximum=1000): <NEW_LINE> <INDENT> assert lam < 740 <NEW_LINE> if cdf < 0 or cdf > 1: <NEW_LINE> <INDENT> raise Exception ("CDF must >= 0 and <= 1") <NEW_LINE> <DEDENT> elif cdf == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> sum2 = 0 <NEW_LINE> newval = exp( -lam ) <NEW_LINE> sum... | inverse poisson distribution.
cdf : the CDF
lam : the lambda of poisson distribution
note: maxmimum return value is 1000
and lambda must be smaller than 740. | 625941dbbd1bec0571d90917 |
def test_valid_blacklisted_token_user(self): <NEW_LINE> <INDENT> with self.client: <NEW_LINE> <INDENT> resp_register = self.register_user('joe', 'joe@gmail.com', '123456') <NEW_LINE> blacklist_token = BlacklistToken( token=json.loads(resp_register.data.decode())['auth_token']) <NEW_LINE> db.session.add(blacklist_token)... | Test for user status with a blacklisted valid token | 625941db45492302aab5e5af |
def _test(self): <NEW_LINE> <INDENT> RHUIManagerCds.unassociate_repo_cds(self.rs.Instances["RHUA"][0], "Cluster1", ["Red Hat Update Infrastructure 2 \(RPMs\) \(6Server-x86_64\)"]) | [TCMS#178463 test] Unassociate rh repo from cluster | 625941dbd99f1b3c44c67873 |
def update(self, pk, **params): <NEW_LINE> <INDENT> if self.__validate_columns_requests(self.__table, params): <NEW_LINE> <INDENT> primary_key = self.__table.primary_key.columns.values()[0].name <NEW_LINE> self.__connection.execute( self.__table.update(self.__table.c[primary_key]==pk), params ) <NEW_LINE> <DEDENT> else... | Updates records in the table | 625941db3eb6a72ae02ec7cc |
def _get_letter_freqs(self, residue_num, all_records, letters, to_ignore): <NEW_LINE> <INDENT> freq_info = self._get_base_letters(letters) <NEW_LINE> total_count = 0 <NEW_LINE> for record in all_records: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if record.seq[residue_num] not in to_ignore: <NEW_LINE> <INDENT> weight... | Determine the frequency of specific letters in the alignment.
Arguments:
o residue_num - The number of the column we are getting frequencies
from.
o all_records - All of the SeqRecords in the alignment.
o letters - The letters we are interested in getting the frequency
for.
o to_ignore - Letters we are specifically su... | 625941dbd6c5a10208144335 |
def prompt_with_options(prompt, options, default): <NEW_LINE> <INDENT> lead_options = [o[0] for o in options] <NEW_LINE> if default is not None: <NEW_LINE> <INDENT> assert default in lead_options <NEW_LINE> lead_options = map( lambda x: x.upper() if x == default else x, lead_options) <NEW_LINE> <DEDENT> hint = '[{}]'.f... | Return the user's choice from the list of option lists.
The first option from each list is chosen as the hint for that option,
for example:
prompt_with_options('do it', [['yes', 'y'], ['no', 'n']], None)
will prompt with:
'do it [yes/no]? '
Note that the choice is converted to lowercase before comparison so... | 625941dbdc8b845886cb581f |
def selectPeriodicidadLecturaPlaca(self): <NEW_LINE> <INDENT> consulta="select periodicidadLecturas from parametros" <NEW_LINE> return consulta | Devuelve la consulta para obtener la periodicidad de lecturas de la placa. | 625941db6e29344779a628f8 |
def add_light(self, name, light): <NEW_LINE> <INDENT> self.lights[name] = light <NEW_LINE> if light.pilight is not None: <NEW_LINE> <INDENT> light.register_dimlevel_callback(self.light_dimmed) <NEW_LINE> light.register_state_callback(self.light_switched) | add light | 625941dbc432627299f04f30 |
def test_check_all_categories2(): <NEW_LINE> <INDENT> get_toolkit(biolink_release="2.2.11") <NEW_LINE> categories = get_biolink_ancestors("biolink:Gene") <NEW_LINE> vbc, ibc, ic = check_all_categories(categories) <NEW_LINE> assert len(vbc) == 4 <NEW_LINE> assert len(ibc) == 0 <NEW_LINE> assert ( len(ic) == 8 ) <NEW_LIN... | Test check_all_categories method. | 625941db63f4b57ef00013fa |
def _train_scaled(self, X: Float2D, Y: Float2D, **kwargs: Any) -> Dict[str, Any]: <NEW_LINE> <INDENT> hist = self._net.fit(X, Y, batch_size=kwargs.get('batch_size', None), callbacks=kwargs.get('callbacks', None), epochs=kwargs.get('epochs', 250), shuffle=False, validation_data=kwargs.get('validation_data', None), verbo... | See super()._train_scaled() | 625941db851cf427c661a7f5 |
def term_model(weight_type, sentence_type, min_weight, min_df, max_df): <NEW_LINE> <INDENT> validation_train_data_filename = "data/small_train.csv" <NEW_LINE> validation_test_data_filename = "data/small_test.csv" <NEW_LINE> validation_train_data = du.read_data_df(validation_train_data_filename, data_type="train") <NEW_... | 根据weight_type和sentence_type跑分类模型
:param weight_type: str,特征权重形式
:param sentence_type: str,句子级别
:param min_weight: 浮点数,特征权重值的阈值,大于该阈值的特征词才被保留
:param min_df: 整数,特征词出现的文档数,大于该阈值的特征词才被保留
:param max_df: 整数,特征词出现的文档数,小于该阈值的特征词才被保留
:return: None | 625941db7cff6e4e81117c6e |
def process(self, request:Request, response:Response, **keyargs): <NEW_LINE> <INDENT> assert isinstance(request, Request), 'Invalid request %s' % request <NEW_LINE> assert isinstance(response, Response), 'Invalid response %s' % response <NEW_LINE> if response.isSuccess is False: return <NEW_LINE> if Request.decoder in ... | @see: HandlerProcessorProceed.process
Create the request decoder. | 625941dba17c0f6771cbe338 |
def p_additional_bound1(self, p): <NEW_LINE> <INDENT> p[0] = p[2] | additional_bound1 : '&' reference_type1 | 625941dbbde94217f36830d7 |
def get_descriptors(self): <NEW_LINE> <INDENT> blacklist = [] <NEW_LINE> results = [] <NEW_LINE> for name, descriptor in Chemical: <NEW_LINE> <INDENT> if name in blacklist: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> results.append(sum(descriptor(chem) for chem in self.reactants if chem.a.size > 1)) <NEW_LINE> res... | Calculates and returns a list of reaction descriptors.
Currently, we are using purely molecular descriptors. In an attempt
use them to characterize a reaction, for each available descriptor,
we are calculating a total sum its values for all reactants and
products separately. The resulting pair of numbers is our reacti... | 625941dbcad5886f8bd272c1 |
def hasData(self) -> bool: <NEW_LINE> <INDENT> return len(self._fileNames) > 0 | Returns: True if there remain files to be read | 625941db16aa5153ce362760 |
def retry_multiple(self, job_ids, as_admin=False): <NEW_LINE> <INDENT> return self.get_runjob().retry_multiple(job_ids=job_ids, as_admin=as_admin) | Authorization Required Read/Write | 625941db4527f215b584c73d |
def test_required_parameter_args_with_some_default(self): <NEW_LINE> <INDENT> def func(a, b=2, c=3): <NEW_LINE> <INDENT> return a+b+c <NEW_LINE> <DEDENT> expected = ['a'] <NEW_LINE> actual = required_parameter(func) <NEW_LINE> self.assertEqual(expected, actual) | should return only params without default in array | 625941db23849d37ff7b3376 |
def get_system_timezones(self, **data): <NEW_LINE> <INDENT> return self.get("/system/timezones/", data=data) | GET /system/timezones/
Returns a :ref:`paginated <pagination>` response with a key of ``timezones``,
containing a list of :format:`timezones <timezone>`. | 625941dbad47b63b2c50a267 |
def test_38(self): <NEW_LINE> <INDENT> test_number = "38" <NEW_LINE> test_description = "Number of legs matches on constraints, staged and active endpoint for senders" <NEW_LINE> if len(self.senders) > 0: <NEW_LINE> <INDENT> for sender in self.senders: <NEW_LINE> <INDENT> url = "single/senders/{}/".format(sender) <NEW_... | Number of legs matches on constraints, staged and active endpoint for senders | 625941db6aa9bd52df03708e |
def _drop_entity(vid): <NEW_LINE> <INDENT> DATASET = 'd' <NEW_LINE> PARTITION = 'p' <NEW_LINE> TABLE = 't' <NEW_LINE> COLUMN = 'c' <NEW_LINE> COLUMN_STAT = 'cs' <NEW_LINE> ENTITIES = [ DATASET, PARTITION, TABLE, COLUMN, COLUMN_STAT] <NEW_LINE> assert vid[0] in ENTITIES <NEW_LINE> return vid[1:] | Removes leads entity flag from the vid. | 625941db91af0d3eaac9bd04 |
def validate(self, action, body): <NEW_LINE> <INDENT> if action not in self.validators: <NEW_LINE> <INDENT> schema = self.get_schema(action) <NEW_LINE> self.validators[action] = validators.Draft4Validator(schema) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.validators[action].validate(body) <NEW_LINE> <DEDENT> exc... | Validates the request data
This method relies on jsonschema and exists
just as a way for third-party transport to validate
the request. It's not recommended to validate every
request since they are already validated server side.
:param action: Action's for which body need
to be validated.
:type action: `str`
:par... | 625941dbc432627299f04f31 |
def __init__(self): <NEW_LINE> <INDENT> self.parts = {} <NEW_LINE> self.sketches = {} <NEW_LINE> self.materials = {} <NEW_LINE> self.loads = {} <NEW_LINE> self.rootAssembly = Assembly() | This method is not from the abaqus file | 625941db3d592f4c4ed1d350 |
def run(argv=None, save_main_session=True): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument( '--input', dest='input', default='gs://test_template/shakespeare/kinglear.txt', help='Input file to process.') <NEW_LINE> parser.add_argument( '--output', dest='output', required=True, help... | Main entry point; defines and runs the wordcount pipeline. | 625941dbf9cc0f698b1408e2 |
def create_text_date_annotations(): <NEW_LINE> <INDENT> res = None <NEW_LINE> status = None <NEW_LINE> if connexion.request.is_json: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> annotation_request = TextDateAnnotationRequest.from_dict(connexion.request.get_json()) <NEW_LINE> note = annotation_request._note <NEW_LINE> a... | Annotate dates in a clinical note
Return the date annotations found in a clinical note # noqa: E501
:rtype: TextDateAnnotations | 625941db73bcbd0ca4b2c35f |
def determine_db_dir(): <NEW_LINE> <INDENT> if platform.system() == "Darwin": <NEW_LINE> <INDENT> return os.path.expanduser("~/Library/Application Support/Artax/") <NEW_LINE> <DEDENT> elif platform.system() == "Windows": <NEW_LINE> <INDENT> return os.path.join(os.environ['APPDATA'], "Artax") <NEW_LINE> <DEDENT> return ... | Return the default location of the artax data directory | 625941db57b8e32f52483785 |
def __update_author_etal_add_emph(self, author): <NEW_LINE> <INDENT> if (self.csl_style == 'soph'): <NEW_LINE> <INDENT> if ('et al.' in author) and (self.export_format == adsFormatter.latex): <NEW_LINE> <INDENT> return author.replace('et al.', '\\emph{et al.}') <NEW_LINE> <DEDENT> <DEDENT> return author | :param author:
:return: | 625941db3c8af77a43ae3a8b |
def procesando_entrada(self, url): <NEW_LINE> <INDENT> print("<p>Procesando entrada</p>") <NEW_LINE> print("<form id='autolog' action='" + url + "' method='post'>") <NEW_LINE> print("<script language='JavaScript' type='text/javascript'>") <NEW_LINE> self.texto_script() <NEW_LINE> print("</script>") | PRocesando entrada | 625941dbde87d2750b86007e |
def test_revisions_all_params_as_user_is_allowed(root_doc, wiki_user, client): <NEW_LINE> <INDENT> url = reverse('wiki.document_revisions', args=(root_doc.slug,), locale=root_doc.locale) <NEW_LINE> all_url = urlparams(url, limit='all') <NEW_LINE> wiki_user.set_password('password') <NEW_LINE> wiki_user.save() <NEW_LINE>... | Users are allowed to request all revisions. | 625941dbfff4ab517eb2f726 |
def delete(self, req, id, body): <NEW_LINE> <INDENT> versionutils.report_deprecated_feature(LOG, DEPRECATE_CG_API_MSG) <NEW_LINE> LOG.debug('delete called for member %s', id) <NEW_LINE> context = req.environ['cinder.context'] <NEW_LINE> force = False <NEW_LINE> if body: <NEW_LINE> <INDENT> self.assert_valid_body(body, ... | Delete a consistency group. | 625941dbf8510a7c17cf99e7 |
def __init__( self, embedding_dim: int, input_size: int, num_heads: int, freeze: bool = False, norm_type: str = None, activation_type: str = None, scale: bool = False, scale_factor: float = None, **kwargs ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.embedding_dim = embedding_dim <NEW_LINE> self.input_size ... | Create new embeddings for the vocabulary.
Use scaling for the Transformer.
:param embedding_dim:
:param input_size:
:param freeze: freeze the embeddings during training | 625941db8e71fb1e9831da91 |
def test_uncheck_should_keep_unchecked_if_called_multiple_times(self): <NEW_LINE> <INDENT> self.assertTrue(self.browser.find_by_name("checked-checkbox").checked) <NEW_LINE> self.browser.uncheck("checked-checkbox") <NEW_LINE> self.browser.uncheck("checked-checkbox") <NEW_LINE> self.assertFalse(self.browser.find_by_name(... | should keep a checkbox unchecked if uncheck() is called multiple times | 625941db6e29344779a628f9 |
def reverse_str1(s, k): <NEW_LINE> <INDENT> res = list(s) <NEW_LINE> for i in range(0, len(s), 2 * k): <NEW_LINE> <INDENT> res[i:i + k] = reversed(res[i:i + k]) <NEW_LINE> <DEDENT> return ''.join(res) | 暴力法。
:param s: (str)
:param k: (int)
:return: (str) | 625941db091ae35668667243 |
def init_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('-f', '--file', type=argparse.FileType('r', encoding='UTF-8'), required=True, help='argument for the input file') <NEW_LINE> args = parser.parse_args() <NEW_LINE> return args | @brief - function containing user args to be passed at run time | 625941dba934411ee375197d |
def preprocessing_fn(inputs): <NEW_LINE> <INDENT> outputs = {} <NEW_LINE> for key in _DENSE_FLOAT_FEATURE_KEYS: <NEW_LINE> <INDENT> outputs[_transformed_name(key)] = tft.scale_to_z_score( _fill_in_missing(inputs[key])) <NEW_LINE> <DEDENT> for key in _VOCAB_FEATURE_KEYS: <NEW_LINE> <INDENT> outputs[_transformed_name(key... | tf.transform's callback function for preprocessing inputs.
Args:
inputs: map from feature keys to raw not-yet-transformed features.
Returns:
Map from string feature key to transformed feature operations. | 625941dbcb5e8a47e48b7d8f |
def ViewshedGenerate(*args, **kwargs): <NEW_LINE> <INDENT> return _gdal.ViewshedGenerate(*args, **kwargs) | ViewshedGenerate(Band srcBand, char const * driverName, char const * targetRasterName, char ** creationOptions, double observerX, double observerY, double observerHeight, double targetHeight, double visibleVal, double invisibleVal, double outOfRangeVal, double noDataVal, double dfCurvCoeff, GDALViewshedMode mode, doubl... | 625941db66656f66f7cbc496 |
def __str__(self) -> str: <NEW_LINE> <INDENT> return self._format_clause_group(self.clauses) | Produce a human readable string to describe this version selector.
:return: A human readable string
:rtype: str | 625941dbd6c5a10208144336 |
def find_degrees(self): <NEW_LINE> <INDENT> f = open(self.data, 'r') <NEW_LINE> degrees = re.findall(r'[\w\s]+,([\w\.\s]+),[\w\s]+Biostatistics', f.read()) <NEW_LINE> f.close() <NEW_LINE> res = {} <NEW_LINE> for degree in degrees: <NEW_LINE> <INDENT> temp = degree.strip().translate(None, '.').split(' ') <NEW_LINE> for ... | Finds degrees held by the professors from a textfile. Returns a dictionary of
unique degrees with a value of the frequency. For those with multiple degrees,
they are split and counted seperately. Ex. MD PhD would count MD +1 and PhD +1. | 625941db97e22403b379d284 |
def _create_fleet(self): <NEW_LINE> <INDENT> alien = Alien(self) <NEW_LINE> alien_width, alien_height = alien.rect.size <NEW_LINE> available_space_x = self.settings.screen_width - (2 * alien_width) <NEW_LINE> number_aliens_x = available_space_x // (2 * alien_width) <NEW_LINE> ship_height = self.ship.rect.height <NEW_LI... | Make the fleet of aliens | 625941db56b00c62f0f14944 |
def is_xml_http_request(self): <NEW_LINE> <INDENT> return (self.headers.get( 'X-Requested-With', '').lower() == 'xmlhttprequest') | Determine whether or not a request has originated via an XmlHttpRequest,
assuming the relevant header has been set by the request.
Returns:
Boolean | 625941db187af65679ca5408 |
def test_raises_error_when_disconnect_a_not_connected_database(self): <NEW_LINE> <INDENT> Database.disconnect.when.called_with().throw(ValueError, "Database isn't connected") | [DatabaseTestCase] - Raises ValueError when disconnect from a not connected database | 625941db7d847024c06be5a8 |
def ensure_dir(d): <NEW_LINE> <INDENT> if not os.path.exists(d): <NEW_LINE> <INDENT> os.makedirs(d) | Create a directory if it does not already exist.
Args:
d (str): A directory. | 625941db9b70327d1c4e10bf |
def test_flattenlist(): <NEW_LINE> <INDENT> root = LinkedList() <NEW_LINE> l10 = Node(10) <NEW_LINE> l5 = Node(5) <NEW_LINE> l12 = Node(12) <NEW_LINE> l7 = Node(7) <NEW_LINE> l11 = Node(11) <NEW_LINE> l4 = Node(4) <NEW_LINE> l20 = Node(20) <NEW_LINE> l2 = Node(2) <NEW_LINE> l13 = Node(13) <NEW_LINE> l16 = Node(16) <NEW... | Call to flatten linked list | 625941db5fcc89381b1e19ab |
def _count_countries(string): <NEW_LINE> <INDENT> return len([country for country, patterns in keywords.items() if any((re.search(pattern, string, flags=re.IGNORECASE) for pattern in patterns))]) | Count the number of unique countries mentioned in the string.
:param string: string
:return: int | 625941dba4f1c619b28b031c |
def get_child_info(self): <NEW_LINE> <INDENT> dChildren = {} <NEW_LINE> if self.iExtraLevelsMode in CARD_SETS_2ND_LEVEL: <NEW_LINE> <INDENT> iParCnt = self.iParentCount <NEW_LINE> for sCardSet, iCnt in self.dChildCardSets.iteritems(): <NEW_LINE> <INDENT> bIncCard, bDecCard = self.get_inc_dec_flags(iCnt) <NEW_LINE> dChi... | Get information about child card sets | 625941dba8370b7717052b88 |
def starring(self, actors, ret_str=""): <NEW_LINE> <INDENT> if not actors: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> actor = actors.pop(0) <NEW_LINE> if not actors: <NEW_LINE> <INDENT> return "Starring " + ret_str + "and %s." % actor <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret_str += "%s, " % actor <NEW_L... | Takes in a list of actors [foo, bar, foobar] and recursively concatenates them
to return a string in the form 'Starring foo, bar, and foobar.' There's no
scientific need for this method to be recursive, other than to learn and try recursion.
:rtype : str | 625941db627d3e7fe0d6913a |
def calculate_image_size_sum(images): <NEW_LINE> <INDENT> total_size = 0 <NEW_LINE> counted = {} <NEW_LINE> for i in reversed(range(len(images))): <NEW_LINE> <INDENT> image_id = images[i]['id'] <NEW_LINE> if image_id not in counted: <NEW_LINE> <INDENT> counted[image_id] = 1 <NEW_LINE> total_size += int(images[i]['size'... | Sum the total size of images in the local repo recalulated to
a reasonable unit.
Avoids counting the same image twice. | 625941db3346ee7daa2b3057 |
def create_volume(self, **kwargs): <NEW_LINE> <INDENT> post_body = json.dumps({'volume': kwargs}) <NEW_LINE> resp, body = self.post('volumes', post_body) <NEW_LINE> body = json.loads(body) <NEW_LINE> self.expected_success(200, resp.status) <NEW_LINE> return rest_client.ResponseBody(resp, body) | Creates a new Volume.
For a full list of available parameters, please refer to the official
API reference:
https://developer.openstack.org/api-ref/block-storage/v2/#create-volume | 625941dbf7d966606f6aa2f1 |
def normPath(pathSring): <NEW_LINE> <INDENT> if pathSring is not None: <NEW_LINE> <INDENT> return os.path.normpath(pathSring) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Normalize path for the os
:param pathString: the path to normalize
:returns: the normalized path or None | 625941db38b623060ff0b0d7 |
@register.filter(name='cut') <NEW_LINE> def cut(value,arg): <NEW_LINE> <INDENT> return value.replace(arg,'') | This cut out all value of "arg" from string | 625941db26238365f5f0f15b |
@user.route("/logout", methods=["GET"]) <NEW_LINE> def logout(): <NEW_LINE> <INDENT> session.clear() <NEW_LINE> return redirect("/") | Log user out | 625941db0c0af96317bb84d1 |
def _map_field_validators(self, field, schema): <NEW_LINE> <INDENT> for v in field.validators: <NEW_LINE> <INDENT> if isinstance(v, EmailValidator): <NEW_LINE> <INDENT> schema['format'] = 'email' <NEW_LINE> <DEDENT> if isinstance(v, URLValidator): <NEW_LINE> <INDENT> schema['format'] = 'uri' <NEW_LINE> <DEDENT> if isin... | map field validators | 625941dbadb09d7d5db6ca77 |
def get_exchange_servers(self): <NEW_LINE> <INDENT> pass | Return all MS Exchanges computer SPNs (Use sensepost ruleR!) | 625941db7047854f462a16f0 |
def __init__(self,inMasters,outMasters): <NEW_LINE> <INDENT> mast_map = {} <NEW_LINE> outMastersIndex = outMasters.index <NEW_LINE> for index,master in enumerate(inMasters): <NEW_LINE> <INDENT> if master in outMasters: <NEW_LINE> <INDENT> mast_map[index] = outMastersIndex(master) <NEW_LINE> <DEDENT> else: <NEW_LINE> <I... | Initiation. | 625941db30bbd722463cc0b2 |
def serialize(self, ar): <NEW_LINE> <INDENT> return _DataModel.RealPDF1D_serialize(self, ar) | serialize(RealPDF1D self, GenericArchive ar) | 625941db5e10d32532c5f210 |
def getMinimumDifference(self, root): <NEW_LINE> <INDENT> self.res = float('inf') <NEW_LINE> self.prev = float('inf') <NEW_LINE> def dfs(node, val): <NEW_LINE> <INDENT> if not node: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> dfs(node.left, node.val) <NEW_LINE> self.res = min(self.res, abs(node.val-self.prev)) <NEW_... | :type root: TreeNode
:rtype: int | 625941dbd486a94d0b98e430 |
def parse_nv_block(decompressor, nv_bytes): <NEW_LINE> <INDENT> headers = {} <NEW_LINE> if not nv_bytes: <NEW_LINE> <INDENT> return headers <NEW_LINE> <DEDENT> data = decompressor.decompress(nv_bytes) <NEW_LINE> num = struct.unpack("!L", data[0:4])[0] <NEW_LINE> data = data[4:] <NEW_LINE> for i in range(0, num): <NEW_L... | This function parses the compressed name-value header block.
:param decompressor: A ``zlib`` decompression object from the stream.
:param nv_bytes: The bytes comprising the name-value header block. | 625941dbff9c53063f47c4dc |
def __str__ (self): <NEW_LINE> <INDENT> addr = id (self) <NEW_LINE> name = type (self).__name__ <NEW_LINE> if self.IsCompleted (): <NEW_LINE> <INDENT> result, error = self.GetResult () <NEW_LINE> if error is None: <NEW_LINE> <INDENT> return '<{} [={}] at {}>'.format (name, result, addr) <NEW_LINE> <DEDENT> else: <NEW_... | String representation of the future
| 625941dbcc40096d61595c39 |
def unwrap(s): <NEW_LINE> <INDENT> s = s[s.find('=') + 1:] <NEW_LINE> s = s.lstrip(' "') <NEW_LINE> s = s.rstrip('"') <NEW_LINE> if s.endswith('\\n'): <NEW_LINE> <INDENT> s = s[:-2] <NEW_LINE> <DEDENT> if s.endswith('\\"'): <NEW_LINE> <INDENT> s = s[:-2] <NEW_LINE> <DEDENT> if s.startswith('\\"'): <NEW_LINE> <INDENT> s... | Strip non-essential character sequences from a string.
>>> unwrap('(String) value = "42\\n"')
'42'
>>> unwrap('(Int) $R0 = 42')
'42'
>>> unwrap('\\"foo\"')
'foo'
>>> unwrap('foo\nbar')
'foo\nbar'
>>> unwrap(' foo ')
'foo' | 625941db0a50d4780f66717e |
def col_normalize(x): <NEW_LINE> <INDENT> x_normed = x / T.sqrt(T.sum(x**2.,axis=0,keepdims=1)+1e-6) <NEW_LINE> return x_normed | Normalize cols of matrix x to unit (L2) norm. | 625941db91af0d3eaac9bd05 |
def test_get_evnet_null(self): <NEW_LINE> <INDENT> r=requests.get(url=self.url,params={'eid':''}) <NEW_LINE> result=r.json() <NEW_LINE> try: <NEW_LINE> <INDENT> self.assertEqual(result['status'],10022) <NEW_LINE> self.assertEqual(result['message'],'query result is empty') <NEW_LINE> print(result) <NEW_LINE> <DEDENT> ex... | 发布会id为空 | 625941dbe76e3b2f99f3aaf1 |
def note_parse(bot): <NEW_LINE> <INDENT> with codecs.open(bot.opt('note.file'),'r',encoding='utf8') as f: <NEW_LINE> <INDENT> lines = f.readlines() <NEW_LINE> <DEDENT> notes = [l.strip() for l in lines if l!='\n'] <NEW_LINE> log.info('Read '+str(len(notes))+' notes from "'+bot.opt('note.file')+'"') <NEW_LINE> return no... | read the note file into a list | 625941db21bff66bcd684c39 |
def soap_GetSortCapabilities(self, *args, **kwargs): <NEW_LINE> <INDENT> log.debug('Action on ContentDirectory: GetSortCapabilities()') <NEW_LINE> return {'SortCaps': 'dc:title'} | Returns the CSV list of meta-data tags that can be used in
sortCriteria.
@param args: list of arguments for the GetSortCapabilities UPnP function
@param kwargs: dict of arguments for the GetSortCapabilities UPnP function
@type args: list
@type kwargs: dict
@return: CSV list of meta-data
@rtype: dict | 625941db44b2445a3393237e |
def consume(self): <NEW_LINE> <INDENT> for msg in self.cons.consume(): <NEW_LINE> <INDENT> gndr_entry = self.create_gndr_entry(msg, self.modelnm) <NEW_LINE> yield gndr_entry | consuming the kafka data / transform the ingested json into predefined template
| 625941dbd486a94d0b98e431 |
def get_version(self): <NEW_LINE> <INDENT> if self._version is None: <NEW_LINE> <INDENT> raise Error("Versioning disabled") <NEW_LINE> <DEDENT> if self._loaded_version is None: <NEW_LINE> <INDENT> raise Error("No file loaded") <NEW_LINE> <DEDENT> return self._loaded_version | Get the version of the loaded config file (for testing only)
Raises Error if no file was loaded or versioning is disabled. | 625941db99fddb7c1c9de67a |
def setup_to_create_cv(self, repo_name=None, repo_url=None, repo_type=None, repo_unprotected=True, rh_repo=None, org_id=None, docker_upstream_name=None): <NEW_LINE> <INDENT> if not rh_repo: <NEW_LINE> <INDENT> repo_name = repo_name or gen_string('alpha') <NEW_LINE> product = entities.Product( organization=org_id or sel... | Create product/repo and sync it | 625941dbd58c6744b4257f48 |
def LoadString(self, *args, **kwargs): <NEW_LINE> <INDENT> pass | Load a string. | 625941dbe8904600ed9f221a |
def __read_csv(path, mode, encoding, kwargs): <NEW_LINE> <INDENT> def read_csv_rows(): <NEW_LINE> <INDENT> if read_all_rows: <NEW_LINE> <INDENT> return list(csv_reader) <NEW_LINE> <DEDENT> m = [] <NEW_LINE> try: <NEW_LINE> <INDENT> for i in range(nrows): <NEW_LINE> <INDENT> m.append(next(csv_reader)) <NEW_LINE> <DEDENT... | _csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
fixed by passing lineterminator='
'
or newline='
', newline='' | 625941dbb57a9660fec33b72 |
def can_run_cdtw(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import aeneas.cdtw.cdtw <NEW_LINE> return True <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> return False | Python C extension for computing DTW | 625941db4e4d5625662d46be |
def quicksort(array, low, high): <NEW_LINE> <INDENT> if low < high: <NEW_LINE> <INDENT> partition_index = qs_partition(array, low, high) <NEW_LINE> quicksort(array, low, partition_index - 1) <NEW_LINE> quicksort(array, partition_index + 1, high) <NEW_LINE> <DEDENT> return array | Quick sort function to recursively establish
bounds using pivot, low and high. This function
recursively splits the array into smaller windows
and there by ensures quick sort is executed within this window. | 625941dba934411ee375197e |
def assertion(self, statement, success_msg, error_msg, desc=''): <NEW_LINE> <INDENT> desc = dict( desc=desc, ex_time=time.time() ) <NEW_LINE> if statement: <NEW_LINE> <INDENT> self.success.append((success_msg, desc)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.error.append((error_msg, desc)) | Called within test functions to store errors and successes
Results will be appended to the correct log reccords | 625941db26238365f5f0f15c |
def add_donation(self, name, donation): <NEW_LINE> <INDENT> if not self.donor_exists(name): <NEW_LINE> <INDENT> self.add_donor(name) <NEW_LINE> <DEDENT> donation = Decimal(donation).quantize(Decimal('.01')) <NEW_LINE> self.donor_list[name].append(donation) <NEW_LINE> return donation | Add a donation to a donor's history.
If donor does not exist, create donor in data. | 625941db379a373c97cfae30 |
def test_host_creation(self): <NEW_LINE> <INDENT> self.assertRaises( TypeError, hosts.Host ) <NEW_LINE> host_model = make_new(HOST) <NEW_LINE> self.assertEquals(type(str()), type(host_model.to_json())) <NEW_LINE> for attr, spec in host_model._attribute_map.items(): <NEW_LINE> <INDENT> value = getattr(host_model, attr) ... | Verify host model | 625941db507cdc57c6306fca |
def stemmed_words(doc): <NEW_LINE> <INDENT> doc = process_text(doc) <NEW_LINE> stemmer = PorterStemmer() <NEW_LINE> analyzer = CountVectorizer(decode_error='ignore').build_analyzer() <NEW_LINE> return (stemmer.stem(w) for w in analyzer(doc)) | Calls the text cleaner and then does stemming. This should be defined as the
'analyzer' in CountVectorizer() when called later.
Parameters
----------
doc : string
The text that will be processed and with words that will be stemmed. | 625941db8e05c05ec3eea661 |
def resolveContext(config, args): <NEW_LINE> <INDENT> data = {} <NEW_LINE> try: <NEW_LINE> <INDENT> data['log_level'] = args.log_level or config.get('stocks', 'log_level') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> data['log_level'] = config.get('stocks', 'log_level') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> d... | Returns a dictionary consisting of keys found
in config and the values of config overwritten
by values of args | 625941db2eb69b55b151cb9c |
def process_submission(self, submission, source_comment, title, dm=None, request_body=None, customargs=None): <NEW_LINE> <INDENT> url = self.process_image_submission(submission=submission, custom_title=title, customargs=customargs) <NEW_LINE> if url is None: <NEW_LINE> <INDENT> self.screen.set_current_action_status('UR... | Send info to process_image_submission and handle errors that arise from that method.
Args:
submission (praw.models.Submission): Post to process
source_comment (praw.models.Comment): Comment that summoned bot
title (str): Title to add to the image
dm (Optional[Any]): Unused variable
request_body (st... | 625941db94891a1f4081bd94 |
def get_list_commits(self, branch: str = None, reverse_order: bool = True) -> Generator[Commit, None, None]: <NEW_LINE> <INDENT> for commit in self.repo.iter_commits(branch, reverse=reverse_order): <NEW_LINE> <INDENT> yield self.get_commit_from_gitpython(commit) | Return a generator of commits of all the commits in the repo.
:return: Generator[Commit], the generator of all the commits in the repo | 625941db6fb2d068a760f38b |
def get_S_safe(z): <NEW_LINE> <INDENT> def s_series(): <NEW_LINE> <INDENT> return (1.0/(factorial(3.0))) - z/factorial(5.0) + z**2/factorial(7.0) - z**3/factorial(9.0) + z**4/factorial(11.0) - z**5/factorial(13.0) + z**6/factorial(15.0) - z**7/factorial(17.0) <NEW_LINE> <DEDENT> with warnings.catch_warnings(): <NEW_LIN... | S function, with catches for znear zero behavior | 625941dbd99f1b3c44c67874 |
@given(simple_typed_classes(), unstructure_strats) <NEW_LINE> def test_simple_roundtrip(cls_and_vals, strat): <NEW_LINE> <INDENT> converter = Converter(unstruct_strat=strat) <NEW_LINE> cl, vals = cls_and_vals <NEW_LINE> inst = cl(*vals) <NEW_LINE> assert inst == converter.structure(converter.unstructure(inst), cl) | Simple classes with metadata can be unstructured and restructured. | 625941dbd268445f265b5158 |
def try_expand_item(self, item: QTreeWidgetItem): <NEW_LINE> <INDENT> expanding_stat = self.expanding_stat.get(item.item_id) <NEW_LINE> if expanding_stat is not None: <NEW_LINE> <INDENT> item.setExpanded(expanding_stat) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> item.setExpanded(False) | 如果状态为展开则展开,否则不展开
:param item:
:return: | 625941db45492302aab5e5b0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.