_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q226800
create_brain
train
def create_brain(path='aiml-en-us-foundation-alice.v1-9.zip'): """ Create an aiml_bot.Bot brain from an AIML zip file or directory of AIML files """ path = find_data_path(path) or path bot = Bot() num_templates = bot._brain.template_count paths = extract_aiml(path=path) for path in paths: ...
python
{ "resource": "" }
q226801
minify_urls
train
def minify_urls(filepath, ext='asc', url_regex=None, output_ext='.urls_minified', access_token=None): """ Use bitly or similar minifier to shrink all URLs in text files within a folder structure. Used for the NLPIA manuscript directory for Manning Publishing bitly API: https://dev.bitly.com/links.html ...
python
{ "resource": "" }
q226802
delimit_slug
train
def delimit_slug(slug, sep=' '): """ Return a str of separated tokens found within a slugLike_This => 'slug Like This' >>> delimit_slug("slugLike_ThisW/aTLA's") 'slug Like This W a TLA s' >>> delimit_slug('slugLike_ThisW/aTLA', '|') 'slug|Like|This|W|a|TLA' """ hyphenated_slug = re.sub(CRE_...
python
{ "resource": "" }
q226803
clean_asciidoc
train
def clean_asciidoc(text): r""" Transform asciidoc text into ASCII text that NL parsers can handle TODO: Tag lines and words with meta data like italics, underlined, bold, title, heading 1, etc >>> clean_asciidoc('**Hello** _world_!') '"Hello" "world"!' """ text = re.sub(r'(\b|^)[\[_*]{1,...
python
{ "resource": "" }
q226804
split_sentences_regex
train
def split_sentences_regex(text): """ Use dead-simple regex to split text into sentences. Very poor accuracy. >>> split_sentences_regex("Hello World. I'm I.B.M.'s Watson. --Watson") ['Hello World.', "I'm I.B.M.'s Watson.", '--Watson'] """ parts = regex.split(r'([a-zA-Z0-9][.?!])[\s$]', text) sen...
python
{ "resource": "" }
q226805
split_sentences_spacy
train
def split_sentences_spacy(text, language_model='en'): r""" You must download a spacy language model with python -m download 'en' The default English language model for spacy tends to be a lot more agressive than NLTK's punkt: >>> split_sentences_nltk("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) -...
python
{ "resource": "" }
q226806
segment_sentences
train
def segment_sentences(path=os.path.join(DATA_PATH, 'book'), splitter=split_sentences_nltk, **find_files_kwargs): """ Return a list of all sentences and empty lines. TODO: 1. process each line with an aggressive sentence segmenter, like DetectorMorse 2. process our manuscript to create a complet...
python
{ "resource": "" }
q226807
fix_hunspell_json
train
def fix_hunspell_json(badjson_path='en_us.json', goodjson_path='en_us_fixed.json'): """Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings Args: badjson_path (str): path to input json file that doesn't properly quote goodjson_path (str): path to output ...
python
{ "resource": "" }
q226808
format_ubuntu_dialog
train
def format_ubuntu_dialog(df): """ Print statements paired with replies, formatted for easy review """ s = '' for i, record in df.iterrows(): statement = list(split_turns(record.Context))[-1] # <1> reply = list(split_turns(record.Utterance))[-1] # <2> s += 'Statement: {}\n'.format(s...
python
{ "resource": "" }
q226809
splitext
train
def splitext(filepath): """ Like os.path.splitext except splits compound extensions as one long one >>> splitext('~/.bashrc.asciidoc.ext.ps4.42') ('~/.bashrc', '.asciidoc.ext.ps4.42') >>> splitext('~/.bash_profile') ('~/.bash_profile', '') """ exts = getattr(CRE_FILENAME_EXT.search(filepath...
python
{ "resource": "" }
q226810
offline_plotly_scatter3d
train
def offline_plotly_scatter3d(df, x=0, y=1, z=-1): """ Plot an offline scatter plot colored according to the categories in the 'name' column. >> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/iris.csv') >> offline_plotly(df) """ data = [] # clusters = [] colors = ...
python
{ "resource": "" }
q226811
offline_plotly_data
train
def offline_plotly_data(data, filename=None, config=None, validate=True, default_width='100%', default_height=525, global_requirejs=False): r""" Write a plotly scatter plot to HTML file that doesn't require server >>> from nlpia.loaders import get_data >>> df = get_data('etpinard') ...
python
{ "resource": "" }
q226812
normalize_etpinard_df
train
def normalize_etpinard_df(df='https://plot.ly/~etpinard/191.csv', columns='x y size text'.split(), category_col='category', possible_categories=['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']): """Reformat a dataframe in etpinard's format for use in plot functions and sklearn models"""...
python
{ "resource": "" }
q226813
offline_plotly_scatter_bubble
train
def offline_plotly_scatter_bubble(df, x='x', y='y', size_col='size', text_col='text', category_col='category', possible_categories=None, filename=None, config={'displaylogo': False}, x...
python
{ "resource": "" }
q226814
format_hex
train
def format_hex(i, num_bytes=4, prefix='0x'): """ Format hexidecimal string from decimal integer value >>> format_hex(42, num_bytes=8, prefix=None) '0000002a' >>> format_hex(23) '0x0017' """ prefix = str(prefix or '') i = int(i or 0) return prefix + '{0:0{1}x}'.format(i, num_bytes)
python
{ "resource": "" }
q226815
is_up_url
train
def is_up_url(url, allow_redirects=False, timeout=5): r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP error code) cleaned up URL (following redirects and possibly adding HTTP schema "ht...
python
{ "resource": "" }
q226816
get_markdown_levels
train
def get_markdown_levels(lines, levels=set((0, 1, 2, 3, 4, 5, 6))): r""" Return a list of 2-tuples with a level integer for the heading levels >>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n') [(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')] >>> get_markdown_levels('- bul...
python
{ "resource": "" }
q226817
iter_lines
train
def iter_lines(url_or_text, ext=None, mode='rt'): r""" Return an iterator over the lines of a file or URI response. >>> len(list(iter_lines('cats_and_dogs.txt'))) 263 >>> len(list(iter_lines(list('abcdefgh')))) 8 >>> len(list(iter_lines('abc\n def\n gh\n'))) 3 >>> len(list(iter_lines('a...
python
{ "resource": "" }
q226818
parse_utf_html
train
def parse_utf_html(url=os.path.join(DATA_PATH, 'utf8_table.html')): """ Parse HTML table UTF8 char descriptions returning DataFrame with `ascii` and `mutliascii` """ utf = pd.read_html(url) utf = [df for df in utf if len(df) > 1023 and len(df.columns) > 2][0] utf = utf.iloc[:1024] if len(utf) == 1025 el...
python
{ "resource": "" }
q226819
clean_csvs
train
def clean_csvs(dialogpath=None): """ Translate non-ASCII characters to spaces or equivalent ASCII characters """ dialogdir = os.dirname(dialogpath) if os.path.isfile(dialogpath) else dialogpath filenames = [dialogpath.split(os.path.sep)[-1]] if os.path.isfile(dialogpath) else os.listdir(dialogpath) for ...
python
{ "resource": "" }
q226820
unicode2ascii
train
def unicode2ascii(text, expand=True): r""" Translate UTF8 characters to ASCII >> unicode2ascii("żółw") zozw utf8_letters = 'ą ę ć ź ż ó ł ń ś “ ” ’'.split() ascii_letters = 'a e c z z o l n s " " \'' """ translate = UTF8_TO_ASCII if not expand else UTF8_TO_MULTIASCII output = '' f...
python
{ "resource": "" }
q226821
clean_df
train
def clean_df(df, header=None, **read_csv_kwargs): """ Convert UTF8 characters in a CSV file or dataframe into ASCII Args: df (DataFrame or str): DataFrame or path or url to CSV """ df = read_csv(df, header=header, **read_csv_kwargs) df = df.fillna(' ') for col in df.columns: df[co...
python
{ "resource": "" }
q226822
get_acronyms
train
def get_acronyms(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript')): """ Find all the 2 and 3-letter acronyms in the manuscript and return as a sorted list of tuples """ acronyms = [] for f, lines in get_lines(manuscript): for line in lines: matches = CRE_ACRONYM.finditer(lin...
python
{ "resource": "" }
q226823
write_glossary
train
def write_glossary(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript'), linesep=None): """ Compose an asciidoc string with acronyms culled from the manuscript """ linesep = linesep or os.linesep lines = ['[acronyms]', '== Acronyms', '', '[acronyms,template="glossary",id="terms"]'] acronyms = g...
python
{ "resource": "" }
q226824
infer_url_title
train
def infer_url_title(url): """ Guess what the page title is going to be from the path and FQDN in the URL >>> infer_url_title('https://ai.googleblog.com/2018/09/the-what-if-tool-code-free-probing-of.html') 'the what if tool code free probing of' """ meta = get_url_filemeta(url) title = '' if...
python
{ "resource": "" }
q226825
translate_book
train
def translate_book(translators=(HyperlinkStyleCorrector().translate, translate_line_footnotes), book_dir=BOOK_PATH, dest=None, include_tags=None, ext='.nlpiabak', skip_untitled=True): """ Fix any style corrections listed in `translate` list of translation functions >>> len...
python
{ "resource": "" }
q226826
filter_lines
train
def filter_lines(input_file, output_file, translate=lambda line: line): """ Translate all the lines of a single file """ filepath, lines = get_lines([input_file])[0] return filepath, [(tag, translate(line=line, tag=tag)) for (tag, line) in lines]
python
{ "resource": "" }
q226827
filter_tagged_lines
train
def filter_tagged_lines(tagged_lines, include_tags=None, exclude_tags=None): r""" Return iterable of tagged lines where the tags all start with one of the include_tags prefixes >>> filter_tagged_lines([('natural', "Hello."), ('code', '[source,python]'), ('code', '>>> hello()')]) <generator object filter_ta...
python
{ "resource": "" }
q226828
accuracy_study
train
def accuracy_study(tdm=None, u=None, s=None, vt=None, verbosity=0, **kwargs): """ Reconstruct the term-document matrix and measure error as SVD terms are truncated """ smat = np.zeros((len(u), len(vt))) np.fill_diagonal(smat, s) smat = pd.DataFrame(smat, columns=vt.index, index=u.index) if verbo...
python
{ "resource": "" }
q226829
get_anki_phrases
train
def get_anki_phrases(lang='english', limit=None): """ Retrieve as many anki paired-statement corpora as you can for the requested language If `ankis` (requested languages) is more than one, then get the english texts associated with those languages. TODO: improve modularity: def function that takes a sing...
python
{ "resource": "" }
q226830
get_anki_phrases_english
train
def get_anki_phrases_english(limit=None): """ Return all the English phrases in the Anki translation flashcards >>> len(get_anki_phrases_english(limit=100)) > 700 True """ texts = set() for lang in ANKI_LANGUAGES: df = get_data(lang) phrases = df.eng.str.strip().values ...
python
{ "resource": "" }
q226831
get_vocab
train
def get_vocab(docs): """ Build a DataFrame containing all the words in the docs provided along with their POS tags etc >>> doc = nlp("Hey Mr. Tangerine Man!") <BLANKLINE> ... >>> get_vocab([doc]) word pos tag dep ent_type ent_iob sentiment 0 ! PUNCT . pun...
python
{ "resource": "" }
q226832
get_word_vectors
train
def get_word_vectors(vocab): """ Create a word2vec embedding matrix for all the words in the vocab """ wv = get_data('word2vec') vectors = np.array(len(vocab), len(wv['the'])) for i, tok in enumerate(vocab): word = tok[0] variations = (word, word.lower(), word.lower()[:-1]) for w...
python
{ "resource": "" }
q226833
get_anki_vocab
train
def get_anki_vocab(lang=['eng'], limit=None, filename='anki_en_vocabulary.csv'): """ Get all the vocab words+tags+wordvectors for the tokens in the Anki translation corpus Returns a DataFrame of with columns = word, pos, tag, dep, ent, ent_iob, sentiment, vectors """ texts = get_anki_phrases(lang=lang,...
python
{ "resource": "" }
q226834
lsa_twitter
train
def lsa_twitter(cased_tokens): """ Latent Sentiment Analyis on random sampling of twitter search results for words listed in cased_tokens """ # Only 5 of these tokens are saved for a no_below=2 filter: # PyCons NLPS #PyCon2016 #NaturalLanguageProcessing #naturallanguageprocessing if cased_tokens is N...
python
{ "resource": "" }
q226835
wc
train
def wc(f, verbose=False, nrows=None): r""" Count lines in a text file References: https://stackoverflow.com/q/845058/623735 >>> with open(os.path.join(DATA_PATH, 'dictionary_fda_drug_names.txt')) as fin: ... print(wc(fin) == wc(fin) == 7037 == wc(fin.name)) True >>> wc(fin.name) ...
python
{ "resource": "" }
q226836
normalize_filepath
train
def normalize_filepath(filepath): r""" Lowercase the filename and ext, expanding extensions like .tgz to .tar.gz. >>> normalize_filepath('/Hello_World.txt\n') 'hello_world.txt' >>> normalize_filepath('NLPIA/src/nlpia/bigdata/Goog New 300Dneg\f.bIn\n.GZ') 'NLPIA/src/nlpia/bigdata/goog new 300dneg.bi...
python
{ "resource": "" }
q226837
find_filepath
train
def find_filepath( filename, basepaths=(os.path.curdir, DATA_PATH, BIGDATA_PATH, BASE_DIR, '~', '~/Downloads', os.path.join('/', 'tmp'), '..')): """ Given a filename or path see if it exists in any of the common places datafiles might be >>> p = find_filepath('iq_test.csv') >>> p == expand_...
python
{ "resource": "" }
q226838
Driver.close
train
def close(self): """ Shut down, closing any open connections in the pool. """ if not self._closed: self._closed = True if self._pool is not None: self._pool.close() self._pool = None
python
{ "resource": "" }
q226839
hydrate_point
train
def hydrate_point(srid, *coordinates): """ Create a new instance of a Point subclass from a raw set of fields. The subclass chosen is determined by the given SRID; a ValueError will be raised if no such subclass can be found. """ try: point_class, dim = __srid_table[srid] except KeyE...
python
{ "resource": "" }
q226840
dehydrate_point
train
def dehydrate_point(value): """ Dehydrator for Point data. :param value: :type value: Point :return: """ dim = len(value) if dim == 2: return Structure(b"X", value.srid, *value) elif dim == 3: return Structure(b"Y", value.srid, *value) else: raise ValueError(...
python
{ "resource": "" }
q226841
PackStreamDehydrator.dehydrate
train
def dehydrate(self, values): """ Convert native values into PackStream values. """ def dehydrate_(obj): try: f = self.dehydration_functions[type(obj)] except KeyError: pass else: return f(obj) if obj...
python
{ "resource": "" }
q226842
Record.get
train
def get(self, key, default=None): """ Obtain a value from the record by key, returning a default value if the key does not exist. :param key: :param default: :return: """ try: index = self.__keys.index(str(key)) except ValueError: ...
python
{ "resource": "" }
q226843
Record.index
train
def index(self, key): """ Return the index of the given item. :param key: :return: """ if isinstance(key, int): if 0 <= key < len(self.__keys): return key raise IndexError(key) elif isinstance(key, str): try: ...
python
{ "resource": "" }
q226844
Record.value
train
def value(self, key=0, default=None): """ Obtain a single value from the record by index or key. If no index or key is specified, the first value is returned. If the specified item does not exist, the default value is returned. :param key: :param default: :return: ...
python
{ "resource": "" }
q226845
Record.values
train
def values(self, *keys): """ Return the values of the record, optionally filtering to include only certain values by index or key. :param keys: indexes or keys of the items to include; if none are provided, all values will be included :return: list of values ...
python
{ "resource": "" }
q226846
Record.items
train
def items(self, *keys): """ Return the fields of the record as a list of key and value tuples :return: """ if keys: d = [] for key in keys: try: i = self.index(key) except KeyError: d.append(...
python
{ "resource": "" }
q226847
_make_plan
train
def _make_plan(plan_dict): """ Construct a Plan or ProfiledPlan from a dictionary of metadata values. :param plan_dict: :return: """ operator_type = plan_dict["operatorType"] identifiers = plan_dict.get("identifiers", []) arguments = plan_dict.get("args", []) children = [_make_plan(chil...
python
{ "resource": "" }
q226848
unit_of_work
train
def unit_of_work(metadata=None, timeout=None): """ This function is a decorator for transaction functions that allows extra control over how the transaction is carried out. For example, a timeout (in seconds) may be applied:: @unit_of_work(timeout=25.0) def count_people(tx): re...
python
{ "resource": "" }
q226849
Session.close
train
def close(self): """ Close the session. This will release any borrowed resources, such as connections, and will roll back any outstanding transactions. """ from neobolt.exceptions import ConnectionExpired, CypherError, ServiceUnavailable try: if self.has_transaction()...
python
{ "resource": "" }
q226850
Session.run
train
def run(self, statement, parameters=None, **kwparameters): """ Run a Cypher statement within an auto-commit transaction. The statement is sent and the result header received immediately but the :class:`.StatementResult` content is fetched lazily as consumed by the client application. ...
python
{ "resource": "" }
q226851
Session.send
train
def send(self): """ Send all outstanding requests. """ from neobolt.exceptions import ConnectionExpired if self._connection: try: self._connection.send() except ConnectionExpired as error: raise SessionExpired(*error.args)
python
{ "resource": "" }
q226852
Session.fetch
train
def fetch(self): """ Attempt to fetch at least one more record. :returns: number of records fetched """ from neobolt.exceptions import ConnectionExpired if self._connection: try: detail_count, _ = self._connection.fetch() except Connection...
python
{ "resource": "" }
q226853
Session.detach
train
def detach(self, result, sync=True): """ Detach a result from this session by fetching and buffering any remaining records. :param result: :param sync: :returns: number of records fetched """ count = 0 if sync and result.attached(): self.send...
python
{ "resource": "" }
q226854
Transaction.run
train
def run(self, statement, parameters=None, **kwparameters): """ Run a Cypher statement within the context of this transaction. The statement is sent to the server lazily, when its result is consumed. To force the statement to be sent to the server, use the :meth:`.Transaction.sync` metho...
python
{ "resource": "" }
q226855
StatementResult.detach
train
def detach(self, sync=True): """ Detach this result from its parent session by fetching the remainder of this result from the network into the buffer. :returns: number of records fetched """ if self.attached(): return self._session.detach(self, sync=sync) els...
python
{ "resource": "" }
q226856
StatementResult.keys
train
def keys(self): """ The keys for the records in this result. :returns: tuple of key names """ try: return self._metadata["fields"] except KeyError: if self.attached(): self._session.send() while self.attached() and "fields" not...
python
{ "resource": "" }
q226857
StatementResult.records
train
def records(self): """ Generator for records obtained from this result. :yields: iterable of :class:`.Record` objects """ records = self._records next_record = records.popleft while records: yield next_record() attached = self.attached if atta...
python
{ "resource": "" }
q226858
StatementResult.summary
train
def summary(self): """ Obtain the summary of this result, buffering any remaining records. :returns: The :class:`.ResultSummary` for this result """ self.detach() if self._summary is None: self._summary = BoltStatementResultSummary(**self._metadata) return se...
python
{ "resource": "" }
q226859
StatementResult.single
train
def single(self): """ Obtain the next and only remaining record from this result. A warning is generated if more than one record is available but the first of these is still returned. :returns: the next :class:`.Record` or :const:`None` if none remain :warns: if more than one r...
python
{ "resource": "" }
q226860
StatementResult.peek
train
def peek(self): """ Obtain the next record from this result without consuming it. This leaves the record in the buffer for further processing. :returns: the next :class:`.Record` or :const:`None` if none remain """ records = self._records if records: return r...
python
{ "resource": "" }
q226861
BoltStatementResult.value
train
def value(self, item=0, default=None): """ Return the remainder of the result as a list of values. :param item: field to return for each remaining record :param default: default value, used if the index of key is unavailable :returns: list of individual values """ return...
python
{ "resource": "" }
q226862
Pipeline.pull
train
def pull(self): """Returns a generator containing the results of the next query in the pipeline""" # n.b. pull is now somewhat misleadingly named because it doesn't do anything # the connection isn't touched until you try and iterate the generator we return lock_acquired = self._pull_loc...
python
{ "resource": "" }
q226863
deprecated
train
def deprecated(message): """ Decorator for deprecating functions and methods. :: @deprecated("'foo' has been deprecated in favour of 'bar'") def foo(x): pass """ def f__(f): def f_(*args, **kwargs): from warnings import warn warn(message, ca...
python
{ "resource": "" }
q226864
experimental
train
def experimental(message): """ Decorator for tagging experimental functions and methods. :: @experimental("'foo' is an experimental function and may be " "removed in a future release") def foo(x): pass """ def f__(f): def f_(*args, **kwargs): ...
python
{ "resource": "" }
q226865
hydrate_time
train
def hydrate_time(nanoseconds, tz=None): """ Hydrator for `Time` and `LocalTime` values. :param nanoseconds: :param tz: :return: Time """ seconds, nanoseconds = map(int, divmod(nanoseconds, 1000000000)) minutes, seconds = map(int, divmod(seconds, 60)) hours, minutes = map(int, divmod(min...
python
{ "resource": "" }
q226866
dehydrate_time
train
def dehydrate_time(value): """ Dehydrator for `time` values. :param value: :type value: Time :return: """ if isinstance(value, Time): nanoseconds = int(value.ticks * 1000000000) elif isinstance(value, time): nanoseconds = (3600000000000 * value.hour + 60000000000 * value.min...
python
{ "resource": "" }
q226867
hydrate_datetime
train
def hydrate_datetime(seconds, nanoseconds, tz=None): """ Hydrator for `DateTime` and `LocalDateTime` values. :param seconds: :param nanoseconds: :param tz: :return: datetime """ minutes, seconds = map(int, divmod(seconds, 60)) hours, minutes = map(int, divmod(minutes, 60)) days, hou...
python
{ "resource": "" }
q226868
dehydrate_datetime
train
def dehydrate_datetime(value): """ Dehydrator for `datetime` values. :param value: :type value: datetime :return: """ def seconds_and_nanoseconds(dt): if isinstance(dt, datetime): dt = DateTime.from_native(dt) zone_epoch = DateTime(1970, 1, 1, tzinfo=dt.tzinfo) ...
python
{ "resource": "" }
q226869
hydrate_duration
train
def hydrate_duration(months, days, seconds, nanoseconds): """ Hydrator for `Duration` values. :param months: :param days: :param seconds: :param nanoseconds: :return: `duration` namedtuple """ return Duration(months=months, days=days, seconds=seconds, nanoseconds=nanoseconds)
python
{ "resource": "" }
q226870
dehydrate_duration
train
def dehydrate_duration(value): """ Dehydrator for `duration` values. :param value: :type value: Duration :return: """ return Structure(b"E", value.months, value.days, value.seconds, int(1000000000 * value.subseconds))
python
{ "resource": "" }
q226871
dehydrate_timedelta
train
def dehydrate_timedelta(value): """ Dehydrator for `timedelta` values. :param value: :type value: timedelta :return: """ months = 0 days = value.days seconds = value.seconds nanoseconds = 1000 * value.microseconds return Structure(b"E", months, days, seconds, nanoseconds)
python
{ "resource": "" }
q226872
_TouchKeywords.zoom
train
def zoom(self, locator, percent="200%", steps=1): """ Zooms in on an element a certain amount. """ driver = self._current_application() element = self._element_find(locator, True, True) driver.zoom(element=element, percent=percent, steps=steps)
python
{ "resource": "" }
q226873
_TouchKeywords.scroll
train
def scroll(self, start_locator, end_locator): """ Scrolls from one element to another Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. """ el1 = self._element_find(start_locator, True, True) ...
python
{ "resource": "" }
q226874
_TouchKeywords.scroll_up
train
def scroll_up(self, locator): """Scrolls up to element""" driver = self._current_application() element = self._element_find(locator, True, True) driver.execute_script("mobile: scroll", {"direction": 'up', 'element': element.id})
python
{ "resource": "" }
q226875
_TouchKeywords.long_press
train
def long_press(self, locator, duration=1000): """ Long press the element with optional duration """ driver = self._current_application() element = self._element_find(locator, True, True) action = TouchAction(driver) action.press(element).wait(duration).release().perform()
python
{ "resource": "" }
q226876
_TouchKeywords.click_a_point
train
def click_a_point(self, x=0, y=0, duration=100): """ Click on a point""" self._info("Clicking on a point (%s,%s)." % (x,y)) driver = self._current_application() action = TouchAction(driver) try: action.press(x=float(x), y=float(y)).wait(float(duration)).release(...
python
{ "resource": "" }
q226877
_TouchKeywords.click_element_at_coordinates
train
def click_element_at_coordinates(self, coordinate_X, coordinate_Y): """ click element at a certain coordinate """ self._info("Pressing at (%s, %s)." % (coordinate_X, coordinate_Y)) driver = self._current_application() action = TouchAction(driver) action.press(x=coordinate_X,...
python
{ "resource": "" }
q226878
_WaitingKeywords.wait_until_element_is_visible
train
def wait_until_element_is_visible(self, locator, timeout=None, error=None): """Waits until element specified with `locator` is visible. Fails if `timeout` expires before the element is visible. See `introduction` for more information about `timeout` and its default value. `erro...
python
{ "resource": "" }
q226879
_WaitingKeywords.wait_until_page_contains
train
def wait_until_page_contains(self, text, timeout=None, error=None): """Waits until `text` appears on current page. Fails if `timeout` expires before the text appears. See `introduction` for more information about `timeout` and its default value. `error` can be used to override ...
python
{ "resource": "" }
q226880
_WaitingKeywords.wait_until_page_does_not_contain
train
def wait_until_page_does_not_contain(self, text, timeout=None, error=None): """Waits until `text` disappears from current page. Fails if `timeout` expires before the `text` disappears. See `introduction` for more information about `timeout` and its default value. `error` can be...
python
{ "resource": "" }
q226881
_WaitingKeywords.wait_until_page_contains_element
train
def wait_until_page_contains_element(self, locator, timeout=None, error=None): """Waits until element specified with `locator` appears on current page. Fails if `timeout` expires before the element appears. See `introduction` for more information about `timeout` and its default value. ...
python
{ "resource": "" }
q226882
_WaitingKeywords.wait_until_page_does_not_contain_element
train
def wait_until_page_does_not_contain_element(self, locator, timeout=None, error=None): """Waits until element specified with `locator` disappears from current page. Fails if `timeout` expires before the element disappears. See `introduction` for more information about `timeout` and its ...
python
{ "resource": "" }
q226883
_AndroidUtilsKeywords.set_network_connection_status
train
def set_network_connection_status(self, connectionStatus): """Sets the network connection Status. Android only. Possible values: | =Value= | =Alias= | =Data= | =Wifi= | =Airplane Mode= | | 0 | (None) | 0 | 0 | 0 | ...
python
{ "resource": "" }
q226884
_AndroidUtilsKeywords.pull_file
train
def pull_file(self, path, decode=False): """Retrieves the file at `path` and return it's content. Android only. - _path_ - the path to the file on the device - _decode_ - True/False decode the data (base64) before returning it (default=False) """ driver = self._curre...
python
{ "resource": "" }
q226885
_AndroidUtilsKeywords.pull_folder
train
def pull_folder(self, path, decode=False): """Retrieves a folder at `path`. Returns the folder's contents zipped. Android only. - _path_ - the path to the folder on the device - _decode_ - True/False decode the data (base64) before returning it (default=False) """ dri...
python
{ "resource": "" }
q226886
_AndroidUtilsKeywords.push_file
train
def push_file(self, path, data, encode=False): """Puts the data in the file specified as `path`. Android only. - _path_ - the path on the device - _data_ - data to be written to the file - _encode_ - True/False encode the data as base64 before writing it to the file (default...
python
{ "resource": "" }
q226887
_AndroidUtilsKeywords.start_activity
train
def start_activity(self, appPackage, appActivity, **opts): """Opens an arbitrary activity during a test. If the activity belongs to another application, that application is started and the activity is opened. Android only. - _appPackage_ - The package containing the activity to start. ...
python
{ "resource": "" }
q226888
_AndroidUtilsKeywords.install_app
train
def install_app(self, app_path, app_package): """ Install App via Appium Android only. - app_path - path to app - app_package - package of install app to verify """ driver = self._current_application() driver.install_app(app_path) return driver.i...
python
{ "resource": "" }
q226889
_ElementKeywords.click_element
train
def click_element(self, locator): """Click element identified by `locator`. Key attributes for arbitrary elements are `index` and `name`. See `introduction` for details about locating elements. """ self._info("Clicking element '%s'." % locator) self._element_find(...
python
{ "resource": "" }
q226890
_ElementKeywords.click_text
train
def click_text(self, text, exact_match=False): """Click text identified by ``text``. By default tries to click first text involves given ``text``, if you would like to click exactly matching text, then set ``exact_match`` to `True`. If there are multiple use of ``text`` and you ...
python
{ "resource": "" }
q226891
_ElementKeywords.input_text
train
def input_text(self, locator, text): """Types the given `text` into text field identified by `locator`. See `introduction` for details about locating elements. """ self._info("Typing text '%s' into text field '%s'" % (text, locator)) self._element_input_text_by_locator(loc...
python
{ "resource": "" }
q226892
_ElementKeywords.input_password
train
def input_password(self, locator, text): """Types the given password into text field identified by `locator`. Difference between this keyword and `Input Text` is that this keyword does not log the given password. See `introduction` for details about locating elements. """ ...
python
{ "resource": "" }
q226893
_ElementKeywords.input_value
train
def input_value(self, locator, text): """Sets the given value into text field identified by `locator`. This is an IOS only keyword, input value makes use of set_value See `introduction` for details about locating elements. """ self._info("Setting text '%s' into text field '%s'" % (...
python
{ "resource": "" }
q226894
_ElementKeywords.page_should_contain_text
train
def page_should_contain_text(self, text, loglevel='INFO'): """Verifies that current page contains `text`. If this keyword fails, it automatically logs the page source using the log level specified with the optional `loglevel` argument. Giving `NONE` as level disables logging. ...
python
{ "resource": "" }
q226895
_ElementKeywords.page_should_not_contain_text
train
def page_should_not_contain_text(self, text, loglevel='INFO'): """Verifies that current page not contains `text`. If this keyword fails, it automatically logs the page source using the log level specified with the optional `loglevel` argument. Giving `NONE` as level disables loggin...
python
{ "resource": "" }
q226896
_ElementKeywords.page_should_contain_element
train
def page_should_contain_element(self, locator, loglevel='INFO'): """Verifies that current page contains `locator` element. If this keyword fails, it automatically logs the page source using the log level specified with the optional `loglevel` argument. Giving `NONE` as level disabl...
python
{ "resource": "" }
q226897
_ElementKeywords.page_should_not_contain_element
train
def page_should_not_contain_element(self, locator, loglevel='INFO'): """Verifies that current page not contains `locator` element. If this keyword fails, it automatically logs the page source using the log level specified with the optional `loglevel` argument. Giving `NONE` as leve...
python
{ "resource": "" }
q226898
_ElementKeywords.element_should_be_disabled
train
def element_should_be_disabled(self, locator, loglevel='INFO'): """Verifies that element identified with locator is disabled. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. """ if self._element_find(locato...
python
{ "resource": "" }
q226899
_ElementKeywords.element_should_be_visible
train
def element_should_be_visible(self, locator, loglevel='INFO'): """Verifies that element identified with locator is visible. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. New in AppiumLibrary 1.4....
python
{ "resource": "" }