sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def movie_body_count(data_set='movie_body_count'):
"""Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R."""
if not data_available(data_set):
download_data(data_set)
from pandas im... | Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R. | entailment |
def movie_body_count_r_classify(data_set='movie_body_count'):
"""Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R."""
data = movie_body_count()['Y']
import pandas as pd
import numpy a... | Data set of movies and body count for movies scraped from www.MovieBodyCounts.com created by Simon Garnier and Randy Olson for exploring differences between Python and R. | entailment |
def movielens100k(data_set='movielens100k'):
"""Data set of movie ratings collected by the University of Minnesota and 'cleaned up' for use."""
if not data_available(data_set):
import zipfile
download_data(data_set)
dir_path = os.path.join(data_path, data_set)
zip = zipfile.ZipFi... | Data set of movie ratings collected by the University of Minnesota and 'cleaned up' for use. | entailment |
def ceres(data_set='ceres'):
"""Twenty two observations of the Dwarf planet Ceres as observed by Giueseppe Piazzi and published in the September edition of Monatlicher Correspondenz in 1801. These were the measurements used by Gauss to fit a model of the planets orbit through which the planet was recovered three mo... | Twenty two observations of the Dwarf planet Ceres as observed by Giueseppe Piazzi and published in the September edition of Monatlicher Correspondenz in 1801. These were the measurements used by Gauss to fit a model of the planets orbit through which the planet was recovered three months later. | entailment |
def calc_horizontal_infrared_radiation_intensity(weatherdata):
""" Estimates the global horizontal infrared radiation intensity based
on drybulb, dewpoint and opaque sky cover.
References:
Walton, G. N. 1983. Thermal Analysis Research Program Reference Manual. NBSSIR 83-
2655. National Bureau of Sta... | Estimates the global horizontal infrared radiation intensity based
on drybulb, dewpoint and opaque sky cover.
References:
Walton, G. N. 1983. Thermal Analysis Research Program Reference Manual. NBSSIR 83-
2655. National Bureau of Standards, p. 21.
Clark, G. and C. Allen, "The Estimation of Atmospher... | entailment |
def download_url(url, dir_name='.', save_name=None, store_directory=None, messages=True, suffix=''):
"""Download a file from a url and save it to disk."""
if sys.version_info>=(3,0):
from urllib.parse import quote
from urllib.request import urlopen
from urllib.error import HTTPError, UR... | Download a file from a url and save it to disk. | entailment |
def access_elementusers(self, elementuser_id, access_id=None, tenant_id=None, api_version="v2.0"):
"""
Get all accesses for a particular user
**Parameters:**:
- **elementuser_id**: Element User ID
- **access_id**: (optional) Access ID
- **tenant_id**: Tenant ID
... | Get all accesses for a particular user
**Parameters:**:
- **elementuser_id**: Element User ID
- **access_id**: (optional) Access ID
- **tenant_id**: Tenant ID
- **api_version**: API version to use (default v2.0)
**Returns:** requests.Response object extended ... | entailment |
def logout(self, api_version="v2.0"):
"""
Logout current session
**Parameters:**:
- **api_version**: API version to use (default v2.0)
**Returns:** requests.Response object extended with cgx_status and cgx_content properties.
"""
cur_ctlr = self._parent_cl... | Logout current session
**Parameters:**:
- **api_version**: API version to use (default v2.0)
**Returns:** requests.Response object extended with cgx_status and cgx_content properties. | entailment |
def login(self, email=None, password=None):
"""
Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts.
Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly.
**Parameters:**:
... | Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts.
Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly.
**Parameters:**:
- **email**: Email to log in for, will prompt if not entere... | entailment |
def use_token(self, token=None):
"""
Function to use static AUTH_TOKEN as auth for the constructor instead of full login process.
**Parameters:**:
- **token**: Static AUTH_TOKEN
**Returns:** Bool on success or failure. In addition the function will mutate the `cloudgenix.API... | Function to use static AUTH_TOKEN as auth for the constructor instead of full login process.
**Parameters:**:
- **token**: Static AUTH_TOKEN
**Returns:** Bool on success or failure. In addition the function will mutate the `cloudgenix.API`
constructor items as needed. | entailment |
def interactive_tenant_update_vars(self):
"""
Function to update the `cloudgenix.API` object with tenant login info. Run after login or client login.
**Returns:** Boolean on success/failure,
"""
api_logger.info('interactive_tenant_update_vars function:')
tenant_resp = se... | Function to update the `cloudgenix.API` object with tenant login info. Run after login or client login.
**Returns:** Boolean on success/failure, | entailment |
def interactive_update_profile_vars(self):
"""
Function to update the `cloudgenix.API` object with profile info. Run after login or client login.
**Returns:** Boolean on success/failure,
"""
profile = self._parent_class.get.profile()
if profile.cgx_status:
... | Function to update the `cloudgenix.API` object with profile info. Run after login or client login.
**Returns:** Boolean on success/failure, | entailment |
def interactive_client_choice(self):
"""
Present a menu for user to select from ESP/MSP managed clients they have permission to.
**Returns:** Tuple with (Boolean success, selected client ID).
"""
clients = self._parent_class.get.clients_t()
clients_perms = self._parent_... | Present a menu for user to select from ESP/MSP managed clients they have permission to.
**Returns:** Tuple with (Boolean success, selected client ID). | entailment |
def quick_menu(self, banner, list_line_format, choice_list):
"""
Function to display a quick menu for user input
**Parameters:**
- **banner:** Text to display before menu
- **list_line_format:** Print'ing string with format spots for index + tuple values
- **choic... | Function to display a quick menu for user input
**Parameters:**
- **banner:** Text to display before menu
- **list_line_format:** Print'ing string with format spots for index + tuple values
- **choice_list:** List of tuple values that you want returned if selected (and printed)
... | entailment |
def check_sso_login(self, operator_email, request_id):
"""
Login to the CloudGenix API, and see if SAML SSO has occurred.
This function is used to check and see if SAML SSO has succeeded while waiting.
**Parameters:**
- **operator_email:** String with the username to log in w... | Login to the CloudGenix API, and see if SAML SSO has occurred.
This function is used to check and see if SAML SSO has succeeded while waiting.
**Parameters:**
- **operator_email:** String with the username to log in with
- **request_id:** String containing the SAML 2.0 Request ID f... | entailment |
def logout(self, force=False):
"""
Interactive logout - ensures uid/tid cleared so `cloudgenix.API` object/ requests.Session can be re-used.
**Parameters:**:
- **force**: Bool, force logout API call, even when using a static AUTH_TOKEN.
**Returns:** Bool of whether the opera... | Interactive logout - ensures uid/tid cleared so `cloudgenix.API` object/ requests.Session can be re-used.
**Parameters:**:
- **force**: Bool, force logout API call, even when using a static AUTH_TOKEN.
**Returns:** Bool of whether the operation succeeded. | entailment |
def jd(api_response):
"""
JD (JSON Dump) function. Meant for quick pretty-printing of CloudGenix Response objects.
Example: `jd(cgx_sess.get.sites())`
**Returns:** No Return, directly prints all output.
"""
try:
# attempt to print the cgx_content. should alw... | JD (JSON Dump) function. Meant for quick pretty-printing of CloudGenix Response objects.
Example: `jd(cgx_sess.get.sites())`
**Returns:** No Return, directly prints all output. | entailment |
def quick_confirm(prompt, default_value):
"""
Function to display a quick confirmation for user input
**Parameters:**
- **prompt:** Text to display before confirm
- **default_value:** Default value for no entry
**Returns:** 'y', 'n', or Default value.
"""
... | Function to display a quick confirmation for user input
**Parameters:**
- **prompt:** Text to display before confirm
- **default_value:** Default value for no entry
**Returns:** 'y', 'n', or Default value. | entailment |
def quick_int_input(prompt, default_value, min_val=1, max_val=30):
"""
Function to display a quick question for integer user input
**Parameters:**
- **prompt:** Text / question to display
- **default_value:** Default value for no entry
- **min_val:** Lowest allowe... | Function to display a quick question for integer user input
**Parameters:**
- **prompt:** Text / question to display
- **default_value:** Default value for no entry
- **min_val:** Lowest allowed integer
- **max_val:** Highest allowed integer
**Returns:** intege... | entailment |
def quick_str_input(prompt, default_value):
"""
Function to display a quick question for text input.
**Parameters:**
- **prompt:** Text / question to display
- **default_value:** Default value for no entry
**Returns:** text_type() or default_value.
"""
... | Function to display a quick question for text input.
**Parameters:**
- **prompt:** Text / question to display
- **default_value:** Default value for no entry
**Returns:** text_type() or default_value. | entailment |
def compare_digests(digest_1, digest_2, is_hex_1=True, is_hex_2=True, threshold=None):
"""
computes bit difference between two nilsisa digests
takes params for format, default is hex string but can accept list
of 32 length ints
Optimized method originally from https://gist.github.com/michelp/6255490... | computes bit difference between two nilsisa digests
takes params for format, default is hex string but can accept list
of 32 length ints
Optimized method originally from https://gist.github.com/michelp/6255490
If `threshold` is set, and the comparison will be less than
`threshold`, then bail out ea... | entailment |
def tran_hash(self, a, b, c, n):
"""implementation of the tran53 hash function"""
return (((TRAN[(a+n)&255]^TRAN[b]*(n+n+1))+TRAN[(c)^TRAN[n]])&255) | implementation of the tran53 hash function | entailment |
def process(self, chunk):
"""
computes the hash of all of the trigrams in the chunk using a window
of length 5
"""
self._digest = None
if isinstance(chunk, text_type):
chunk = chunk.encode('utf-8')
# chunk is a byte string
for char in chunk:
... | computes the hash of all of the trigrams in the chunk using a window
of length 5 | entailment |
def compute_digest(self):
"""
using a threshold (mean of the accumulator), computes the nilsimsa digest
"""
num_trigrams = 0
if self.num_char == 3: # 3 chars -> 1 trigram
num_trigrams = 1
elif self.num_char == 4: # 4 chars -> 4 trigrams
... | using a threshold (mean of the accumulator), computes the nilsimsa digest | entailment |
def from_file(self, fname):
"""read in a file and compute digest"""
f = open(fname, "rb")
data = f.read()
self.update(data)
f.close() | read in a file and compute digest | entailment |
def compare(self, digest_2, is_hex = False):
"""
returns difference between the nilsimsa digests between the current
object and a given digest
"""
# convert hex string to list of ints
if is_hex:
digest_2 = convert_hex_to_ints(digest_2)
bit_diff = 0
... | returns difference between the nilsimsa digests between the current
object and a given digest | entailment |
def login(self, data, api_version="v2.0"):
"""
Login api
**Parameters:**:
- **data**: Dictionary containing data to POST as JSON
- **api_version**: API version to use (default v2.0)
**Returns:** requests.Response object extended with cgx_status and cgx_content pr... | Login api
**Parameters:**:
- **data**: Dictionary containing data to POST as JSON
- **api_version**: API version to use (default v2.0)
**Returns:** requests.Response object extended with cgx_status and cgx_content properties. | entailment |
def tenant_forgot_password_login(self, data, tenant_id=None, api_version="v2.0"):
"""
Forgot password API
**Parameters:**:
- **data**: Dictionary containing data to POST as JSON
- **tenant_id**: Tenant ID
- **api_version**: API version to use (default v2.0)
... | Forgot password API
**Parameters:**:
- **data**: Dictionary containing data to POST as JSON
- **tenant_id**: Tenant ID
- **api_version**: API version to use (default v2.0)
**Returns:** requests.Response object extended with cgx_status and cgx_content properties. | entailment |
def is_valid_file(parser,arg):
"""verify the validity of the given file. Never trust the End-User"""
if not os.path.exists(arg):
parser.error("File %s not found"%arg)
else:
return arg | verify the validity of the given file. Never trust the End-User | entailment |
def getID(code_file):
"""Get the language ID of the input file language"""
json_path = ghostfolder+'/'+json_file
if os.path.exists(json_path):
pass
else:
download_file('https://ghostbin.com/languages.json')
lang = detect_lang(code_file)
json_data = json.load(file(json_path))#don't think i need this though
... | Get the language ID of the input file language | entailment |
def detect_lang(path):
"""Detect the language used in the given file."""
blob = FileBlob(path, os.getcwd())
if blob.is_text:
print('Programming language of the file detected: {0}'.format(blob.language.name))
return blob.language.name
else:#images, binary and what-have-you won't be pasted
print('File not a tex... | Detect the language used in the given file. | entailment |
def set_serial(self, android_serial):
"""
Specify given *android_serial* device to perform test.
You do not have to specify the device when there is only one device connects to the computer.
When you need to use multiple devices, do not use this keyword to switch between devices in tes... | Specify given *android_serial* device to perform test.
You do not have to specify the device when there is only one device connects to the computer.
When you need to use multiple devices, do not use this keyword to switch between devices in test execution.
Using different library name when im... | entailment |
def click_at_coordinates(self, x, y):
"""
Click at (x,y) coordinates.
"""
self.device.click(int(x), int(y)) | Click at (x,y) coordinates. | entailment |
def swipe_by_coordinates(self, sx, sy, ex, ey, steps=10):
"""
Swipe from (sx, sy) to (ex, ey) with *steps* .
Example:
| Swipe By Coordinates | 540 | 1340 | 940 | 1340 | | # Swipe from (540, 1340) to (940, 100) with default steps 10 |
| Swipe By Coordinates | 540 | 1340 | 940... | Swipe from (sx, sy) to (ex, ey) with *steps* .
Example:
| Swipe By Coordinates | 540 | 1340 | 940 | 1340 | | # Swipe from (540, 1340) to (940, 100) with default steps 10 |
| Swipe By Coordinates | 540 | 1340 | 940 | 1340 | 100 | # Swipe from (540, 1340) to (940, 100) with steps 100 | | entailment |
def swipe_left(self, steps=10, *args, **selectors):
"""
Swipe the UI object with *selectors* from center to left.
Example:
| Swipe Left | description=Home screen 3 | | # swipe the UI object left |
| Swipe Left | 5 |... | Swipe the UI object with *selectors* from center to left.
Example:
| Swipe Left | description=Home screen 3 | | # swipe the UI object left |
| Swipe Left | 5 | description=Home screen 3 | # swipe the UI object left with steps=5 |
... | entailment |
def swipe_right(self, steps=10, *args, **selectors):
"""
Swipe the UI object with *selectors* from center to right
See `Swipe Left` for more details.
"""
self.device(**selectors).swipe.right(steps=steps) | Swipe the UI object with *selectors* from center to right
See `Swipe Left` for more details. | entailment |
def swipe_top(self, steps=10, *args, **selectors):
"""
Swipe the UI object with *selectors* from center to top
See `Swipe Left` for more details.
"""
self.device(**selectors).swipe.up(steps=steps) | Swipe the UI object with *selectors* from center to top
See `Swipe Left` for more details. | entailment |
def swipe_bottom(self, steps=10, *args, **selectors):
"""
Swipe the UI object with *selectors* from center to bottom
See `Swipe Left` for more details.
"""
self.device(**selectors).swipe.down(steps=steps) | Swipe the UI object with *selectors* from center to bottom
See `Swipe Left` for more details. | entailment |
def drag_by_coordinates(self,sx, sy, ex, ey, steps=10):
"""
Drag from (sx, sy) to (ex, ey) with steps
See `Swipe By Coordinates` also.
"""
self.device.drag(sx, sy, ex, ey, steps) | Drag from (sx, sy) to (ex, ey) with steps
See `Swipe By Coordinates` also. | entailment |
def wait_for_exists(self, timeout=0, *args, **selectors):
"""
Wait for the object which has *selectors* within the given timeout.
Return true if the object *appear* in the given timeout. Else return false.
"""
return self.device(**selectors).wait.exists(timeout=timeout) | Wait for the object which has *selectors* within the given timeout.
Return true if the object *appear* in the given timeout. Else return false. | entailment |
def wait_until_gone(self, timeout=0, *args, **selectors):
"""
Wait for the object which has *selectors* within the given timeout.
Return true if the object *disappear* in the given timeout. Else return false.
"""
return self.device(**selectors).wait.gone(timeout=timeout) | Wait for the object which has *selectors* within the given timeout.
Return true if the object *disappear* in the given timeout. Else return false. | entailment |
def fling_forward_horizontally(self, *args, **selectors):
"""
Perform fling forward (horizontally)action on the object which has *selectors* attributes.
Return whether the object can be fling or not.
"""
return self.device(**selectors).fling.horiz.forward() | Perform fling forward (horizontally)action on the object which has *selectors* attributes.
Return whether the object can be fling or not. | entailment |
def fling_backward_horizontally(self, *args, **selectors):
"""
Perform fling backward (horizontally)action on the object which has *selectors* attributes.
Return whether the object can be fling or not.
"""
return self.device(**selectors).fling.horiz.backward() | Perform fling backward (horizontally)action on the object which has *selectors* attributes.
Return whether the object can be fling or not. | entailment |
def fling_forward_vertically(self, *args, **selectors):
"""
Perform fling forward (vertically)action on the object which has *selectors* attributes.
Return whether the object can be fling or not.
"""
return self.device(**selectors).fling.vert.forward() | Perform fling forward (vertically)action on the object which has *selectors* attributes.
Return whether the object can be fling or not. | entailment |
def fling_backward_vertically(self, *args, **selectors):
"""
Perform fling backward (vertically)action on the object which has *selectors* attributes.
Return whether the object can be fling or not.
"""
return self.device(**selectors).fling.vert.backward() | Perform fling backward (vertically)action on the object which has *selectors* attributes.
Return whether the object can be fling or not. | entailment |
def scroll_to_beginning_horizontally(self, steps=10, *args,**selectors):
"""
Scroll the object which has *selectors* attributes to *beginning* horizontally.
See `Scroll Forward Vertically` for more details.
"""
return self.device(**selectors).scroll.horiz.toBeginning(steps=steps... | Scroll the object which has *selectors* attributes to *beginning* horizontally.
See `Scroll Forward Vertically` for more details. | entailment |
def scroll_to_end_horizontally(self, steps=10, *args, **selectors):
"""
Scroll the object which has *selectors* attributes to *end* horizontally.
See `Scroll Forward Vertically` for more details.
"""
return self.device(**selectors).scroll.horiz.toEnd(steps=steps) | Scroll the object which has *selectors* attributes to *end* horizontally.
See `Scroll Forward Vertically` for more details. | entailment |
def scroll_forward_horizontally(self, steps=10, *args, **selectors):
"""
Perform scroll forward (horizontally)action on the object which has *selectors* attributes.
Return whether the object can be Scroll or not.
See `Scroll Forward Vertically` for more details.
"""
ret... | Perform scroll forward (horizontally)action on the object which has *selectors* attributes.
Return whether the object can be Scroll or not.
See `Scroll Forward Vertically` for more details. | entailment |
def scroll_backward_horizontally(self, steps=10, *args, **selectors):
"""
Perform scroll backward (horizontally)action on the object which has *selectors* attributes.
Return whether the object can be Scroll or not.
See `Scroll Forward Vertically` for more details.
"""
r... | Perform scroll backward (horizontally)action on the object which has *selectors* attributes.
Return whether the object can be Scroll or not.
See `Scroll Forward Vertically` for more details. | entailment |
def scroll_to_horizontally(self, obj, *args,**selectors):
"""
Scroll(horizontally) on the object: obj to specific UI object which has *selectors* attributes appears.
Return true if the UI object, else return false.
See `Scroll To Vertically` for more details.
"""
return... | Scroll(horizontally) on the object: obj to specific UI object which has *selectors* attributes appears.
Return true if the UI object, else return false.
See `Scroll To Vertically` for more details. | entailment |
def scroll_to_beginning_vertically(self, steps=10, *args,**selectors):
"""
Scroll the object which has *selectors* attributes to *beginning* vertically.
See `Scroll Forward Vertically` for more details.
"""
return self.device(**selectors).scroll.vert.toBeginning(steps=steps) | Scroll the object which has *selectors* attributes to *beginning* vertically.
See `Scroll Forward Vertically` for more details. | entailment |
def scroll_to_end_vertically(self, steps=10, *args, **selectors):
"""
Scroll the object which has *selectors* attributes to *end* vertically.
See `Scroll Forward Vertically` for more details.
"""
return self.device(**selectors).scroll.vert.toEnd(steps=steps) | Scroll the object which has *selectors* attributes to *end* vertically.
See `Scroll Forward Vertically` for more details. | entailment |
def scroll_forward_vertically(self, steps=10, *args, **selectors):
"""
Perform scroll forward (vertically)action on the object which has *selectors* attributes.
Return whether the object can be Scroll or not.
Example:
| ${can_be_scroll} | Scroll Forward Vertically | className=a... | Perform scroll forward (vertically)action on the object which has *selectors* attributes.
Return whether the object can be Scroll or not.
Example:
| ${can_be_scroll} | Scroll Forward Vertically | className=android.widget.ListView | | # Scroll forward the... | entailment |
def scroll_backward_vertically(self, steps=10, *args, **selectors):
"""
Perform scroll backward (vertically)action on the object which has *selectors* attributes.
Return whether the object can be Scroll or not.
See `Scroll Forward Vertically` for more details.
"""
retur... | Perform scroll backward (vertically)action on the object which has *selectors* attributes.
Return whether the object can be Scroll or not.
See `Scroll Forward Vertically` for more details. | entailment |
def scroll_to_vertically(self, obj, *args,**selectors):
"""
Scroll(vertically) on the object: obj to specific UI object which has *selectors* attributes appears.
Return true if the UI object, else return false.
Example:
| ${list} | Get Object | className=andro... | Scroll(vertically) on the object: obj to specific UI object which has *selectors* attributes appears.
Return true if the UI object, else return false.
Example:
| ${list} | Get Object | className=android.widget.ListView | | # Get the list object |
| ${... | entailment |
def screenshot(self, scale=None, quality=None):
"""
Take a screenshot of device and log in the report with timestamp, scale for screenshot size and quality for screenshot quality
default scale=1.0 quality=100
"""
output_dir = BuiltIn().get_variable_value('${OUTPUTDIR}')
t... | Take a screenshot of device and log in the report with timestamp, scale for screenshot size and quality for screenshot quality
default scale=1.0 quality=100 | entailment |
def register_click_watcher(self, watcher_name, selectors, *condition_list):
"""
The watcher click on the object which has the *selectors* when conditions match.
"""
watcher = self.device.watcher(watcher_name)
for condition in condition_list:
watcher.when(**self.__unic... | The watcher click on the object which has the *selectors* when conditions match. | entailment |
def register_press_watcher(self, watcher_name, press_keys, *condition_list):
"""
The watcher perform *press_keys* action sequentially when conditions match.
"""
def unicode_to_list(a_unicode):
a_list = list()
comma_count = a_unicode.count(',')
for coun... | The watcher perform *press_keys* action sequentially when conditions match. | entailment |
def remove_watchers(self, watcher_name = None):
"""
Remove watcher with *watcher_name* or remove all watchers.
"""
if watcher_name == None:
self.device.watchers.remove()
else:
self.device.watchers.remove(watcher_name) | Remove watcher with *watcher_name* or remove all watchers. | entailment |
def get_count(self, *args, **selectors):
"""
Return the count of UI object with *selectors*
Example:
| ${count} | Get Count | text=Accessibility | # Get the count of UI object text=Accessibility |
| ${accessibility_text} | Get Object | text=Ac... | Return the count of UI object with *selectors*
Example:
| ${count} | Get Count | text=Accessibility | # Get the count of UI object text=Accessibility |
| ${accessibility_text} | Get Object | text=Accessibility | # These two keywords combination ... | entailment |
def get_info_of_object(self, obj, selector=None):
"""
return info dictionary of the *obj*
The info example:
{
u'contentDescription': u'',
u'checked': False,
u'scrollable': True,
u'text': u'',
u'packageName': u'com.android.launcher',
u... | return info dictionary of the *obj*
The info example:
{
u'contentDescription': u'',
u'checked': False,
u'scrollable': True,
u'text': u'',
u'packageName': u'com.android.launcher',
u'selected': False,
u'enabled': True,
u'bounds':
... | entailment |
def call(self, obj, method, *args, **selectors):
"""
This keyword can use object method from original python uiautomator
See more details from https://github.com/xiaocong/uiautomator
Example:
| ${accessibility_text} | Get Object | text=Accessibility | # Get the UI o... | This keyword can use object method from original python uiautomator
See more details from https://github.com/xiaocong/uiautomator
Example:
| ${accessibility_text} | Get Object | text=Accessibility | # Get the UI object |
| Call | ${ac... | entailment |
def set_text(self, input_text, *args, **selectors):
"""
Set *input_text* to the UI object with *selectors*
"""
self.device(**selectors).set_text(input_text) | Set *input_text* to the UI object with *selectors* | entailment |
def clear_text(self, *args, **selectors):
"""
Clear text of the UI object with *selectors*
"""
while True:
target = self.device(**selectors)
text = target.info['text']
target.clear_text()
remain_text = target.info['text']
if te... | Clear text of the UI object with *selectors* | entailment |
def open_notification(self):
"""
Open notification
Built in support for Android 4.3 (API level 18)
Using swipe action as a workaround for API level lower than 18
"""
sdk_version = self.device.info['sdkInt']
if sdk_version < 18:
height = self.device.... | Open notification
Built in support for Android 4.3 (API level 18)
Using swipe action as a workaround for API level lower than 18 | entailment |
def sleep(self, time):
"""
Sleep(no action) for *time* (in millisecond)
"""
target = 'wait for %s' % str(time)
self.device(text=target).wait.exists(timeout=time) | Sleep(no action) for *time* (in millisecond) | entailment |
def connect_to_wifi(self, ssid, password=None):
"""
[Test Agent]
Connect to *ssid* with *password*
"""
cmd = 'am broadcast -a testagent -e action CONNECT_TO_WIFI -e ssid %s -e password %s' % (ssid, password)
self.adb.shell_cmd(cmd) | [Test Agent]
Connect to *ssid* with *password* | entailment |
def merge_sims(oldsims, newsims, clip=None):
"""Merge two precomputed similarity lists, truncating the result to `clip` most similar items."""
if oldsims is None:
result = newsims or []
elif newsims is None:
result = oldsims
else:
result = sorted(oldsims + newsims, key=lambda ite... | Merge two precomputed similarity lists, truncating the result to `clip` most similar items. | entailment |
def terminate(self):
"""Delete all files created by this index, invalidating `self`. Use with care."""
try:
self.id2sims.terminate()
except:
pass
import glob
for fname in glob.glob(self.fname + '*'):
try:
os.remove(fname)
... | Delete all files created by this index, invalidating `self`. Use with care. | entailment |
def index_documents(self, fresh_docs, model):
"""
Update fresh index with new documents (potentially replacing old ones with
the same id). `fresh_docs` is a dictionary-like object (=dict, sqlitedict, shelve etc)
that maps document_id->document.
"""
docids = fresh_docs.key... | Update fresh index with new documents (potentially replacing old ones with
the same id). `fresh_docs` is a dictionary-like object (=dict, sqlitedict, shelve etc)
that maps document_id->document. | entailment |
def update_ids(self, docids):
"""Update id->pos mapping with new document ids."""
logger.info("updating %i id mappings" % len(docids))
for docid in docids:
if docid is not None:
pos = self.id2pos.get(docid, None)
if pos is not None:
... | Update id->pos mapping with new document ids. | entailment |
def update_mappings(self):
"""Synchronize id<->position mappings."""
self.pos2id = dict((v, k) for k, v in self.id2pos.iteritems())
assert len(self.pos2id) == len(self.id2pos), "duplicate ids or positions detected" | Synchronize id<->position mappings. | entailment |
def delete(self, docids):
"""Delete documents (specified by their ids) from the index."""
logger.debug("deleting %i documents from %s" % (len(docids), self))
deleted = 0
for docid in docids:
try:
del self.id2pos[docid]
deleted += 1
... | Delete documents (specified by their ids) from the index. | entailment |
def sims2scores(self, sims, eps=1e-7):
"""Convert raw similarity vector to a list of (docid, similarity) results."""
result = []
if isinstance(sims, numpy.ndarray):
sims = abs(sims) # TODO or maybe clip? are opposite vectors "similar" or "dissimilar"?!
for pos in numpy.ar... | Convert raw similarity vector to a list of (docid, similarity) results. | entailment |
def vec_by_id(self, docid):
"""Return indexed vector corresponding to document `docid`."""
pos = self.id2pos[docid]
return self.qindex.vector_by_id(pos) | Return indexed vector corresponding to document `docid`. | entailment |
def sims_by_id(self, docid):
"""Find the most similar documents to the (already indexed) document with `docid`."""
result = self.id2sims.get(docid, None)
if result is None:
self.qindex.num_best = self.topsims
sims = self.qindex.similarity_by_id(self.id2pos[docid])
... | Find the most similar documents to the (already indexed) document with `docid`. | entailment |
def sims_by_vec(self, vec, normalize=None):
"""
Find the most similar documents to a given vector (=already processed document).
"""
if normalize is None:
normalize = self.qindex.normalize
norm, self.qindex.normalize = self.qindex.normalize, normalize # store old valu... | Find the most similar documents to a given vector (=already processed document). | entailment |
def merge(self, other):
"""Merge documents from the other index. Update precomputed similarities
in the process."""
other.qindex.normalize, other.qindex.num_best = False, self.topsims
# update precomputed "most similar" for old documents (in case some of
# the new docs make it to... | Merge documents from the other index. Update precomputed similarities
in the process. | entailment |
def doc2vec(self, doc):
"""Convert a single SimilarityDocument to vector."""
bow = self.dictionary.doc2bow(doc['tokens'])
if self.method == 'lsi':
return self.lsi[self.tfidf[bow]]
elif self.method == 'lda':
return self.lda[bow]
elif self.method == 'lda_tfi... | Convert a single SimilarityDocument to vector. | entailment |
def docs2vecs(self, docs):
"""Convert multiple SimilarityDocuments to vectors (batch version of doc2vec)."""
bows = (self.dictionary.doc2bow(doc['tokens']) for doc in docs)
if self.method == 'lsi':
return self.lsi[self.tfidf[bows]]
elif self.method == 'lda':
retur... | Convert multiple SimilarityDocuments to vectors (batch version of doc2vec). | entailment |
def flush(self, save_index=False, save_model=False, clear_buffer=False):
"""Commit all changes, clear all caches."""
if save_index:
if self.fresh_index is not None:
self.fresh_index.save(self.location('index_fresh'))
if self.opt_index is not None:
... | Commit all changes, clear all caches. | entailment |
def close(self):
"""Explicitly close open file handles, databases etc."""
try:
self.payload.close()
except:
pass
try:
self.model.close()
except:
pass
try:
self.fresh_index.close()
except:
pass... | Explicitly close open file handles, databases etc. | entailment |
def buffer(self, documents):
"""
Add a sequence of documents to be processed (indexed or trained on).
Here, the documents are simply collected; real processing is done later,
during the `self.index` or `self.train` calls.
`buffer` can be called repeatedly; the result is the sam... | Add a sequence of documents to be processed (indexed or trained on).
Here, the documents are simply collected; real processing is done later,
during the `self.index` or `self.train` calls.
`buffer` can be called repeatedly; the result is the same as if it was
called once, with a concat... | entailment |
def train(self, corpus=None, method='auto', clear_buffer=True, params=None):
"""
Create an indexing model. Will overwrite the model if it already exists.
All indexes become invalid, because documents in them use a now-obsolete
representation.
The model is trained on documents pr... | Create an indexing model. Will overwrite the model if it already exists.
All indexes become invalid, because documents in them use a now-obsolete
representation.
The model is trained on documents previously entered via `buffer`,
or directly on `corpus`, if specified. | entailment |
def index(self, corpus=None, clear_buffer=True):
"""
Permanently index all documents previously added via `buffer`, or
directly index documents from `corpus`, if specified.
The indexing model must already exist (see `train`) before this function
is called.
"""
if... | Permanently index all documents previously added via `buffer`, or
directly index documents from `corpus`, if specified.
The indexing model must already exist (see `train`) before this function
is called. | entailment |
def optimize(self):
"""
Precompute top similarities for all indexed documents. This speeds up
`find_similar` queries by id (but not queries by fulltext).
Internally, documents are moved from a fresh index (=no precomputed similarities)
to an optimized index (precomputed similari... | Precompute top similarities for all indexed documents. This speeds up
`find_similar` queries by id (but not queries by fulltext).
Internally, documents are moved from a fresh index (=no precomputed similarities)
to an optimized index (precomputed similarities). Similarity queries always
... | entailment |
def drop_index(self, keep_model=True):
"""Drop all indexed documents. If `keep_model` is False, also dropped the model."""
modelstr = "" if keep_model else "and model "
logger.info("deleting similarity index " + modelstr + "from %s" % self.basename)
# delete indexes
for index in... | Drop all indexed documents. If `keep_model` is False, also dropped the model. | entailment |
def delete(self, docids):
"""Delete specified documents from the index."""
logger.info("asked to drop %i documents" % len(docids))
for index in [self.opt_index, self.fresh_index]:
if index is not None:
index.delete(docids)
self.flush(save_index=True) | Delete specified documents from the index. | entailment |
def find_similar(self, doc, min_score=0.0, max_results=100):
"""
Find `max_results` most similar articles in the index, each having similarity
score of at least `min_score`. The resulting list may be shorter than `max_results`,
in case there are not enough matching documents.
`d... | Find `max_results` most similar articles in the index, each having similarity
score of at least `min_score`. The resulting list may be shorter than `max_results`,
in case there are not enough matching documents.
`doc` is either a string (=document id, previously indexed) or a
dict conta... | entailment |
def keys(self):
"""Return ids of all indexed documents."""
result = []
if self.fresh_index is not None:
result += self.fresh_index.keys()
if self.opt_index is not None:
result += self.opt_index.keys()
return result | Return ids of all indexed documents. | entailment |
def check_session(self):
"""
Make sure a session is open.
If it's not and autosession is turned on, create a new session automatically.
If it's not and autosession is off, raise an exception.
"""
if self.session is None:
if self.autosession:
s... | Make sure a session is open.
If it's not and autosession is turned on, create a new session automatically.
If it's not and autosession is off, raise an exception. | entailment |
def open_session(self):
"""
Open a new session to modify this server.
You can either call this fnc directly, or turn on autosession which will
open/commit sessions for you transparently.
"""
if self.session is not None:
msg = "session already open; commit it ... | Open a new session to modify this server.
You can either call this fnc directly, or turn on autosession which will
open/commit sessions for you transparently. | entailment |
def buffer(self, *args, **kwargs):
"""Buffer documents, in the current session"""
self.check_session()
result = self.session.buffer(*args, **kwargs)
return result | Buffer documents, in the current session | entailment |
def index(self, *args, **kwargs):
"""Index documents, in the current session"""
self.check_session()
result = self.session.index(*args, **kwargs)
if self.autosession:
self.commit()
return result | Index documents, in the current session | entailment |
def drop_index(self, keep_model=True):
"""Drop all indexed documents from the session. Optionally, drop model too."""
self.check_session()
result = self.session.drop_index(keep_model)
if self.autosession:
self.commit()
return result | Drop all indexed documents from the session. Optionally, drop model too. | entailment |
def delete(self, docids):
"""Delete documents from the current session."""
self.check_session()
result = self.session.delete(docids)
if self.autosession:
self.commit()
return result | Delete documents from the current session. | entailment |
def optimize(self):
"""Optimize index for faster by-document-id queries."""
self.check_session()
result = self.session.optimize()
if self.autosession:
self.commit()
return result | Optimize index for faster by-document-id queries. | entailment |
def commit(self):
"""Commit changes made by the latest session."""
if self.session is not None:
logger.info("committing transaction in %s" % self)
tmp = self.stable
self.stable, self.session = self.session, None
self.istable = 1 - self.istable
... | Commit changes made by the latest session. | entailment |
def rollback(self):
"""Ignore all changes made in the latest session (terminate the session)."""
if self.session is not None:
logger.info("rolling back transaction in %s" % self)
self.session.close()
self.session = None
self.lock_update.release()
e... | Ignore all changes made in the latest session (terminate the session). | entailment |
def set_autosession(self, value=None):
"""
Turn autosession (automatic committing after each modification call) on/off.
If value is None, only query the current value (don't change anything).
"""
if value is not None:
self.rollback()
self.autosession = val... | Turn autosession (automatic committing after each modification call) on/off.
If value is None, only query the current value (don't change anything). | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.