repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Animation_setPlaybackRate
def Animation_setPlaybackRate(self, playbackRate): """ Function path: Animation.setPlaybackRate Domain: Animation Method name: setPlaybackRate Parameters: Required arguments: 'playbackRate' (type: number) -> Playback rate for animations on page No return value. Description: Sets the playback rate of the document timeline. """ assert isinstance(playbackRate, (float, int) ), "Argument 'playbackRate' must be of type '['float', 'int']'. Received type: '%s'" % type( playbackRate) subdom_funcs = self.synchronous_command('Animation.setPlaybackRate', playbackRate=playbackRate) return subdom_funcs
python
def Animation_setPlaybackRate(self, playbackRate): """ Function path: Animation.setPlaybackRate Domain: Animation Method name: setPlaybackRate Parameters: Required arguments: 'playbackRate' (type: number) -> Playback rate for animations on page No return value. Description: Sets the playback rate of the document timeline. """ assert isinstance(playbackRate, (float, int) ), "Argument 'playbackRate' must be of type '['float', 'int']'. Received type: '%s'" % type( playbackRate) subdom_funcs = self.synchronous_command('Animation.setPlaybackRate', playbackRate=playbackRate) return subdom_funcs
[ "def", "Animation_setPlaybackRate", "(", "self", ",", "playbackRate", ")", ":", "assert", "isinstance", "(", "playbackRate", ",", "(", "float", ",", "int", ")", ")", ",", "\"Argument 'playbackRate' must be of type '['float', 'int']'. Received type: '%s'\"", "%", "type", ...
Function path: Animation.setPlaybackRate Domain: Animation Method name: setPlaybackRate Parameters: Required arguments: 'playbackRate' (type: number) -> Playback rate for animations on page No return value. Description: Sets the playback rate of the document timeline.
[ "Function", "path", ":", "Animation", ".", "setPlaybackRate", "Domain", ":", "Animation", "Method", "name", ":", "setPlaybackRate", "Parameters", ":", "Required", "arguments", ":", "playbackRate", "(", "type", ":", "number", ")", "-", ">", "Playback", "rate", ...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6028-L6046
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Animation_getCurrentTime
def Animation_getCurrentTime(self, id): """ Function path: Animation.getCurrentTime Domain: Animation Method name: getCurrentTime Parameters: Required arguments: 'id' (type: string) -> Id of animation. Returns: 'currentTime' (type: number) -> Current time of the page. Description: Returns the current time of the an animation. """ assert isinstance(id, (str,) ), "Argument 'id' must be of type '['str']'. Received type: '%s'" % type( id) subdom_funcs = self.synchronous_command('Animation.getCurrentTime', id=id) return subdom_funcs
python
def Animation_getCurrentTime(self, id): """ Function path: Animation.getCurrentTime Domain: Animation Method name: getCurrentTime Parameters: Required arguments: 'id' (type: string) -> Id of animation. Returns: 'currentTime' (type: number) -> Current time of the page. Description: Returns the current time of the an animation. """ assert isinstance(id, (str,) ), "Argument 'id' must be of type '['str']'. Received type: '%s'" % type( id) subdom_funcs = self.synchronous_command('Animation.getCurrentTime', id=id) return subdom_funcs
[ "def", "Animation_getCurrentTime", "(", "self", ",", "id", ")", ":", "assert", "isinstance", "(", "id", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'id' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "id", ")", "subdom_funcs", "=", "se...
Function path: Animation.getCurrentTime Domain: Animation Method name: getCurrentTime Parameters: Required arguments: 'id' (type: string) -> Id of animation. Returns: 'currentTime' (type: number) -> Current time of the page. Description: Returns the current time of the an animation.
[ "Function", "path", ":", "Animation", ".", "getCurrentTime", "Domain", ":", "Animation", "Method", "name", ":", "getCurrentTime", "Parameters", ":", "Required", "arguments", ":", "id", "(", "type", ":", "string", ")", "-", ">", "Id", "of", "animation", ".", ...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6048-L6066
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Animation_setPaused
def Animation_setPaused(self, animations, paused): """ Function path: Animation.setPaused Domain: Animation Method name: setPaused Parameters: Required arguments: 'animations' (type: array) -> Animations to set the pause state of. 'paused' (type: boolean) -> Paused state to set to. No return value. Description: Sets the paused state of a set of animations. """ assert isinstance(animations, (list, tuple) ), "Argument 'animations' must be of type '['list', 'tuple']'. Received type: '%s'" % type( animations) assert isinstance(paused, (bool,) ), "Argument 'paused' must be of type '['bool']'. Received type: '%s'" % type( paused) subdom_funcs = self.synchronous_command('Animation.setPaused', animations =animations, paused=paused) return subdom_funcs
python
def Animation_setPaused(self, animations, paused): """ Function path: Animation.setPaused Domain: Animation Method name: setPaused Parameters: Required arguments: 'animations' (type: array) -> Animations to set the pause state of. 'paused' (type: boolean) -> Paused state to set to. No return value. Description: Sets the paused state of a set of animations. """ assert isinstance(animations, (list, tuple) ), "Argument 'animations' must be of type '['list', 'tuple']'. Received type: '%s'" % type( animations) assert isinstance(paused, (bool,) ), "Argument 'paused' must be of type '['bool']'. Received type: '%s'" % type( paused) subdom_funcs = self.synchronous_command('Animation.setPaused', animations =animations, paused=paused) return subdom_funcs
[ "def", "Animation_setPaused", "(", "self", ",", "animations", ",", "paused", ")", ":", "assert", "isinstance", "(", "animations", ",", "(", "list", ",", "tuple", ")", ")", ",", "\"Argument 'animations' must be of type '['list', 'tuple']'. Received type: '%s'\"", "%", ...
Function path: Animation.setPaused Domain: Animation Method name: setPaused Parameters: Required arguments: 'animations' (type: array) -> Animations to set the pause state of. 'paused' (type: boolean) -> Paused state to set to. No return value. Description: Sets the paused state of a set of animations.
[ "Function", "path", ":", "Animation", ".", "setPaused", "Domain", ":", "Animation", "Method", "name", ":", "setPaused", "Parameters", ":", "Required", "arguments", ":", "animations", "(", "type", ":", "array", ")", "-", ">", "Animations", "to", "set", "the",...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6068-L6090
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Animation_setTiming
def Animation_setTiming(self, animationId, duration, delay): """ Function path: Animation.setTiming Domain: Animation Method name: setTiming Parameters: Required arguments: 'animationId' (type: string) -> Animation id. 'duration' (type: number) -> Duration of the animation. 'delay' (type: number) -> Delay of the animation. No return value. Description: Sets the timing of an animation node. """ assert isinstance(animationId, (str,) ), "Argument 'animationId' must be of type '['str']'. Received type: '%s'" % type( animationId) assert isinstance(duration, (float, int) ), "Argument 'duration' must be of type '['float', 'int']'. Received type: '%s'" % type( duration) assert isinstance(delay, (float, int) ), "Argument 'delay' must be of type '['float', 'int']'. Received type: '%s'" % type( delay) subdom_funcs = self.synchronous_command('Animation.setTiming', animationId=animationId, duration=duration, delay=delay) return subdom_funcs
python
def Animation_setTiming(self, animationId, duration, delay): """ Function path: Animation.setTiming Domain: Animation Method name: setTiming Parameters: Required arguments: 'animationId' (type: string) -> Animation id. 'duration' (type: number) -> Duration of the animation. 'delay' (type: number) -> Delay of the animation. No return value. Description: Sets the timing of an animation node. """ assert isinstance(animationId, (str,) ), "Argument 'animationId' must be of type '['str']'. Received type: '%s'" % type( animationId) assert isinstance(duration, (float, int) ), "Argument 'duration' must be of type '['float', 'int']'. Received type: '%s'" % type( duration) assert isinstance(delay, (float, int) ), "Argument 'delay' must be of type '['float', 'int']'. Received type: '%s'" % type( delay) subdom_funcs = self.synchronous_command('Animation.setTiming', animationId=animationId, duration=duration, delay=delay) return subdom_funcs
[ "def", "Animation_setTiming", "(", "self", ",", "animationId", ",", "duration", ",", "delay", ")", ":", "assert", "isinstance", "(", "animationId", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'animationId' must be of type '['str']'. Received type: '%s'\"", "%", ...
Function path: Animation.setTiming Domain: Animation Method name: setTiming Parameters: Required arguments: 'animationId' (type: string) -> Animation id. 'duration' (type: number) -> Duration of the animation. 'delay' (type: number) -> Delay of the animation. No return value. Description: Sets the timing of an animation node.
[ "Function", "path", ":", "Animation", ".", "setTiming", "Domain", ":", "Animation", "Method", "name", ":", "setTiming", "Parameters", ":", "Required", "arguments", ":", "animationId", "(", "type", ":", "string", ")", "-", ">", "Animation", "id", ".", "durati...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6092-L6118
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Animation_seekAnimations
def Animation_seekAnimations(self, animations, currentTime): """ Function path: Animation.seekAnimations Domain: Animation Method name: seekAnimations Parameters: Required arguments: 'animations' (type: array) -> List of animation ids to seek. 'currentTime' (type: number) -> Set the current time of each animation. No return value. Description: Seek a set of animations to a particular time within each animation. """ assert isinstance(animations, (list, tuple) ), "Argument 'animations' must be of type '['list', 'tuple']'. Received type: '%s'" % type( animations) assert isinstance(currentTime, (float, int) ), "Argument 'currentTime' must be of type '['float', 'int']'. Received type: '%s'" % type( currentTime) subdom_funcs = self.synchronous_command('Animation.seekAnimations', animations=animations, currentTime=currentTime) return subdom_funcs
python
def Animation_seekAnimations(self, animations, currentTime): """ Function path: Animation.seekAnimations Domain: Animation Method name: seekAnimations Parameters: Required arguments: 'animations' (type: array) -> List of animation ids to seek. 'currentTime' (type: number) -> Set the current time of each animation. No return value. Description: Seek a set of animations to a particular time within each animation. """ assert isinstance(animations, (list, tuple) ), "Argument 'animations' must be of type '['list', 'tuple']'. Received type: '%s'" % type( animations) assert isinstance(currentTime, (float, int) ), "Argument 'currentTime' must be of type '['float', 'int']'. Received type: '%s'" % type( currentTime) subdom_funcs = self.synchronous_command('Animation.seekAnimations', animations=animations, currentTime=currentTime) return subdom_funcs
[ "def", "Animation_seekAnimations", "(", "self", ",", "animations", ",", "currentTime", ")", ":", "assert", "isinstance", "(", "animations", ",", "(", "list", ",", "tuple", ")", ")", ",", "\"Argument 'animations' must be of type '['list', 'tuple']'. Received type: '%s'\"",...
Function path: Animation.seekAnimations Domain: Animation Method name: seekAnimations Parameters: Required arguments: 'animations' (type: array) -> List of animation ids to seek. 'currentTime' (type: number) -> Set the current time of each animation. No return value. Description: Seek a set of animations to a particular time within each animation.
[ "Function", "path", ":", "Animation", ".", "seekAnimations", "Domain", ":", "Animation", "Method", "name", ":", "seekAnimations", "Parameters", ":", "Required", "arguments", ":", "animations", "(", "type", ":", "array", ")", "-", ">", "List", "of", "animation"...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6120-L6142
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Animation_releaseAnimations
def Animation_releaseAnimations(self, animations): """ Function path: Animation.releaseAnimations Domain: Animation Method name: releaseAnimations Parameters: Required arguments: 'animations' (type: array) -> List of animation ids to seek. No return value. Description: Releases a set of animations to no longer be manipulated. """ assert isinstance(animations, (list, tuple) ), "Argument 'animations' must be of type '['list', 'tuple']'. Received type: '%s'" % type( animations) subdom_funcs = self.synchronous_command('Animation.releaseAnimations', animations=animations) return subdom_funcs
python
def Animation_releaseAnimations(self, animations): """ Function path: Animation.releaseAnimations Domain: Animation Method name: releaseAnimations Parameters: Required arguments: 'animations' (type: array) -> List of animation ids to seek. No return value. Description: Releases a set of animations to no longer be manipulated. """ assert isinstance(animations, (list, tuple) ), "Argument 'animations' must be of type '['list', 'tuple']'. Received type: '%s'" % type( animations) subdom_funcs = self.synchronous_command('Animation.releaseAnimations', animations=animations) return subdom_funcs
[ "def", "Animation_releaseAnimations", "(", "self", ",", "animations", ")", ":", "assert", "isinstance", "(", "animations", ",", "(", "list", ",", "tuple", ")", ")", ",", "\"Argument 'animations' must be of type '['list', 'tuple']'. Received type: '%s'\"", "%", "type", "...
Function path: Animation.releaseAnimations Domain: Animation Method name: releaseAnimations Parameters: Required arguments: 'animations' (type: array) -> List of animation ids to seek. No return value. Description: Releases a set of animations to no longer be manipulated.
[ "Function", "path", ":", "Animation", ".", "releaseAnimations", "Domain", ":", "Animation", "Method", "name", ":", "releaseAnimations", "Parameters", ":", "Required", "arguments", ":", "animations", "(", "type", ":", "array", ")", "-", ">", "List", "of", "anim...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6144-L6162
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Animation_resolveAnimation
def Animation_resolveAnimation(self, animationId): """ Function path: Animation.resolveAnimation Domain: Animation Method name: resolveAnimation Parameters: Required arguments: 'animationId' (type: string) -> Animation id. Returns: 'remoteObject' (type: Runtime.RemoteObject) -> Corresponding remote object. Description: Gets the remote object of the Animation. """ assert isinstance(animationId, (str,) ), "Argument 'animationId' must be of type '['str']'. Received type: '%s'" % type( animationId) subdom_funcs = self.synchronous_command('Animation.resolveAnimation', animationId=animationId) return subdom_funcs
python
def Animation_resolveAnimation(self, animationId): """ Function path: Animation.resolveAnimation Domain: Animation Method name: resolveAnimation Parameters: Required arguments: 'animationId' (type: string) -> Animation id. Returns: 'remoteObject' (type: Runtime.RemoteObject) -> Corresponding remote object. Description: Gets the remote object of the Animation. """ assert isinstance(animationId, (str,) ), "Argument 'animationId' must be of type '['str']'. Received type: '%s'" % type( animationId) subdom_funcs = self.synchronous_command('Animation.resolveAnimation', animationId=animationId) return subdom_funcs
[ "def", "Animation_resolveAnimation", "(", "self", ",", "animationId", ")", ":", "assert", "isinstance", "(", "animationId", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'animationId' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "animationId",...
Function path: Animation.resolveAnimation Domain: Animation Method name: resolveAnimation Parameters: Required arguments: 'animationId' (type: string) -> Animation id. Returns: 'remoteObject' (type: Runtime.RemoteObject) -> Corresponding remote object. Description: Gets the remote object of the Animation.
[ "Function", "path", ":", "Animation", ".", "resolveAnimation", "Domain", ":", "Animation", "Method", "name", ":", "resolveAnimation", "Parameters", ":", "Required", "arguments", ":", "animationId", "(", "type", ":", "string", ")", "-", ">", "Animation", "id", ...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6164-L6183
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Storage_clearDataForOrigin
def Storage_clearDataForOrigin(self, origin, storageTypes): """ Function path: Storage.clearDataForOrigin Domain: Storage Method name: clearDataForOrigin Parameters: Required arguments: 'origin' (type: string) -> Security origin. 'storageTypes' (type: string) -> Comma separated origin names. No return value. Description: Clears storage for origin. """ assert isinstance(origin, (str,) ), "Argument 'origin' must be of type '['str']'. Received type: '%s'" % type( origin) assert isinstance(storageTypes, (str,) ), "Argument 'storageTypes' must be of type '['str']'. Received type: '%s'" % type( storageTypes) subdom_funcs = self.synchronous_command('Storage.clearDataForOrigin', origin=origin, storageTypes=storageTypes) return subdom_funcs
python
def Storage_clearDataForOrigin(self, origin, storageTypes): """ Function path: Storage.clearDataForOrigin Domain: Storage Method name: clearDataForOrigin Parameters: Required arguments: 'origin' (type: string) -> Security origin. 'storageTypes' (type: string) -> Comma separated origin names. No return value. Description: Clears storage for origin. """ assert isinstance(origin, (str,) ), "Argument 'origin' must be of type '['str']'. Received type: '%s'" % type( origin) assert isinstance(storageTypes, (str,) ), "Argument 'storageTypes' must be of type '['str']'. Received type: '%s'" % type( storageTypes) subdom_funcs = self.synchronous_command('Storage.clearDataForOrigin', origin=origin, storageTypes=storageTypes) return subdom_funcs
[ "def", "Storage_clearDataForOrigin", "(", "self", ",", "origin", ",", "storageTypes", ")", ":", "assert", "isinstance", "(", "origin", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'origin' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "ori...
Function path: Storage.clearDataForOrigin Domain: Storage Method name: clearDataForOrigin Parameters: Required arguments: 'origin' (type: string) -> Security origin. 'storageTypes' (type: string) -> Comma separated origin names. No return value. Description: Clears storage for origin.
[ "Function", "path", ":", "Storage", ".", "clearDataForOrigin", "Domain", ":", "Storage", "Method", "name", ":", "clearDataForOrigin", "Parameters", ":", "Required", "arguments", ":", "origin", "(", "type", ":", "string", ")", "-", ">", "Security", "origin", "....
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6215-L6237
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Storage_getUsageAndQuota
def Storage_getUsageAndQuota(self, origin): """ Function path: Storage.getUsageAndQuota Domain: Storage Method name: getUsageAndQuota Parameters: Required arguments: 'origin' (type: string) -> Security origin. Returns: 'usage' (type: number) -> Storage usage (bytes). 'quota' (type: number) -> Storage quota (bytes). 'usageBreakdown' (type: array) -> Storage usage per type (bytes). Description: Returns usage and quota in bytes. """ assert isinstance(origin, (str,) ), "Argument 'origin' must be of type '['str']'. Received type: '%s'" % type( origin) subdom_funcs = self.synchronous_command('Storage.getUsageAndQuota', origin=origin) return subdom_funcs
python
def Storage_getUsageAndQuota(self, origin): """ Function path: Storage.getUsageAndQuota Domain: Storage Method name: getUsageAndQuota Parameters: Required arguments: 'origin' (type: string) -> Security origin. Returns: 'usage' (type: number) -> Storage usage (bytes). 'quota' (type: number) -> Storage quota (bytes). 'usageBreakdown' (type: array) -> Storage usage per type (bytes). Description: Returns usage and quota in bytes. """ assert isinstance(origin, (str,) ), "Argument 'origin' must be of type '['str']'. Received type: '%s'" % type( origin) subdom_funcs = self.synchronous_command('Storage.getUsageAndQuota', origin=origin) return subdom_funcs
[ "def", "Storage_getUsageAndQuota", "(", "self", ",", "origin", ")", ":", "assert", "isinstance", "(", "origin", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'origin' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "origin", ")", "subdom_func...
Function path: Storage.getUsageAndQuota Domain: Storage Method name: getUsageAndQuota Parameters: Required arguments: 'origin' (type: string) -> Security origin. Returns: 'usage' (type: number) -> Storage usage (bytes). 'quota' (type: number) -> Storage quota (bytes). 'usageBreakdown' (type: array) -> Storage usage per type (bytes). Description: Returns usage and quota in bytes.
[ "Function", "path", ":", "Storage", ".", "getUsageAndQuota", "Domain", ":", "Storage", "Method", "name", ":", "getUsageAndQuota", "Parameters", ":", "Required", "arguments", ":", "origin", "(", "type", ":", "string", ")", "-", ">", "Security", "origin", ".", ...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6239-L6260
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Storage_trackCacheStorageForOrigin
def Storage_trackCacheStorageForOrigin(self, origin): """ Function path: Storage.trackCacheStorageForOrigin Domain: Storage Method name: trackCacheStorageForOrigin Parameters: Required arguments: 'origin' (type: string) -> Security origin. No return value. Description: Registers origin to be notified when an update occurs to its cache storage list. """ assert isinstance(origin, (str,) ), "Argument 'origin' must be of type '['str']'. Received type: '%s'" % type( origin) subdom_funcs = self.synchronous_command('Storage.trackCacheStorageForOrigin', origin=origin) return subdom_funcs
python
def Storage_trackCacheStorageForOrigin(self, origin): """ Function path: Storage.trackCacheStorageForOrigin Domain: Storage Method name: trackCacheStorageForOrigin Parameters: Required arguments: 'origin' (type: string) -> Security origin. No return value. Description: Registers origin to be notified when an update occurs to its cache storage list. """ assert isinstance(origin, (str,) ), "Argument 'origin' must be of type '['str']'. Received type: '%s'" % type( origin) subdom_funcs = self.synchronous_command('Storage.trackCacheStorageForOrigin', origin=origin) return subdom_funcs
[ "def", "Storage_trackCacheStorageForOrigin", "(", "self", ",", "origin", ")", ":", "assert", "isinstance", "(", "origin", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'origin' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "origin", ")", "s...
Function path: Storage.trackCacheStorageForOrigin Domain: Storage Method name: trackCacheStorageForOrigin Parameters: Required arguments: 'origin' (type: string) -> Security origin. No return value. Description: Registers origin to be notified when an update occurs to its cache storage list.
[ "Function", "path", ":", "Storage", ".", "trackCacheStorageForOrigin", "Domain", ":", "Storage", "Method", "name", ":", "trackCacheStorageForOrigin", "Parameters", ":", "Required", "arguments", ":", "origin", "(", "type", ":", "string", ")", "-", ">", "Security", ...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6262-L6280
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Storage_untrackCacheStorageForOrigin
def Storage_untrackCacheStorageForOrigin(self, origin): """ Function path: Storage.untrackCacheStorageForOrigin Domain: Storage Method name: untrackCacheStorageForOrigin Parameters: Required arguments: 'origin' (type: string) -> Security origin. No return value. Description: Unregisters origin from receiving notifications for cache storage. """ assert isinstance(origin, (str,) ), "Argument 'origin' must be of type '['str']'. Received type: '%s'" % type( origin) subdom_funcs = self.synchronous_command( 'Storage.untrackCacheStorageForOrigin', origin=origin) return subdom_funcs
python
def Storage_untrackCacheStorageForOrigin(self, origin): """ Function path: Storage.untrackCacheStorageForOrigin Domain: Storage Method name: untrackCacheStorageForOrigin Parameters: Required arguments: 'origin' (type: string) -> Security origin. No return value. Description: Unregisters origin from receiving notifications for cache storage. """ assert isinstance(origin, (str,) ), "Argument 'origin' must be of type '['str']'. Received type: '%s'" % type( origin) subdom_funcs = self.synchronous_command( 'Storage.untrackCacheStorageForOrigin', origin=origin) return subdom_funcs
[ "def", "Storage_untrackCacheStorageForOrigin", "(", "self", ",", "origin", ")", ":", "assert", "isinstance", "(", "origin", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'origin' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "origin", ")", ...
Function path: Storage.untrackCacheStorageForOrigin Domain: Storage Method name: untrackCacheStorageForOrigin Parameters: Required arguments: 'origin' (type: string) -> Security origin. No return value. Description: Unregisters origin from receiving notifications for cache storage.
[ "Function", "path", ":", "Storage", ".", "untrackCacheStorageForOrigin", "Domain", ":", "Storage", "Method", "name", ":", "untrackCacheStorageForOrigin", "Parameters", ":", "Required", "arguments", ":", "origin", "(", "type", ":", "string", ")", "-", ">", "Securit...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6282-L6300
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Log_startViolationsReport
def Log_startViolationsReport(self, config): """ Function path: Log.startViolationsReport Domain: Log Method name: startViolationsReport Parameters: Required arguments: 'config' (type: array) -> Configuration for violations. No return value. Description: start violation reporting. """ assert isinstance(config, (list, tuple) ), "Argument 'config' must be of type '['list', 'tuple']'. Received type: '%s'" % type( config) subdom_funcs = self.synchronous_command('Log.startViolationsReport', config=config) return subdom_funcs
python
def Log_startViolationsReport(self, config): """ Function path: Log.startViolationsReport Domain: Log Method name: startViolationsReport Parameters: Required arguments: 'config' (type: array) -> Configuration for violations. No return value. Description: start violation reporting. """ assert isinstance(config, (list, tuple) ), "Argument 'config' must be of type '['list', 'tuple']'. Received type: '%s'" % type( config) subdom_funcs = self.synchronous_command('Log.startViolationsReport', config=config) return subdom_funcs
[ "def", "Log_startViolationsReport", "(", "self", ",", "config", ")", ":", "assert", "isinstance", "(", "config", ",", "(", "list", ",", "tuple", ")", ")", ",", "\"Argument 'config' must be of type '['list', 'tuple']'. Received type: '%s'\"", "%", "type", "(", "config"...
Function path: Log.startViolationsReport Domain: Log Method name: startViolationsReport Parameters: Required arguments: 'config' (type: array) -> Configuration for violations. No return value. Description: start violation reporting.
[ "Function", "path", ":", "Log", ".", "startViolationsReport", "Domain", ":", "Log", "Method", "name", ":", "startViolationsReport", "Parameters", ":", "Required", "arguments", ":", "config", "(", "type", ":", "array", ")", "-", ">", "Configuration", "for", "vi...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6341-L6359
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Tethering_bind
def Tethering_bind(self, port): """ Function path: Tethering.bind Domain: Tethering Method name: bind Parameters: Required arguments: 'port' (type: integer) -> Port number to bind. No return value. Description: Request browser port binding. """ assert isinstance(port, (int,) ), "Argument 'port' must be of type '['int']'. Received type: '%s'" % type( port) subdom_funcs = self.synchronous_command('Tethering.bind', port=port) return subdom_funcs
python
def Tethering_bind(self, port): """ Function path: Tethering.bind Domain: Tethering Method name: bind Parameters: Required arguments: 'port' (type: integer) -> Port number to bind. No return value. Description: Request browser port binding. """ assert isinstance(port, (int,) ), "Argument 'port' must be of type '['int']'. Received type: '%s'" % type( port) subdom_funcs = self.synchronous_command('Tethering.bind', port=port) return subdom_funcs
[ "def", "Tethering_bind", "(", "self", ",", "port", ")", ":", "assert", "isinstance", "(", "port", ",", "(", "int", ",", ")", ")", ",", "\"Argument 'port' must be of type '['int']'. Received type: '%s'\"", "%", "type", "(", "port", ")", "subdom_funcs", "=", "self...
Function path: Tethering.bind Domain: Tethering Method name: bind Parameters: Required arguments: 'port' (type: integer) -> Port number to bind. No return value. Description: Request browser port binding.
[ "Function", "path", ":", "Tethering", ".", "bind", "Domain", ":", "Tethering", "Method", "name", ":", "bind", "Parameters", ":", "Required", "arguments", ":", "port", "(", "type", ":", "integer", ")", "-", ">", "Port", "number", "to", "bind", ".", "No", ...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6391-L6408
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Tethering_unbind
def Tethering_unbind(self, port): """ Function path: Tethering.unbind Domain: Tethering Method name: unbind Parameters: Required arguments: 'port' (type: integer) -> Port number to unbind. No return value. Description: Request browser port unbinding. """ assert isinstance(port, (int,) ), "Argument 'port' must be of type '['int']'. Received type: '%s'" % type( port) subdom_funcs = self.synchronous_command('Tethering.unbind', port=port) return subdom_funcs
python
def Tethering_unbind(self, port): """ Function path: Tethering.unbind Domain: Tethering Method name: unbind Parameters: Required arguments: 'port' (type: integer) -> Port number to unbind. No return value. Description: Request browser port unbinding. """ assert isinstance(port, (int,) ), "Argument 'port' must be of type '['int']'. Received type: '%s'" % type( port) subdom_funcs = self.synchronous_command('Tethering.unbind', port=port) return subdom_funcs
[ "def", "Tethering_unbind", "(", "self", ",", "port", ")", ":", "assert", "isinstance", "(", "port", ",", "(", "int", ",", ")", ")", ",", "\"Argument 'port' must be of type '['int']'. Received type: '%s'\"", "%", "type", "(", "port", ")", "subdom_funcs", "=", "se...
Function path: Tethering.unbind Domain: Tethering Method name: unbind Parameters: Required arguments: 'port' (type: integer) -> Port number to unbind. No return value. Description: Request browser port unbinding.
[ "Function", "path", ":", "Tethering", ".", "unbind", "Domain", ":", "Tethering", "Method", "name", ":", "unbind", "Parameters", ":", "Required", "arguments", ":", "port", "(", "type", ":", "integer", ")", "-", ">", "Port", "number", "to", "unbind", ".", ...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6410-L6427
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Browser_setWindowBounds
def Browser_setWindowBounds(self, windowId, bounds): """ Function path: Browser.setWindowBounds Domain: Browser Method name: setWindowBounds Parameters: Required arguments: 'windowId' (type: WindowID) -> Browser window id. 'bounds' (type: Bounds) -> New window bounds. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined with 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged. No return value. Description: Set position and/or size of the browser window. """ subdom_funcs = self.synchronous_command('Browser.setWindowBounds', windowId=windowId, bounds=bounds) return subdom_funcs
python
def Browser_setWindowBounds(self, windowId, bounds): """ Function path: Browser.setWindowBounds Domain: Browser Method name: setWindowBounds Parameters: Required arguments: 'windowId' (type: WindowID) -> Browser window id. 'bounds' (type: Bounds) -> New window bounds. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined with 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged. No return value. Description: Set position and/or size of the browser window. """ subdom_funcs = self.synchronous_command('Browser.setWindowBounds', windowId=windowId, bounds=bounds) return subdom_funcs
[ "def", "Browser_setWindowBounds", "(", "self", ",", "windowId", ",", "bounds", ")", ":", "subdom_funcs", "=", "self", ".", "synchronous_command", "(", "'Browser.setWindowBounds'", ",", "windowId", "=", "windowId", ",", "bounds", "=", "bounds", ")", "return", "su...
Function path: Browser.setWindowBounds Domain: Browser Method name: setWindowBounds Parameters: Required arguments: 'windowId' (type: WindowID) -> Browser window id. 'bounds' (type: Bounds) -> New window bounds. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined with 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged. No return value. Description: Set position and/or size of the browser window.
[ "Function", "path", ":", "Browser", ".", "setWindowBounds", "Domain", ":", "Browser", "Method", "name", ":", "setWindowBounds", "Parameters", ":", "Required", "arguments", ":", "windowId", "(", "type", ":", "WindowID", ")", "-", ">", "Browser", "window", "id",...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6466-L6482
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Runtime_evaluate
def Runtime_evaluate(self, expression, **kwargs): """ Function path: Runtime.evaluate Domain: Runtime Method name: evaluate Parameters: Required arguments: 'expression' (type: string) -> Expression to evaluate. Optional arguments: 'objectGroup' (type: string) -> Symbolic group name that can be used to release multiple objects. 'includeCommandLineAPI' (type: boolean) -> Determines whether Command Line API should be available during the evaluation. 'silent' (type: boolean) -> In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. 'contextId' (type: ExecutionContextId) -> Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. 'returnByValue' (type: boolean) -> Whether the result is expected to be a JSON object that should be sent by value. 'generatePreview' (type: boolean) -> Whether preview should be generated for the result. 'userGesture' (type: boolean) -> Whether execution should be treated as initiated by user in the UI. 'awaitPromise' (type: boolean) -> Whether execution should <code>await</code> for resulting value and return once awaited promise is resolved. Returns: 'result' (type: RemoteObject) -> Evaluation result. 'exceptionDetails' (type: ExceptionDetails) -> Exception details. Description: Evaluates expression on global object. """ assert isinstance(expression, (str,) ), "Argument 'expression' must be of type '['str']'. Received type: '%s'" % type( expression) if 'objectGroup' in kwargs: assert isinstance(kwargs['objectGroup'], (str,) ), "Optional argument 'objectGroup' must be of type '['str']'. Received type: '%s'" % type( kwargs['objectGroup']) if 'includeCommandLineAPI' in kwargs: assert isinstance(kwargs['includeCommandLineAPI'], (bool,) ), "Optional argument 'includeCommandLineAPI' must be of type '['bool']'. Received type: '%s'" % type( kwargs['includeCommandLineAPI']) if 'silent' in kwargs: assert isinstance(kwargs['silent'], (bool,) ), "Optional argument 'silent' must be of type '['bool']'. Received type: '%s'" % type( kwargs['silent']) if 'returnByValue' in kwargs: assert isinstance(kwargs['returnByValue'], (bool,) ), "Optional argument 'returnByValue' must be of type '['bool']'. Received type: '%s'" % type( kwargs['returnByValue']) if 'generatePreview' in kwargs: assert isinstance(kwargs['generatePreview'], (bool,) ), "Optional argument 'generatePreview' must be of type '['bool']'. Received type: '%s'" % type( kwargs['generatePreview']) if 'userGesture' in kwargs: assert isinstance(kwargs['userGesture'], (bool,) ), "Optional argument 'userGesture' must be of type '['bool']'. Received type: '%s'" % type( kwargs['userGesture']) if 'awaitPromise' in kwargs: assert isinstance(kwargs['awaitPromise'], (bool,) ), "Optional argument 'awaitPromise' must be of type '['bool']'. Received type: '%s'" % type( kwargs['awaitPromise']) expected = ['objectGroup', 'includeCommandLineAPI', 'silent', 'contextId', 'returnByValue', 'generatePreview', 'userGesture', 'awaitPromise'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['objectGroup', 'includeCommandLineAPI', 'silent', 'contextId', 'returnByValue', 'generatePreview', 'userGesture', 'awaitPromise']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('Runtime.evaluate', expression= expression, **kwargs) return subdom_funcs
python
def Runtime_evaluate(self, expression, **kwargs): """ Function path: Runtime.evaluate Domain: Runtime Method name: evaluate Parameters: Required arguments: 'expression' (type: string) -> Expression to evaluate. Optional arguments: 'objectGroup' (type: string) -> Symbolic group name that can be used to release multiple objects. 'includeCommandLineAPI' (type: boolean) -> Determines whether Command Line API should be available during the evaluation. 'silent' (type: boolean) -> In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. 'contextId' (type: ExecutionContextId) -> Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. 'returnByValue' (type: boolean) -> Whether the result is expected to be a JSON object that should be sent by value. 'generatePreview' (type: boolean) -> Whether preview should be generated for the result. 'userGesture' (type: boolean) -> Whether execution should be treated as initiated by user in the UI. 'awaitPromise' (type: boolean) -> Whether execution should <code>await</code> for resulting value and return once awaited promise is resolved. Returns: 'result' (type: RemoteObject) -> Evaluation result. 'exceptionDetails' (type: ExceptionDetails) -> Exception details. Description: Evaluates expression on global object. """ assert isinstance(expression, (str,) ), "Argument 'expression' must be of type '['str']'. Received type: '%s'" % type( expression) if 'objectGroup' in kwargs: assert isinstance(kwargs['objectGroup'], (str,) ), "Optional argument 'objectGroup' must be of type '['str']'. Received type: '%s'" % type( kwargs['objectGroup']) if 'includeCommandLineAPI' in kwargs: assert isinstance(kwargs['includeCommandLineAPI'], (bool,) ), "Optional argument 'includeCommandLineAPI' must be of type '['bool']'. Received type: '%s'" % type( kwargs['includeCommandLineAPI']) if 'silent' in kwargs: assert isinstance(kwargs['silent'], (bool,) ), "Optional argument 'silent' must be of type '['bool']'. Received type: '%s'" % type( kwargs['silent']) if 'returnByValue' in kwargs: assert isinstance(kwargs['returnByValue'], (bool,) ), "Optional argument 'returnByValue' must be of type '['bool']'. Received type: '%s'" % type( kwargs['returnByValue']) if 'generatePreview' in kwargs: assert isinstance(kwargs['generatePreview'], (bool,) ), "Optional argument 'generatePreview' must be of type '['bool']'. Received type: '%s'" % type( kwargs['generatePreview']) if 'userGesture' in kwargs: assert isinstance(kwargs['userGesture'], (bool,) ), "Optional argument 'userGesture' must be of type '['bool']'. Received type: '%s'" % type( kwargs['userGesture']) if 'awaitPromise' in kwargs: assert isinstance(kwargs['awaitPromise'], (bool,) ), "Optional argument 'awaitPromise' must be of type '['bool']'. Received type: '%s'" % type( kwargs['awaitPromise']) expected = ['objectGroup', 'includeCommandLineAPI', 'silent', 'contextId', 'returnByValue', 'generatePreview', 'userGesture', 'awaitPromise'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['objectGroup', 'includeCommandLineAPI', 'silent', 'contextId', 'returnByValue', 'generatePreview', 'userGesture', 'awaitPromise']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('Runtime.evaluate', expression= expression, **kwargs) return subdom_funcs
[ "def", "Runtime_evaluate", "(", "self", ",", "expression", ",", "*", "*", "kwargs", ")", ":", "assert", "isinstance", "(", "expression", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'expression' must be of type '['str']'. Received type: '%s'\"", "%", "type", "...
Function path: Runtime.evaluate Domain: Runtime Method name: evaluate Parameters: Required arguments: 'expression' (type: string) -> Expression to evaluate. Optional arguments: 'objectGroup' (type: string) -> Symbolic group name that can be used to release multiple objects. 'includeCommandLineAPI' (type: boolean) -> Determines whether Command Line API should be available during the evaluation. 'silent' (type: boolean) -> In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. 'contextId' (type: ExecutionContextId) -> Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. 'returnByValue' (type: boolean) -> Whether the result is expected to be a JSON object that should be sent by value. 'generatePreview' (type: boolean) -> Whether preview should be generated for the result. 'userGesture' (type: boolean) -> Whether execution should be treated as initiated by user in the UI. 'awaitPromise' (type: boolean) -> Whether execution should <code>await</code> for resulting value and return once awaited promise is resolved. Returns: 'result' (type: RemoteObject) -> Evaluation result. 'exceptionDetails' (type: ExceptionDetails) -> Exception details. Description: Evaluates expression on global object.
[ "Function", "path", ":", "Runtime", ".", "evaluate", "Domain", ":", "Runtime", "Method", "name", ":", "evaluate", "Parameters", ":", "Required", "arguments", ":", "expression", "(", "type", ":", "string", ")", "-", ">", "Expression", "to", "evaluate", ".", ...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6516-L6578
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Runtime_callFunctionOn
def Runtime_callFunctionOn(self, functionDeclaration, **kwargs): """ Function path: Runtime.callFunctionOn Domain: Runtime Method name: callFunctionOn Parameters: Required arguments: 'functionDeclaration' (type: string) -> Declaration of the function to call. Optional arguments: 'objectId' (type: RemoteObjectId) -> Identifier of the object to call function on. Either objectId or executionContextId should be specified. 'arguments' (type: array) -> Call arguments. All call arguments must belong to the same JavaScript world as the target object. 'silent' (type: boolean) -> In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. 'returnByValue' (type: boolean) -> Whether the result is expected to be a JSON object which should be sent by value. 'generatePreview' (type: boolean) -> Whether preview should be generated for the result. 'userGesture' (type: boolean) -> Whether execution should be treated as initiated by user in the UI. 'awaitPromise' (type: boolean) -> Whether execution should <code>await</code> for resulting value and return once awaited promise is resolved. 'executionContextId' (type: ExecutionContextId) -> Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. 'objectGroup' (type: string) -> Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. Returns: 'result' (type: RemoteObject) -> Call result. 'exceptionDetails' (type: ExceptionDetails) -> Exception details. Description: Calls function with given declaration on the given object. Object group of the result is inherited from the target object. """ assert isinstance(functionDeclaration, (str,) ), "Argument 'functionDeclaration' must be of type '['str']'. Received type: '%s'" % type( functionDeclaration) if 'arguments' in kwargs: assert isinstance(kwargs['arguments'], (list, tuple) ), "Optional argument 'arguments' must be of type '['list', 'tuple']'. Received type: '%s'" % type( kwargs['arguments']) if 'silent' in kwargs: assert isinstance(kwargs['silent'], (bool,) ), "Optional argument 'silent' must be of type '['bool']'. Received type: '%s'" % type( kwargs['silent']) if 'returnByValue' in kwargs: assert isinstance(kwargs['returnByValue'], (bool,) ), "Optional argument 'returnByValue' must be of type '['bool']'. Received type: '%s'" % type( kwargs['returnByValue']) if 'generatePreview' in kwargs: assert isinstance(kwargs['generatePreview'], (bool,) ), "Optional argument 'generatePreview' must be of type '['bool']'. Received type: '%s'" % type( kwargs['generatePreview']) if 'userGesture' in kwargs: assert isinstance(kwargs['userGesture'], (bool,) ), "Optional argument 'userGesture' must be of type '['bool']'. Received type: '%s'" % type( kwargs['userGesture']) if 'awaitPromise' in kwargs: assert isinstance(kwargs['awaitPromise'], (bool,) ), "Optional argument 'awaitPromise' must be of type '['bool']'. Received type: '%s'" % type( kwargs['awaitPromise']) if 'objectGroup' in kwargs: assert isinstance(kwargs['objectGroup'], (str,) ), "Optional argument 'objectGroup' must be of type '['str']'. Received type: '%s'" % type( kwargs['objectGroup']) expected = ['objectId', 'arguments', 'silent', 'returnByValue', 'generatePreview', 'userGesture', 'awaitPromise', 'executionContextId', 'objectGroup'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['objectId', 'arguments', 'silent', 'returnByValue', 'generatePreview', 'userGesture', 'awaitPromise', 'executionContextId', 'objectGroup']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('Runtime.callFunctionOn', functionDeclaration=functionDeclaration, **kwargs) return subdom_funcs
python
def Runtime_callFunctionOn(self, functionDeclaration, **kwargs): """ Function path: Runtime.callFunctionOn Domain: Runtime Method name: callFunctionOn Parameters: Required arguments: 'functionDeclaration' (type: string) -> Declaration of the function to call. Optional arguments: 'objectId' (type: RemoteObjectId) -> Identifier of the object to call function on. Either objectId or executionContextId should be specified. 'arguments' (type: array) -> Call arguments. All call arguments must belong to the same JavaScript world as the target object. 'silent' (type: boolean) -> In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. 'returnByValue' (type: boolean) -> Whether the result is expected to be a JSON object which should be sent by value. 'generatePreview' (type: boolean) -> Whether preview should be generated for the result. 'userGesture' (type: boolean) -> Whether execution should be treated as initiated by user in the UI. 'awaitPromise' (type: boolean) -> Whether execution should <code>await</code> for resulting value and return once awaited promise is resolved. 'executionContextId' (type: ExecutionContextId) -> Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. 'objectGroup' (type: string) -> Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. Returns: 'result' (type: RemoteObject) -> Call result. 'exceptionDetails' (type: ExceptionDetails) -> Exception details. Description: Calls function with given declaration on the given object. Object group of the result is inherited from the target object. """ assert isinstance(functionDeclaration, (str,) ), "Argument 'functionDeclaration' must be of type '['str']'. Received type: '%s'" % type( functionDeclaration) if 'arguments' in kwargs: assert isinstance(kwargs['arguments'], (list, tuple) ), "Optional argument 'arguments' must be of type '['list', 'tuple']'. Received type: '%s'" % type( kwargs['arguments']) if 'silent' in kwargs: assert isinstance(kwargs['silent'], (bool,) ), "Optional argument 'silent' must be of type '['bool']'. Received type: '%s'" % type( kwargs['silent']) if 'returnByValue' in kwargs: assert isinstance(kwargs['returnByValue'], (bool,) ), "Optional argument 'returnByValue' must be of type '['bool']'. Received type: '%s'" % type( kwargs['returnByValue']) if 'generatePreview' in kwargs: assert isinstance(kwargs['generatePreview'], (bool,) ), "Optional argument 'generatePreview' must be of type '['bool']'. Received type: '%s'" % type( kwargs['generatePreview']) if 'userGesture' in kwargs: assert isinstance(kwargs['userGesture'], (bool,) ), "Optional argument 'userGesture' must be of type '['bool']'. Received type: '%s'" % type( kwargs['userGesture']) if 'awaitPromise' in kwargs: assert isinstance(kwargs['awaitPromise'], (bool,) ), "Optional argument 'awaitPromise' must be of type '['bool']'. Received type: '%s'" % type( kwargs['awaitPromise']) if 'objectGroup' in kwargs: assert isinstance(kwargs['objectGroup'], (str,) ), "Optional argument 'objectGroup' must be of type '['str']'. Received type: '%s'" % type( kwargs['objectGroup']) expected = ['objectId', 'arguments', 'silent', 'returnByValue', 'generatePreview', 'userGesture', 'awaitPromise', 'executionContextId', 'objectGroup'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['objectId', 'arguments', 'silent', 'returnByValue', 'generatePreview', 'userGesture', 'awaitPromise', 'executionContextId', 'objectGroup']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('Runtime.callFunctionOn', functionDeclaration=functionDeclaration, **kwargs) return subdom_funcs
[ "def", "Runtime_callFunctionOn", "(", "self", ",", "functionDeclaration", ",", "*", "*", "kwargs", ")", ":", "assert", "isinstance", "(", "functionDeclaration", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'functionDeclaration' must be of type '['str']'. Received ty...
Function path: Runtime.callFunctionOn Domain: Runtime Method name: callFunctionOn Parameters: Required arguments: 'functionDeclaration' (type: string) -> Declaration of the function to call. Optional arguments: 'objectId' (type: RemoteObjectId) -> Identifier of the object to call function on. Either objectId or executionContextId should be specified. 'arguments' (type: array) -> Call arguments. All call arguments must belong to the same JavaScript world as the target object. 'silent' (type: boolean) -> In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. 'returnByValue' (type: boolean) -> Whether the result is expected to be a JSON object which should be sent by value. 'generatePreview' (type: boolean) -> Whether preview should be generated for the result. 'userGesture' (type: boolean) -> Whether execution should be treated as initiated by user in the UI. 'awaitPromise' (type: boolean) -> Whether execution should <code>await</code> for resulting value and return once awaited promise is resolved. 'executionContextId' (type: ExecutionContextId) -> Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. 'objectGroup' (type: string) -> Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. Returns: 'result' (type: RemoteObject) -> Call result. 'exceptionDetails' (type: ExceptionDetails) -> Exception details. Description: Calls function with given declaration on the given object. Object group of the result is inherited from the target object.
[ "Function", "path", ":", "Runtime", ".", "callFunctionOn", "Domain", ":", "Runtime", "Method", "name", ":", "callFunctionOn", "Parameters", ":", "Required", "arguments", ":", "functionDeclaration", "(", "type", ":", "string", ")", "-", ">", "Declaration", "of", ...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6614-L6678
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Runtime_releaseObjectGroup
def Runtime_releaseObjectGroup(self, objectGroup): """ Function path: Runtime.releaseObjectGroup Domain: Runtime Method name: releaseObjectGroup Parameters: Required arguments: 'objectGroup' (type: string) -> Symbolic object group name. No return value. Description: Releases all remote objects that belong to a given group. """ assert isinstance(objectGroup, (str,) ), "Argument 'objectGroup' must be of type '['str']'. Received type: '%s'" % type( objectGroup) subdom_funcs = self.synchronous_command('Runtime.releaseObjectGroup', objectGroup=objectGroup) return subdom_funcs
python
def Runtime_releaseObjectGroup(self, objectGroup): """ Function path: Runtime.releaseObjectGroup Domain: Runtime Method name: releaseObjectGroup Parameters: Required arguments: 'objectGroup' (type: string) -> Symbolic object group name. No return value. Description: Releases all remote objects that belong to a given group. """ assert isinstance(objectGroup, (str,) ), "Argument 'objectGroup' must be of type '['str']'. Received type: '%s'" % type( objectGroup) subdom_funcs = self.synchronous_command('Runtime.releaseObjectGroup', objectGroup=objectGroup) return subdom_funcs
[ "def", "Runtime_releaseObjectGroup", "(", "self", ",", "objectGroup", ")", ":", "assert", "isinstance", "(", "objectGroup", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'objectGroup' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "objectGroup",...
Function path: Runtime.releaseObjectGroup Domain: Runtime Method name: releaseObjectGroup Parameters: Required arguments: 'objectGroup' (type: string) -> Symbolic object group name. No return value. Description: Releases all remote objects that belong to a given group.
[ "Function", "path", ":", "Runtime", ".", "releaseObjectGroup", "Domain", ":", "Runtime", "Method", "name", ":", "releaseObjectGroup", "Parameters", ":", "Required", "arguments", ":", "objectGroup", "(", "type", ":", "string", ")", "-", ">", "Symbolic", "object",...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6737-L6755
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Runtime_setCustomObjectFormatterEnabled
def Runtime_setCustomObjectFormatterEnabled(self, enabled): """ Function path: Runtime.setCustomObjectFormatterEnabled Domain: Runtime Method name: setCustomObjectFormatterEnabled WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'enabled' (type: boolean) -> No description No return value. """ assert isinstance(enabled, (bool,) ), "Argument 'enabled' must be of type '['bool']'. Received type: '%s'" % type( enabled) subdom_funcs = self.synchronous_command( 'Runtime.setCustomObjectFormatterEnabled', enabled=enabled) return subdom_funcs
python
def Runtime_setCustomObjectFormatterEnabled(self, enabled): """ Function path: Runtime.setCustomObjectFormatterEnabled Domain: Runtime Method name: setCustomObjectFormatterEnabled WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'enabled' (type: boolean) -> No description No return value. """ assert isinstance(enabled, (bool,) ), "Argument 'enabled' must be of type '['bool']'. Received type: '%s'" % type( enabled) subdom_funcs = self.synchronous_command( 'Runtime.setCustomObjectFormatterEnabled', enabled=enabled) return subdom_funcs
[ "def", "Runtime_setCustomObjectFormatterEnabled", "(", "self", ",", "enabled", ")", ":", "assert", "isinstance", "(", "enabled", ",", "(", "bool", ",", ")", ")", ",", "\"Argument 'enabled' must be of type '['bool']'. Received type: '%s'\"", "%", "type", "(", "enabled", ...
Function path: Runtime.setCustomObjectFormatterEnabled Domain: Runtime Method name: setCustomObjectFormatterEnabled WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'enabled' (type: boolean) -> No description No return value.
[ "Function", "path", ":", "Runtime", ".", "setCustomObjectFormatterEnabled", "Domain", ":", "Runtime", "Method", "name", ":", "setCustomObjectFormatterEnabled", "WARNING", ":", "This", "function", "is", "marked", "Experimental", "!", "Parameters", ":", "Required", "arg...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6809-L6828
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Runtime_compileScript
def Runtime_compileScript(self, expression, sourceURL, persistScript, **kwargs ): """ Function path: Runtime.compileScript Domain: Runtime Method name: compileScript Parameters: Required arguments: 'expression' (type: string) -> Expression to compile. 'sourceURL' (type: string) -> Source url to be set for the script. 'persistScript' (type: boolean) -> Specifies whether the compiled script should be persisted. Optional arguments: 'executionContextId' (type: ExecutionContextId) -> Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. Returns: 'scriptId' (type: ScriptId) -> Id of the script. 'exceptionDetails' (type: ExceptionDetails) -> Exception details. Description: Compiles expression. """ assert isinstance(expression, (str,) ), "Argument 'expression' must be of type '['str']'. Received type: '%s'" % type( expression) assert isinstance(sourceURL, (str,) ), "Argument 'sourceURL' must be of type '['str']'. Received type: '%s'" % type( sourceURL) assert isinstance(persistScript, (bool,) ), "Argument 'persistScript' must be of type '['bool']'. Received type: '%s'" % type( persistScript) expected = ['executionContextId'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['executionContextId']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('Runtime.compileScript', expression=expression, sourceURL=sourceURL, persistScript= persistScript, **kwargs) return subdom_funcs
python
def Runtime_compileScript(self, expression, sourceURL, persistScript, **kwargs ): """ Function path: Runtime.compileScript Domain: Runtime Method name: compileScript Parameters: Required arguments: 'expression' (type: string) -> Expression to compile. 'sourceURL' (type: string) -> Source url to be set for the script. 'persistScript' (type: boolean) -> Specifies whether the compiled script should be persisted. Optional arguments: 'executionContextId' (type: ExecutionContextId) -> Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. Returns: 'scriptId' (type: ScriptId) -> Id of the script. 'exceptionDetails' (type: ExceptionDetails) -> Exception details. Description: Compiles expression. """ assert isinstance(expression, (str,) ), "Argument 'expression' must be of type '['str']'. Received type: '%s'" % type( expression) assert isinstance(sourceURL, (str,) ), "Argument 'sourceURL' must be of type '['str']'. Received type: '%s'" % type( sourceURL) assert isinstance(persistScript, (bool,) ), "Argument 'persistScript' must be of type '['bool']'. Received type: '%s'" % type( persistScript) expected = ['executionContextId'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['executionContextId']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('Runtime.compileScript', expression=expression, sourceURL=sourceURL, persistScript= persistScript, **kwargs) return subdom_funcs
[ "def", "Runtime_compileScript", "(", "self", ",", "expression", ",", "sourceURL", ",", "persistScript", ",", "*", "*", "kwargs", ")", ":", "assert", "isinstance", "(", "expression", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'expression' must be of type '[...
Function path: Runtime.compileScript Domain: Runtime Method name: compileScript Parameters: Required arguments: 'expression' (type: string) -> Expression to compile. 'sourceURL' (type: string) -> Source url to be set for the script. 'persistScript' (type: boolean) -> Specifies whether the compiled script should be persisted. Optional arguments: 'executionContextId' (type: ExecutionContextId) -> Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. Returns: 'scriptId' (type: ScriptId) -> Id of the script. 'exceptionDetails' (type: ExceptionDetails) -> Exception details. Description: Compiles expression.
[ "Function", "path", ":", "Runtime", ".", "compileScript", "Domain", ":", "Runtime", "Method", "name", ":", "compileScript", "Parameters", ":", "Required", "arguments", ":", "expression", "(", "type", ":", "string", ")", "-", ">", "Expression", "to", "compile",...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6830-L6866
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Runtime_runScript
def Runtime_runScript(self, scriptId, **kwargs): """ Function path: Runtime.runScript Domain: Runtime Method name: runScript Parameters: Required arguments: 'scriptId' (type: ScriptId) -> Id of the script to run. Optional arguments: 'executionContextId' (type: ExecutionContextId) -> Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. 'objectGroup' (type: string) -> Symbolic group name that can be used to release multiple objects. 'silent' (type: boolean) -> In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. 'includeCommandLineAPI' (type: boolean) -> Determines whether Command Line API should be available during the evaluation. 'returnByValue' (type: boolean) -> Whether the result is expected to be a JSON object which should be sent by value. 'generatePreview' (type: boolean) -> Whether preview should be generated for the result. 'awaitPromise' (type: boolean) -> Whether execution should <code>await</code> for resulting value and return once awaited promise is resolved. Returns: 'result' (type: RemoteObject) -> Run result. 'exceptionDetails' (type: ExceptionDetails) -> Exception details. Description: Runs script with given id in a given context. """ if 'objectGroup' in kwargs: assert isinstance(kwargs['objectGroup'], (str,) ), "Optional argument 'objectGroup' must be of type '['str']'. Received type: '%s'" % type( kwargs['objectGroup']) if 'silent' in kwargs: assert isinstance(kwargs['silent'], (bool,) ), "Optional argument 'silent' must be of type '['bool']'. Received type: '%s'" % type( kwargs['silent']) if 'includeCommandLineAPI' in kwargs: assert isinstance(kwargs['includeCommandLineAPI'], (bool,) ), "Optional argument 'includeCommandLineAPI' must be of type '['bool']'. Received type: '%s'" % type( kwargs['includeCommandLineAPI']) if 'returnByValue' in kwargs: assert isinstance(kwargs['returnByValue'], (bool,) ), "Optional argument 'returnByValue' must be of type '['bool']'. Received type: '%s'" % type( kwargs['returnByValue']) if 'generatePreview' in kwargs: assert isinstance(kwargs['generatePreview'], (bool,) ), "Optional argument 'generatePreview' must be of type '['bool']'. Received type: '%s'" % type( kwargs['generatePreview']) if 'awaitPromise' in kwargs: assert isinstance(kwargs['awaitPromise'], (bool,) ), "Optional argument 'awaitPromise' must be of type '['bool']'. Received type: '%s'" % type( kwargs['awaitPromise']) expected = ['executionContextId', 'objectGroup', 'silent', 'includeCommandLineAPI', 'returnByValue', 'generatePreview', 'awaitPromise'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['executionContextId', 'objectGroup', 'silent', 'includeCommandLineAPI', 'returnByValue', 'generatePreview', 'awaitPromise']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('Runtime.runScript', scriptId= scriptId, **kwargs) return subdom_funcs
python
def Runtime_runScript(self, scriptId, **kwargs): """ Function path: Runtime.runScript Domain: Runtime Method name: runScript Parameters: Required arguments: 'scriptId' (type: ScriptId) -> Id of the script to run. Optional arguments: 'executionContextId' (type: ExecutionContextId) -> Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. 'objectGroup' (type: string) -> Symbolic group name that can be used to release multiple objects. 'silent' (type: boolean) -> In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. 'includeCommandLineAPI' (type: boolean) -> Determines whether Command Line API should be available during the evaluation. 'returnByValue' (type: boolean) -> Whether the result is expected to be a JSON object which should be sent by value. 'generatePreview' (type: boolean) -> Whether preview should be generated for the result. 'awaitPromise' (type: boolean) -> Whether execution should <code>await</code> for resulting value and return once awaited promise is resolved. Returns: 'result' (type: RemoteObject) -> Run result. 'exceptionDetails' (type: ExceptionDetails) -> Exception details. Description: Runs script with given id in a given context. """ if 'objectGroup' in kwargs: assert isinstance(kwargs['objectGroup'], (str,) ), "Optional argument 'objectGroup' must be of type '['str']'. Received type: '%s'" % type( kwargs['objectGroup']) if 'silent' in kwargs: assert isinstance(kwargs['silent'], (bool,) ), "Optional argument 'silent' must be of type '['bool']'. Received type: '%s'" % type( kwargs['silent']) if 'includeCommandLineAPI' in kwargs: assert isinstance(kwargs['includeCommandLineAPI'], (bool,) ), "Optional argument 'includeCommandLineAPI' must be of type '['bool']'. Received type: '%s'" % type( kwargs['includeCommandLineAPI']) if 'returnByValue' in kwargs: assert isinstance(kwargs['returnByValue'], (bool,) ), "Optional argument 'returnByValue' must be of type '['bool']'. Received type: '%s'" % type( kwargs['returnByValue']) if 'generatePreview' in kwargs: assert isinstance(kwargs['generatePreview'], (bool,) ), "Optional argument 'generatePreview' must be of type '['bool']'. Received type: '%s'" % type( kwargs['generatePreview']) if 'awaitPromise' in kwargs: assert isinstance(kwargs['awaitPromise'], (bool,) ), "Optional argument 'awaitPromise' must be of type '['bool']'. Received type: '%s'" % type( kwargs['awaitPromise']) expected = ['executionContextId', 'objectGroup', 'silent', 'includeCommandLineAPI', 'returnByValue', 'generatePreview', 'awaitPromise'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['executionContextId', 'objectGroup', 'silent', 'includeCommandLineAPI', 'returnByValue', 'generatePreview', 'awaitPromise']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('Runtime.runScript', scriptId= scriptId, **kwargs) return subdom_funcs
[ "def", "Runtime_runScript", "(", "self", ",", "scriptId", ",", "*", "*", "kwargs", ")", ":", "if", "'objectGroup'", "in", "kwargs", ":", "assert", "isinstance", "(", "kwargs", "[", "'objectGroup'", "]", ",", "(", "str", ",", ")", ")", ",", "\"Optional ar...
Function path: Runtime.runScript Domain: Runtime Method name: runScript Parameters: Required arguments: 'scriptId' (type: ScriptId) -> Id of the script to run. Optional arguments: 'executionContextId' (type: ExecutionContextId) -> Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. 'objectGroup' (type: string) -> Symbolic group name that can be used to release multiple objects. 'silent' (type: boolean) -> In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides <code>setPauseOnException</code> state. 'includeCommandLineAPI' (type: boolean) -> Determines whether Command Line API should be available during the evaluation. 'returnByValue' (type: boolean) -> Whether the result is expected to be a JSON object which should be sent by value. 'generatePreview' (type: boolean) -> Whether preview should be generated for the result. 'awaitPromise' (type: boolean) -> Whether execution should <code>await</code> for resulting value and return once awaited promise is resolved. Returns: 'result' (type: RemoteObject) -> Run result. 'exceptionDetails' (type: ExceptionDetails) -> Exception details. Description: Runs script with given id in a given context.
[ "Function", "path", ":", "Runtime", ".", "runScript", "Domain", ":", "Runtime", "Method", "name", ":", "runScript", "Parameters", ":", "Required", "arguments", ":", "scriptId", "(", "type", ":", "ScriptId", ")", "-", ">", "Id", "of", "the", "script", "to",...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6868-L6923
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Debugger_setBreakpointsActive
def Debugger_setBreakpointsActive(self, active): """ Function path: Debugger.setBreakpointsActive Domain: Debugger Method name: setBreakpointsActive Parameters: Required arguments: 'active' (type: boolean) -> New value for breakpoints active state. No return value. Description: Activates / deactivates all breakpoints on the page. """ assert isinstance(active, (bool,) ), "Argument 'active' must be of type '['bool']'. Received type: '%s'" % type( active) subdom_funcs = self.synchronous_command('Debugger.setBreakpointsActive', active=active) return subdom_funcs
python
def Debugger_setBreakpointsActive(self, active): """ Function path: Debugger.setBreakpointsActive Domain: Debugger Method name: setBreakpointsActive Parameters: Required arguments: 'active' (type: boolean) -> New value for breakpoints active state. No return value. Description: Activates / deactivates all breakpoints on the page. """ assert isinstance(active, (bool,) ), "Argument 'active' must be of type '['bool']'. Received type: '%s'" % type( active) subdom_funcs = self.synchronous_command('Debugger.setBreakpointsActive', active=active) return subdom_funcs
[ "def", "Debugger_setBreakpointsActive", "(", "self", ",", "active", ")", ":", "assert", "isinstance", "(", "active", ",", "(", "bool", ",", ")", ")", ",", "\"Argument 'active' must be of type '['bool']'. Received type: '%s'\"", "%", "type", "(", "active", ")", "subd...
Function path: Debugger.setBreakpointsActive Domain: Debugger Method name: setBreakpointsActive Parameters: Required arguments: 'active' (type: boolean) -> New value for breakpoints active state. No return value. Description: Activates / deactivates all breakpoints on the page.
[ "Function", "path", ":", "Debugger", ".", "setBreakpointsActive", "Domain", ":", "Debugger", "Method", "name", ":", "setBreakpointsActive", "Parameters", ":", "Required", "arguments", ":", "active", "(", "type", ":", "boolean", ")", "-", ">", "New", "value", "...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6970-L6988
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Debugger_setSkipAllPauses
def Debugger_setSkipAllPauses(self, skip): """ Function path: Debugger.setSkipAllPauses Domain: Debugger Method name: setSkipAllPauses Parameters: Required arguments: 'skip' (type: boolean) -> New value for skip pauses state. No return value. Description: Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). """ assert isinstance(skip, (bool,) ), "Argument 'skip' must be of type '['bool']'. Received type: '%s'" % type( skip) subdom_funcs = self.synchronous_command('Debugger.setSkipAllPauses', skip =skip) return subdom_funcs
python
def Debugger_setSkipAllPauses(self, skip): """ Function path: Debugger.setSkipAllPauses Domain: Debugger Method name: setSkipAllPauses Parameters: Required arguments: 'skip' (type: boolean) -> New value for skip pauses state. No return value. Description: Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). """ assert isinstance(skip, (bool,) ), "Argument 'skip' must be of type '['bool']'. Received type: '%s'" % type( skip) subdom_funcs = self.synchronous_command('Debugger.setSkipAllPauses', skip =skip) return subdom_funcs
[ "def", "Debugger_setSkipAllPauses", "(", "self", ",", "skip", ")", ":", "assert", "isinstance", "(", "skip", ",", "(", "bool", ",", ")", ")", ",", "\"Argument 'skip' must be of type '['bool']'. Received type: '%s'\"", "%", "type", "(", "skip", ")", "subdom_funcs", ...
Function path: Debugger.setSkipAllPauses Domain: Debugger Method name: setSkipAllPauses Parameters: Required arguments: 'skip' (type: boolean) -> New value for skip pauses state. No return value. Description: Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc).
[ "Function", "path", ":", "Debugger", ".", "setSkipAllPauses", "Domain", ":", "Debugger", "Method", "name", ":", "setSkipAllPauses", "Parameters", ":", "Required", "arguments", ":", "skip", "(", "type", ":", "boolean", ")", "-", ">", "New", "value", "for", "s...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L6990-L7008
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Debugger_setScriptSource
def Debugger_setScriptSource(self, scriptId, scriptSource, **kwargs): """ Function path: Debugger.setScriptSource Domain: Debugger Method name: setScriptSource Parameters: Required arguments: 'scriptId' (type: Runtime.ScriptId) -> Id of the script to edit. 'scriptSource' (type: string) -> New content of the script. Optional arguments: 'dryRun' (type: boolean) -> If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. Returns: 'callFrames' (type: array) -> New stack trace in case editing has happened while VM was stopped. 'stackChanged' (type: boolean) -> Whether current call stack was modified after applying the changes. 'asyncStackTrace' (type: Runtime.StackTrace) -> Async stack trace, if any. 'exceptionDetails' (type: Runtime.ExceptionDetails) -> Exception details if any. Description: Edits JavaScript source live. """ assert isinstance(scriptSource, (str,) ), "Argument 'scriptSource' must be of type '['str']'. Received type: '%s'" % type( scriptSource) if 'dryRun' in kwargs: assert isinstance(kwargs['dryRun'], (bool,) ), "Optional argument 'dryRun' must be of type '['bool']'. Received type: '%s'" % type( kwargs['dryRun']) expected = ['dryRun'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['dryRun']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('Debugger.setScriptSource', scriptId=scriptId, scriptSource=scriptSource, **kwargs) return subdom_funcs
python
def Debugger_setScriptSource(self, scriptId, scriptSource, **kwargs): """ Function path: Debugger.setScriptSource Domain: Debugger Method name: setScriptSource Parameters: Required arguments: 'scriptId' (type: Runtime.ScriptId) -> Id of the script to edit. 'scriptSource' (type: string) -> New content of the script. Optional arguments: 'dryRun' (type: boolean) -> If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. Returns: 'callFrames' (type: array) -> New stack trace in case editing has happened while VM was stopped. 'stackChanged' (type: boolean) -> Whether current call stack was modified after applying the changes. 'asyncStackTrace' (type: Runtime.StackTrace) -> Async stack trace, if any. 'exceptionDetails' (type: Runtime.ExceptionDetails) -> Exception details if any. Description: Edits JavaScript source live. """ assert isinstance(scriptSource, (str,) ), "Argument 'scriptSource' must be of type '['str']'. Received type: '%s'" % type( scriptSource) if 'dryRun' in kwargs: assert isinstance(kwargs['dryRun'], (bool,) ), "Optional argument 'dryRun' must be of type '['bool']'. Received type: '%s'" % type( kwargs['dryRun']) expected = ['dryRun'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['dryRun']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('Debugger.setScriptSource', scriptId=scriptId, scriptSource=scriptSource, **kwargs) return subdom_funcs
[ "def", "Debugger_setScriptSource", "(", "self", ",", "scriptId", ",", "scriptSource", ",", "*", "*", "kwargs", ")", ":", "assert", "isinstance", "(", "scriptSource", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'scriptSource' must be of type '['str']'. Received ...
Function path: Debugger.setScriptSource Domain: Debugger Method name: setScriptSource Parameters: Required arguments: 'scriptId' (type: Runtime.ScriptId) -> Id of the script to edit. 'scriptSource' (type: string) -> New content of the script. Optional arguments: 'dryRun' (type: boolean) -> If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. Returns: 'callFrames' (type: array) -> New stack trace in case editing has happened while VM was stopped. 'stackChanged' (type: boolean) -> Whether current call stack was modified after applying the changes. 'asyncStackTrace' (type: Runtime.StackTrace) -> Async stack trace, if any. 'exceptionDetails' (type: Runtime.ExceptionDetails) -> Exception details if any. Description: Edits JavaScript source live.
[ "Function", "path", ":", "Debugger", ".", "setScriptSource", "Domain", ":", "Debugger", "Method", "name", ":", "setScriptSource", "Parameters", ":", "Required", "arguments", ":", "scriptId", "(", "type", ":", "Runtime", ".", "ScriptId", ")", "-", ">", "Id", ...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L7280-L7313
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Debugger_setPauseOnExceptions
def Debugger_setPauseOnExceptions(self, state): """ Function path: Debugger.setPauseOnExceptions Domain: Debugger Method name: setPauseOnExceptions Parameters: Required arguments: 'state' (type: string) -> Pause on exceptions mode. No return value. Description: Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is <code>none</code>. """ assert isinstance(state, (str,) ), "Argument 'state' must be of type '['str']'. Received type: '%s'" % type( state) subdom_funcs = self.synchronous_command('Debugger.setPauseOnExceptions', state=state) return subdom_funcs
python
def Debugger_setPauseOnExceptions(self, state): """ Function path: Debugger.setPauseOnExceptions Domain: Debugger Method name: setPauseOnExceptions Parameters: Required arguments: 'state' (type: string) -> Pause on exceptions mode. No return value. Description: Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is <code>none</code>. """ assert isinstance(state, (str,) ), "Argument 'state' must be of type '['str']'. Received type: '%s'" % type( state) subdom_funcs = self.synchronous_command('Debugger.setPauseOnExceptions', state=state) return subdom_funcs
[ "def", "Debugger_setPauseOnExceptions", "(", "self", ",", "state", ")", ":", "assert", "isinstance", "(", "state", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'state' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "state", ")", "subdom_fun...
Function path: Debugger.setPauseOnExceptions Domain: Debugger Method name: setPauseOnExceptions Parameters: Required arguments: 'state' (type: string) -> Pause on exceptions mode. No return value. Description: Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is <code>none</code>.
[ "Function", "path", ":", "Debugger", ".", "setPauseOnExceptions", "Domain", ":", "Debugger", "Method", "name", ":", "setPauseOnExceptions", "Parameters", ":", "Required", "arguments", ":", "state", "(", "type", ":", "string", ")", "-", ">", "Pause", "on", "exc...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L7352-L7370
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Debugger_setVariableValue
def Debugger_setVariableValue(self, scopeNumber, variableName, newValue, callFrameId): """ Function path: Debugger.setVariableValue Domain: Debugger Method name: setVariableValue Parameters: Required arguments: 'scopeNumber' (type: integer) -> 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. 'variableName' (type: string) -> Variable name. 'newValue' (type: Runtime.CallArgument) -> New variable value. 'callFrameId' (type: CallFrameId) -> Id of callframe that holds variable. No return value. Description: Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. """ assert isinstance(scopeNumber, (int,) ), "Argument 'scopeNumber' must be of type '['int']'. Received type: '%s'" % type( scopeNumber) assert isinstance(variableName, (str,) ), "Argument 'variableName' must be of type '['str']'. Received type: '%s'" % type( variableName) subdom_funcs = self.synchronous_command('Debugger.setVariableValue', scopeNumber=scopeNumber, variableName=variableName, newValue=newValue, callFrameId=callFrameId) return subdom_funcs
python
def Debugger_setVariableValue(self, scopeNumber, variableName, newValue, callFrameId): """ Function path: Debugger.setVariableValue Domain: Debugger Method name: setVariableValue Parameters: Required arguments: 'scopeNumber' (type: integer) -> 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. 'variableName' (type: string) -> Variable name. 'newValue' (type: Runtime.CallArgument) -> New variable value. 'callFrameId' (type: CallFrameId) -> Id of callframe that holds variable. No return value. Description: Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. """ assert isinstance(scopeNumber, (int,) ), "Argument 'scopeNumber' must be of type '['int']'. Received type: '%s'" % type( scopeNumber) assert isinstance(variableName, (str,) ), "Argument 'variableName' must be of type '['str']'. Received type: '%s'" % type( variableName) subdom_funcs = self.synchronous_command('Debugger.setVariableValue', scopeNumber=scopeNumber, variableName=variableName, newValue=newValue, callFrameId=callFrameId) return subdom_funcs
[ "def", "Debugger_setVariableValue", "(", "self", ",", "scopeNumber", ",", "variableName", ",", "newValue", ",", "callFrameId", ")", ":", "assert", "isinstance", "(", "scopeNumber", ",", "(", "int", ",", ")", ")", ",", "\"Argument 'scopeNumber' must be of type '['int...
Function path: Debugger.setVariableValue Domain: Debugger Method name: setVariableValue Parameters: Required arguments: 'scopeNumber' (type: integer) -> 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. 'variableName' (type: string) -> Variable name. 'newValue' (type: Runtime.CallArgument) -> New variable value. 'callFrameId' (type: CallFrameId) -> Id of callframe that holds variable. No return value. Description: Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually.
[ "Function", "path", ":", "Debugger", ".", "setVariableValue", "Domain", ":", "Debugger", "Method", "name", ":", "setVariableValue", "Parameters", ":", "Required", "arguments", ":", "scopeNumber", "(", "type", ":", "integer", ")", "-", ">", "0", "-", "based", ...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L7431-L7457
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Debugger_setAsyncCallStackDepth
def Debugger_setAsyncCallStackDepth(self, maxDepth): """ Function path: Debugger.setAsyncCallStackDepth Domain: Debugger Method name: setAsyncCallStackDepth Parameters: Required arguments: 'maxDepth' (type: integer) -> Maximum depth of async call stacks. Setting to <code>0</code> will effectively disable collecting async call stacks (default). No return value. Description: Enables or disables async call stacks tracking. """ assert isinstance(maxDepth, (int,) ), "Argument 'maxDepth' must be of type '['int']'. Received type: '%s'" % type( maxDepth) subdom_funcs = self.synchronous_command('Debugger.setAsyncCallStackDepth', maxDepth=maxDepth) return subdom_funcs
python
def Debugger_setAsyncCallStackDepth(self, maxDepth): """ Function path: Debugger.setAsyncCallStackDepth Domain: Debugger Method name: setAsyncCallStackDepth Parameters: Required arguments: 'maxDepth' (type: integer) -> Maximum depth of async call stacks. Setting to <code>0</code> will effectively disable collecting async call stacks (default). No return value. Description: Enables or disables async call stacks tracking. """ assert isinstance(maxDepth, (int,) ), "Argument 'maxDepth' must be of type '['int']'. Received type: '%s'" % type( maxDepth) subdom_funcs = self.synchronous_command('Debugger.setAsyncCallStackDepth', maxDepth=maxDepth) return subdom_funcs
[ "def", "Debugger_setAsyncCallStackDepth", "(", "self", ",", "maxDepth", ")", ":", "assert", "isinstance", "(", "maxDepth", ",", "(", "int", ",", ")", ")", ",", "\"Argument 'maxDepth' must be of type '['int']'. Received type: '%s'\"", "%", "type", "(", "maxDepth", ")",...
Function path: Debugger.setAsyncCallStackDepth Domain: Debugger Method name: setAsyncCallStackDepth Parameters: Required arguments: 'maxDepth' (type: integer) -> Maximum depth of async call stacks. Setting to <code>0</code> will effectively disable collecting async call stacks (default). No return value. Description: Enables or disables async call stacks tracking.
[ "Function", "path", ":", "Debugger", ".", "setAsyncCallStackDepth", "Domain", ":", "Debugger", "Method", "name", ":", "setAsyncCallStackDepth", "Parameters", ":", "Required", "arguments", ":", "maxDepth", "(", "type", ":", "integer", ")", "-", ">", "Maximum", "d...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L7459-L7477
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Debugger_setBlackboxPatterns
def Debugger_setBlackboxPatterns(self, patterns): """ Function path: Debugger.setBlackboxPatterns Domain: Debugger Method name: setBlackboxPatterns WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'patterns' (type: array) -> Array of regexps that will be used to check script url for blackbox state. No return value. Description: Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. """ assert isinstance(patterns, (list, tuple) ), "Argument 'patterns' must be of type '['list', 'tuple']'. Received type: '%s'" % type( patterns) subdom_funcs = self.synchronous_command('Debugger.setBlackboxPatterns', patterns=patterns) return subdom_funcs
python
def Debugger_setBlackboxPatterns(self, patterns): """ Function path: Debugger.setBlackboxPatterns Domain: Debugger Method name: setBlackboxPatterns WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'patterns' (type: array) -> Array of regexps that will be used to check script url for blackbox state. No return value. Description: Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. """ assert isinstance(patterns, (list, tuple) ), "Argument 'patterns' must be of type '['list', 'tuple']'. Received type: '%s'" % type( patterns) subdom_funcs = self.synchronous_command('Debugger.setBlackboxPatterns', patterns=patterns) return subdom_funcs
[ "def", "Debugger_setBlackboxPatterns", "(", "self", ",", "patterns", ")", ":", "assert", "isinstance", "(", "patterns", ",", "(", "list", ",", "tuple", ")", ")", ",", "\"Argument 'patterns' must be of type '['list', 'tuple']'. Received type: '%s'\"", "%", "type", "(", ...
Function path: Debugger.setBlackboxPatterns Domain: Debugger Method name: setBlackboxPatterns WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'patterns' (type: array) -> Array of regexps that will be used to check script url for blackbox state. No return value. Description: Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful.
[ "Function", "path", ":", "Debugger", ".", "setBlackboxPatterns", "Domain", ":", "Debugger", "Method", "name", ":", "setBlackboxPatterns", "WARNING", ":", "This", "function", "is", "marked", "Experimental", "!", "Parameters", ":", "Required", "arguments", ":", "pat...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L7479-L7499
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Debugger_setBlackboxedRanges
def Debugger_setBlackboxedRanges(self, scriptId, positions): """ Function path: Debugger.setBlackboxedRanges Domain: Debugger Method name: setBlackboxedRanges WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'scriptId' (type: Runtime.ScriptId) -> Id of the script. 'positions' (type: array) -> No description No return value. Description: Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. """ assert isinstance(positions, (list, tuple) ), "Argument 'positions' must be of type '['list', 'tuple']'. Received type: '%s'" % type( positions) subdom_funcs = self.synchronous_command('Debugger.setBlackboxedRanges', scriptId=scriptId, positions=positions) return subdom_funcs
python
def Debugger_setBlackboxedRanges(self, scriptId, positions): """ Function path: Debugger.setBlackboxedRanges Domain: Debugger Method name: setBlackboxedRanges WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'scriptId' (type: Runtime.ScriptId) -> Id of the script. 'positions' (type: array) -> No description No return value. Description: Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. """ assert isinstance(positions, (list, tuple) ), "Argument 'positions' must be of type '['list', 'tuple']'. Received type: '%s'" % type( positions) subdom_funcs = self.synchronous_command('Debugger.setBlackboxedRanges', scriptId=scriptId, positions=positions) return subdom_funcs
[ "def", "Debugger_setBlackboxedRanges", "(", "self", ",", "scriptId", ",", "positions", ")", ":", "assert", "isinstance", "(", "positions", ",", "(", "list", ",", "tuple", ")", ")", ",", "\"Argument 'positions' must be of type '['list', 'tuple']'. Received type: '%s'\"", ...
Function path: Debugger.setBlackboxedRanges Domain: Debugger Method name: setBlackboxedRanges WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'scriptId' (type: Runtime.ScriptId) -> Id of the script. 'positions' (type: array) -> No description No return value. Description: Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted.
[ "Function", "path", ":", "Debugger", ".", "setBlackboxedRanges", "Domain", ":", "Debugger", "Method", "name", ":", "setBlackboxedRanges", "WARNING", ":", "This", "function", "is", "marked", "Experimental", "!", "Parameters", ":", "Required", "arguments", ":", "scr...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L7501-L7522
train
fake-name/ChromeController
ChromeController/Generator/Generated.py
ChromeRemoteDebugInterface.Profiler_setSamplingInterval
def Profiler_setSamplingInterval(self, interval): """ Function path: Profiler.setSamplingInterval Domain: Profiler Method name: setSamplingInterval Parameters: Required arguments: 'interval' (type: integer) -> New sampling interval in microseconds. No return value. Description: Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. """ assert isinstance(interval, (int,) ), "Argument 'interval' must be of type '['int']'. Received type: '%s'" % type( interval) subdom_funcs = self.synchronous_command('Profiler.setSamplingInterval', interval=interval) return subdom_funcs
python
def Profiler_setSamplingInterval(self, interval): """ Function path: Profiler.setSamplingInterval Domain: Profiler Method name: setSamplingInterval Parameters: Required arguments: 'interval' (type: integer) -> New sampling interval in microseconds. No return value. Description: Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. """ assert isinstance(interval, (int,) ), "Argument 'interval' must be of type '['int']'. Received type: '%s'" % type( interval) subdom_funcs = self.synchronous_command('Profiler.setSamplingInterval', interval=interval) return subdom_funcs
[ "def", "Profiler_setSamplingInterval", "(", "self", ",", "interval", ")", ":", "assert", "isinstance", "(", "interval", ",", "(", "int", ",", ")", ")", ",", "\"Argument 'interval' must be of type '['int']'. Received type: '%s'\"", "%", "type", "(", "interval", ")", ...
Function path: Profiler.setSamplingInterval Domain: Profiler Method name: setSamplingInterval Parameters: Required arguments: 'interval' (type: integer) -> New sampling interval in microseconds. No return value. Description: Changes CPU profiler sampling interval. Must be called before CPU profiles recording started.
[ "Function", "path", ":", "Profiler", ".", "setSamplingInterval", "Domain", ":", "Profiler", "Method", "name", ":", "setSamplingInterval", "Parameters", ":", "Required", "arguments", ":", "interval", "(", "type", ":", "integer", ")", "-", ">", "New", "sampling", ...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L7587-L7605
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.update_headers
def update_headers(self, header_args): ''' Given a set of headers, update both the user-agent and additional headers for the remote browser. header_args must be a dict. Keys are the names of the corresponding HTTP header. return value is a 2-tuple of the results of the user-agent update, as well as the extra headers update. If no 'User-Agent' key is present in the new headers, the first item in the tuple will be None ''' assert isinstance(header_args, dict), "header_args must be a dict, passed type was %s" \ % (type(header_args), ) ua = header_args.pop('User-Agent', None) ret_1 = None if ua: ret_1 = self.Network_setUserAgentOverride(userAgent=ua) ret_2 = self.Network_setExtraHTTPHeaders(headers = header_args) return (ret_1, ret_2)
python
def update_headers(self, header_args): ''' Given a set of headers, update both the user-agent and additional headers for the remote browser. header_args must be a dict. Keys are the names of the corresponding HTTP header. return value is a 2-tuple of the results of the user-agent update, as well as the extra headers update. If no 'User-Agent' key is present in the new headers, the first item in the tuple will be None ''' assert isinstance(header_args, dict), "header_args must be a dict, passed type was %s" \ % (type(header_args), ) ua = header_args.pop('User-Agent', None) ret_1 = None if ua: ret_1 = self.Network_setUserAgentOverride(userAgent=ua) ret_2 = self.Network_setExtraHTTPHeaders(headers = header_args) return (ret_1, ret_2)
[ "def", "update_headers", "(", "self", ",", "header_args", ")", ":", "assert", "isinstance", "(", "header_args", ",", "dict", ")", ",", "\"header_args must be a dict, passed type was %s\"", "%", "(", "type", "(", "header_args", ")", ",", ")", "ua", "=", "header_a...
Given a set of headers, update both the user-agent and additional headers for the remote browser. header_args must be a dict. Keys are the names of the corresponding HTTP header. return value is a 2-tuple of the results of the user-agent update, as well as the extra headers update. If no 'User-Agent' key is present in the new headers, the first item in the tuple will be None
[ "Given", "a", "set", "of", "headers", "update", "both", "the", "user", "-", "agent", "and", "additional", "headers", "for", "the", "remote", "browser", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L96-L121
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.get_cookies
def get_cookies(self): ''' Retreive the cookies from the remote browser. Return value is a list of http.cookiejar.Cookie() instances. These can be directly used with the various http.cookiejar.XXXCookieJar cookie management classes. ''' ret = self.Network_getAllCookies() assert 'result' in ret, "No return value in function response!" assert 'cookies' in ret['result'], "No 'cookies' key in function response" cookies = [] for raw_cookie in ret['result']['cookies']: # Chromium seems to support the following key values for the cookie dict: # "name" # "value" # "domain" # "path" # "expires" # "httpOnly" # "session" # "secure" # # This seems supported by the fact that the underlying chromium cookie implementation has # the following members: # std::string name_; # std::string value_; # std::string domain_; # std::string path_; # base::Time creation_date_; # base::Time expiry_date_; # base::Time last_access_date_; # bool secure_; # bool httponly_; # CookieSameSite same_site_; # CookiePriority priority_; # # See chromium/net/cookies/canonical_cookie.h for more. # # I suspect the python cookie implementation is derived exactly from the standard, while the # chromium implementation is more of a practically derived structure. # Network.setCookie baked_cookie = http.cookiejar.Cookie( # We assume V0 cookies, principally because I don't think I've /ever/ actually encountered a V1 cookie. # Chromium doesn't seem to specify it. version = 0, name = raw_cookie['name'], value = raw_cookie['value'], port = None, port_specified = False, domain = raw_cookie['domain'], domain_specified = True, domain_initial_dot = False, path = raw_cookie['path'], path_specified = False, secure = raw_cookie['secure'], expires = raw_cookie['expires'], discard = raw_cookie['session'], comment = None, comment_url = None, rest = {"httponly":"%s" % raw_cookie['httpOnly']}, rfc2109 = False ) cookies.append(baked_cookie) return cookies
python
def get_cookies(self): ''' Retreive the cookies from the remote browser. Return value is a list of http.cookiejar.Cookie() instances. These can be directly used with the various http.cookiejar.XXXCookieJar cookie management classes. ''' ret = self.Network_getAllCookies() assert 'result' in ret, "No return value in function response!" assert 'cookies' in ret['result'], "No 'cookies' key in function response" cookies = [] for raw_cookie in ret['result']['cookies']: # Chromium seems to support the following key values for the cookie dict: # "name" # "value" # "domain" # "path" # "expires" # "httpOnly" # "session" # "secure" # # This seems supported by the fact that the underlying chromium cookie implementation has # the following members: # std::string name_; # std::string value_; # std::string domain_; # std::string path_; # base::Time creation_date_; # base::Time expiry_date_; # base::Time last_access_date_; # bool secure_; # bool httponly_; # CookieSameSite same_site_; # CookiePriority priority_; # # See chromium/net/cookies/canonical_cookie.h for more. # # I suspect the python cookie implementation is derived exactly from the standard, while the # chromium implementation is more of a practically derived structure. # Network.setCookie baked_cookie = http.cookiejar.Cookie( # We assume V0 cookies, principally because I don't think I've /ever/ actually encountered a V1 cookie. # Chromium doesn't seem to specify it. version = 0, name = raw_cookie['name'], value = raw_cookie['value'], port = None, port_specified = False, domain = raw_cookie['domain'], domain_specified = True, domain_initial_dot = False, path = raw_cookie['path'], path_specified = False, secure = raw_cookie['secure'], expires = raw_cookie['expires'], discard = raw_cookie['session'], comment = None, comment_url = None, rest = {"httponly":"%s" % raw_cookie['httpOnly']}, rfc2109 = False ) cookies.append(baked_cookie) return cookies
[ "def", "get_cookies", "(", "self", ")", ":", "ret", "=", "self", ".", "Network_getAllCookies", "(", ")", "assert", "'result'", "in", "ret", ",", "\"No return value in function response!\"", "assert", "'cookies'", "in", "ret", "[", "'result'", "]", ",", "\"No 'co...
Retreive the cookies from the remote browser. Return value is a list of http.cookiejar.Cookie() instances. These can be directly used with the various http.cookiejar.XXXCookieJar cookie management classes.
[ "Retreive", "the", "cookies", "from", "the", "remote", "browser", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L165-L236
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.set_cookie
def set_cookie(self, cookie): ''' Add a cookie to the remote chromium instance. Passed value `cookie` must be an instance of `http.cookiejar.Cookie()`. ''' # Function path: Network.setCookie # Domain: Network # Method name: setCookie # WARNING: This function is marked 'Experimental'! # Parameters: # Required arguments: # 'url' (type: string) -> The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. # 'name' (type: string) -> The name of the cookie. # 'value' (type: string) -> The value of the cookie. # Optional arguments: # 'domain' (type: string) -> If omitted, the cookie becomes a host-only cookie. # 'path' (type: string) -> Defaults to the path portion of the url parameter. # 'secure' (type: boolean) -> Defaults ot false. # 'httpOnly' (type: boolean) -> Defaults to false. # 'sameSite' (type: CookieSameSite) -> Defaults to browser default behavior. # 'expirationDate' (type: Timestamp) -> If omitted, the cookie becomes a session cookie. # Returns: # 'success' (type: boolean) -> True if successfully set cookie. # Description: Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. assert isinstance(cookie, http.cookiejar.Cookie), 'The value passed to `set_cookie` must be an instance of http.cookiejar.Cookie().' + \ ' Passed: %s ("%s").' % (type(cookie), cookie) # Yeah, the cookielib stores this attribute as a string, despite it containing a # boolean value. No idea why. is_http_only = str(cookie.get_nonstandard_attr('httponly', 'False')).lower() == "true" # I'm unclear what the "url" field is actually for. A cookie only needs the domain and # path component to be fully defined. Considering the API apparently allows the domain and # path parameters to be unset, I think it forms a partially redundant, with some # strange interactions with mode-changing between host-only and more general # cookies depending on what's set where. # Anyways, given we need a URL for the API to work properly, we produce a fake # host url by building it out of the relevant cookie properties. fake_url = urllib.parse.urlunsplit(( "http" if is_http_only else "https", # Scheme cookie.domain, # netloc cookie.path, # path '', # query '', # fragment )) params = { 'url' : fake_url, 'name' : cookie.name, 'value' : cookie.value if cookie.value else "", 'domain' : cookie.domain, 'path' : cookie.path, 'secure' : cookie.secure, 'expires' : float(cookie.expires) if cookie.expires else float(2**32), 'httpOnly' : is_http_only, # The "sameSite" flag appears to be a chromium-only extension for controlling # cookie sending in non-first-party contexts. See: # https://bugs.chromium.org/p/chromium/issues/detail?id=459154 # Anyways, we just use the default here, whatever that is. # sameSite = cookie.xxx } ret = self.Network_setCookie(**params) return ret
python
def set_cookie(self, cookie): ''' Add a cookie to the remote chromium instance. Passed value `cookie` must be an instance of `http.cookiejar.Cookie()`. ''' # Function path: Network.setCookie # Domain: Network # Method name: setCookie # WARNING: This function is marked 'Experimental'! # Parameters: # Required arguments: # 'url' (type: string) -> The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. # 'name' (type: string) -> The name of the cookie. # 'value' (type: string) -> The value of the cookie. # Optional arguments: # 'domain' (type: string) -> If omitted, the cookie becomes a host-only cookie. # 'path' (type: string) -> Defaults to the path portion of the url parameter. # 'secure' (type: boolean) -> Defaults ot false. # 'httpOnly' (type: boolean) -> Defaults to false. # 'sameSite' (type: CookieSameSite) -> Defaults to browser default behavior. # 'expirationDate' (type: Timestamp) -> If omitted, the cookie becomes a session cookie. # Returns: # 'success' (type: boolean) -> True if successfully set cookie. # Description: Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. assert isinstance(cookie, http.cookiejar.Cookie), 'The value passed to `set_cookie` must be an instance of http.cookiejar.Cookie().' + \ ' Passed: %s ("%s").' % (type(cookie), cookie) # Yeah, the cookielib stores this attribute as a string, despite it containing a # boolean value. No idea why. is_http_only = str(cookie.get_nonstandard_attr('httponly', 'False')).lower() == "true" # I'm unclear what the "url" field is actually for. A cookie only needs the domain and # path component to be fully defined. Considering the API apparently allows the domain and # path parameters to be unset, I think it forms a partially redundant, with some # strange interactions with mode-changing between host-only and more general # cookies depending on what's set where. # Anyways, given we need a URL for the API to work properly, we produce a fake # host url by building it out of the relevant cookie properties. fake_url = urllib.parse.urlunsplit(( "http" if is_http_only else "https", # Scheme cookie.domain, # netloc cookie.path, # path '', # query '', # fragment )) params = { 'url' : fake_url, 'name' : cookie.name, 'value' : cookie.value if cookie.value else "", 'domain' : cookie.domain, 'path' : cookie.path, 'secure' : cookie.secure, 'expires' : float(cookie.expires) if cookie.expires else float(2**32), 'httpOnly' : is_http_only, # The "sameSite" flag appears to be a chromium-only extension for controlling # cookie sending in non-first-party contexts. See: # https://bugs.chromium.org/p/chromium/issues/detail?id=459154 # Anyways, we just use the default here, whatever that is. # sameSite = cookie.xxx } ret = self.Network_setCookie(**params) return ret
[ "def", "set_cookie", "(", "self", ",", "cookie", ")", ":", "# Function path: Network.setCookie", "# Domain: Network", "# Method name: setCookie", "# WARNING: This function is marked 'Experimental'!", "# Parameters:", "# Required arguments:", "# 'url' (type: string...
Add a cookie to the remote chromium instance. Passed value `cookie` must be an instance of `http.cookiejar.Cookie()`.
[ "Add", "a", "cookie", "to", "the", "remote", "chromium", "instance", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L238-L310
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.get_current_url
def get_current_url(self): ''' Probe the remote session for the current window URL. This is primarily used to do things like unwrap redirects, or circumvent outbound url wrappers. ''' res = self.Page_getNavigationHistory() assert 'result' in res assert 'currentIndex' in res['result'] assert 'entries' in res['result'] return res['result']['entries'][res['result']['currentIndex']]['url']
python
def get_current_url(self): ''' Probe the remote session for the current window URL. This is primarily used to do things like unwrap redirects, or circumvent outbound url wrappers. ''' res = self.Page_getNavigationHistory() assert 'result' in res assert 'currentIndex' in res['result'] assert 'entries' in res['result'] return res['result']['entries'][res['result']['currentIndex']]['url']
[ "def", "get_current_url", "(", "self", ")", ":", "res", "=", "self", ".", "Page_getNavigationHistory", "(", ")", "assert", "'result'", "in", "res", "assert", "'currentIndex'", "in", "res", "[", "'result'", "]", "assert", "'entries'", "in", "res", "[", "'resu...
Probe the remote session for the current window URL. This is primarily used to do things like unwrap redirects, or circumvent outbound url wrappers.
[ "Probe", "the", "remote", "session", "for", "the", "current", "window", "URL", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L337-L350
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.get_page_url_title
def get_page_url_title(self): ''' Get the title and current url from the remote session. Return is a 2-tuple: (page_title, page_url). ''' cr_tab_id = self.transport._get_cr_tab_meta_for_key(self.tab_id)['id'] targets = self.Target_getTargets() assert 'result' in targets assert 'targetInfos' in targets['result'] for tgt in targets['result']['targetInfos']: if tgt['targetId'] == cr_tab_id: # { # 'title': 'Page Title 1', # 'targetId': '9d2c503c-e39e-42cc-b950-96db073918ee', # 'attached': True, # 'url': 'http://localhost:47181/with_title_1', # 'type': 'page' # } title = tgt['title'] cur_url = tgt['url'] return title, cur_url
python
def get_page_url_title(self): ''' Get the title and current url from the remote session. Return is a 2-tuple: (page_title, page_url). ''' cr_tab_id = self.transport._get_cr_tab_meta_for_key(self.tab_id)['id'] targets = self.Target_getTargets() assert 'result' in targets assert 'targetInfos' in targets['result'] for tgt in targets['result']['targetInfos']: if tgt['targetId'] == cr_tab_id: # { # 'title': 'Page Title 1', # 'targetId': '9d2c503c-e39e-42cc-b950-96db073918ee', # 'attached': True, # 'url': 'http://localhost:47181/with_title_1', # 'type': 'page' # } title = tgt['title'] cur_url = tgt['url'] return title, cur_url
[ "def", "get_page_url_title", "(", "self", ")", ":", "cr_tab_id", "=", "self", ".", "transport", ".", "_get_cr_tab_meta_for_key", "(", "self", ".", "tab_id", ")", "[", "'id'", "]", "targets", "=", "self", ".", "Target_getTargets", "(", ")", "assert", "'result...
Get the title and current url from the remote session. Return is a 2-tuple: (page_title, page_url).
[ "Get", "the", "title", "and", "current", "url", "from", "the", "remote", "session", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L352-L378
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.execute_javascript
def execute_javascript(self, *args, **kwargs): ''' Execute a javascript string in the context of the browser tab. ''' ret = self.__exec_js(*args, **kwargs) return ret
python
def execute_javascript(self, *args, **kwargs): ''' Execute a javascript string in the context of the browser tab. ''' ret = self.__exec_js(*args, **kwargs) return ret
[ "def", "execute_javascript", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "self", ".", "__exec_js", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "ret" ]
Execute a javascript string in the context of the browser tab.
[ "Execute", "a", "javascript", "string", "in", "the", "context", "of", "the", "browser", "tab", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L400-L406
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.find_element
def find_element(self, search): ''' DOM_performSearch(self, query, includeUserAgentShadowDOM) Python Function: DOM_performSearch Domain: DOM Method name: performSearch WARNING: This function is marked 'Experimental'! Parameters: 'query' (type: string) -> Plain text or query selector or XPath search query. 'includeUserAgentShadowDOM' (type: boolean) -> True to search in user agent shadow DOM. Returns: 'searchId' (type: string) -> Unique search session identifier. 'resultCount' (type: integer) -> Number of search results. Description: Searches for a given string in the DOM tree. Use <code>getSearchResults</code> to access search results or <code>cancelSearch</code> to end this search session. Python Function: DOM_getSearchResults Domain: DOM Method name: getSearchResults WARNING: This function is marked 'Experimental'! Parameters: 'searchId' (type: string) -> Unique search session identifier. 'fromIndex' (type: integer) -> Start index of the search result to be returned. 'toIndex' (type: integer) -> End index of the search result to be returned. Returns: 'nodeIds' (type: array) -> Ids of the search result nodes. Description: Returns search results from given <code>fromIndex</code> to given <code>toIndex</code> from the sarch with the given identifier. DOM_discardSearchResults(self, searchId) Python Function: DOM_discardSearchResults Domain: DOM Method name: discardSearchResults WARNING: This function is marked 'Experimental'! Parameters: 'searchId' (type: string) -> Unique search session identifier. No return value. Description: Discards search results from the session with the given id. <code>getSearchResults</code> should no longer be called for that search. ''' res = self.DOM_performSearch(search, includeUserAgentShadowDOM=False) assert 'result' in res assert 'searchId' in res['result'] searchid = res['result']['searchId'] res_cnt = res['result']['resultCount'] self.log.debug("%s", res) self.log.debug("%s", searchid) if res_cnt == 0: return None items = self.DOM_getSearchResults(searchId=searchid, fromIndex=0, toIndex=res_cnt) self.log.debug("Results:") self.log.debug("%s", items)
python
def find_element(self, search): ''' DOM_performSearch(self, query, includeUserAgentShadowDOM) Python Function: DOM_performSearch Domain: DOM Method name: performSearch WARNING: This function is marked 'Experimental'! Parameters: 'query' (type: string) -> Plain text or query selector or XPath search query. 'includeUserAgentShadowDOM' (type: boolean) -> True to search in user agent shadow DOM. Returns: 'searchId' (type: string) -> Unique search session identifier. 'resultCount' (type: integer) -> Number of search results. Description: Searches for a given string in the DOM tree. Use <code>getSearchResults</code> to access search results or <code>cancelSearch</code> to end this search session. Python Function: DOM_getSearchResults Domain: DOM Method name: getSearchResults WARNING: This function is marked 'Experimental'! Parameters: 'searchId' (type: string) -> Unique search session identifier. 'fromIndex' (type: integer) -> Start index of the search result to be returned. 'toIndex' (type: integer) -> End index of the search result to be returned. Returns: 'nodeIds' (type: array) -> Ids of the search result nodes. Description: Returns search results from given <code>fromIndex</code> to given <code>toIndex</code> from the sarch with the given identifier. DOM_discardSearchResults(self, searchId) Python Function: DOM_discardSearchResults Domain: DOM Method name: discardSearchResults WARNING: This function is marked 'Experimental'! Parameters: 'searchId' (type: string) -> Unique search session identifier. No return value. Description: Discards search results from the session with the given id. <code>getSearchResults</code> should no longer be called for that search. ''' res = self.DOM_performSearch(search, includeUserAgentShadowDOM=False) assert 'result' in res assert 'searchId' in res['result'] searchid = res['result']['searchId'] res_cnt = res['result']['resultCount'] self.log.debug("%s", res) self.log.debug("%s", searchid) if res_cnt == 0: return None items = self.DOM_getSearchResults(searchId=searchid, fromIndex=0, toIndex=res_cnt) self.log.debug("Results:") self.log.debug("%s", items)
[ "def", "find_element", "(", "self", ",", "search", ")", ":", "res", "=", "self", ".", "DOM_performSearch", "(", "search", ",", "includeUserAgentShadowDOM", "=", "False", ")", "assert", "'result'", "in", "res", "assert", "'searchId'", "in", "res", "[", "'resu...
DOM_performSearch(self, query, includeUserAgentShadowDOM) Python Function: DOM_performSearch Domain: DOM Method name: performSearch WARNING: This function is marked 'Experimental'! Parameters: 'query' (type: string) -> Plain text or query selector or XPath search query. 'includeUserAgentShadowDOM' (type: boolean) -> True to search in user agent shadow DOM. Returns: 'searchId' (type: string) -> Unique search session identifier. 'resultCount' (type: integer) -> Number of search results. Description: Searches for a given string in the DOM tree. Use <code>getSearchResults</code> to access search results or <code>cancelSearch</code> to end this search session. Python Function: DOM_getSearchResults Domain: DOM Method name: getSearchResults WARNING: This function is marked 'Experimental'! Parameters: 'searchId' (type: string) -> Unique search session identifier. 'fromIndex' (type: integer) -> Start index of the search result to be returned. 'toIndex' (type: integer) -> End index of the search result to be returned. Returns: 'nodeIds' (type: array) -> Ids of the search result nodes. Description: Returns search results from given <code>fromIndex</code> to given <code>toIndex</code> from the sarch with the given identifier. DOM_discardSearchResults(self, searchId) Python Function: DOM_discardSearchResults Domain: DOM Method name: discardSearchResults WARNING: This function is marked 'Experimental'! Parameters: 'searchId' (type: string) -> Unique search session identifier. No return value. Description: Discards search results from the session with the given id. <code>getSearchResults</code> should no longer be called for that search.
[ "DOM_performSearch", "(", "self", "query", "includeUserAgentShadowDOM", ")", "Python", "Function", ":", "DOM_performSearch", "Domain", ":", "DOM", "Method", "name", ":", "performSearch" ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L408-L467
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.get_unpacked_response_body
def get_unpacked_response_body(self, requestId, mimetype="application/unknown"): ''' Return a unpacked, decoded resposne body from Network_getResponseBody() ''' content = self.Network_getResponseBody(requestId) assert 'result' in content result = content['result'] assert 'base64Encoded' in result assert 'body' in result if result['base64Encoded']: content = base64.b64decode(result['body']) else: content = result['body'] self.log.info("Navigate complete. Received %s byte response with type %s.", len(content), mimetype) return {'binary' : result['base64Encoded'], 'mimetype' : mimetype, 'content' : content}
python
def get_unpacked_response_body(self, requestId, mimetype="application/unknown"): ''' Return a unpacked, decoded resposne body from Network_getResponseBody() ''' content = self.Network_getResponseBody(requestId) assert 'result' in content result = content['result'] assert 'base64Encoded' in result assert 'body' in result if result['base64Encoded']: content = base64.b64decode(result['body']) else: content = result['body'] self.log.info("Navigate complete. Received %s byte response with type %s.", len(content), mimetype) return {'binary' : result['base64Encoded'], 'mimetype' : mimetype, 'content' : content}
[ "def", "get_unpacked_response_body", "(", "self", ",", "requestId", ",", "mimetype", "=", "\"application/unknown\"", ")", ":", "content", "=", "self", ".", "Network_getResponseBody", "(", "requestId", ")", "assert", "'result'", "in", "content", "result", "=", "con...
Return a unpacked, decoded resposne body from Network_getResponseBody()
[ "Return", "a", "unpacked", "decoded", "resposne", "body", "from", "Network_getResponseBody", "()" ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L527-L546
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.handle_page_location_changed
def handle_page_location_changed(self, timeout=None): ''' If the chrome tab has internally redirected (generally because jerberscript), this will walk the page navigation responses and attempt to fetch the response body for the tab's latest location. ''' # In general, this is often called after other mechanisms have confirmed # that the tab has already navigated. As such, we want to not wait a while # to discover something went wrong, so use a timeout that basically just # results in checking the available buffer, and nothing else. if not timeout: timeout = 0.1 self.log.debug("We may have redirected. Checking.") messages = self.transport.recv_all_filtered(filter_funcs.capture_loading_events, tab_key=self.tab_id) if not messages: raise ChromeError("Couldn't track redirect! No idea what to do!") last_message = messages[-1] self.log.info("Probably a redirect! New content url: '%s'", last_message['params']['documentURL']) resp = self.transport.recv_filtered(filter_funcs.network_response_recieved_for_url(last_message['params']['documentURL'], last_message['params']['frameId']), tab_key=self.tab_id) resp = resp['params'] ctype = 'application/unknown' resp_response = resp['response'] if 'mimeType' in resp_response: ctype = resp_response['mimeType'] if 'headers' in resp_response and 'content-type' in resp_response['headers']: ctype = resp_response['headers']['content-type'].split(";")[0] # We assume the last document request was the redirect. # This is /probably/ kind of a poor practice, but what the hell. # I have no idea what this would do if there are non-html documents (or if that can even happen.) return self.get_unpacked_response_body(last_message['params']['requestId'], mimetype=ctype)
python
def handle_page_location_changed(self, timeout=None): ''' If the chrome tab has internally redirected (generally because jerberscript), this will walk the page navigation responses and attempt to fetch the response body for the tab's latest location. ''' # In general, this is often called after other mechanisms have confirmed # that the tab has already navigated. As such, we want to not wait a while # to discover something went wrong, so use a timeout that basically just # results in checking the available buffer, and nothing else. if not timeout: timeout = 0.1 self.log.debug("We may have redirected. Checking.") messages = self.transport.recv_all_filtered(filter_funcs.capture_loading_events, tab_key=self.tab_id) if not messages: raise ChromeError("Couldn't track redirect! No idea what to do!") last_message = messages[-1] self.log.info("Probably a redirect! New content url: '%s'", last_message['params']['documentURL']) resp = self.transport.recv_filtered(filter_funcs.network_response_recieved_for_url(last_message['params']['documentURL'], last_message['params']['frameId']), tab_key=self.tab_id) resp = resp['params'] ctype = 'application/unknown' resp_response = resp['response'] if 'mimeType' in resp_response: ctype = resp_response['mimeType'] if 'headers' in resp_response and 'content-type' in resp_response['headers']: ctype = resp_response['headers']['content-type'].split(";")[0] # We assume the last document request was the redirect. # This is /probably/ kind of a poor practice, but what the hell. # I have no idea what this would do if there are non-html documents (or if that can even happen.) return self.get_unpacked_response_body(last_message['params']['requestId'], mimetype=ctype)
[ "def", "handle_page_location_changed", "(", "self", ",", "timeout", "=", "None", ")", ":", "# In general, this is often called after other mechanisms have confirmed", "# that the tab has already navigated. As such, we want to not wait a while", "# to discover something went wrong, so use a t...
If the chrome tab has internally redirected (generally because jerberscript), this will walk the page navigation responses and attempt to fetch the response body for the tab's latest location.
[ "If", "the", "chrome", "tab", "has", "internally", "redirected", "(", "generally", "because", "jerberscript", ")", "this", "will", "walk", "the", "page", "navigation", "responses", "and", "attempt", "to", "fetch", "the", "response", "body", "for", "the", "tab"...
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L549-L587
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.blocking_navigate_and_get_source
def blocking_navigate_and_get_source(self, url, timeout=DEFAULT_TIMEOUT_SECS): ''' Do a blocking navigate to url `url`, and then extract the response body and return that. This effectively returns the *unrendered* page content that's sent over the wire. As such, if the page does any modification of the contained markup during rendering (via javascript), this function will not reflect the changes made by the javascript. The rendered page content can be retreived by calling `get_rendered_page_source()`. Due to the remote api structure, accessing the raw content after the content has been loaded is not possible, so any task requiring the raw content must be careful to request it before it actually navigates to said content. Return value is a dictionary with two keys: { 'binary' : (boolean, true if content is binary, false if not) 'content' : (string of bytestring, depending on whether `binary` is true or not) } ''' resp = self.blocking_navigate(url, timeout) assert 'requestId' in resp assert 'response' in resp # self.log.debug('blocking_navigate Response %s', pprint.pformat(resp)) ctype = 'application/unknown' resp_response = resp['response'] if 'mimeType' in resp_response: ctype = resp_response['mimeType'] if 'headers' in resp_response and 'content-type' in resp_response['headers']: ctype = resp_response['headers']['content-type'].split(";")[0] self.log.debug("Trying to get response body") try: ret = self.get_unpacked_response_body(resp['requestId'], mimetype=ctype) except ChromeError: ret = self.handle_page_location_changed(timeout) return ret
python
def blocking_navigate_and_get_source(self, url, timeout=DEFAULT_TIMEOUT_SECS): ''' Do a blocking navigate to url `url`, and then extract the response body and return that. This effectively returns the *unrendered* page content that's sent over the wire. As such, if the page does any modification of the contained markup during rendering (via javascript), this function will not reflect the changes made by the javascript. The rendered page content can be retreived by calling `get_rendered_page_source()`. Due to the remote api structure, accessing the raw content after the content has been loaded is not possible, so any task requiring the raw content must be careful to request it before it actually navigates to said content. Return value is a dictionary with two keys: { 'binary' : (boolean, true if content is binary, false if not) 'content' : (string of bytestring, depending on whether `binary` is true or not) } ''' resp = self.blocking_navigate(url, timeout) assert 'requestId' in resp assert 'response' in resp # self.log.debug('blocking_navigate Response %s', pprint.pformat(resp)) ctype = 'application/unknown' resp_response = resp['response'] if 'mimeType' in resp_response: ctype = resp_response['mimeType'] if 'headers' in resp_response and 'content-type' in resp_response['headers']: ctype = resp_response['headers']['content-type'].split(";")[0] self.log.debug("Trying to get response body") try: ret = self.get_unpacked_response_body(resp['requestId'], mimetype=ctype) except ChromeError: ret = self.handle_page_location_changed(timeout) return ret
[ "def", "blocking_navigate_and_get_source", "(", "self", ",", "url", ",", "timeout", "=", "DEFAULT_TIMEOUT_SECS", ")", ":", "resp", "=", "self", ".", "blocking_navigate", "(", "url", ",", "timeout", ")", "assert", "'requestId'", "in", "resp", "assert", "'response...
Do a blocking navigate to url `url`, and then extract the response body and return that. This effectively returns the *unrendered* page content that's sent over the wire. As such, if the page does any modification of the contained markup during rendering (via javascript), this function will not reflect the changes made by the javascript. The rendered page content can be retreived by calling `get_rendered_page_source()`. Due to the remote api structure, accessing the raw content after the content has been loaded is not possible, so any task requiring the raw content must be careful to request it before it actually navigates to said content. Return value is a dictionary with two keys: { 'binary' : (boolean, true if content is binary, false if not) 'content' : (string of bytestring, depending on whether `binary` is true or not) }
[ "Do", "a", "blocking", "navigate", "to", "url", "url", "and", "then", "extract", "the", "response", "body", "and", "return", "that", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L589-L633
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.get_rendered_page_source
def get_rendered_page_source(self, dom_idle_requirement_secs=3, max_wait_timeout=30): ''' Get the HTML markup for the current page. This is done by looking up the root DOM node, and then requesting the outer HTML for that node ID. This calls return will reflect any modifications made by javascript to the page. For unmodified content, use `blocking_navigate_and_get_source()` dom_idle_requirement_secs specifies the period of time for which there must have been no DOM modifications before treating the rendered output as "final". This call will therefore block for at least dom_idle_requirement_secs seconds. ''' # There are a bunch of events which generally indicate a page is still doing *things*. # I have some concern about how this will handle things like advertisements, which # basically load crap forever. That's why we have the max_wait_timeout. target_events = [ "Page.frameResized", "Page.frameStartedLoading", "Page.frameNavigated", "Page.frameAttached", "Page.frameStoppedLoading", "Page.frameScheduledNavigation", "Page.domContentEventFired", "Page.frameClearedScheduledNavigation", "Page.loadEventFired", "DOM.documentUpdated", "DOM.childNodeInserted", "DOM.childNodeRemoved", "DOM.childNodeCountUpdated", ] start_time = time.time() try: while 1: if time.time() - start_time > max_wait_timeout: self.log.debug("Page was not idle after waiting %s seconds. Giving up and extracting content now.", max_wait_timeout) self.transport.recv_filtered(filter_funcs.wait_for_methods(target_events), tab_key=self.tab_id, timeout=dom_idle_requirement_secs) except ChromeResponseNotReceived: # We timed out, the DOM is probably idle. pass # We have to find the DOM root node ID dom_attr = self.DOM_getDocument(depth=-1, pierce=False) assert 'result' in dom_attr assert 'root' in dom_attr['result'] assert 'nodeId' in dom_attr['result']['root'] # Now, we have the root node ID. root_node_id = dom_attr['result']['root']['nodeId'] # Use that to get the HTML for the specified node response = self.DOM_getOuterHTML(nodeId=root_node_id) assert 'result' in response assert 'outerHTML' in response['result'] return response['result']['outerHTML']
python
def get_rendered_page_source(self, dom_idle_requirement_secs=3, max_wait_timeout=30): ''' Get the HTML markup for the current page. This is done by looking up the root DOM node, and then requesting the outer HTML for that node ID. This calls return will reflect any modifications made by javascript to the page. For unmodified content, use `blocking_navigate_and_get_source()` dom_idle_requirement_secs specifies the period of time for which there must have been no DOM modifications before treating the rendered output as "final". This call will therefore block for at least dom_idle_requirement_secs seconds. ''' # There are a bunch of events which generally indicate a page is still doing *things*. # I have some concern about how this will handle things like advertisements, which # basically load crap forever. That's why we have the max_wait_timeout. target_events = [ "Page.frameResized", "Page.frameStartedLoading", "Page.frameNavigated", "Page.frameAttached", "Page.frameStoppedLoading", "Page.frameScheduledNavigation", "Page.domContentEventFired", "Page.frameClearedScheduledNavigation", "Page.loadEventFired", "DOM.documentUpdated", "DOM.childNodeInserted", "DOM.childNodeRemoved", "DOM.childNodeCountUpdated", ] start_time = time.time() try: while 1: if time.time() - start_time > max_wait_timeout: self.log.debug("Page was not idle after waiting %s seconds. Giving up and extracting content now.", max_wait_timeout) self.transport.recv_filtered(filter_funcs.wait_for_methods(target_events), tab_key=self.tab_id, timeout=dom_idle_requirement_secs) except ChromeResponseNotReceived: # We timed out, the DOM is probably idle. pass # We have to find the DOM root node ID dom_attr = self.DOM_getDocument(depth=-1, pierce=False) assert 'result' in dom_attr assert 'root' in dom_attr['result'] assert 'nodeId' in dom_attr['result']['root'] # Now, we have the root node ID. root_node_id = dom_attr['result']['root']['nodeId'] # Use that to get the HTML for the specified node response = self.DOM_getOuterHTML(nodeId=root_node_id) assert 'result' in response assert 'outerHTML' in response['result'] return response['result']['outerHTML']
[ "def", "get_rendered_page_source", "(", "self", ",", "dom_idle_requirement_secs", "=", "3", ",", "max_wait_timeout", "=", "30", ")", ":", "# There are a bunch of events which generally indicate a page is still doing *things*.", "# I have some concern about how this will handle things l...
Get the HTML markup for the current page. This is done by looking up the root DOM node, and then requesting the outer HTML for that node ID. This calls return will reflect any modifications made by javascript to the page. For unmodified content, use `blocking_navigate_and_get_source()` dom_idle_requirement_secs specifies the period of time for which there must have been no DOM modifications before treating the rendered output as "final". This call will therefore block for at least dom_idle_requirement_secs seconds.
[ "Get", "the", "HTML", "markup", "for", "the", "current", "page", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L636-L698
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.take_screeshot
def take_screeshot(self): ''' Take a screenshot of the virtual viewport content. Return value is a png image as a bytestring. ''' resp = self.Page_captureScreenshot() assert 'result' in resp assert 'data' in resp['result'] imgdat = base64.b64decode(resp['result']['data']) return imgdat
python
def take_screeshot(self): ''' Take a screenshot of the virtual viewport content. Return value is a png image as a bytestring. ''' resp = self.Page_captureScreenshot() assert 'result' in resp assert 'data' in resp['result'] imgdat = base64.b64decode(resp['result']['data']) return imgdat
[ "def", "take_screeshot", "(", "self", ")", ":", "resp", "=", "self", ".", "Page_captureScreenshot", "(", ")", "assert", "'result'", "in", "resp", "assert", "'data'", "in", "resp", "[", "'result'", "]", "imgdat", "=", "base64", ".", "b64decode", "(", "resp"...
Take a screenshot of the virtual viewport content. Return value is a png image as a bytestring.
[ "Take", "a", "screenshot", "of", "the", "virtual", "viewport", "content", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L701-L711
train
fake-name/ChromeController
ChromeController/manager.py
ChromeRemoteDebugInterface.blocking_navigate
def blocking_navigate(self, url, timeout=DEFAULT_TIMEOUT_SECS): ''' Do a blocking navigate to url `url`. This function triggers a navigation, and then waits for the browser to claim the page has finished loading. Roughly, this corresponds to the javascript `DOMContentLoaded` event, meaning the dom for the page is ready. Internals: A navigation command results in a sequence of events: - Page.frameStartedLoading" (with frameid) - Page.frameStoppedLoading" (with frameid) - Page.loadEventFired" (not attached to an ID) Therefore, this call triggers a navigation option, and then waits for the expected set of response event messages. ''' self.transport.flush(tab_key=self.tab_id) ret = self.Page_navigate(url = url) assert("result" in ret), "Missing return content" assert("frameId" in ret['result']), "Missing 'frameId' in return content" assert("loaderId" in ret['result']), "Missing 'loaderId' in return content" expected_id = ret['result']['frameId'] loader_id = ret['result']['loaderId'] try: self.log.debug("Waiting for frame navigated command response.") self.transport.recv_filtered(filter_funcs.check_frame_navigated_command(expected_id), tab_key=self.tab_id, timeout=timeout) self.log.debug("Waiting for frameStartedLoading response.") self.transport.recv_filtered(filter_funcs.check_frame_load_command("Page.frameStartedLoading"), tab_key=self.tab_id, timeout=timeout) self.log.debug("Waiting for frameStoppedLoading response.") self.transport.recv_filtered(filter_funcs.check_frame_load_command("Page.frameStoppedLoading"), tab_key=self.tab_id, timeout=timeout) # self.transport.recv_filtered(check_load_event_fired, tab_key=self.tab_id, timeout=timeout) self.log.debug("Waiting for responseReceived response.") resp = self.transport.recv_filtered(filter_funcs.network_response_recieved_for_url(url=None, expected_id=expected_id), tab_key=self.tab_id, timeout=timeout) if resp is None: raise ChromeNavigateTimedOut("Blocking navigate timed out!") return resp['params'] # The `Page.frameNavigated ` event does not get fired for non-markup responses. # Therefore, if we timeout on waiting for that, check to see if we received a binary response. except ChromeResponseNotReceived: # So this is basically broken, fix is https://bugs.chromium.org/p/chromium/issues/detail?id=831887 # but that bug report isn't fixed yet. # Siiiigh. self.log.warning("Failed to receive expected response to navigate command. Checking if response is a binary object.") resp = self.transport.recv_filtered( keycheck = filter_funcs.check_frame_loader_command( method_name = "Network.responseReceived", loader_id = loader_id ), tab_key = self.tab_id, timeout = timeout) return resp['params']
python
def blocking_navigate(self, url, timeout=DEFAULT_TIMEOUT_SECS): ''' Do a blocking navigate to url `url`. This function triggers a navigation, and then waits for the browser to claim the page has finished loading. Roughly, this corresponds to the javascript `DOMContentLoaded` event, meaning the dom for the page is ready. Internals: A navigation command results in a sequence of events: - Page.frameStartedLoading" (with frameid) - Page.frameStoppedLoading" (with frameid) - Page.loadEventFired" (not attached to an ID) Therefore, this call triggers a navigation option, and then waits for the expected set of response event messages. ''' self.transport.flush(tab_key=self.tab_id) ret = self.Page_navigate(url = url) assert("result" in ret), "Missing return content" assert("frameId" in ret['result']), "Missing 'frameId' in return content" assert("loaderId" in ret['result']), "Missing 'loaderId' in return content" expected_id = ret['result']['frameId'] loader_id = ret['result']['loaderId'] try: self.log.debug("Waiting for frame navigated command response.") self.transport.recv_filtered(filter_funcs.check_frame_navigated_command(expected_id), tab_key=self.tab_id, timeout=timeout) self.log.debug("Waiting for frameStartedLoading response.") self.transport.recv_filtered(filter_funcs.check_frame_load_command("Page.frameStartedLoading"), tab_key=self.tab_id, timeout=timeout) self.log.debug("Waiting for frameStoppedLoading response.") self.transport.recv_filtered(filter_funcs.check_frame_load_command("Page.frameStoppedLoading"), tab_key=self.tab_id, timeout=timeout) # self.transport.recv_filtered(check_load_event_fired, tab_key=self.tab_id, timeout=timeout) self.log.debug("Waiting for responseReceived response.") resp = self.transport.recv_filtered(filter_funcs.network_response_recieved_for_url(url=None, expected_id=expected_id), tab_key=self.tab_id, timeout=timeout) if resp is None: raise ChromeNavigateTimedOut("Blocking navigate timed out!") return resp['params'] # The `Page.frameNavigated ` event does not get fired for non-markup responses. # Therefore, if we timeout on waiting for that, check to see if we received a binary response. except ChromeResponseNotReceived: # So this is basically broken, fix is https://bugs.chromium.org/p/chromium/issues/detail?id=831887 # but that bug report isn't fixed yet. # Siiiigh. self.log.warning("Failed to receive expected response to navigate command. Checking if response is a binary object.") resp = self.transport.recv_filtered( keycheck = filter_funcs.check_frame_loader_command( method_name = "Network.responseReceived", loader_id = loader_id ), tab_key = self.tab_id, timeout = timeout) return resp['params']
[ "def", "blocking_navigate", "(", "self", ",", "url", ",", "timeout", "=", "DEFAULT_TIMEOUT_SECS", ")", ":", "self", ".", "transport", ".", "flush", "(", "tab_key", "=", "self", ".", "tab_id", ")", "ret", "=", "self", ".", "Page_navigate", "(", "url", "="...
Do a blocking navigate to url `url`. This function triggers a navigation, and then waits for the browser to claim the page has finished loading. Roughly, this corresponds to the javascript `DOMContentLoaded` event, meaning the dom for the page is ready. Internals: A navigation command results in a sequence of events: - Page.frameStartedLoading" (with frameid) - Page.frameStoppedLoading" (with frameid) - Page.loadEventFired" (not attached to an ID) Therefore, this call triggers a navigation option, and then waits for the expected set of response event messages.
[ "Do", "a", "blocking", "navigate", "to", "url", "url", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager.py#L714-L780
train
fake-name/ChromeController
ChromeController/tab_pool.py
TabPooledChromium.tab
def tab(self, netloc=None, url=None, extra_id=None, use_tid=False): ''' Get a chromium tab from the pool, optionally one that has an association with a specific netloc/URL. If no url or netloc is specified, the per-thread identifier will be used. If `extra_id` is specified, it's stringified value will be mixed into the pool key If `use_tid` is true, the per-thread identifier will be mixed into the pool key. In all cases, the tab pool is a least-recently-used cache, so the tab that has been accessed the least recently will be automatically closed if a new tab is requested, and there are already `tab_pool_max_size` tabs created. ''' assert self.alive, "Chrome has been shut down! Cannot continue!" if not netloc and url: netloc = urllib.parse.urlparse(url).netloc self.log.debug("Getting tab for netloc: %s (url: %s)", netloc, url) # Coerce to string type so even if it's none, it doesn't hurt anything. key = str(netloc) if extra_id: key += " " + str(extra_id) if use_tid or not key: key += " " + str(threading.get_ident()) if self.__started_pid != os.getpid(): self.log.error("TabPooledChromium instances are not safe to share across multiple processes.") self.log.error("Please create a new in each separate multiprocesssing process.") raise RuntimeError("TabPooledChromium instances are not safe to share across multiple processes.") with self.__counter_lock: self.__active_tabs.setdefault(key, 0) self.__active_tabs[key] += 1 if self.__active_tabs[key] > 1: self.log.warning("Tab with key %s checked out more then once simultaneously") try: lock, tab = self.__tab_cache[key] with lock: yield tab finally: with self.__counter_lock: self.__active_tabs[key] -= 1 if self.__active_tabs[key] == 0: self.__active_tabs.pop(key)
python
def tab(self, netloc=None, url=None, extra_id=None, use_tid=False): ''' Get a chromium tab from the pool, optionally one that has an association with a specific netloc/URL. If no url or netloc is specified, the per-thread identifier will be used. If `extra_id` is specified, it's stringified value will be mixed into the pool key If `use_tid` is true, the per-thread identifier will be mixed into the pool key. In all cases, the tab pool is a least-recently-used cache, so the tab that has been accessed the least recently will be automatically closed if a new tab is requested, and there are already `tab_pool_max_size` tabs created. ''' assert self.alive, "Chrome has been shut down! Cannot continue!" if not netloc and url: netloc = urllib.parse.urlparse(url).netloc self.log.debug("Getting tab for netloc: %s (url: %s)", netloc, url) # Coerce to string type so even if it's none, it doesn't hurt anything. key = str(netloc) if extra_id: key += " " + str(extra_id) if use_tid or not key: key += " " + str(threading.get_ident()) if self.__started_pid != os.getpid(): self.log.error("TabPooledChromium instances are not safe to share across multiple processes.") self.log.error("Please create a new in each separate multiprocesssing process.") raise RuntimeError("TabPooledChromium instances are not safe to share across multiple processes.") with self.__counter_lock: self.__active_tabs.setdefault(key, 0) self.__active_tabs[key] += 1 if self.__active_tabs[key] > 1: self.log.warning("Tab with key %s checked out more then once simultaneously") try: lock, tab = self.__tab_cache[key] with lock: yield tab finally: with self.__counter_lock: self.__active_tabs[key] -= 1 if self.__active_tabs[key] == 0: self.__active_tabs.pop(key)
[ "def", "tab", "(", "self", ",", "netloc", "=", "None", ",", "url", "=", "None", ",", "extra_id", "=", "None", ",", "use_tid", "=", "False", ")", ":", "assert", "self", ".", "alive", ",", "\"Chrome has been shut down! Cannot continue!\"", "if", "not", "netl...
Get a chromium tab from the pool, optionally one that has an association with a specific netloc/URL. If no url or netloc is specified, the per-thread identifier will be used. If `extra_id` is specified, it's stringified value will be mixed into the pool key If `use_tid` is true, the per-thread identifier will be mixed into the pool key. In all cases, the tab pool is a least-recently-used cache, so the tab that has been accessed the least recently will be automatically closed if a new tab is requested, and there are already `tab_pool_max_size` tabs created.
[ "Get", "a", "chromium", "tab", "from", "the", "pool", "optionally", "one", "that", "has", "an", "association", "with", "a", "specific", "netloc", "/", "URL", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/tab_pool.py#L88-L132
train
fake-name/ChromeController
ChromeController/exit_handler.py
on_parent_exit
def on_parent_exit(signame): """ Return a function to be run in a child process which will trigger SIGNAME to be sent when the parent process dies """ signum = getattr(signal, signame) def set_parent_exit_signal(): # http://linux.die.net/man/2/prctl result = cdll['libc.so.6'].prctl(PR_SET_PDEATHSIG, signum) if result != 0: raise PrCtlError('prctl failed with error code %s' % result) return set_parent_exit_signal
python
def on_parent_exit(signame): """ Return a function to be run in a child process which will trigger SIGNAME to be sent when the parent process dies """ signum = getattr(signal, signame) def set_parent_exit_signal(): # http://linux.die.net/man/2/prctl result = cdll['libc.so.6'].prctl(PR_SET_PDEATHSIG, signum) if result != 0: raise PrCtlError('prctl failed with error code %s' % result) return set_parent_exit_signal
[ "def", "on_parent_exit", "(", "signame", ")", ":", "signum", "=", "getattr", "(", "signal", ",", "signame", ")", "def", "set_parent_exit_signal", "(", ")", ":", "# http://linux.die.net/man/2/prctl", "result", "=", "cdll", "[", "'libc.so.6'", "]", ".", "prctl", ...
Return a function to be run in a child process which will trigger SIGNAME to be sent when the parent process dies
[ "Return", "a", "function", "to", "be", "run", "in", "a", "child", "process", "which", "will", "trigger", "SIGNAME", "to", "be", "sent", "when", "the", "parent", "process", "dies" ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/exit_handler.py#L22-L33
train
fake-name/ChromeController
ChromeController/chrome_context.py
ChromeContext
def ChromeContext(*args, **kwargs): ''' Context manager for conveniently handling the lifetime of the underlying chromium instance. In general, this should be the preferred way to use an instance of `ChromeRemoteDebugInterface`. All parameters are forwarded through to the underlying ChromeRemoteDebugInterface() constructor. ''' log = logging.getLogger("Main.ChromeController.ChromeContext") chrome_created = False try: chrome_instance = ChromeRemoteDebugInterface(*args, **kwargs) chrome_created = True log.info("Entering chrome context") yield chrome_instance except Exception as e: log.error("Exception in chrome context!") for line in traceback.format_exc().split("\n"): log.error(line) raise e finally: log.info("Exiting chrome context") if chrome_created: chrome_instance.close()
python
def ChromeContext(*args, **kwargs): ''' Context manager for conveniently handling the lifetime of the underlying chromium instance. In general, this should be the preferred way to use an instance of `ChromeRemoteDebugInterface`. All parameters are forwarded through to the underlying ChromeRemoteDebugInterface() constructor. ''' log = logging.getLogger("Main.ChromeController.ChromeContext") chrome_created = False try: chrome_instance = ChromeRemoteDebugInterface(*args, **kwargs) chrome_created = True log.info("Entering chrome context") yield chrome_instance except Exception as e: log.error("Exception in chrome context!") for line in traceback.format_exc().split("\n"): log.error(line) raise e finally: log.info("Exiting chrome context") if chrome_created: chrome_instance.close()
[ "def", "ChromeContext", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "\"Main.ChromeController.ChromeContext\"", ")", "chrome_created", "=", "False", "try", ":", "chrome_instance", "=", "ChromeRemoteDebugInterfa...
Context manager for conveniently handling the lifetime of the underlying chromium instance. In general, this should be the preferred way to use an instance of `ChromeRemoteDebugInterface`. All parameters are forwarded through to the underlying ChromeRemoteDebugInterface() constructor.
[ "Context", "manager", "for", "conveniently", "handling", "the", "lifetime", "of", "the", "underlying", "chromium", "instance", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/chrome_context.py#L9-L34
train
fake-name/ChromeController
ChromeController/manager_base.py
ChromeInterface.synchronous_command
def synchronous_command(self, *args, **kwargs): ''' Forward a command to the remote chrome instance via the transport connection, and check the return for an error. If the command resulted in an error, a `ChromeController.ChromeError` is raised, with the error string containing the response from the remote chrome instance describing the problem and it's cause. Otherwise, the decoded json data-structure returned from the remote instance is returned. ''' self.transport.check_process_ded() ret = self.transport.synchronous_command(tab_key=self.tab_id, *args, **kwargs) self.transport.check_process_ded() self.__check_ret(ret) self.transport.check_process_ded() return ret
python
def synchronous_command(self, *args, **kwargs): ''' Forward a command to the remote chrome instance via the transport connection, and check the return for an error. If the command resulted in an error, a `ChromeController.ChromeError` is raised, with the error string containing the response from the remote chrome instance describing the problem and it's cause. Otherwise, the decoded json data-structure returned from the remote instance is returned. ''' self.transport.check_process_ded() ret = self.transport.synchronous_command(tab_key=self.tab_id, *args, **kwargs) self.transport.check_process_ded() self.__check_ret(ret) self.transport.check_process_ded() return ret
[ "def", "synchronous_command", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "transport", ".", "check_process_ded", "(", ")", "ret", "=", "self", ".", "transport", ".", "synchronous_command", "(", "tab_key", "=", "self", "...
Forward a command to the remote chrome instance via the transport connection, and check the return for an error. If the command resulted in an error, a `ChromeController.ChromeError` is raised, with the error string containing the response from the remote chrome instance describing the problem and it's cause. Otherwise, the decoded json data-structure returned from the remote instance is returned.
[ "Forward", "a", "command", "to", "the", "remote", "chrome", "instance", "via", "the", "transport", "connection", "and", "check", "the", "return", "for", "an", "error", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager_base.py#L82-L101
train
fake-name/ChromeController
ChromeController/manager_base.py
ChromeInterface.drain_transport
def drain_transport(self): ''' "Drain" the transport connection. This command simply returns all waiting messages sent from the remote chrome instance. This can be useful when waiting for a specific asynchronous message from chrome, but higher level calls are better suited for managing wait-for-message type needs. ''' self.transport.check_process_ded() ret = self.transport.drain(tab_key=self.tab_id) self.transport.check_process_ded() return ret
python
def drain_transport(self): ''' "Drain" the transport connection. This command simply returns all waiting messages sent from the remote chrome instance. This can be useful when waiting for a specific asynchronous message from chrome, but higher level calls are better suited for managing wait-for-message type needs. ''' self.transport.check_process_ded() ret = self.transport.drain(tab_key=self.tab_id) self.transport.check_process_ded() return ret
[ "def", "drain_transport", "(", "self", ")", ":", "self", ".", "transport", ".", "check_process_ded", "(", ")", "ret", "=", "self", ".", "transport", ".", "drain", "(", "tab_key", "=", "self", ".", "tab_id", ")", "self", ".", "transport", ".", "check_proc...
"Drain" the transport connection. This command simply returns all waiting messages sent from the remote chrome instance. This can be useful when waiting for a specific asynchronous message from chrome, but higher level calls are better suited for managing wait-for-message type needs.
[ "Drain", "the", "transport", "connection", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/manager_base.py#L103-L116
train
fake-name/ChromeController
logSetup.py
resetLoggingLocks
def resetLoggingLocks(): ''' This function is a HACK! Basically, if we fork() while a logging lock is held, the lock is /copied/ while in the acquired state. However, since we've forked, the thread that acquired the lock no longer exists, so it can never unlock the lock, and we end up blocking forever. Therefore, we manually enter the logging module, and forcefully release all the locks it holds. THIS IS NOT SAFE (or thread-safe). Basically, it MUST be called right after a process starts, and no where else. ''' try: logging._releaseLock() except RuntimeError: pass # The lock is already released # Iterate over the root logger hierarchy, and # force-free all locks. # if logging.Logger.root for handler in logging.Logger.manager.loggerDict.values(): if hasattr(handler, "lock") and handler.lock: try: handler.lock.release() except RuntimeError: pass
python
def resetLoggingLocks(): ''' This function is a HACK! Basically, if we fork() while a logging lock is held, the lock is /copied/ while in the acquired state. However, since we've forked, the thread that acquired the lock no longer exists, so it can never unlock the lock, and we end up blocking forever. Therefore, we manually enter the logging module, and forcefully release all the locks it holds. THIS IS NOT SAFE (or thread-safe). Basically, it MUST be called right after a process starts, and no where else. ''' try: logging._releaseLock() except RuntimeError: pass # The lock is already released # Iterate over the root logger hierarchy, and # force-free all locks. # if logging.Logger.root for handler in logging.Logger.manager.loggerDict.values(): if hasattr(handler, "lock") and handler.lock: try: handler.lock.release() except RuntimeError: pass
[ "def", "resetLoggingLocks", "(", ")", ":", "try", ":", "logging", ".", "_releaseLock", "(", ")", "except", "RuntimeError", ":", "pass", "# The lock is already released", "# Iterate over the root logger hierarchy, and", "# force-free all locks.", "# if logging.Logger.root", "f...
This function is a HACK! Basically, if we fork() while a logging lock is held, the lock is /copied/ while in the acquired state. However, since we've forked, the thread that acquired the lock no longer exists, so it can never unlock the lock, and we end up blocking forever. Therefore, we manually enter the logging module, and forcefully release all the locks it holds. THIS IS NOT SAFE (or thread-safe). Basically, it MUST be called right after a process starts, and no where else.
[ "This", "function", "is", "a", "HACK!" ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/logSetup.py#L51-L81
train
fake-name/ChromeController
logSetup.py
RobustFileHandler.stream_emit
def stream_emit(self, record, source_name): """ Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an 'encoding' attribute, it is used to determine how to do the output to the stream. """ if not source_name in self.output_streams: out_path = os.path.abspath("./logs") logpath = ansi_escape.sub('', source_name.replace("/", ";").replace(":", ";").replace("?", "-")) filename = "log {path}.txt".format(path=logpath) print("Opening output log file for path: %s" % filename) self.output_streams[source_name] = open(os.path.join(out_path, filename), self.mode, encoding=self.encoding) stream = self.output_streams[source_name] try: msg = self.format(record) stream.write(msg) stream.write(self.terminator) stream.flush() self.flush() except Exception: self.handleError(record)
python
def stream_emit(self, record, source_name): """ Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an 'encoding' attribute, it is used to determine how to do the output to the stream. """ if not source_name in self.output_streams: out_path = os.path.abspath("./logs") logpath = ansi_escape.sub('', source_name.replace("/", ";").replace(":", ";").replace("?", "-")) filename = "log {path}.txt".format(path=logpath) print("Opening output log file for path: %s" % filename) self.output_streams[source_name] = open(os.path.join(out_path, filename), self.mode, encoding=self.encoding) stream = self.output_streams[source_name] try: msg = self.format(record) stream.write(msg) stream.write(self.terminator) stream.flush() self.flush() except Exception: self.handleError(record)
[ "def", "stream_emit", "(", "self", ",", "record", ",", "source_name", ")", ":", "if", "not", "source_name", "in", "self", ".", "output_streams", ":", "out_path", "=", "os", ".", "path", ".", "abspath", "(", "\"./logs\"", ")", "logpath", "=", "ansi_escape",...
Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an 'encoding' attribute, it is used to determine how to do the output to the stream.
[ "Emit", "a", "record", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/logSetup.py#L177-L204
train
fake-name/ChromeController
logSetup.py
RobustFileHandler.emit
def emit(self, record): """ Emit a record. If the stream was not opened because 'delay' was specified in the constructor, open it before calling the superclass's emit. """ failures = 0 while failures < 3: try: self.stream_emit(record, record.name) break except: failures += 1 else: traceback.print_stack() print("Error writing to file?") self.close()
python
def emit(self, record): """ Emit a record. If the stream was not opened because 'delay' was specified in the constructor, open it before calling the superclass's emit. """ failures = 0 while failures < 3: try: self.stream_emit(record, record.name) break except: failures += 1 else: traceback.print_stack() print("Error writing to file?") self.close()
[ "def", "emit", "(", "self", ",", "record", ")", ":", "failures", "=", "0", "while", "failures", "<", "3", ":", "try", ":", "self", ".", "stream_emit", "(", "record", ",", "record", ".", "name", ")", "break", "except", ":", "failures", "+=", "1", "e...
Emit a record. If the stream was not opened because 'delay' was specified in the constructor, open it before calling the superclass's emit.
[ "Emit", "a", "record", "." ]
914dd136184e8f1165c7aa6ef30418aaf10c61f0
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/logSetup.py#L206-L225
train
meshy/colour-runner
colour_runner/django_runner.py
ColourRunnerMixin.run_suite
def run_suite(self, suite, **kwargs): """This is the version from Django 1.7.""" return self.test_runner( verbosity=self.verbosity, failfast=self.failfast, no_colour=self.no_colour, ).run(suite)
python
def run_suite(self, suite, **kwargs): """This is the version from Django 1.7.""" return self.test_runner( verbosity=self.verbosity, failfast=self.failfast, no_colour=self.no_colour, ).run(suite)
[ "def", "run_suite", "(", "self", ",", "suite", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "test_runner", "(", "verbosity", "=", "self", ".", "verbosity", ",", "failfast", "=", "self", ".", "failfast", ",", "no_colour", "=", "self", ".", ...
This is the version from Django 1.7.
[ "This", "is", "the", "version", "from", "Django", "1", ".", "7", "." ]
40301226e37ce0901904746f373a5816fb22f022
https://github.com/meshy/colour-runner/blob/40301226e37ce0901904746f373a5816fb22f022/colour_runner/django_runner.py#L11-L17
train
chrisvoncsefalvay/diffiehellman
diffiehellman/diffiehellman.py
DiffieHellman.generate_private_key
def generate_private_key(self): """ Generates a private key of key_length bits and attaches it to the object as the __private_key variable. :return: void :rtype: void """ key_length = self.key_length // 8 + 8 key = 0 try: key = int.from_bytes(rng(key_length), byteorder='big') except: key = int(hex(rng(key_length)), base=16) self.__private_key = key
python
def generate_private_key(self): """ Generates a private key of key_length bits and attaches it to the object as the __private_key variable. :return: void :rtype: void """ key_length = self.key_length // 8 + 8 key = 0 try: key = int.from_bytes(rng(key_length), byteorder='big') except: key = int(hex(rng(key_length)), base=16) self.__private_key = key
[ "def", "generate_private_key", "(", "self", ")", ":", "key_length", "=", "self", ".", "key_length", "//", "8", "+", "8", "key", "=", "0", "try", ":", "key", "=", "int", ".", "from_bytes", "(", "rng", "(", "key_length", ")", ",", "byteorder", "=", "'b...
Generates a private key of key_length bits and attaches it to the object as the __private_key variable. :return: void :rtype: void
[ "Generates", "a", "private", "key", "of", "key_length", "bits", "and", "attaches", "it", "to", "the", "object", "as", "the", "__private_key", "variable", "." ]
06e656ea918c6c069d931a4e9443cb4b57d0a0cb
https://github.com/chrisvoncsefalvay/diffiehellman/blob/06e656ea918c6c069d931a4e9443cb4b57d0a0cb/diffiehellman/diffiehellman.py#L60-L75
train
chrisvoncsefalvay/diffiehellman
diffiehellman/diffiehellman.py
DiffieHellman.generate_public_key
def generate_public_key(self): """ Generates public key. :return: void :rtype: void """ self.public_key = pow(self.generator, self.__private_key, self.prime)
python
def generate_public_key(self): """ Generates public key. :return: void :rtype: void """ self.public_key = pow(self.generator, self.__private_key, self.prime)
[ "def", "generate_public_key", "(", "self", ")", ":", "self", ".", "public_key", "=", "pow", "(", "self", ".", "generator", ",", "self", ".", "__private_key", ",", "self", ".", "prime", ")" ]
Generates public key. :return: void :rtype: void
[ "Generates", "public", "key", "." ]
06e656ea918c6c069d931a4e9443cb4b57d0a0cb
https://github.com/chrisvoncsefalvay/diffiehellman/blob/06e656ea918c6c069d931a4e9443cb4b57d0a0cb/diffiehellman/diffiehellman.py#L81-L90
train
chrisvoncsefalvay/diffiehellman
diffiehellman/diffiehellman.py
DiffieHellman.generate_shared_secret
def generate_shared_secret(self, other_public_key, echo_return_key=False): """ Generates shared secret from the other party's public key. :param other_public_key: Other party's public key :type other_public_key: int :param echo_return_key: Echo return shared key :type bool :return: void :rtype: void """ if self.verify_public_key(other_public_key) is False: raise MalformedPublicKey self.shared_secret = pow(other_public_key, self.__private_key, self.prime) shared_secret_as_bytes = self.shared_secret.to_bytes(self.shared_secret.bit_length() // 8 + 1, byteorder='big') _h = sha256() _h.update(bytes(shared_secret_as_bytes)) self.shared_key = _h.hexdigest() if echo_return_key is True: return self.shared_key
python
def generate_shared_secret(self, other_public_key, echo_return_key=False): """ Generates shared secret from the other party's public key. :param other_public_key: Other party's public key :type other_public_key: int :param echo_return_key: Echo return shared key :type bool :return: void :rtype: void """ if self.verify_public_key(other_public_key) is False: raise MalformedPublicKey self.shared_secret = pow(other_public_key, self.__private_key, self.prime) shared_secret_as_bytes = self.shared_secret.to_bytes(self.shared_secret.bit_length() // 8 + 1, byteorder='big') _h = sha256() _h.update(bytes(shared_secret_as_bytes)) self.shared_key = _h.hexdigest() if echo_return_key is True: return self.shared_key
[ "def", "generate_shared_secret", "(", "self", ",", "other_public_key", ",", "echo_return_key", "=", "False", ")", ":", "if", "self", ".", "verify_public_key", "(", "other_public_key", ")", "is", "False", ":", "raise", "MalformedPublicKey", "self", ".", "shared_sec...
Generates shared secret from the other party's public key. :param other_public_key: Other party's public key :type other_public_key: int :param echo_return_key: Echo return shared key :type bool :return: void :rtype: void
[ "Generates", "shared", "secret", "from", "the", "other", "party", "s", "public", "key", "." ]
06e656ea918c6c069d931a4e9443cb4b57d0a0cb
https://github.com/chrisvoncsefalvay/diffiehellman/blob/06e656ea918c6c069d931a4e9443cb4b57d0a0cb/diffiehellman/diffiehellman.py#L93-L119
train
chrisvoncsefalvay/diffiehellman
diffiehellman/decorators.py
requires_private_key
def requires_private_key(func): """ Decorator for functions that require the private key to be defined. """ def func_wrapper(self, *args, **kwargs): if hasattr(self, "_DiffieHellman__private_key"): func(self, *args, **kwargs) else: self.generate_private_key() func(self, *args, **kwargs) return func_wrapper
python
def requires_private_key(func): """ Decorator for functions that require the private key to be defined. """ def func_wrapper(self, *args, **kwargs): if hasattr(self, "_DiffieHellman__private_key"): func(self, *args, **kwargs) else: self.generate_private_key() func(self, *args, **kwargs) return func_wrapper
[ "def", "requires_private_key", "(", "func", ")", ":", "def", "func_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ",", "\"_DiffieHellman__private_key\"", ")", ":", "func", "(", "self", ",", "*", ...
Decorator for functions that require the private key to be defined.
[ "Decorator", "for", "functions", "that", "require", "the", "private", "key", "to", "be", "defined", "." ]
06e656ea918c6c069d931a4e9443cb4b57d0a0cb
https://github.com/chrisvoncsefalvay/diffiehellman/blob/06e656ea918c6c069d931a4e9443cb4b57d0a0cb/diffiehellman/decorators.py#L32-L44
train
chrisvoncsefalvay/diffiehellman
diffiehellman/decorators.py
requires_public_key
def requires_public_key(func): """ Decorator for functions that require the public key to be defined. By definition, this includes the private key, as such, it's enough to use this to effect definition of both public and private key. """ def func_wrapper(self, *args, **kwargs): if hasattr(self, "public_key"): func(self, *args, **kwargs) else: self.generate_public_key() func(self, *args, **kwargs) return func_wrapper
python
def requires_public_key(func): """ Decorator for functions that require the public key to be defined. By definition, this includes the private key, as such, it's enough to use this to effect definition of both public and private key. """ def func_wrapper(self, *args, **kwargs): if hasattr(self, "public_key"): func(self, *args, **kwargs) else: self.generate_public_key() func(self, *args, **kwargs) return func_wrapper
[ "def", "requires_public_key", "(", "func", ")", ":", "def", "func_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ",", "\"public_key\"", ")", ":", "func", "(", "self", ",", "*", "args", ",", ...
Decorator for functions that require the public key to be defined. By definition, this includes the private key, as such, it's enough to use this to effect definition of both public and private key.
[ "Decorator", "for", "functions", "that", "require", "the", "public", "key", "to", "be", "defined", ".", "By", "definition", "this", "includes", "the", "private", "key", "as", "such", "it", "s", "enough", "to", "use", "this", "to", "effect", "definition", "...
06e656ea918c6c069d931a4e9443cb4b57d0a0cb
https://github.com/chrisvoncsefalvay/diffiehellman/blob/06e656ea918c6c069d931a4e9443cb4b57d0a0cb/diffiehellman/decorators.py#L47-L59
train
wiredrive/wtframework
wtframework/wtf/utils/debug_utils.py
print_debug
def print_debug(*args, **kwargs): """ Print if and only if the debug flag is set true in the config.yaml file. Args: args : var args of print arguments. """ if WTF_CONFIG_READER.get("debug", False) == True: print(*args, **kwargs)
python
def print_debug(*args, **kwargs): """ Print if and only if the debug flag is set true in the config.yaml file. Args: args : var args of print arguments. """ if WTF_CONFIG_READER.get("debug", False) == True: print(*args, **kwargs)
[ "def", "print_debug", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "WTF_CONFIG_READER", ".", "get", "(", "\"debug\"", ",", "False", ")", "==", "True", ":", "print", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Print if and only if the debug flag is set true in the config.yaml file. Args: args : var args of print arguments.
[ "Print", "if", "and", "only", "if", "the", "debug", "flag", "is", "set", "true", "in", "the", "config", ".", "yaml", "file", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/debug_utils.py#L64-L73
train
wiredrive/wtframework
wtframework/wtf/utils/debug_utils.py
TimeDebugger.print_time
def print_time(self, message="Time is now: ", print_frame_info=True): """ Print the current elapsed time. Kwargs: message (str) : Message to prefix the time stamp. print_frame_info (bool) : Add frame info to the print message. """ if print_frame_info: frame_info = inspect.getouterframes(inspect.currentframe())[1] print(message, (datetime.now() - self.start_time), frame_info) else: print(message, (datetime.now() - self.start_time))
python
def print_time(self, message="Time is now: ", print_frame_info=True): """ Print the current elapsed time. Kwargs: message (str) : Message to prefix the time stamp. print_frame_info (bool) : Add frame info to the print message. """ if print_frame_info: frame_info = inspect.getouterframes(inspect.currentframe())[1] print(message, (datetime.now() - self.start_time), frame_info) else: print(message, (datetime.now() - self.start_time))
[ "def", "print_time", "(", "self", ",", "message", "=", "\"Time is now: \"", ",", "print_frame_info", "=", "True", ")", ":", "if", "print_frame_info", ":", "frame_info", "=", "inspect", ".", "getouterframes", "(", "inspect", ".", "currentframe", "(", ")", ")", ...
Print the current elapsed time. Kwargs: message (str) : Message to prefix the time stamp. print_frame_info (bool) : Add frame info to the print message.
[ "Print", "the", "current", "elapsed", "time", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/debug_utils.py#L39-L52
train
wiredrive/wtframework
wtframework/wtf/web/web_utils.py
WebUtils.check_url
def check_url(url): ''' Check if resource at URL is fetchable. (by trying to fetch it and checking for 200 status. Args: url (str): Url to check. Returns: Returns a tuple of {True/False, response code} ''' request = urllib2.Request(url) try: response = urlopen(request) return True, response.code except urllib2.HTTPError as e: return False, e.code
python
def check_url(url): ''' Check if resource at URL is fetchable. (by trying to fetch it and checking for 200 status. Args: url (str): Url to check. Returns: Returns a tuple of {True/False, response code} ''' request = urllib2.Request(url) try: response = urlopen(request) return True, response.code except urllib2.HTTPError as e: return False, e.code
[ "def", "check_url", "(", "url", ")", ":", "request", "=", "urllib2", ".", "Request", "(", "url", ")", "try", ":", "response", "=", "urlopen", "(", "request", ")", "return", "True", ",", "response", ".", "code", "except", "urllib2", ".", "HTTPError", "a...
Check if resource at URL is fetchable. (by trying to fetch it and checking for 200 status. Args: url (str): Url to check. Returns: Returns a tuple of {True/False, response code}
[ "Check", "if", "resource", "at", "URL", "is", "fetchable", ".", "(", "by", "trying", "to", "fetch", "it", "and", "checking", "for", "200", "status", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/web_utils.py#L38-L54
train
wiredrive/wtframework
wtframework/wtf/web/web_utils.py
WebUtils.get_base_url
def get_base_url(webdriver): """ Get the current base URL. Args: webdriver: Selenium WebDriver instance. Returns: str - base URL. Usage:: driver.get("http://www.google.com/?q=hello+world") WebUtils.get_base_url(driver) #returns 'http://www.google.com' """ current_url = webdriver.current_url try: return re.findall("^[^/]+//[^/$]+", current_url)[0] except: raise RuntimeError( u("Unable to process base url: {0}").format(current_url))
python
def get_base_url(webdriver): """ Get the current base URL. Args: webdriver: Selenium WebDriver instance. Returns: str - base URL. Usage:: driver.get("http://www.google.com/?q=hello+world") WebUtils.get_base_url(driver) #returns 'http://www.google.com' """ current_url = webdriver.current_url try: return re.findall("^[^/]+//[^/$]+", current_url)[0] except: raise RuntimeError( u("Unable to process base url: {0}").format(current_url))
[ "def", "get_base_url", "(", "webdriver", ")", ":", "current_url", "=", "webdriver", ".", "current_url", "try", ":", "return", "re", ".", "findall", "(", "\"^[^/]+//[^/$]+\"", ",", "current_url", ")", "[", "0", "]", "except", ":", "raise", "RuntimeError", "("...
Get the current base URL. Args: webdriver: Selenium WebDriver instance. Returns: str - base URL. Usage:: driver.get("http://www.google.com/?q=hello+world") WebUtils.get_base_url(driver) #returns 'http://www.google.com'
[ "Get", "the", "current", "base", "URL", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/web_utils.py#L57-L79
train
wiredrive/wtframework
wtframework/wtf/web/web_utils.py
WebUtils.get_browser_datetime
def get_browser_datetime(webdriver): """ Get the current date/time on the web browser as a Python datetime object. This date matches 'new Date();' when ran in JavaScript console. Args: webdriver: Selenium WebDriver instance Returns: datetime - Python datetime object. Usage:: browser_datetime = WebUtils.get_browser_datetime(driver) local_datetime = datetime.now() print("Difference time difference between browser and your local machine is:", local_datetime - browser_datetime) """ js_stmt = """ var wtf_get_date = new Date(); return {'month':wtf_get_date.getMonth(), 'day':wtf_get_date.getDate(), 'year':wtf_get_date.getFullYear(), 'hours':wtf_get_date.getHours(), 'minutes':wtf_get_date.getMinutes(), 'seconds':wtf_get_date.getSeconds(), 'milliseconds':wtf_get_date.getMilliseconds()}; """ browser_date = webdriver.execute_script(js_stmt) return datetime(int(browser_date['year']), int(browser_date['month']) + 1, # javascript months start at 0 int(browser_date['day']), int(browser_date['hours']), int(browser_date['minutes']), int(browser_date['seconds']), int(browser_date['milliseconds']))
python
def get_browser_datetime(webdriver): """ Get the current date/time on the web browser as a Python datetime object. This date matches 'new Date();' when ran in JavaScript console. Args: webdriver: Selenium WebDriver instance Returns: datetime - Python datetime object. Usage:: browser_datetime = WebUtils.get_browser_datetime(driver) local_datetime = datetime.now() print("Difference time difference between browser and your local machine is:", local_datetime - browser_datetime) """ js_stmt = """ var wtf_get_date = new Date(); return {'month':wtf_get_date.getMonth(), 'day':wtf_get_date.getDate(), 'year':wtf_get_date.getFullYear(), 'hours':wtf_get_date.getHours(), 'minutes':wtf_get_date.getMinutes(), 'seconds':wtf_get_date.getSeconds(), 'milliseconds':wtf_get_date.getMilliseconds()}; """ browser_date = webdriver.execute_script(js_stmt) return datetime(int(browser_date['year']), int(browser_date['month']) + 1, # javascript months start at 0 int(browser_date['day']), int(browser_date['hours']), int(browser_date['minutes']), int(browser_date['seconds']), int(browser_date['milliseconds']))
[ "def", "get_browser_datetime", "(", "webdriver", ")", ":", "js_stmt", "=", "\"\"\"\n var wtf_get_date = new Date();\n return {'month':wtf_get_date.getMonth(), \n 'day':wtf_get_date.getDate(), \n 'year':wtf_get_date.getFullYear(),\n ...
Get the current date/time on the web browser as a Python datetime object. This date matches 'new Date();' when ran in JavaScript console. Args: webdriver: Selenium WebDriver instance Returns: datetime - Python datetime object. Usage:: browser_datetime = WebUtils.get_browser_datetime(driver) local_datetime = datetime.now() print("Difference time difference between browser and your local machine is:", local_datetime - browser_datetime)
[ "Get", "the", "current", "date", "/", "time", "on", "the", "web", "browser", "as", "a", "Python", "datetime", "object", ".", "This", "date", "matches", "new", "Date", "()", ";", "when", "ran", "in", "JavaScript", "console", ".", "Args", ":", "webdriver",...
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/web_utils.py#L82-L116
train
wiredrive/wtframework
wtframework/wtf/web/web_utils.py
WebUtils.is_webdriver_mobile
def is_webdriver_mobile(webdriver): """ Check if a web driver if mobile. Args: webdriver (WebDriver): Selenium webdriver. """ browser = webdriver.capabilities['browserName'] if (browser == u('iPhone') or browser == u('android')): return True else: return False
python
def is_webdriver_mobile(webdriver): """ Check if a web driver if mobile. Args: webdriver (WebDriver): Selenium webdriver. """ browser = webdriver.capabilities['browserName'] if (browser == u('iPhone') or browser == u('android')): return True else: return False
[ "def", "is_webdriver_mobile", "(", "webdriver", ")", ":", "browser", "=", "webdriver", ".", "capabilities", "[", "'browserName'", "]", "if", "(", "browser", "==", "u", "(", "'iPhone'", ")", "or", "browser", "==", "u", "(", "'android'", ")", ")", ":", "re...
Check if a web driver if mobile. Args: webdriver (WebDriver): Selenium webdriver.
[ "Check", "if", "a", "web", "driver", "if", "mobile", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/web_utils.py#L119-L133
train
wiredrive/wtframework
wtframework/wtf/web/web_utils.py
WebUtils.is_webdriver_ios
def is_webdriver_ios(webdriver): """ Check if a web driver if mobile. Args: webdriver (WebDriver): Selenium webdriver. """ browser = webdriver.capabilities['browserName'] if (browser == u('iPhone') or browser == u('iPad')): return True else: return False
python
def is_webdriver_ios(webdriver): """ Check if a web driver if mobile. Args: webdriver (WebDriver): Selenium webdriver. """ browser = webdriver.capabilities['browserName'] if (browser == u('iPhone') or browser == u('iPad')): return True else: return False
[ "def", "is_webdriver_ios", "(", "webdriver", ")", ":", "browser", "=", "webdriver", ".", "capabilities", "[", "'browserName'", "]", "if", "(", "browser", "==", "u", "(", "'iPhone'", ")", "or", "browser", "==", "u", "(", "'iPad'", ")", ")", ":", "return",...
Check if a web driver if mobile. Args: webdriver (WebDriver): Selenium webdriver.
[ "Check", "if", "a", "web", "driver", "if", "mobile", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/web_utils.py#L136-L150
train
wiredrive/wtframework
wtframework/wtf/web/web_utils.py
WebUtils.row_to_dictionary
def row_to_dictionary(header_row_web_element, row_webelement): """ Converts a row into a dictionary of key/values. (Note: assumes all rows/columns have uniform cells. Does not account for any row or column spans) Args: header_row_web_element (WebElement): WebElement reference to the column headers. row_webelement (WebElement): WebElement reference to row. Returns: Returns a dictionary object containing keys consistenting of the column headers and values consisting of the row contents. Usage:: self.webdriver.get("http://the-internet.herokuapp.com/tables") header = self.webdriver.find_element_by_css_selector("#table1 thead tr") target_row = self.webdriver.find_element_by_css_selector("#table1 tbody tr") row_values = WebUtils.row_to_dictionary(header, target_row) row_values == {'Last Name': 'Smith', 'Due': '$50.00', 'First Name': 'John', 'Web Site': 'http://www.jsmith.com', 'Action': 'edit delete', 'Email': 'jsmith@gmail.com'} """ headers = header_row_web_element.find_elements_by_tag_name("th") data_cells = row_webelement.find_elements_by_tag_name("td") value_dictionary = {} for i in range(len(data_cells)): value_dictionary[ headers[i].text ] = data_cells[i].text return value_dictionary
python
def row_to_dictionary(header_row_web_element, row_webelement): """ Converts a row into a dictionary of key/values. (Note: assumes all rows/columns have uniform cells. Does not account for any row or column spans) Args: header_row_web_element (WebElement): WebElement reference to the column headers. row_webelement (WebElement): WebElement reference to row. Returns: Returns a dictionary object containing keys consistenting of the column headers and values consisting of the row contents. Usage:: self.webdriver.get("http://the-internet.herokuapp.com/tables") header = self.webdriver.find_element_by_css_selector("#table1 thead tr") target_row = self.webdriver.find_element_by_css_selector("#table1 tbody tr") row_values = WebUtils.row_to_dictionary(header, target_row) row_values == {'Last Name': 'Smith', 'Due': '$50.00', 'First Name': 'John', 'Web Site': 'http://www.jsmith.com', 'Action': 'edit delete', 'Email': 'jsmith@gmail.com'} """ headers = header_row_web_element.find_elements_by_tag_name("th") data_cells = row_webelement.find_elements_by_tag_name("td") value_dictionary = {} for i in range(len(data_cells)): value_dictionary[ headers[i].text ] = data_cells[i].text return value_dictionary
[ "def", "row_to_dictionary", "(", "header_row_web_element", ",", "row_webelement", ")", ":", "headers", "=", "header_row_web_element", ".", "find_elements_by_tag_name", "(", "\"th\"", ")", "data_cells", "=", "row_webelement", ".", "find_elements_by_tag_name", "(", "\"td\""...
Converts a row into a dictionary of key/values. (Note: assumes all rows/columns have uniform cells. Does not account for any row or column spans) Args: header_row_web_element (WebElement): WebElement reference to the column headers. row_webelement (WebElement): WebElement reference to row. Returns: Returns a dictionary object containing keys consistenting of the column headers and values consisting of the row contents. Usage:: self.webdriver.get("http://the-internet.herokuapp.com/tables") header = self.webdriver.find_element_by_css_selector("#table1 thead tr") target_row = self.webdriver.find_element_by_css_selector("#table1 tbody tr") row_values = WebUtils.row_to_dictionary(header, target_row) row_values == {'Last Name': 'Smith', 'Due': '$50.00', 'First Name': 'John', 'Web Site': 'http://www.jsmith.com', 'Action': 'edit delete', 'Email': 'jsmith@gmail.com'}
[ "Converts", "a", "row", "into", "a", "dictionary", "of", "key", "/", "values", ".", "(", "Note", ":", "assumes", "all", "rows", "/", "columns", "have", "uniform", "cells", ".", "Does", "not", "account", "for", "any", "row", "or", "column", "spans", ")"...
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/web_utils.py#L154-L191
train
wiredrive/wtframework
wtframework/wtf/web/web_utils.py
WebUtils.switch_to_window
def switch_to_window(page_class, webdriver): """ Utility method for switching between windows. It will search through currently open windows, then switch to the window matching the provided PageObject class. Args: page_class (PageObject): Page class to search for/instantiate. webdriver (WebDriver): Selenium webdriver. Usage:: WebUtils.switch_to_window(DetailsPopUpPage, driver) # switches to the pop up window. """ window_list = list(webdriver.window_handles) original_window = webdriver.current_window_handle for window_handle in window_list: webdriver.switch_to_window(window_handle) try: return PageFactory.create_page(page_class, webdriver) except: pass webdriver.switch_to_window(original_window) raise WindowNotFoundError( u("Window {0} not found.").format(page_class.__class__.__name__))
python
def switch_to_window(page_class, webdriver): """ Utility method for switching between windows. It will search through currently open windows, then switch to the window matching the provided PageObject class. Args: page_class (PageObject): Page class to search for/instantiate. webdriver (WebDriver): Selenium webdriver. Usage:: WebUtils.switch_to_window(DetailsPopUpPage, driver) # switches to the pop up window. """ window_list = list(webdriver.window_handles) original_window = webdriver.current_window_handle for window_handle in window_list: webdriver.switch_to_window(window_handle) try: return PageFactory.create_page(page_class, webdriver) except: pass webdriver.switch_to_window(original_window) raise WindowNotFoundError( u("Window {0} not found.").format(page_class.__class__.__name__))
[ "def", "switch_to_window", "(", "page_class", ",", "webdriver", ")", ":", "window_list", "=", "list", "(", "webdriver", ".", "window_handles", ")", "original_window", "=", "webdriver", ".", "current_window_handle", "for", "window_handle", "in", "window_list", ":", ...
Utility method for switching between windows. It will search through currently open windows, then switch to the window matching the provided PageObject class. Args: page_class (PageObject): Page class to search for/instantiate. webdriver (WebDriver): Selenium webdriver. Usage:: WebUtils.switch_to_window(DetailsPopUpPage, driver) # switches to the pop up window.
[ "Utility", "method", "for", "switching", "between", "windows", ".", "It", "will", "search", "through", "currently", "open", "windows", "then", "switch", "to", "the", "window", "matching", "the", "provided", "PageObject", "class", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/web_utils.py#L196-L221
train
wiredrive/wtframework
wtframework/wtf/web/web_utils.py
BrowserStandBy.start_standby
def start_standby(cls, webdriver=None, max_time=WTF_TIMEOUT_MANAGER.EPIC, sleep=5): """ Create an instance of BrowserStandBy() and immediately return a running instance. This is best used in a 'with' block. Example:: with BrowserStandBy.start_standby(): # Now browser is in standby, you can do a bunch of stuff with in this block. # ... # We are now outside the block, and the browser standby has ended. """ return cls(webdriver=webdriver, max_time=max_time, sleep=sleep, _autostart=True)
python
def start_standby(cls, webdriver=None, max_time=WTF_TIMEOUT_MANAGER.EPIC, sleep=5): """ Create an instance of BrowserStandBy() and immediately return a running instance. This is best used in a 'with' block. Example:: with BrowserStandBy.start_standby(): # Now browser is in standby, you can do a bunch of stuff with in this block. # ... # We are now outside the block, and the browser standby has ended. """ return cls(webdriver=webdriver, max_time=max_time, sleep=sleep, _autostart=True)
[ "def", "start_standby", "(", "cls", ",", "webdriver", "=", "None", ",", "max_time", "=", "WTF_TIMEOUT_MANAGER", ".", "EPIC", ",", "sleep", "=", "5", ")", ":", "return", "cls", "(", "webdriver", "=", "webdriver", ",", "max_time", "=", "max_time", ",", "sl...
Create an instance of BrowserStandBy() and immediately return a running instance. This is best used in a 'with' block. Example:: with BrowserStandBy.start_standby(): # Now browser is in standby, you can do a bunch of stuff with in this block. # ... # We are now outside the block, and the browser standby has ended.
[ "Create", "an", "instance", "of", "BrowserStandBy", "()", "and", "immediately", "return", "a", "running", "instance", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/web_utils.py#L267-L282
train
wiredrive/wtframework
wtframework/wtf/web/web_utils.py
BrowserStandBy.start
def start(self): """ Start standing by. A periodic command like 'current_url' will be sent to the webdriver instance to prevent it from timing out. """ self._end_time = datetime.now() + timedelta(seconds=self._max_time) self._thread = Thread(target=lambda: self.__stand_by_loop()) self._keep_running = True self._thread.start() return self
python
def start(self): """ Start standing by. A periodic command like 'current_url' will be sent to the webdriver instance to prevent it from timing out. """ self._end_time = datetime.now() + timedelta(seconds=self._max_time) self._thread = Thread(target=lambda: self.__stand_by_loop()) self._keep_running = True self._thread.start() return self
[ "def", "start", "(", "self", ")", ":", "self", ".", "_end_time", "=", "datetime", ".", "now", "(", ")", "+", "timedelta", "(", "seconds", "=", "self", ".", "_max_time", ")", "self", ".", "_thread", "=", "Thread", "(", "target", "=", "lambda", ":", ...
Start standing by. A periodic command like 'current_url' will be sent to the webdriver instance to prevent it from timing out.
[ "Start", "standing", "by", ".", "A", "periodic", "command", "like", "current_url", "will", "be", "sent", "to", "the", "webdriver", "instance", "to", "prevent", "it", "from", "timing", "out", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/web_utils.py#L284-L294
train
wiredrive/wtframework
wtframework/wtf/utils/file_utils.py
temp_path
def temp_path(file_name=None): """ Gets a temp path. Kwargs: file_name (str) : if file name is specified, it gets appended to the temp dir. Usage:: temp_file_path = temp_path("myfile") copyfile("myfile", temp_file_path) # copies 'myfile' to '/tmp/myfile' """ if file_name is None: file_name = generate_timestamped_string("wtf_temp_file") return os.path.join(tempfile.gettempdir(), file_name)
python
def temp_path(file_name=None): """ Gets a temp path. Kwargs: file_name (str) : if file name is specified, it gets appended to the temp dir. Usage:: temp_file_path = temp_path("myfile") copyfile("myfile", temp_file_path) # copies 'myfile' to '/tmp/myfile' """ if file_name is None: file_name = generate_timestamped_string("wtf_temp_file") return os.path.join(tempfile.gettempdir(), file_name)
[ "def", "temp_path", "(", "file_name", "=", "None", ")", ":", "if", "file_name", "is", "None", ":", "file_name", "=", "generate_timestamped_string", "(", "\"wtf_temp_file\"", ")", "return", "os", ".", "path", ".", "join", "(", "tempfile", ".", "gettempdir", "...
Gets a temp path. Kwargs: file_name (str) : if file name is specified, it gets appended to the temp dir. Usage:: temp_file_path = temp_path("myfile") copyfile("myfile", temp_file_path) # copies 'myfile' to '/tmp/myfile'
[ "Gets", "a", "temp", "path", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/file_utils.py#L29-L46
train
wiredrive/wtframework
wtframework/wtf/utils/file_utils.py
create_temp_file
def create_temp_file(file_name=None, string_or_another_file=""): """ Creates a temp file using a given name. Temp files are placed in the Project/temp/ directory. Any temp files being created with an existing temp file, will be overridden. This is useful for testing uploads, where you would want to create a temporary file with a desired name, upload it, then delete the file when you're done. Kwargs: file_name (str): Name of file string_or_another_file: Contents to set this file to. If this is set to a file, it will copy that file. If this is set to a string, then it will write this string to the temp file. Return: str - Returns the file path to the generated temp file. Usage:: temp_file_path = create_temp_file("mytestfile", "The nimble fox jumps over the lazy dog.") file_obj = open(temp_file_path) os.remove(temp_file_path) """ temp_file_path = temp_path(file_name) if isinstance(string_or_another_file, file): # attempt to read it as a file. temp_file = open(temp_file_path, "wb") temp_file.write(string_or_another_file.read()) else: # handle as a string type if we can't handle as a file. temp_file = codecs.open(temp_file_path, "w+", "utf-8") temp_file.write(string_or_another_file) temp_file.close() return temp_file_path
python
def create_temp_file(file_name=None, string_or_another_file=""): """ Creates a temp file using a given name. Temp files are placed in the Project/temp/ directory. Any temp files being created with an existing temp file, will be overridden. This is useful for testing uploads, where you would want to create a temporary file with a desired name, upload it, then delete the file when you're done. Kwargs: file_name (str): Name of file string_or_another_file: Contents to set this file to. If this is set to a file, it will copy that file. If this is set to a string, then it will write this string to the temp file. Return: str - Returns the file path to the generated temp file. Usage:: temp_file_path = create_temp_file("mytestfile", "The nimble fox jumps over the lazy dog.") file_obj = open(temp_file_path) os.remove(temp_file_path) """ temp_file_path = temp_path(file_name) if isinstance(string_or_another_file, file): # attempt to read it as a file. temp_file = open(temp_file_path, "wb") temp_file.write(string_or_another_file.read()) else: # handle as a string type if we can't handle as a file. temp_file = codecs.open(temp_file_path, "w+", "utf-8") temp_file.write(string_or_another_file) temp_file.close() return temp_file_path
[ "def", "create_temp_file", "(", "file_name", "=", "None", ",", "string_or_another_file", "=", "\"\"", ")", ":", "temp_file_path", "=", "temp_path", "(", "file_name", ")", "if", "isinstance", "(", "string_or_another_file", ",", "file", ")", ":", "# attempt to read ...
Creates a temp file using a given name. Temp files are placed in the Project/temp/ directory. Any temp files being created with an existing temp file, will be overridden. This is useful for testing uploads, where you would want to create a temporary file with a desired name, upload it, then delete the file when you're done. Kwargs: file_name (str): Name of file string_or_another_file: Contents to set this file to. If this is set to a file, it will copy that file. If this is set to a string, then it will write this string to the temp file. Return: str - Returns the file path to the generated temp file. Usage:: temp_file_path = create_temp_file("mytestfile", "The nimble fox jumps over the lazy dog.") file_obj = open(temp_file_path) os.remove(temp_file_path)
[ "Creates", "a", "temp", "file", "using", "a", "given", "name", ".", "Temp", "files", "are", "placed", "in", "the", "Project", "/", "temp", "/", "directory", ".", "Any", "temp", "files", "being", "created", "with", "an", "existing", "temp", "file", "will"...
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/file_utils.py#L49-L84
train
wiredrive/wtframework
wtframework/wtf/utils/file_utils.py
download_to_tempfile
def download_to_tempfile(url, file_name=None, extension=None): """ Downloads a URL contents to a tempfile. This is useful for testing downloads. It will download the contents of a URL to a tempfile, which you then can open and use to validate the downloaded contents. Args: url (str) : URL of the contents to download. Kwargs: file_name (str): Name of file. extension (str): Extension to use. Return: str - Returns path to the temp file. """ if not file_name: file_name = generate_timestamped_string("wtf_temp_file") if extension: file_path = temp_path(file_name + extension) else: ext = "" try: ext = re.search(u"\\.\\w+$", file_name).group(0) except: pass file_path = temp_path(file_name + ext) webFile = urllib.urlopen(url) localFile = open(file_path, 'w') localFile.write(webFile.read()) webFile.close() localFile.close() return file_path
python
def download_to_tempfile(url, file_name=None, extension=None): """ Downloads a URL contents to a tempfile. This is useful for testing downloads. It will download the contents of a URL to a tempfile, which you then can open and use to validate the downloaded contents. Args: url (str) : URL of the contents to download. Kwargs: file_name (str): Name of file. extension (str): Extension to use. Return: str - Returns path to the temp file. """ if not file_name: file_name = generate_timestamped_string("wtf_temp_file") if extension: file_path = temp_path(file_name + extension) else: ext = "" try: ext = re.search(u"\\.\\w+$", file_name).group(0) except: pass file_path = temp_path(file_name + ext) webFile = urllib.urlopen(url) localFile = open(file_path, 'w') localFile.write(webFile.read()) webFile.close() localFile.close() return file_path
[ "def", "download_to_tempfile", "(", "url", ",", "file_name", "=", "None", ",", "extension", "=", "None", ")", ":", "if", "not", "file_name", ":", "file_name", "=", "generate_timestamped_string", "(", "\"wtf_temp_file\"", ")", "if", "extension", ":", "file_path",...
Downloads a URL contents to a tempfile. This is useful for testing downloads. It will download the contents of a URL to a tempfile, which you then can open and use to validate the downloaded contents. Args: url (str) : URL of the contents to download. Kwargs: file_name (str): Name of file. extension (str): Extension to use. Return: str - Returns path to the temp file.
[ "Downloads", "a", "URL", "contents", "to", "a", "tempfile", ".", "This", "is", "useful", "for", "testing", "downloads", ".", "It", "will", "download", "the", "contents", "of", "a", "URL", "to", "a", "tempfile", "which", "you", "then", "can", "open", "and...
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/file_utils.py#L87-L124
train
wiredrive/wtframework
wtframework/wtf/web/page.py
PageObject.create_page
def create_page(cls, webdriver=None, **kwargs): """Class method short cut to call PageFactory on itself. Use it to instantiate this PageObject using a webdriver. Args: webdriver (Webdriver): Instance of Selenium Webdriver. Returns: PageObject Raises: InvalidPageError """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() return PageFactory.create_page(cls, webdriver=webdriver, **kwargs)
python
def create_page(cls, webdriver=None, **kwargs): """Class method short cut to call PageFactory on itself. Use it to instantiate this PageObject using a webdriver. Args: webdriver (Webdriver): Instance of Selenium Webdriver. Returns: PageObject Raises: InvalidPageError """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() return PageFactory.create_page(cls, webdriver=webdriver, **kwargs)
[ "def", "create_page", "(", "cls", ",", "webdriver", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "webdriver", ":", "webdriver", "=", "WTF_WEBDRIVER_MANAGER", ".", "get_driver", "(", ")", "return", "PageFactory", ".", "create_page", "(", "cl...
Class method short cut to call PageFactory on itself. Use it to instantiate this PageObject using a webdriver. Args: webdriver (Webdriver): Instance of Selenium Webdriver. Returns: PageObject Raises: InvalidPageError
[ "Class", "method", "short", "cut", "to", "call", "PageFactory", "on", "itself", ".", "Use", "it", "to", "instantiate", "this", "PageObject", "using", "a", "webdriver", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/page.py#L114-L130
train
wiredrive/wtframework
wtframework/wtf/web/page.py
PageFactory.create_page
def create_page(page_object_class_or_interface, webdriver=None, **kwargs): """ Instantiate a page object from a given Interface or Abstract class. Args: page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or Interface to attempt to consturct. Kwargs: webdriver (WebDriver): Selenium Webdriver to use to instantiate the page. If none is provided, then it was use the default from WTF_WEBDRIVER_MANAGER Returns: PageObject Raises: NoMatchingPageError Instantiating a Page from PageObject from class usage:: my_page_instance = PageFactory.create_page(MyPageClass) Instantiating a Page from an Interface or base class:: import pages.mysite.* # Make sure you import classes first, or else PageFactory will not know about it. my_page_instance = PageFactory.create_page(MyPageInterfaceClass) Instantiating a Page from a list of classes.:: my_page_instance = PageFactory.create_page([PossiblePage1, PossiblePage2]) Note: It'll only be able to detect pages that are imported. To it's best to do an import of all pages implementing a base class or the interface inside the __init__.py of the package directory. """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() # will be used later when tracking best matched page. current_matched_page = None # used to track if there is a valid page object within the set of PageObjects searched. was_validate_called = False # Walk through all classes if a list was passed. if type(page_object_class_or_interface) == list: subclasses = [] for page_class in page_object_class_or_interface: # attempt to instantiate class. page = PageFactory.__instantiate_page_object(page_class, webdriver, **kwargs) if isinstance(page, PageObject): was_validate_called = True if (current_matched_page == None or page > current_matched_page): current_matched_page = page elif page is True: was_validate_called = True # check for subclasses subclasses += PageFactory.__itersubclasses(page_class) else: # A single class was passed in, try to instantiate the class. page_class = page_object_class_or_interface page = PageFactory.__instantiate_page_object(page_class, webdriver, **kwargs) # Check if we got a valid PageObject back. if isinstance(page, PageObject): was_validate_called = True current_matched_page = page elif page is True: was_validate_called = True # check for subclasses subclasses = PageFactory.__itersubclasses( page_object_class_or_interface) # Iterate over subclasses of the passed in classes to see if we have a # better match. for pageClass in subclasses: try: page = PageFactory.__instantiate_page_object(pageClass, webdriver, **kwargs) # If we get a valid PageObject match, check to see if the ranking is higher # than our current PageObject. if isinstance(page, PageObject): was_validate_called = True if current_matched_page == None or page > current_matched_page: current_matched_page = page elif page is True: was_validate_called = True except InvalidPageError as e: _wtflog.debug("InvalidPageError: %s", e) pass # This happens when the page fails check. except TypeError as e: _wtflog.debug("TypeError: %s", e) # this happens when it tries to instantiate the original # abstract class. pass except Exception as e: _wtflog.debug("Exception during page instantiation: %s", e) # Unexpected exception. raise e # If no matching classes. if not isinstance(current_matched_page, PageObject): # Check that there is at least 1 valid page object that was passed in. if was_validate_called is False: raise TypeError("Neither the PageObjects nor it's subclasses have implemented " + "'PageObject._validate(self, webdriver)'.") try: current_url = webdriver.current_url raise NoMatchingPageError(u("There's, no matching classes to this page. URL:{0}") .format(current_url)) except: raise NoMatchingPageError(u("There's, no matching classes to this page. ")) else: return current_matched_page
python
def create_page(page_object_class_or_interface, webdriver=None, **kwargs): """ Instantiate a page object from a given Interface or Abstract class. Args: page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or Interface to attempt to consturct. Kwargs: webdriver (WebDriver): Selenium Webdriver to use to instantiate the page. If none is provided, then it was use the default from WTF_WEBDRIVER_MANAGER Returns: PageObject Raises: NoMatchingPageError Instantiating a Page from PageObject from class usage:: my_page_instance = PageFactory.create_page(MyPageClass) Instantiating a Page from an Interface or base class:: import pages.mysite.* # Make sure you import classes first, or else PageFactory will not know about it. my_page_instance = PageFactory.create_page(MyPageInterfaceClass) Instantiating a Page from a list of classes.:: my_page_instance = PageFactory.create_page([PossiblePage1, PossiblePage2]) Note: It'll only be able to detect pages that are imported. To it's best to do an import of all pages implementing a base class or the interface inside the __init__.py of the package directory. """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() # will be used later when tracking best matched page. current_matched_page = None # used to track if there is a valid page object within the set of PageObjects searched. was_validate_called = False # Walk through all classes if a list was passed. if type(page_object_class_or_interface) == list: subclasses = [] for page_class in page_object_class_or_interface: # attempt to instantiate class. page = PageFactory.__instantiate_page_object(page_class, webdriver, **kwargs) if isinstance(page, PageObject): was_validate_called = True if (current_matched_page == None or page > current_matched_page): current_matched_page = page elif page is True: was_validate_called = True # check for subclasses subclasses += PageFactory.__itersubclasses(page_class) else: # A single class was passed in, try to instantiate the class. page_class = page_object_class_or_interface page = PageFactory.__instantiate_page_object(page_class, webdriver, **kwargs) # Check if we got a valid PageObject back. if isinstance(page, PageObject): was_validate_called = True current_matched_page = page elif page is True: was_validate_called = True # check for subclasses subclasses = PageFactory.__itersubclasses( page_object_class_or_interface) # Iterate over subclasses of the passed in classes to see if we have a # better match. for pageClass in subclasses: try: page = PageFactory.__instantiate_page_object(pageClass, webdriver, **kwargs) # If we get a valid PageObject match, check to see if the ranking is higher # than our current PageObject. if isinstance(page, PageObject): was_validate_called = True if current_matched_page == None or page > current_matched_page: current_matched_page = page elif page is True: was_validate_called = True except InvalidPageError as e: _wtflog.debug("InvalidPageError: %s", e) pass # This happens when the page fails check. except TypeError as e: _wtflog.debug("TypeError: %s", e) # this happens when it tries to instantiate the original # abstract class. pass except Exception as e: _wtflog.debug("Exception during page instantiation: %s", e) # Unexpected exception. raise e # If no matching classes. if not isinstance(current_matched_page, PageObject): # Check that there is at least 1 valid page object that was passed in. if was_validate_called is False: raise TypeError("Neither the PageObjects nor it's subclasses have implemented " + "'PageObject._validate(self, webdriver)'.") try: current_url = webdriver.current_url raise NoMatchingPageError(u("There's, no matching classes to this page. URL:{0}") .format(current_url)) except: raise NoMatchingPageError(u("There's, no matching classes to this page. ")) else: return current_matched_page
[ "def", "create_page", "(", "page_object_class_or_interface", ",", "webdriver", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "webdriver", ":", "webdriver", "=", "WTF_WEBDRIVER_MANAGER", ".", "get_driver", "(", ")", "# will be used later when tracking ...
Instantiate a page object from a given Interface or Abstract class. Args: page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or Interface to attempt to consturct. Kwargs: webdriver (WebDriver): Selenium Webdriver to use to instantiate the page. If none is provided, then it was use the default from WTF_WEBDRIVER_MANAGER Returns: PageObject Raises: NoMatchingPageError Instantiating a Page from PageObject from class usage:: my_page_instance = PageFactory.create_page(MyPageClass) Instantiating a Page from an Interface or base class:: import pages.mysite.* # Make sure you import classes first, or else PageFactory will not know about it. my_page_instance = PageFactory.create_page(MyPageInterfaceClass) Instantiating a Page from a list of classes.:: my_page_instance = PageFactory.create_page([PossiblePage1, PossiblePage2]) Note: It'll only be able to detect pages that are imported. To it's best to do an import of all pages implementing a base class or the interface inside the __init__.py of the package directory.
[ "Instantiate", "a", "page", "object", "from", "a", "given", "Interface", "or", "Abstract", "class", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/page.py#L167-L296
train
wiredrive/wtframework
wtframework/wtf/web/page.py
PageFactory.__instantiate_page_object
def __instantiate_page_object(page_obj_class, webdriver, **kwargs): """ Attempts to instantiate a page object. Args: page_obj_class (PageObject) - PageObject to instantiate. webdriver (WebDriver) - Selenium webdriver to associate with the PageObject Returns: PageObject - If page object instantiation succeeded. True - If page object instantiation failed, but validation was called. None - If validation did not occur. """ try: page = page_obj_class(webdriver, **kwargs) return page except InvalidPageError: # This happens when the page fails check. # Means validate was implemented, but the check didn't pass. return True except TypeError: # this happens when it tries to instantiate the original abstract # class, or a PageObject where _validate() was not implemented. return False except Exception as e: # Unexpected exception. raise e
python
def __instantiate_page_object(page_obj_class, webdriver, **kwargs): """ Attempts to instantiate a page object. Args: page_obj_class (PageObject) - PageObject to instantiate. webdriver (WebDriver) - Selenium webdriver to associate with the PageObject Returns: PageObject - If page object instantiation succeeded. True - If page object instantiation failed, but validation was called. None - If validation did not occur. """ try: page = page_obj_class(webdriver, **kwargs) return page except InvalidPageError: # This happens when the page fails check. # Means validate was implemented, but the check didn't pass. return True except TypeError: # this happens when it tries to instantiate the original abstract # class, or a PageObject where _validate() was not implemented. return False except Exception as e: # Unexpected exception. raise e
[ "def", "__instantiate_page_object", "(", "page_obj_class", ",", "webdriver", ",", "*", "*", "kwargs", ")", ":", "try", ":", "page", "=", "page_obj_class", "(", "webdriver", ",", "*", "*", "kwargs", ")", "return", "page", "except", "InvalidPageError", ":", "#...
Attempts to instantiate a page object. Args: page_obj_class (PageObject) - PageObject to instantiate. webdriver (WebDriver) - Selenium webdriver to associate with the PageObject Returns: PageObject - If page object instantiation succeeded. True - If page object instantiation failed, but validation was called. None - If validation did not occur.
[ "Attempts", "to", "instantiate", "a", "page", "object", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/page.py#L299-L326
train
wiredrive/wtframework
wtframework/wtf/web/page.py
PageFactory.__itersubclasses
def __itersubclasses(cls, _seen=None): """ Credit goes to: http://code.activestate.com/recipes/576949-find-all-subclasses-of-a-given-class/ itersubclasses(cls) Generator over all subclasses of a given class, in depth first order. >>> list(itersubclasses(int)) == [bool] True >>> class A(object): pass >>> class B(A): pass >>> class C(A): pass >>> class D(B,C): pass >>> class E(D): pass >>> >>> for cls in itersubclasses(A): ... print(cls.__name__) B D E C >>> # get ALL (new-style) classes currently defined >>> [cls.__name__ for cls in itersubclasses(object)] #doctest: +ELLIPSIS ['type', ...'tuple', ...] """ if not isinstance(cls, type): raise TypeError(u('Argument ({0}) passed to PageFactory does not appear to be a valid Class.').format(cls), "Check to make sure the first parameter is an PageObject class, interface, or mixin.") if _seen is None: _seen = set() try: subs = cls.__subclasses__() except TypeError: # fails only when cls is type subs = cls.__subclasses__(cls) for sub in subs: if sub not in _seen: _seen.add(sub) yield sub for sub in PageFactory.__itersubclasses(sub, _seen): yield sub
python
def __itersubclasses(cls, _seen=None): """ Credit goes to: http://code.activestate.com/recipes/576949-find-all-subclasses-of-a-given-class/ itersubclasses(cls) Generator over all subclasses of a given class, in depth first order. >>> list(itersubclasses(int)) == [bool] True >>> class A(object): pass >>> class B(A): pass >>> class C(A): pass >>> class D(B,C): pass >>> class E(D): pass >>> >>> for cls in itersubclasses(A): ... print(cls.__name__) B D E C >>> # get ALL (new-style) classes currently defined >>> [cls.__name__ for cls in itersubclasses(object)] #doctest: +ELLIPSIS ['type', ...'tuple', ...] """ if not isinstance(cls, type): raise TypeError(u('Argument ({0}) passed to PageFactory does not appear to be a valid Class.').format(cls), "Check to make sure the first parameter is an PageObject class, interface, or mixin.") if _seen is None: _seen = set() try: subs = cls.__subclasses__() except TypeError: # fails only when cls is type subs = cls.__subclasses__(cls) for sub in subs: if sub not in _seen: _seen.add(sub) yield sub for sub in PageFactory.__itersubclasses(sub, _seen): yield sub
[ "def", "__itersubclasses", "(", "cls", ",", "_seen", "=", "None", ")", ":", "if", "not", "isinstance", "(", "cls", ",", "type", ")", ":", "raise", "TypeError", "(", "u", "(", "'Argument ({0}) passed to PageFactory does not appear to be a valid Class.'", ")", ".", ...
Credit goes to: http://code.activestate.com/recipes/576949-find-all-subclasses-of-a-given-class/ itersubclasses(cls) Generator over all subclasses of a given class, in depth first order. >>> list(itersubclasses(int)) == [bool] True >>> class A(object): pass >>> class B(A): pass >>> class C(A): pass >>> class D(B,C): pass >>> class E(D): pass >>> >>> for cls in itersubclasses(A): ... print(cls.__name__) B D E C >>> # get ALL (new-style) classes currently defined >>> [cls.__name__ for cls in itersubclasses(object)] #doctest: +ELLIPSIS ['type', ...'tuple', ...]
[ "Credit", "goes", "to", ":", "http", ":", "//", "code", ".", "activestate", ".", "com", "/", "recipes", "/", "576949", "-", "find", "-", "all", "-", "subclasses", "-", "of", "-", "a", "-", "given", "-", "class", "/" ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/page.py#L330-L371
train
wiredrive/wtframework
wtframework/wtf/web/page.py
PageObjectUtils.check_css_selectors
def check_css_selectors(webdriver, *selectors): """Returns true if all CSS selectors passed in is found. This can be used to quickly validate a page. Args: webdriver (Webdriver) : Selenium Webdriver instance selectors (str) : N number of CSS selectors strings to match against the page. Returns: True, False - if the page matches all selectors. Usage Example:: # Checks for a Form with id='loginForm' and a button with class 'login' if not PageObjectUtils.check_css_selectors("form#loginForm", "button.login"): raise InvalidPageError("This is not the login page.") You can use this within a PageObject's `_validate_page(webdriver)` method for validating pages. """ for selector in selectors: try: webdriver.find_element_by_css_selector(selector) except: return False # A selector failed. return True
python
def check_css_selectors(webdriver, *selectors): """Returns true if all CSS selectors passed in is found. This can be used to quickly validate a page. Args: webdriver (Webdriver) : Selenium Webdriver instance selectors (str) : N number of CSS selectors strings to match against the page. Returns: True, False - if the page matches all selectors. Usage Example:: # Checks for a Form with id='loginForm' and a button with class 'login' if not PageObjectUtils.check_css_selectors("form#loginForm", "button.login"): raise InvalidPageError("This is not the login page.") You can use this within a PageObject's `_validate_page(webdriver)` method for validating pages. """ for selector in selectors: try: webdriver.find_element_by_css_selector(selector) except: return False # A selector failed. return True
[ "def", "check_css_selectors", "(", "webdriver", ",", "*", "selectors", ")", ":", "for", "selector", "in", "selectors", ":", "try", ":", "webdriver", ".", "find_element_by_css_selector", "(", "selector", ")", "except", ":", "return", "False", "# A selector failed."...
Returns true if all CSS selectors passed in is found. This can be used to quickly validate a page. Args: webdriver (Webdriver) : Selenium Webdriver instance selectors (str) : N number of CSS selectors strings to match against the page. Returns: True, False - if the page matches all selectors. Usage Example:: # Checks for a Form with id='loginForm' and a button with class 'login' if not PageObjectUtils.check_css_selectors("form#loginForm", "button.login"): raise InvalidPageError("This is not the login page.") You can use this within a PageObject's `_validate_page(webdriver)` method for validating pages.
[ "Returns", "true", "if", "all", "CSS", "selectors", "passed", "in", "is", "found", ".", "This", "can", "be", "used", "to", "quickly", "validate", "a", "page", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/page.py#L387-L413
train
wiredrive/wtframework
wtframework/wtf/web/page.py
PageUtils.wait_until_page_loaded
def wait_until_page_loaded(page_obj_class, webdriver=None, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, bad_page_classes=[], message=None, **kwargs): """ Waits until the page is loaded. Args: page_obj_class (Class) : PageObject class Kwargs: webdriver (Webdriver) : Selenium Webdriver. Default uses WTF_WEBDRIVER_MANAGER's instance. timeout (number) : Number of seconds to wait to allow the page to load. sleep (number) : Number of seconds to wait between polling. bad_page_classes (list) : List of PageObject classes to fail if matched. For example, ServerError page. message (string) : Use your own message with PageLoadTimeoutError raised. Returns: PageObject Raises: PageUtilOperationTimeoutError : Timeout occurred before the desired PageObject was matched. BadPageEncounteredError : One or more of the PageObject in the specified 'bad_page_classes' list was matched. Usage Example:: webdriver.get("http://www.mysite.com/login") # Wait up to 60 seconds for the page to load. login_page = wait_until_page_loaded(LoginPage, timeout=60, [ServerErrorPage]) This will wait for the login_page to load, then return a LoginPage() PageObject. """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() # convert this param to list if not already. if type(bad_page_classes) != list: bad_page_classes = [bad_page_classes] end_time = datetime.now() + timedelta(seconds=timeout) last_exception = None while datetime.now() < end_time: # Check to see if we're at our target page. try: page = PageFactory.create_page( page_obj_class, webdriver=webdriver, **kwargs) return page except Exception as e: _wtflog.debug("Encountered exception: %s ", e) last_exception = e # Check to see if we're at one of those labled 'Bad' pages. for bad_page_class in bad_page_classes: try: PageFactory.create_page( bad_page_class, webdriver=webdriver, **kwargs) # if the if/else statement succeeds, than we have an error. raise BadPageEncounteredError( u("Encountered a bad page. ") + bad_page_class.__name__) except BadPageEncounteredError as e: raise e except: pass # We didn't hit a bad page class yet. # sleep till the next iteration. time.sleep(sleep) print "Unable to construct page, last exception", last_exception # Attempt to get current URL to assist in debugging try: current_url = webdriver.current_url except: # unable to get current URL, could be a webdriver for a non-webpage like mobile app. current_url = None if message: err_msg = u(message) + u("{page}:{url}")\ .format(page=PageUtils.__get_name_for_class__(page_obj_class), url=current_url) else: err_msg = u("Timed out while waiting for {page} to load. Url:{url}")\ .format(page=PageUtils.__get_name_for_class__(page_obj_class), url=current_url) raise PageLoadTimeoutError(err_msg)
python
def wait_until_page_loaded(page_obj_class, webdriver=None, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, bad_page_classes=[], message=None, **kwargs): """ Waits until the page is loaded. Args: page_obj_class (Class) : PageObject class Kwargs: webdriver (Webdriver) : Selenium Webdriver. Default uses WTF_WEBDRIVER_MANAGER's instance. timeout (number) : Number of seconds to wait to allow the page to load. sleep (number) : Number of seconds to wait between polling. bad_page_classes (list) : List of PageObject classes to fail if matched. For example, ServerError page. message (string) : Use your own message with PageLoadTimeoutError raised. Returns: PageObject Raises: PageUtilOperationTimeoutError : Timeout occurred before the desired PageObject was matched. BadPageEncounteredError : One or more of the PageObject in the specified 'bad_page_classes' list was matched. Usage Example:: webdriver.get("http://www.mysite.com/login") # Wait up to 60 seconds for the page to load. login_page = wait_until_page_loaded(LoginPage, timeout=60, [ServerErrorPage]) This will wait for the login_page to load, then return a LoginPage() PageObject. """ if not webdriver: webdriver = WTF_WEBDRIVER_MANAGER.get_driver() # convert this param to list if not already. if type(bad_page_classes) != list: bad_page_classes = [bad_page_classes] end_time = datetime.now() + timedelta(seconds=timeout) last_exception = None while datetime.now() < end_time: # Check to see if we're at our target page. try: page = PageFactory.create_page( page_obj_class, webdriver=webdriver, **kwargs) return page except Exception as e: _wtflog.debug("Encountered exception: %s ", e) last_exception = e # Check to see if we're at one of those labled 'Bad' pages. for bad_page_class in bad_page_classes: try: PageFactory.create_page( bad_page_class, webdriver=webdriver, **kwargs) # if the if/else statement succeeds, than we have an error. raise BadPageEncounteredError( u("Encountered a bad page. ") + bad_page_class.__name__) except BadPageEncounteredError as e: raise e except: pass # We didn't hit a bad page class yet. # sleep till the next iteration. time.sleep(sleep) print "Unable to construct page, last exception", last_exception # Attempt to get current URL to assist in debugging try: current_url = webdriver.current_url except: # unable to get current URL, could be a webdriver for a non-webpage like mobile app. current_url = None if message: err_msg = u(message) + u("{page}:{url}")\ .format(page=PageUtils.__get_name_for_class__(page_obj_class), url=current_url) else: err_msg = u("Timed out while waiting for {page} to load. Url:{url}")\ .format(page=PageUtils.__get_name_for_class__(page_obj_class), url=current_url) raise PageLoadTimeoutError(err_msg)
[ "def", "wait_until_page_loaded", "(", "page_obj_class", ",", "webdriver", "=", "None", ",", "timeout", "=", "WTF_TIMEOUT_MANAGER", ".", "NORMAL", ",", "sleep", "=", "0.5", ",", "bad_page_classes", "=", "[", "]", ",", "message", "=", "None", ",", "*", "*", ...
Waits until the page is loaded. Args: page_obj_class (Class) : PageObject class Kwargs: webdriver (Webdriver) : Selenium Webdriver. Default uses WTF_WEBDRIVER_MANAGER's instance. timeout (number) : Number of seconds to wait to allow the page to load. sleep (number) : Number of seconds to wait between polling. bad_page_classes (list) : List of PageObject classes to fail if matched. For example, ServerError page. message (string) : Use your own message with PageLoadTimeoutError raised. Returns: PageObject Raises: PageUtilOperationTimeoutError : Timeout occurred before the desired PageObject was matched. BadPageEncounteredError : One or more of the PageObject in the specified 'bad_page_classes' list was matched. Usage Example:: webdriver.get("http://www.mysite.com/login") # Wait up to 60 seconds for the page to load. login_page = wait_until_page_loaded(LoginPage, timeout=60, [ServerErrorPage]) This will wait for the login_page to load, then return a LoginPage() PageObject.
[ "Waits", "until", "the", "page", "is", "loaded", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/page.py#L422-L510
train
wiredrive/wtframework
wtframework/wtf/web/page.py
PageUtils.wait_until_page_ready
def wait_until_page_ready(page_object, timeout=WTF_TIMEOUT_MANAGER.NORMAL): """Waits until document.readyState == Complete (e.g. ready to execute javascript commands) Args: page_object (PageObject) : PageObject class Kwargs: timeout (number) : timeout period """ try: do_until(lambda: page_object.webdriver.execute_script("return document.readyState").lower() == 'complete', timeout) except wait_utils.OperationTimeoutError: raise PageUtilOperationTimeoutError( "Timeout occurred while waiting for page to be ready.")
python
def wait_until_page_ready(page_object, timeout=WTF_TIMEOUT_MANAGER.NORMAL): """Waits until document.readyState == Complete (e.g. ready to execute javascript commands) Args: page_object (PageObject) : PageObject class Kwargs: timeout (number) : timeout period """ try: do_until(lambda: page_object.webdriver.execute_script("return document.readyState").lower() == 'complete', timeout) except wait_utils.OperationTimeoutError: raise PageUtilOperationTimeoutError( "Timeout occurred while waiting for page to be ready.")
[ "def", "wait_until_page_ready", "(", "page_object", ",", "timeout", "=", "WTF_TIMEOUT_MANAGER", ".", "NORMAL", ")", ":", "try", ":", "do_until", "(", "lambda", ":", "page_object", ".", "webdriver", ".", "execute_script", "(", "\"return document.readyState\"", ")", ...
Waits until document.readyState == Complete (e.g. ready to execute javascript commands) Args: page_object (PageObject) : PageObject class Kwargs: timeout (number) : timeout period
[ "Waits", "until", "document", ".", "readyState", "==", "Complete", "(", "e", ".", "g", ".", "ready", "to", "execute", "javascript", "commands", ")" ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/page.py#L513-L527
train
wiredrive/wtframework
wtframework/wtf/assets.py
AssetManager.get_asset_path
def get_asset_path(self, filename): """ Get the full system path of a given asset if it exists. Otherwise it throws an error. Args: filename (str) - File name of a file in /assets folder to fetch the path for. Returns: str - path to the target file. Raises: AssetNotFoundError - if asset does not exist in the asset folder. Usage:: path = WTF_ASSET_MANAGER.get_asset_path("my_asset.png") # path = /your/workspace/location/WTFProjectName/assets/my_asset.png """ if os.path.exists(os.path.join(self._asset_path, filename)): return os.path.join(self._asset_path, filename) else: raise AssetNotFoundError( u("Cannot find asset: {0}").format(filename))
python
def get_asset_path(self, filename): """ Get the full system path of a given asset if it exists. Otherwise it throws an error. Args: filename (str) - File name of a file in /assets folder to fetch the path for. Returns: str - path to the target file. Raises: AssetNotFoundError - if asset does not exist in the asset folder. Usage:: path = WTF_ASSET_MANAGER.get_asset_path("my_asset.png") # path = /your/workspace/location/WTFProjectName/assets/my_asset.png """ if os.path.exists(os.path.join(self._asset_path, filename)): return os.path.join(self._asset_path, filename) else: raise AssetNotFoundError( u("Cannot find asset: {0}").format(filename))
[ "def", "get_asset_path", "(", "self", ",", "filename", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_asset_path", ",", "filename", ")", ")", ":", "return", "os", ".", "path", ".", "join",...
Get the full system path of a given asset if it exists. Otherwise it throws an error. Args: filename (str) - File name of a file in /assets folder to fetch the path for. Returns: str - path to the target file. Raises: AssetNotFoundError - if asset does not exist in the asset folder. Usage:: path = WTF_ASSET_MANAGER.get_asset_path("my_asset.png") # path = /your/workspace/location/WTFProjectName/assets/my_asset.png
[ "Get", "the", "full", "system", "path", "of", "a", "given", "asset", "if", "it", "exists", ".", "Otherwise", "it", "throws", "an", "error", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/assets.py#L47-L70
train
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverFactory.create_webdriver
def create_webdriver(self, testname=None): ''' Creates an instance of Selenium webdriver based on config settings. This should only be called by a shutdown hook. Do not call directly within a test. Kwargs: testname: Optional test name to pass, this gets appended to the test name sent to selenium grid. Returns: WebDriver - Selenium Webdriver instance. ''' try: driver_type = self._config_reader.get( self.DRIVER_TYPE_CONFIG) except: driver_type = self.DRIVER_TYPE_LOCAL _wtflog.warn("%s setting is missing from config. Using default setting, %s", self.DRIVER_TYPE_CONFIG, driver_type) if driver_type == self.DRIVER_TYPE_REMOTE: # Create desired capabilities. self.webdriver = self.__create_remote_webdriver_from_config( testname=testname) else: # handle as local webdriver self.webdriver = self.__create_driver_from_browser_config() try: self.webdriver.maximize_window() except: # wait a short period and try again. time.sleep(self._timeout_mgr.BRIEF) try: self.webdriver.maximize_window() except Exception as e: if (isinstance(e, WebDriverException) and "implemented" in e.msg.lower()): pass # Maximizing window not supported by this webdriver. else: _wtflog.warn("Unable to maxmize browser window. " + "It may be possible the browser did not instantiate correctly. % s", e) return self.webdriver
python
def create_webdriver(self, testname=None): ''' Creates an instance of Selenium webdriver based on config settings. This should only be called by a shutdown hook. Do not call directly within a test. Kwargs: testname: Optional test name to pass, this gets appended to the test name sent to selenium grid. Returns: WebDriver - Selenium Webdriver instance. ''' try: driver_type = self._config_reader.get( self.DRIVER_TYPE_CONFIG) except: driver_type = self.DRIVER_TYPE_LOCAL _wtflog.warn("%s setting is missing from config. Using default setting, %s", self.DRIVER_TYPE_CONFIG, driver_type) if driver_type == self.DRIVER_TYPE_REMOTE: # Create desired capabilities. self.webdriver = self.__create_remote_webdriver_from_config( testname=testname) else: # handle as local webdriver self.webdriver = self.__create_driver_from_browser_config() try: self.webdriver.maximize_window() except: # wait a short period and try again. time.sleep(self._timeout_mgr.BRIEF) try: self.webdriver.maximize_window() except Exception as e: if (isinstance(e, WebDriverException) and "implemented" in e.msg.lower()): pass # Maximizing window not supported by this webdriver. else: _wtflog.warn("Unable to maxmize browser window. " + "It may be possible the browser did not instantiate correctly. % s", e) return self.webdriver
[ "def", "create_webdriver", "(", "self", ",", "testname", "=", "None", ")", ":", "try", ":", "driver_type", "=", "self", ".", "_config_reader", ".", "get", "(", "self", ".", "DRIVER_TYPE_CONFIG", ")", "except", ":", "driver_type", "=", "self", ".", "DRIVER_...
Creates an instance of Selenium webdriver based on config settings. This should only be called by a shutdown hook. Do not call directly within a test. Kwargs: testname: Optional test name to pass, this gets appended to the test name sent to selenium grid. Returns: WebDriver - Selenium Webdriver instance.
[ "Creates", "an", "instance", "of", "Selenium", "webdriver", "based", "on", "config", "settings", ".", "This", "should", "only", "be", "called", "by", "a", "shutdown", "hook", ".", "Do", "not", "call", "directly", "within", "a", "test", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L116-L161
train
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverFactory.__create_driver_from_browser_config
def __create_driver_from_browser_config(self): ''' Reads the config value for browser type. ''' try: browser_type = self._config_reader.get( WebDriverFactory.BROWSER_TYPE_CONFIG) except KeyError: _wtflog("%s missing is missing from config file. Using defaults", WebDriverFactory.BROWSER_TYPE_CONFIG) browser_type = WebDriverFactory.FIREFOX # Special Chrome Sauce options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) options.add_argument("always-authorize-plugins") browser_type_dict = { self.CHROME: lambda: webdriver.Chrome( self._config_reader.get(WebDriverFactory.CHROME_DRIVER_PATH), chrome_options=options), self.FIREFOX: lambda: webdriver.Firefox(), self.INTERNETEXPLORER: lambda: webdriver.Ie(), self.OPERA: lambda: webdriver.Opera(), self.PHANTOMJS: lambda: self.__create_phantom_js_driver(), self.SAFARI: lambda: self.__create_safari_driver() } try: return browser_type_dict[browser_type]() except KeyError: raise TypeError( u("Unsupported Browser Type {0}").format(browser_type))
python
def __create_driver_from_browser_config(self): ''' Reads the config value for browser type. ''' try: browser_type = self._config_reader.get( WebDriverFactory.BROWSER_TYPE_CONFIG) except KeyError: _wtflog("%s missing is missing from config file. Using defaults", WebDriverFactory.BROWSER_TYPE_CONFIG) browser_type = WebDriverFactory.FIREFOX # Special Chrome Sauce options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) options.add_argument("always-authorize-plugins") browser_type_dict = { self.CHROME: lambda: webdriver.Chrome( self._config_reader.get(WebDriverFactory.CHROME_DRIVER_PATH), chrome_options=options), self.FIREFOX: lambda: webdriver.Firefox(), self.INTERNETEXPLORER: lambda: webdriver.Ie(), self.OPERA: lambda: webdriver.Opera(), self.PHANTOMJS: lambda: self.__create_phantom_js_driver(), self.SAFARI: lambda: self.__create_safari_driver() } try: return browser_type_dict[browser_type]() except KeyError: raise TypeError( u("Unsupported Browser Type {0}").format(browser_type))
[ "def", "__create_driver_from_browser_config", "(", "self", ")", ":", "try", ":", "browser_type", "=", "self", ".", "_config_reader", ".", "get", "(", "WebDriverFactory", ".", "BROWSER_TYPE_CONFIG", ")", "except", "KeyError", ":", "_wtflog", "(", "\"%s missing is mis...
Reads the config value for browser type.
[ "Reads", "the", "config", "value", "for", "browser", "type", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L163-L195
train
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverFactory.__create_safari_driver
def __create_safari_driver(self): ''' Creates an instance of Safari webdriver. ''' # Check for selenium jar env file needed for safari driver. if not os.getenv(self.__SELENIUM_SERVER_JAR_ENV): # If not set, check if we have a config setting for it. try: selenium_server_path = self._config_reader.get( self.SELENIUM_SERVER_LOCATION) self._env_vars[ self.__SELENIUM_SERVER_JAR_ENV] = selenium_server_path except KeyError: raise RuntimeError(u("Missing selenium server path config {0}.").format( self.SELENIUM_SERVER_LOCATION)) return webdriver.Safari()
python
def __create_safari_driver(self): ''' Creates an instance of Safari webdriver. ''' # Check for selenium jar env file needed for safari driver. if not os.getenv(self.__SELENIUM_SERVER_JAR_ENV): # If not set, check if we have a config setting for it. try: selenium_server_path = self._config_reader.get( self.SELENIUM_SERVER_LOCATION) self._env_vars[ self.__SELENIUM_SERVER_JAR_ENV] = selenium_server_path except KeyError: raise RuntimeError(u("Missing selenium server path config {0}.").format( self.SELENIUM_SERVER_LOCATION)) return webdriver.Safari()
[ "def", "__create_safari_driver", "(", "self", ")", ":", "# Check for selenium jar env file needed for safari driver.", "if", "not", "os", ".", "getenv", "(", "self", ".", "__SELENIUM_SERVER_JAR_ENV", ")", ":", "# If not set, check if we have a config setting for it.", "try", ...
Creates an instance of Safari webdriver.
[ "Creates", "an", "instance", "of", "Safari", "webdriver", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L198-L214
train
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverFactory.__create_phantom_js_driver
def __create_phantom_js_driver(self): ''' Creates an instance of PhantomJS driver. ''' try: return webdriver.PhantomJS(executable_path=self._config_reader.get(self.PHANTOMEJS_EXEC_PATH), service_args=['--ignore-ssl-errors=true']) except KeyError: return webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'])
python
def __create_phantom_js_driver(self): ''' Creates an instance of PhantomJS driver. ''' try: return webdriver.PhantomJS(executable_path=self._config_reader.get(self.PHANTOMEJS_EXEC_PATH), service_args=['--ignore-ssl-errors=true']) except KeyError: return webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'])
[ "def", "__create_phantom_js_driver", "(", "self", ")", ":", "try", ":", "return", "webdriver", ".", "PhantomJS", "(", "executable_path", "=", "self", ".", "_config_reader", ".", "get", "(", "self", ".", "PHANTOMEJS_EXEC_PATH", ")", ",", "service_args", "=", "[...
Creates an instance of PhantomJS driver.
[ "Creates", "an", "instance", "of", "PhantomJS", "driver", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L216-L224
train
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverFactory.__create_remote_webdriver_from_config
def __create_remote_webdriver_from_config(self, testname=None): ''' Reads the config value for browser type. ''' desired_capabilities = self._generate_desired_capabilities(testname) remote_url = self._config_reader.get( WebDriverFactory.REMOTE_URL_CONFIG) # Instantiate remote webdriver. driver = webdriver.Remote( desired_capabilities=desired_capabilities, command_executor=remote_url ) # Log IP Address of node if configured, so it can be used to # troubleshoot issues if they occur. log_driver_props = \ self._config_reader.get( WebDriverFactory.LOG_REMOTEDRIVER_PROPS, default_value=False ) in [True, "true", "TRUE", "True"] if "wd/hub" in remote_url and log_driver_props: try: grid_addr = remote_url[:remote_url.index("wd/hub")] info_request_response = urllib2.urlopen( grid_addr + "grid/api/testsession?session=" + driver.session_id, "", 5000) node_info = info_request_response.read() _wtflog.info( u("RemoteWebdriver using node: ") + u(node_info).strip()) except: # Unable to get IP Address of remote webdriver. # This happens with many 3rd party grid providers as they don't want you accessing info on nodes on # their internal network. pass return driver
python
def __create_remote_webdriver_from_config(self, testname=None): ''' Reads the config value for browser type. ''' desired_capabilities = self._generate_desired_capabilities(testname) remote_url = self._config_reader.get( WebDriverFactory.REMOTE_URL_CONFIG) # Instantiate remote webdriver. driver = webdriver.Remote( desired_capabilities=desired_capabilities, command_executor=remote_url ) # Log IP Address of node if configured, so it can be used to # troubleshoot issues if they occur. log_driver_props = \ self._config_reader.get( WebDriverFactory.LOG_REMOTEDRIVER_PROPS, default_value=False ) in [True, "true", "TRUE", "True"] if "wd/hub" in remote_url and log_driver_props: try: grid_addr = remote_url[:remote_url.index("wd/hub")] info_request_response = urllib2.urlopen( grid_addr + "grid/api/testsession?session=" + driver.session_id, "", 5000) node_info = info_request_response.read() _wtflog.info( u("RemoteWebdriver using node: ") + u(node_info).strip()) except: # Unable to get IP Address of remote webdriver. # This happens with many 3rd party grid providers as they don't want you accessing info on nodes on # their internal network. pass return driver
[ "def", "__create_remote_webdriver_from_config", "(", "self", ",", "testname", "=", "None", ")", ":", "desired_capabilities", "=", "self", ".", "_generate_desired_capabilities", "(", "testname", ")", "remote_url", "=", "self", ".", "_config_reader", ".", "get", "(", ...
Reads the config value for browser type.
[ "Reads", "the", "config", "value", "for", "browser", "type", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L226-L261
train
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.clean_up_webdrivers
def clean_up_webdrivers(self): ''' Clean up webdrivers created during execution. ''' # Quit webdrivers. _wtflog.info("WebdriverManager: Cleaning up webdrivers") try: if self.__use_shutdown_hook: for key in self.__registered_drivers.keys(): for driver in self.__registered_drivers[key]: try: _wtflog.debug( "Shutdown hook closing Webdriver for thread: %s", key) driver.quit() except: pass except: pass
python
def clean_up_webdrivers(self): ''' Clean up webdrivers created during execution. ''' # Quit webdrivers. _wtflog.info("WebdriverManager: Cleaning up webdrivers") try: if self.__use_shutdown_hook: for key in self.__registered_drivers.keys(): for driver in self.__registered_drivers[key]: try: _wtflog.debug( "Shutdown hook closing Webdriver for thread: %s", key) driver.quit() except: pass except: pass
[ "def", "clean_up_webdrivers", "(", "self", ")", ":", "# Quit webdrivers.", "_wtflog", ".", "info", "(", "\"WebdriverManager: Cleaning up webdrivers\"", ")", "try", ":", "if", "self", ".", "__use_shutdown_hook", ":", "for", "key", "in", "self", ".", "__registered_dri...
Clean up webdrivers created during execution.
[ "Clean", "up", "webdrivers", "created", "during", "execution", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L402-L419
train
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.close_driver
def close_driver(self): """ Close current running instance of Webdriver. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") WTF_WEBDRIVER_MANAGER.close_driver() """ channel = self.__get_channel() driver = self.__get_driver_for_channel(channel) if self.__config.get(self.REUSE_BROWSER, True): # If reuse browser is set, we'll avoid closing it and just clear out the cookies, # and reset the location. try: driver.delete_all_cookies() # check to see if webdriver is still responding driver.get("about:blank") except: pass if driver is not None: try: driver.quit() except: pass self.__unregister_driver(channel) if driver in self.__registered_drivers[channel]: self.__registered_drivers[channel].remove(driver) self.webdriver = None
python
def close_driver(self): """ Close current running instance of Webdriver. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") WTF_WEBDRIVER_MANAGER.close_driver() """ channel = self.__get_channel() driver = self.__get_driver_for_channel(channel) if self.__config.get(self.REUSE_BROWSER, True): # If reuse browser is set, we'll avoid closing it and just clear out the cookies, # and reset the location. try: driver.delete_all_cookies() # check to see if webdriver is still responding driver.get("about:blank") except: pass if driver is not None: try: driver.quit() except: pass self.__unregister_driver(channel) if driver in self.__registered_drivers[channel]: self.__registered_drivers[channel].remove(driver) self.webdriver = None
[ "def", "close_driver", "(", "self", ")", ":", "channel", "=", "self", ".", "__get_channel", "(", ")", "driver", "=", "self", ".", "__get_driver_for_channel", "(", "channel", ")", "if", "self", ".", "__config", ".", "get", "(", "self", ".", "REUSE_BROWSER",...
Close current running instance of Webdriver. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") WTF_WEBDRIVER_MANAGER.close_driver()
[ "Close", "current", "running", "instance", "of", "Webdriver", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L421-L453
train
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.get_driver
def get_driver(self): ''' Get an already running instance of Webdriver. If there is none, it will create one. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") same_driver = WTF_WEBDRIVER_MANAGER.get_driver() print(driver is same_driver) # True ''' driver = self.__get_driver_for_channel(self.__get_channel()) if driver is None: driver = self.new_driver() return driver
python
def get_driver(self): ''' Get an already running instance of Webdriver. If there is none, it will create one. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") same_driver = WTF_WEBDRIVER_MANAGER.get_driver() print(driver is same_driver) # True ''' driver = self.__get_driver_for_channel(self.__get_channel()) if driver is None: driver = self.new_driver() return driver
[ "def", "get_driver", "(", "self", ")", ":", "driver", "=", "self", ".", "__get_driver_for_channel", "(", "self", ".", "__get_channel", "(", ")", ")", "if", "driver", "is", "None", ":", "driver", "=", "self", ".", "new_driver", "(", ")", "return", "driver...
Get an already running instance of Webdriver. If there is none, it will create one. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") same_driver = WTF_WEBDRIVER_MANAGER.get_driver() print(driver is same_driver) # True
[ "Get", "an", "already", "running", "instance", "of", "Webdriver", ".", "If", "there", "is", "none", "it", "will", "create", "one", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L455-L473
train
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.new_driver
def new_driver(self, testname=None): ''' Used at a start of a test to get a new instance of WebDriver. If the 'resuebrowser' setting is true, it will use a recycled WebDriver instance with delete_all_cookies() called. Kwargs: testname (str) - Optional test name to pass to Selenium Grid. Helpful for labeling tests on 3rd party WebDriver cloud providers. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") ''' channel = self.__get_channel() # Get reference for the current driver. driver = self.__get_driver_for_channel(channel) if self.__config.get(WebDriverManager.REUSE_BROWSER, True): if driver is None: driver = self._webdriver_factory.create_webdriver( testname=testname) # Register webdriver so it can be retrieved by the manager and # cleaned up after exit. self.__register_driver(channel, driver) else: try: # Attempt to get the browser to a pristine state as possible when we are # reusing this for another test. driver.delete_all_cookies() # check to see if webdriver is still responding driver.get("about:blank") except: # In the case the browser is unhealthy, we should kill it # and serve a new one. try: if driver.is_online(): driver.quit() except: pass driver = self._webdriver_factory.create_webdriver( testname=testname) self.__register_driver(channel, driver) else: # Attempt to tear down any existing webdriver. if driver is not None: try: driver.quit() except: pass self.__unregister_driver(channel) driver = self._webdriver_factory.create_webdriver( testname=testname) self.__register_driver(channel, driver) return driver
python
def new_driver(self, testname=None): ''' Used at a start of a test to get a new instance of WebDriver. If the 'resuebrowser' setting is true, it will use a recycled WebDriver instance with delete_all_cookies() called. Kwargs: testname (str) - Optional test name to pass to Selenium Grid. Helpful for labeling tests on 3rd party WebDriver cloud providers. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") ''' channel = self.__get_channel() # Get reference for the current driver. driver = self.__get_driver_for_channel(channel) if self.__config.get(WebDriverManager.REUSE_BROWSER, True): if driver is None: driver = self._webdriver_factory.create_webdriver( testname=testname) # Register webdriver so it can be retrieved by the manager and # cleaned up after exit. self.__register_driver(channel, driver) else: try: # Attempt to get the browser to a pristine state as possible when we are # reusing this for another test. driver.delete_all_cookies() # check to see if webdriver is still responding driver.get("about:blank") except: # In the case the browser is unhealthy, we should kill it # and serve a new one. try: if driver.is_online(): driver.quit() except: pass driver = self._webdriver_factory.create_webdriver( testname=testname) self.__register_driver(channel, driver) else: # Attempt to tear down any existing webdriver. if driver is not None: try: driver.quit() except: pass self.__unregister_driver(channel) driver = self._webdriver_factory.create_webdriver( testname=testname) self.__register_driver(channel, driver) return driver
[ "def", "new_driver", "(", "self", ",", "testname", "=", "None", ")", ":", "channel", "=", "self", ".", "__get_channel", "(", ")", "# Get reference for the current driver.", "driver", "=", "self", ".", "__get_driver_for_channel", "(", "channel", ")", "if", "self"...
Used at a start of a test to get a new instance of WebDriver. If the 'resuebrowser' setting is true, it will use a recycled WebDriver instance with delete_all_cookies() called. Kwargs: testname (str) - Optional test name to pass to Selenium Grid. Helpful for labeling tests on 3rd party WebDriver cloud providers. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com")
[ "Used", "at", "a", "start", "of", "a", "test", "to", "get", "a", "new", "instance", "of", "WebDriver", ".", "If", "the", "resuebrowser", "setting", "is", "true", "it", "will", "use", "a", "recycled", "WebDriver", "instance", "with", "delete_all_cookies", "...
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L488-L552
train
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.__register_driver
def __register_driver(self, channel, webdriver): "Register webdriver to a channel." # Add to list of webdrivers to cleanup. if not self.__registered_drivers.has_key(channel): self.__registered_drivers[channel] = [] # set to new empty array self.__registered_drivers[channel].append(webdriver) # Set singleton instance for the channel self.__webdriver[channel] = webdriver
python
def __register_driver(self, channel, webdriver): "Register webdriver to a channel." # Add to list of webdrivers to cleanup. if not self.__registered_drivers.has_key(channel): self.__registered_drivers[channel] = [] # set to new empty array self.__registered_drivers[channel].append(webdriver) # Set singleton instance for the channel self.__webdriver[channel] = webdriver
[ "def", "__register_driver", "(", "self", ",", "channel", ",", "webdriver", ")", ":", "# Add to list of webdrivers to cleanup.", "if", "not", "self", ".", "__registered_drivers", ".", "has_key", "(", "channel", ")", ":", "self", ".", "__registered_drivers", "[", "c...
Register webdriver to a channel.
[ "Register", "webdriver", "to", "a", "channel", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L555-L565
train
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.__unregister_driver
def __unregister_driver(self, channel): "Unregister webdriver" driver = self.__get_driver_for_channel(channel) if self.__registered_drivers.has_key(channel) \ and driver in self.__registered_drivers[channel]: self.__registered_drivers[channel].remove(driver) self.__webdriver[channel] = None
python
def __unregister_driver(self, channel): "Unregister webdriver" driver = self.__get_driver_for_channel(channel) if self.__registered_drivers.has_key(channel) \ and driver in self.__registered_drivers[channel]: self.__registered_drivers[channel].remove(driver) self.__webdriver[channel] = None
[ "def", "__unregister_driver", "(", "self", ",", "channel", ")", ":", "driver", "=", "self", ".", "__get_driver_for_channel", "(", "channel", ")", "if", "self", ".", "__registered_drivers", ".", "has_key", "(", "channel", ")", "and", "driver", "in", "self", "...
Unregister webdriver
[ "Unregister", "webdriver" ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L567-L576
train
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.__get_channel
def __get_channel(self): "Get the channel to register webdriver to." if self.__config.get(WebDriverManager.ENABLE_THREADING_SUPPORT, False): channel = current_thread().ident else: channel = 0 return channel
python
def __get_channel(self): "Get the channel to register webdriver to." if self.__config.get(WebDriverManager.ENABLE_THREADING_SUPPORT, False): channel = current_thread().ident else: channel = 0 return channel
[ "def", "__get_channel", "(", "self", ")", ":", "if", "self", ".", "__config", ".", "get", "(", "WebDriverManager", ".", "ENABLE_THREADING_SUPPORT", ",", "False", ")", ":", "channel", "=", "current_thread", "(", ")", ".", "ident", "else", ":", "channel", "=...
Get the channel to register webdriver to.
[ "Get", "the", "channel", "to", "register", "webdriver", "to", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L585-L592
train
wiredrive/wtframework
wtframework/wtf/web/capture.py
WebScreenShotUtil.take_screenshot
def take_screenshot(webdriver, file_name): """ Captures a screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as. """ folder_location = os.path.join(ProjectUtils.get_project_root(), WebScreenShotUtil.SCREEN_SHOT_LOCATION) WebScreenShotUtil.__capture_screenshot( webdriver, folder_location, file_name + ".png")
python
def take_screenshot(webdriver, file_name): """ Captures a screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as. """ folder_location = os.path.join(ProjectUtils.get_project_root(), WebScreenShotUtil.SCREEN_SHOT_LOCATION) WebScreenShotUtil.__capture_screenshot( webdriver, folder_location, file_name + ".png")
[ "def", "take_screenshot", "(", "webdriver", ",", "file_name", ")", ":", "folder_location", "=", "os", ".", "path", ".", "join", "(", "ProjectUtils", ".", "get_project_root", "(", ")", ",", "WebScreenShotUtil", ".", "SCREEN_SHOT_LOCATION", ")", "WebScreenShotUtil",...
Captures a screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as.
[ "Captures", "a", "screenshot", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/capture.py#L34-L47
train
wiredrive/wtframework
wtframework/wtf/web/capture.py
WebScreenShotUtil.take_reference_screenshot
def take_reference_screenshot(webdriver, file_name): """ Captures a screenshot as a reference screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as. """ folder_location = os.path.join(ProjectUtils.get_project_root(), WebScreenShotUtil.REFERENCE_SCREEN_SHOT_LOCATION) WebScreenShotUtil.__capture_screenshot( webdriver, folder_location, file_name + ".png")
python
def take_reference_screenshot(webdriver, file_name): """ Captures a screenshot as a reference screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as. """ folder_location = os.path.join(ProjectUtils.get_project_root(), WebScreenShotUtil.REFERENCE_SCREEN_SHOT_LOCATION) WebScreenShotUtil.__capture_screenshot( webdriver, folder_location, file_name + ".png")
[ "def", "take_reference_screenshot", "(", "webdriver", ",", "file_name", ")", ":", "folder_location", "=", "os", ".", "path", ".", "join", "(", "ProjectUtils", ".", "get_project_root", "(", ")", ",", "WebScreenShotUtil", ".", "REFERENCE_SCREEN_SHOT_LOCATION", ")", ...
Captures a screenshot as a reference screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as.
[ "Captures", "a", "screenshot", "as", "a", "reference", "screenshot", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/capture.py#L50-L62
train
wiredrive/wtframework
wtframework/wtf/web/capture.py
WebScreenShotUtil.__capture_screenshot
def __capture_screenshot(webdriver, folder_location, file_name): "Capture a screenshot" # Check folder location exists. if not os.path.exists(folder_location): os.makedirs(folder_location) file_location = os.path.join(folder_location, file_name) if isinstance(webdriver, remote.webdriver.WebDriver): # If this is a remote webdriver. We need to transmit the image data # back across system boundries as a base 64 encoded string so it can # be decoded back on the local system and written to disk. base64_data = webdriver.get_screenshot_as_base64() screenshot_data = base64.decodestring(base64_data) screenshot_file = open(file_location, "wb") screenshot_file.write(screenshot_data) screenshot_file.close() else: webdriver.save_screenshot(file_location)
python
def __capture_screenshot(webdriver, folder_location, file_name): "Capture a screenshot" # Check folder location exists. if not os.path.exists(folder_location): os.makedirs(folder_location) file_location = os.path.join(folder_location, file_name) if isinstance(webdriver, remote.webdriver.WebDriver): # If this is a remote webdriver. We need to transmit the image data # back across system boundries as a base 64 encoded string so it can # be decoded back on the local system and written to disk. base64_data = webdriver.get_screenshot_as_base64() screenshot_data = base64.decodestring(base64_data) screenshot_file = open(file_location, "wb") screenshot_file.write(screenshot_data) screenshot_file.close() else: webdriver.save_screenshot(file_location)
[ "def", "__capture_screenshot", "(", "webdriver", ",", "folder_location", ",", "file_name", ")", ":", "# Check folder location exists.", "if", "not", "os", ".", "path", ".", "exists", "(", "folder_location", ")", ":", "os", ".", "makedirs", "(", "folder_location", ...
Capture a screenshot
[ "Capture", "a", "screenshot" ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/capture.py#L65-L83
train
wiredrive/wtframework
wtframework/wtf/utils/project_utils.py
ProjectUtils.get_project_root
def get_project_root(cls): ''' Return path of the project directory. Use this method for getting paths relative to the project. However, for data, it's recommended you use WTF_DATA_MANAGER and for assets it's recommended to use WTF_ASSET_MANAGER, which are already singleton instances that manger the /data, and /assets folder for you. Returns: str - path of project root directory. ''' if(cls.__root_folder__ != None): return cls.__root_folder__ # Check for enviornment variable override. try: cls.__root_folder__ = os.environ[cls.WTF_HOME_CONFIG_ENV_VAR] except KeyError: # Means WTF_HOME override isn't specified. pass # Search starting from the current working directory and traverse up parent directories for the # hidden file denoting the project root folder. path = os.getcwd() seperator_matches = re.finditer("/|\\\\", path) paths_to_search = [path] for match in seperator_matches: p = path[:match.start()] paths_to_search.insert(0, p) for path in paths_to_search: target_path = os.path.join(path, cls.__WTF_ROOT_FOLDER_FILE) if os.path.isfile(target_path): cls.__root_folder__ = path return cls.__root_folder__ raise RuntimeError(u("Missing root project folder locator file '.wtf_root_folder'.") + u("Check to make sure this file is located in your project directory."))
python
def get_project_root(cls): ''' Return path of the project directory. Use this method for getting paths relative to the project. However, for data, it's recommended you use WTF_DATA_MANAGER and for assets it's recommended to use WTF_ASSET_MANAGER, which are already singleton instances that manger the /data, and /assets folder for you. Returns: str - path of project root directory. ''' if(cls.__root_folder__ != None): return cls.__root_folder__ # Check for enviornment variable override. try: cls.__root_folder__ = os.environ[cls.WTF_HOME_CONFIG_ENV_VAR] except KeyError: # Means WTF_HOME override isn't specified. pass # Search starting from the current working directory and traverse up parent directories for the # hidden file denoting the project root folder. path = os.getcwd() seperator_matches = re.finditer("/|\\\\", path) paths_to_search = [path] for match in seperator_matches: p = path[:match.start()] paths_to_search.insert(0, p) for path in paths_to_search: target_path = os.path.join(path, cls.__WTF_ROOT_FOLDER_FILE) if os.path.isfile(target_path): cls.__root_folder__ = path return cls.__root_folder__ raise RuntimeError(u("Missing root project folder locator file '.wtf_root_folder'.") + u("Check to make sure this file is located in your project directory."))
[ "def", "get_project_root", "(", "cls", ")", ":", "if", "(", "cls", ".", "__root_folder__", "!=", "None", ")", ":", "return", "cls", ".", "__root_folder__", "# Check for enviornment variable override.", "try", ":", "cls", ".", "__root_folder__", "=", "os", ".", ...
Return path of the project directory. Use this method for getting paths relative to the project. However, for data, it's recommended you use WTF_DATA_MANAGER and for assets it's recommended to use WTF_ASSET_MANAGER, which are already singleton instances that manger the /data, and /assets folder for you. Returns: str - path of project root directory.
[ "Return", "path", "of", "the", "project", "directory", ".", "Use", "this", "method", "for", "getting", "paths", "relative", "to", "the", "project", ".", "However", "for", "data", "it", "s", "recommended", "you", "use", "WTF_DATA_MANAGER", "and", "for", "asse...
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/project_utils.py#L38-L75
train
wiredrive/wtframework
wtframework/wtf/utils/wait_utils.py
do_until
def do_until(lambda_expr, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, message=None): ''' A retry wrapper that'll keep performing the action until it succeeds. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: lambda_expr (lambda) : Expression to evaluate. Kwargs: timeout (number): Timeout period in seconds. sleep (number) : Sleep time to wait between iterations message (str) : Provide a message for TimeoutError raised. Returns: The value of the evaluated lambda expression. Usage:: do_until(lambda: driver.find_element_by_id("save").click(), timeout=30, sleep=0.5) Is equivalent to: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: return driver.find_element_by_id("save").click() except: pass time.sleep(0.5) raise OperationTimeoutError() ''' __check_condition_parameter_is_function(lambda_expr) end_time = datetime.now() + timedelta(seconds=timeout) last_exception = None while datetime.now() < end_time: try: return lambda_expr() except Exception as e: last_exception = e time.sleep(sleep) if message: raise OperationTimeoutError(message, last_exception) else: raise OperationTimeoutError("Operation timed out.", last_exception)
python
def do_until(lambda_expr, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, message=None): ''' A retry wrapper that'll keep performing the action until it succeeds. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: lambda_expr (lambda) : Expression to evaluate. Kwargs: timeout (number): Timeout period in seconds. sleep (number) : Sleep time to wait between iterations message (str) : Provide a message for TimeoutError raised. Returns: The value of the evaluated lambda expression. Usage:: do_until(lambda: driver.find_element_by_id("save").click(), timeout=30, sleep=0.5) Is equivalent to: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: return driver.find_element_by_id("save").click() except: pass time.sleep(0.5) raise OperationTimeoutError() ''' __check_condition_parameter_is_function(lambda_expr) end_time = datetime.now() + timedelta(seconds=timeout) last_exception = None while datetime.now() < end_time: try: return lambda_expr() except Exception as e: last_exception = e time.sleep(sleep) if message: raise OperationTimeoutError(message, last_exception) else: raise OperationTimeoutError("Operation timed out.", last_exception)
[ "def", "do_until", "(", "lambda_expr", ",", "timeout", "=", "WTF_TIMEOUT_MANAGER", ".", "NORMAL", ",", "sleep", "=", "0.5", ",", "message", "=", "None", ")", ":", "__check_condition_parameter_is_function", "(", "lambda_expr", ")", "end_time", "=", "datetime", "....
A retry wrapper that'll keep performing the action until it succeeds. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: lambda_expr (lambda) : Expression to evaluate. Kwargs: timeout (number): Timeout period in seconds. sleep (number) : Sleep time to wait between iterations message (str) : Provide a message for TimeoutError raised. Returns: The value of the evaluated lambda expression. Usage:: do_until(lambda: driver.find_element_by_id("save").click(), timeout=30, sleep=0.5) Is equivalent to: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: return driver.find_element_by_id("save").click() except: pass time.sleep(0.5) raise OperationTimeoutError()
[ "A", "retry", "wrapper", "that", "ll", "keep", "performing", "the", "action", "until", "it", "succeeds", ".", "(", "main", "differnce", "between", "do_until", "and", "wait_until", "is", "do_until", "will", "keep", "trying", "until", "a", "value", "is", "retu...
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/wait_utils.py#L39-L88
train
wiredrive/wtframework
wtframework/wtf/utils/wait_utils.py
wait_and_ignore
def wait_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): ''' Waits wrapper that'll wait for the condition to become true, but will not error if the condition isn't met. Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. Example:: wait_and_ignore(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): break; except: pass time.sleep(0.5) ''' try: return wait_until(condition, timeout, sleep) except: pass
python
def wait_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): ''' Waits wrapper that'll wait for the condition to become true, but will not error if the condition isn't met. Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. Example:: wait_and_ignore(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): break; except: pass time.sleep(0.5) ''' try: return wait_until(condition, timeout, sleep) except: pass
[ "def", "wait_and_ignore", "(", "condition", ",", "timeout", "=", "WTF_TIMEOUT_MANAGER", ".", "NORMAL", ",", "sleep", "=", "0.5", ")", ":", "try", ":", "return", "wait_until", "(", "condition", ",", "timeout", ",", "sleep", ")", "except", ":", "pass" ]
Waits wrapper that'll wait for the condition to become true, but will not error if the condition isn't met. Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. Example:: wait_and_ignore(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): break; except: pass time.sleep(0.5)
[ "Waits", "wrapper", "that", "ll", "wait", "for", "the", "condition", "to", "become", "true", "but", "will", "not", "error", "if", "the", "condition", "isn", "t", "met", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/wait_utils.py#L91-L123
train
wiredrive/wtframework
wtframework/wtf/utils/wait_utils.py
wait_until
def wait_until(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, pass_exceptions=False, message=None): ''' Waits wrapper that'll wait for the condition to become true. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. pass_exceptions (bool) : If set true, any exceptions raised will be re-raised up the chain. Normally exceptions are ignored. message (str) : Optional message to pass into OperationTimeoutError if the wait times out. Example:: wait_until(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) did_succeed = False while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): did_succeed = True break; except: pass time.sleep(0.5) if not did_succeed: raise OperationTimeoutError() ''' __check_condition_parameter_is_function(condition) last_exception = None end_time = datetime.now() + timedelta(seconds=timeout) while datetime.now() < end_time: try: if condition(): return except Exception as e: if pass_exceptions: raise e else: last_exception = e time.sleep(sleep) if message: if last_exception: raise OperationTimeoutError(message, e) else: raise OperationTimeoutError(message) else: if last_exception: raise OperationTimeoutError("Operation timed out.", e) else: raise OperationTimeoutError("Operation timed out.")
python
def wait_until(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, pass_exceptions=False, message=None): ''' Waits wrapper that'll wait for the condition to become true. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. pass_exceptions (bool) : If set true, any exceptions raised will be re-raised up the chain. Normally exceptions are ignored. message (str) : Optional message to pass into OperationTimeoutError if the wait times out. Example:: wait_until(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) did_succeed = False while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): did_succeed = True break; except: pass time.sleep(0.5) if not did_succeed: raise OperationTimeoutError() ''' __check_condition_parameter_is_function(condition) last_exception = None end_time = datetime.now() + timedelta(seconds=timeout) while datetime.now() < end_time: try: if condition(): return except Exception as e: if pass_exceptions: raise e else: last_exception = e time.sleep(sleep) if message: if last_exception: raise OperationTimeoutError(message, e) else: raise OperationTimeoutError(message) else: if last_exception: raise OperationTimeoutError("Operation timed out.", e) else: raise OperationTimeoutError("Operation timed out.")
[ "def", "wait_until", "(", "condition", ",", "timeout", "=", "WTF_TIMEOUT_MANAGER", ".", "NORMAL", ",", "sleep", "=", "0.5", ",", "pass_exceptions", "=", "False", ",", "message", "=", "None", ")", ":", "__check_condition_parameter_is_function", "(", "condition", ...
Waits wrapper that'll wait for the condition to become true. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. pass_exceptions (bool) : If set true, any exceptions raised will be re-raised up the chain. Normally exceptions are ignored. message (str) : Optional message to pass into OperationTimeoutError if the wait times out. Example:: wait_until(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) did_succeed = False while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): did_succeed = True break; except: pass time.sleep(0.5) if not did_succeed: raise OperationTimeoutError()
[ "Waits", "wrapper", "that", "ll", "wait", "for", "the", "condition", "to", "become", "true", ".", "(", "main", "differnce", "between", "do_until", "and", "wait_until", "is", "do_until", "will", "keep", "trying", "until", "a", "value", "is", "returned", "whil...
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/wait_utils.py#L125-L187
train
wiredrive/wtframework
wtframework/wtf/email.py
IMapEmailAccountObject.check_email_exists_by_subject
def check_email_exists_by_subject(self, subject, match_recipient=None): """ Searches for Email by Subject. Returns True or False. Args: subject (str): Subject to search for. Kwargs: match_recipient (str) : Recipient to match exactly. (don't care if not specified) Returns: True - email found, False - email not found """ # Select inbox to fetch the latest mail on server. self._mail.select("inbox") try: matches = self.__search_email_by_subject(subject, match_recipient) if len(matches) <= 0: return False else: return True except Exception as e: raise e
python
def check_email_exists_by_subject(self, subject, match_recipient=None): """ Searches for Email by Subject. Returns True or False. Args: subject (str): Subject to search for. Kwargs: match_recipient (str) : Recipient to match exactly. (don't care if not specified) Returns: True - email found, False - email not found """ # Select inbox to fetch the latest mail on server. self._mail.select("inbox") try: matches = self.__search_email_by_subject(subject, match_recipient) if len(matches) <= 0: return False else: return True except Exception as e: raise e
[ "def", "check_email_exists_by_subject", "(", "self", ",", "subject", ",", "match_recipient", "=", "None", ")", ":", "# Select inbox to fetch the latest mail on server.", "self", ".", "_mail", ".", "select", "(", "\"inbox\"", ")", "try", ":", "matches", "=", "self", ...
Searches for Email by Subject. Returns True or False. Args: subject (str): Subject to search for. Kwargs: match_recipient (str) : Recipient to match exactly. (don't care if not specified) Returns: True - email found, False - email not found
[ "Searches", "for", "Email", "by", "Subject", ".", "Returns", "True", "or", "False", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/email.py#L65-L89
train
wiredrive/wtframework
wtframework/wtf/email.py
IMapEmailAccountObject.find_emails_by_subject
def find_emails_by_subject(self, subject, limit=50, match_recipient=None): """ Searches for Email by Subject. Returns email's imap message IDs as a list if matching subjects is found. Args: subject (str) - Subject to search for. Kwargs: limit (int) - Limit search to X number of matches, default 50 match_recipient (str) - Recipient to exactly (don't care if not specified) Returns: list - List of Integers representing imap message UIDs. """ # Select inbox to fetch the latest mail on server. self._mail.select("inbox") matching_uids = self.__search_email_by_subject( subject, match_recipient) return matching_uids
python
def find_emails_by_subject(self, subject, limit=50, match_recipient=None): """ Searches for Email by Subject. Returns email's imap message IDs as a list if matching subjects is found. Args: subject (str) - Subject to search for. Kwargs: limit (int) - Limit search to X number of matches, default 50 match_recipient (str) - Recipient to exactly (don't care if not specified) Returns: list - List of Integers representing imap message UIDs. """ # Select inbox to fetch the latest mail on server. self._mail.select("inbox") matching_uids = self.__search_email_by_subject( subject, match_recipient) return matching_uids
[ "def", "find_emails_by_subject", "(", "self", ",", "subject", ",", "limit", "=", "50", ",", "match_recipient", "=", "None", ")", ":", "# Select inbox to fetch the latest mail on server.", "self", ".", "_mail", ".", "select", "(", "\"inbox\"", ")", "matching_uids", ...
Searches for Email by Subject. Returns email's imap message IDs as a list if matching subjects is found. Args: subject (str) - Subject to search for. Kwargs: limit (int) - Limit search to X number of matches, default 50 match_recipient (str) - Recipient to exactly (don't care if not specified) Returns: list - List of Integers representing imap message UIDs.
[ "Searches", "for", "Email", "by", "Subject", ".", "Returns", "email", "s", "imap", "message", "IDs", "as", "a", "list", "if", "matching", "subjects", "is", "found", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/email.py#L91-L113
train