idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
59,700
def getKeyboardText ( self , pchText , cchText ) : fn = self . function_table . getKeyboardText result = fn ( pchText , cchText ) return result
Get the text that was entered into the text input
59,701
def setKeyboardTransformAbsolute ( self , eTrackingOrigin ) : fn = self . function_table . setKeyboardTransformAbsolute pmatTrackingOriginToKeyboardTransform = HmdMatrix34_t ( ) fn ( eTrackingOrigin , byref ( pmatTrackingOriginToKeyboardTransform ) ) return pmatTrackingOriginToKeyboardTransform
Set the position of the keyboard in world space
59,702
def showMessageOverlay ( self , pchText , pchCaption , pchButton0Text , pchButton1Text , pchButton2Text , pchButton3Text ) : fn = self . function_table . showMessageOverlay result = fn ( pchText , pchCaption , pchButton0Text , pchButton1Text , pchButton2Text , pchButton3Text ) return result
Show the message overlay . This will block and return you a result .
59,703
def freeRenderModel ( self ) : fn = self . function_table . freeRenderModel pRenderModel = RenderModel_t ( ) fn ( byref ( pRenderModel ) ) return pRenderModel
Frees a previously returned render model It is safe to call this on a null ptr .
59,704
def loadTexture_Async ( self , textureId ) : fn = self . function_table . loadTexture_Async ppTexture = POINTER ( RenderModel_TextureMap_t ) ( ) result = fn ( textureId , byref ( ppTexture ) ) return result , ppTexture
Loads and returns a texture for use in the application .
59,705
def freeTexture ( self ) : fn = self . function_table . freeTexture pTexture = RenderModel_TextureMap_t ( ) fn ( byref ( pTexture ) ) return pTexture
Frees a previously returned texture It is safe to call this on a null ptr .
59,706
def loadTextureD3D11_Async ( self , textureId , pD3D11Device ) : fn = self . function_table . loadTextureD3D11_Async ppD3D11Texture2D = c_void_p ( ) result = fn ( textureId , pD3D11Device , byref ( ppD3D11Texture2D ) ) return result , ppD3D11Texture2D . value
Creates a D3D11 texture and loads data into it .
59,707
def loadIntoTextureD3D11_Async ( self , textureId , pDstTexture ) : fn = self . function_table . loadIntoTextureD3D11_Async result = fn ( textureId , pDstTexture ) return result
Helper function to copy the bits into an existing texture .
59,708
def getRenderModelName ( self , unRenderModelIndex , pchRenderModelName , unRenderModelNameLen ) : fn = self . function_table . getRenderModelName result = fn ( unRenderModelIndex , pchRenderModelName , unRenderModelNameLen ) return result
Use this to get the names of available render models . Index does not correlate to a tracked device index but is only used for iterating over all available render models . If the index is out of range this function will return 0 . Otherwise it will return the size of the buffer required for the name .
59,709
def getComponentName ( self , pchRenderModelName , unComponentIndex , pchComponentName , unComponentNameLen ) : fn = self . function_table . getComponentName result = fn ( pchRenderModelName , unComponentIndex , pchComponentName , unComponentNameLen ) return result
Use this to get the names of available components . Index does not correlate to a tracked device index but is only used for iterating over all available components . If the index is out of range this function will return 0 . Otherwise it will return the size of the buffer required for the name .
59,710
def getComponentState ( self , pchRenderModelName , pchComponentName ) : fn = self . function_table . getComponentState pControllerState = VRControllerState_t ( ) pState = RenderModel_ControllerMode_State_t ( ) pComponentState = RenderModel_ComponentState_t ( ) result = fn ( pchRenderModelName , pchComponentName , byref ( pControllerState ) , byref ( pState ) , byref ( pComponentState ) ) return result , pControllerState , pState , pComponentState
This version of GetComponentState takes a controller state block instead of an action origin . This function is deprecated . You should use the new input system and GetComponentStateForDevicePath instead .
59,711
def renderModelHasComponent ( self , pchRenderModelName , pchComponentName ) : fn = self . function_table . renderModelHasComponent result = fn ( pchRenderModelName , pchComponentName ) return result
Returns true if the render model has a component with the specified name
59,712
def getRenderModelThumbnailURL ( self , pchRenderModelName , pchThumbnailURL , unThumbnailURLLen ) : fn = self . function_table . getRenderModelThumbnailURL peError = EVRRenderModelError ( ) result = fn ( pchRenderModelName , pchThumbnailURL , unThumbnailURLLen , byref ( peError ) ) return result , peError
Returns the URL of the thumbnail image for this rendermodel
59,713
def getRenderModelOriginalPath ( self , pchRenderModelName , pchOriginalPath , unOriginalPathLen ) : fn = self . function_table . getRenderModelOriginalPath peError = EVRRenderModelError ( ) result = fn ( pchRenderModelName , pchOriginalPath , unOriginalPathLen , byref ( peError ) ) return result , peError
Provides a render model path that will load the unskinned model if the model name provided has been replace by the user . If the model hasn t been replaced the path value will still be a valid path to load the model . Pass this to LoadRenderModel_Async etc . to load the model .
59,714
def getRenderModelErrorNameFromEnum ( self , error ) : fn = self . function_table . getRenderModelErrorNameFromEnum result = fn ( error ) return result
Returns a string for a render model error
59,715
def removeNotification ( self , notificationId ) : fn = self . function_table . removeNotification result = fn ( notificationId ) return result
Destroy a notification hiding it first if it currently shown to the user .
59,716
def hookScreenshot ( self , numTypes ) : fn = self . function_table . hookScreenshot pSupportedTypes = EVRScreenshotType ( ) result = fn ( byref ( pSupportedTypes ) , numTypes ) return result , pSupportedTypes
Called by the running VR application to indicate that it wishes to be in charge of screenshots . If the application does not call this the Compositor will only support VRScreenshotType_Stereo screenshots that will be captured without notification to the running app . Once hooked your application will receive a VREvent_RequestScreenshot event when the user presses the buttons to take a screenshot .
59,717
def getScreenshotPropertyType ( self , screenshotHandle ) : fn = self . function_table . getScreenshotPropertyType pError = EVRScreenshotError ( ) result = fn ( screenshotHandle , byref ( pError ) ) return result , pError
When your application receives a VREvent_RequestScreenshot event call these functions to get the details of the screenshot request .
59,718
def updateScreenshotProgress ( self , screenshotHandle , flProgress ) : fn = self . function_table . updateScreenshotProgress result = fn ( screenshotHandle , flProgress ) return result
Call this if the application is taking the screen shot will take more than a few ms processing . This will result in an overlay being presented that shows a completion bar .
59,719
def takeStereoScreenshot ( self , pchPreviewFilename , pchVRFilename ) : fn = self . function_table . takeStereoScreenshot pOutScreenshotHandle = ScreenshotHandle_t ( ) result = fn ( byref ( pOutScreenshotHandle ) , pchPreviewFilename , pchVRFilename ) return result , pOutScreenshotHandle
Tells the compositor to take an internal screenshot of type VRScreenshotType_Stereo . It will take the current submitted scene textures of the running application and write them into the preview image and a side - by - side file for the VR image . This is similar to request screenshot but doesn t ever talk to the application just takes the shot and submits .
59,720
def loadSharedResource ( self , pchResourceName , pchBuffer , unBufferLen ) : fn = self . function_table . loadSharedResource result = fn ( pchResourceName , pchBuffer , unBufferLen ) return result
Loads the specified resource into the provided buffer if large enough . Returns the size in bytes of the buffer required to hold the specified resource .
59,721
def getResourceFullPath ( self , pchResourceName , pchResourceTypeDirectory , pchPathBuffer , unBufferLen ) : fn = self . function_table . getResourceFullPath result = fn ( pchResourceName , pchResourceTypeDirectory , pchPathBuffer , unBufferLen ) return result
Provides the full path to the specified resource . Resource names can include named directories for drivers and other things and this resolves all of those and returns the actual physical path . pchResourceTypeDirectory is the subdirectory of resources to look in .
59,722
def getDriverName ( self , nDriver , pchValue , unBufferSize ) : fn = self . function_table . getDriverName result = fn ( nDriver , pchValue , unBufferSize ) return result
Returns the length of the number of bytes necessary to hold this string including the trailing null .
59,723
def getActionSetHandle ( self , pchActionSetName ) : fn = self . function_table . getActionSetHandle pHandle = VRActionSetHandle_t ( ) result = fn ( pchActionSetName , byref ( pHandle ) ) return result , pHandle
Returns a handle for an action set . This handle is used for all performance - sensitive calls .
59,724
def getActionHandle ( self , pchActionName ) : fn = self . function_table . getActionHandle pHandle = VRActionHandle_t ( ) result = fn ( pchActionName , byref ( pHandle ) ) return result , pHandle
Returns a handle for an action . This handle is used for all performance - sensitive calls .
59,725
def getDigitalActionData ( self , action , unActionDataSize , ulRestrictToDevice ) : fn = self . function_table . getDigitalActionData pActionData = InputDigitalActionData_t ( ) result = fn ( action , byref ( pActionData ) , unActionDataSize , ulRestrictToDevice ) return result , pActionData
Reads the state of a digital action given its handle . This will return VRInputError_WrongType if the type of action is something other than digital
59,726
def getAnalogActionData ( self , action , unActionDataSize , ulRestrictToDevice ) : fn = self . function_table . getAnalogActionData pActionData = InputAnalogActionData_t ( ) result = fn ( action , byref ( pActionData ) , unActionDataSize , ulRestrictToDevice ) return result , pActionData
Reads the state of an analog action given its handle . This will return VRInputError_WrongType if the type of action is something other than analog
59,727
def getPoseActionData ( self , action , eOrigin , fPredictedSecondsFromNow , unActionDataSize , ulRestrictToDevice ) : fn = self . function_table . getPoseActionData pActionData = InputPoseActionData_t ( ) result = fn ( action , eOrigin , fPredictedSecondsFromNow , byref ( pActionData ) , unActionDataSize , ulRestrictToDevice ) return result , pActionData
Reads the state of a pose action given its handle .
59,728
def getSkeletalActionData ( self , action , unActionDataSize ) : fn = self . function_table . getSkeletalActionData pActionData = InputSkeletalActionData_t ( ) result = fn ( action , byref ( pActionData ) , unActionDataSize ) return result , pActionData
Reads the state of a skeletal action given its handle .
59,729
def getBoneCount ( self , action ) : fn = self . function_table . getBoneCount pBoneCount = c_uint32 ( ) result = fn ( action , byref ( pBoneCount ) ) return result , pBoneCount . value
Reads the number of bones in skeleton associated with the given action
59,730
def getBoneHierarchy ( self , action , unIndexArayCount ) : fn = self . function_table . getBoneHierarchy pParentIndices = BoneIndex_t ( ) result = fn ( action , byref ( pParentIndices ) , unIndexArayCount ) return result , pParentIndices
Fills the given array with the index of each bone s parent in the skeleton associated with the given action
59,731
def getBoneName ( self , action , nBoneIndex , pchBoneName , unNameBufferSize ) : fn = self . function_table . getBoneName result = fn ( action , nBoneIndex , pchBoneName , unNameBufferSize ) return result
Fills the given buffer with the name of the bone at the given index in the skeleton associated with the given action
59,732
def getSkeletalReferenceTransforms ( self , action , eTransformSpace , eReferencePose , unTransformArrayCount ) : fn = self . function_table . getSkeletalReferenceTransforms pTransformArray = VRBoneTransform_t ( ) result = fn ( action , eTransformSpace , eReferencePose , byref ( pTransformArray ) , unTransformArrayCount ) return result , pTransformArray
Fills the given buffer with the transforms for a specific static skeletal reference pose
59,733
def getSkeletalTrackingLevel ( self , action ) : fn = self . function_table . getSkeletalTrackingLevel pSkeletalTrackingLevel = EVRSkeletalTrackingLevel ( ) result = fn ( action , byref ( pSkeletalTrackingLevel ) ) return result , pSkeletalTrackingLevel
Reads the level of accuracy to which the controller is able to track the user to recreate a skeletal pose
59,734
def getSkeletalBoneData ( self , action , eTransformSpace , eMotionRange , unTransformArrayCount ) : fn = self . function_table . getSkeletalBoneData pTransformArray = VRBoneTransform_t ( ) result = fn ( action , eTransformSpace , eMotionRange , byref ( pTransformArray ) , unTransformArrayCount ) return result , pTransformArray
Reads the state of the skeletal bone data associated with this action and copies it into the given buffer .
59,735
def getSkeletalSummaryData ( self , action ) : fn = self . function_table . getSkeletalSummaryData pSkeletalSummaryData = VRSkeletalSummaryData_t ( ) result = fn ( action , byref ( pSkeletalSummaryData ) ) return result , pSkeletalSummaryData
Reads summary information about the current pose of the skeleton associated with the given action .
59,736
def decompressSkeletalBoneData ( self , pvCompressedBuffer , unCompressedBufferSize , eTransformSpace , unTransformArrayCount ) : fn = self . function_table . decompressSkeletalBoneData pTransformArray = VRBoneTransform_t ( ) result = fn ( pvCompressedBuffer , unCompressedBufferSize , eTransformSpace , byref ( pTransformArray ) , unTransformArrayCount ) return result , pTransformArray
Turns a compressed buffer from GetSkeletalBoneDataCompressed and turns it back into a bone transform array .
59,737
def triggerHapticVibrationAction ( self , action , fStartSecondsFromNow , fDurationSeconds , fFrequency , fAmplitude , ulRestrictToDevice ) : fn = self . function_table . triggerHapticVibrationAction result = fn ( action , fStartSecondsFromNow , fDurationSeconds , fFrequency , fAmplitude , ulRestrictToDevice ) return result
Triggers a haptic event as described by the specified action
59,738
def getActionOrigins ( self , actionSetHandle , digitalActionHandle , originOutCount ) : fn = self . function_table . getActionOrigins originsOut = VRInputValueHandle_t ( ) result = fn ( actionSetHandle , digitalActionHandle , byref ( originsOut ) , originOutCount ) return result , originsOut
Retrieve origin handles for an action
59,739
def getOriginLocalizedName ( self , origin , pchNameArray , unNameArraySize , unStringSectionsToInclude ) : fn = self . function_table . getOriginLocalizedName result = fn ( origin , pchNameArray , unNameArraySize , unStringSectionsToInclude ) return result
Retrieves the name of the origin in the current language . unStringSectionsToInclude is a bitfield of values in EVRInputStringBits that allows the application to specify which parts of the origin s information it wants a string for .
59,740
def getOriginTrackedDeviceInfo ( self , origin , unOriginInfoSize ) : fn = self . function_table . getOriginTrackedDeviceInfo pOriginInfo = InputOriginInfo_t ( ) result = fn ( origin , byref ( pOriginInfo ) , unOriginInfoSize ) return result , pOriginInfo
Retrieves useful information for the origin of this action
59,741
def showActionOrigins ( self , actionSetHandle , ulActionHandle ) : fn = self . function_table . showActionOrigins result = fn ( actionSetHandle , ulActionHandle ) return result
Shows the current binding for the action in - headset
59,742
def showBindingsForActionSet ( self , unSizeOfVRSelectedActionSet_t , unSetCount , originToHighlight ) : fn = self . function_table . showBindingsForActionSet pSets = VRActiveActionSet_t ( ) result = fn ( byref ( pSets ) , unSizeOfVRSelectedActionSet_t , unSetCount , originToHighlight ) return result , pSets
Shows the current binding all the actions in the specified action sets
59,743
def open ( self , pchPath , mode , unElementSize , unElements ) : fn = self . function_table . open pulBuffer = IOBufferHandle_t ( ) result = fn ( pchPath , mode , unElementSize , unElements , byref ( pulBuffer ) ) return result , pulBuffer
opens an existing or creates a new IOBuffer of unSize bytes
59,744
def close ( self , ulBuffer ) : fn = self . function_table . close result = fn ( ulBuffer ) return result
closes a previously opened or created buffer
59,745
def propertyContainer ( self , ulBuffer ) : fn = self . function_table . propertyContainer result = fn ( ulBuffer ) return result
retrieves the property container of an buffer .
59,746
def hasReaders ( self , ulBuffer ) : fn = self . function_table . hasReaders result = fn ( ulBuffer ) return result
inexpensively checks for readers to allow writers to fast - fail potentially expensive copies and writes .
59,747
async def execute ( self , sql , * params ) : if self . _echo : logger . info ( sql ) logger . info ( "%r" , sql ) await self . _run_operation ( self . _impl . execute , sql , * params ) return self
Executes the given operation substituting any markers with the given parameters .
59,748
def executemany ( self , sql , * params ) : fut = self . _run_operation ( self . _impl . executemany , sql , * params ) return fut
Prepare a database query or command and then execute it against all parameter sequences found in the sequence seq_of_params .
59,749
def fetchmany ( self , size ) : fut = self . _run_operation ( self . _impl . fetchmany , size ) return fut
Returns a list of remaining rows containing no more than size rows used to process results in chunks . The list will be empty when there are no more rows .
59,750
def tables ( self , ** kw ) : fut = self . _run_operation ( self . _impl . tables , ** kw ) return fut
Creates a result set of tables in the database that match the given criteria .
59,751
def columns ( self , ** kw ) : fut = self . _run_operation ( self . _impl . columns , ** kw ) return fut
Creates a results set of column names in specified tables by executing the ODBC SQLColumns function . Each row fetched has the following columns .
59,752
def statistics ( self , catalog = None , schema = None , unique = False , quick = True ) : fut = self . _run_operation ( self . _impl . statistics , catalog = catalog , schema = schema , unique = unique , quick = quick ) return fut
Creates a results set of statistics about a single table and the indexes associated with the table by executing SQLStatistics .
59,753
def rowIdColumns ( self , table , catalog = None , schema = None , nullable = True ) : fut = self . _run_operation ( self . _impl . rowIdColumns , table , catalog = catalog , schema = schema , nullable = nullable ) return fut
Executes SQLSpecialColumns with SQL_BEST_ROWID which creates a result set of columns that uniquely identify a row
59,754
def primaryKeys ( self , table , catalog = None , schema = None ) : fut = self . _run_operation ( self . _impl . primaryKeys , table , catalog = catalog , schema = schema ) return fut
Creates a result set of column names that make up the primary key for a table by executing the SQLPrimaryKeys function .
59,755
def getTypeInfo ( self , sql_type ) : fut = self . _run_operation ( self . _impl . getTypeInfo , sql_type ) return fut
Executes SQLGetTypeInfo a creates a result set with information about the specified data type or all data types supported by the ODBC driver if not specified .
59,756
def procedures ( self , * a , ** kw ) : fut = self . _run_operation ( self . _impl . procedures , * a , ** kw ) return fut
Executes SQLProcedures and creates a result set of information about the procedures in the data source .
59,757
async def dataSources ( loop = None , executor = None ) : loop = loop or asyncio . get_event_loop ( ) sources = await loop . run_in_executor ( executor , _dataSources ) return sources
Returns a dictionary mapping available DSNs to their descriptions .
59,758
def connect ( * , dsn , autocommit = False , ansi = False , timeout = 0 , loop = None , executor = None , echo = False , after_created = None , ** kwargs ) : return _ContextManager ( _connect ( dsn = dsn , autocommit = autocommit , ansi = ansi , timeout = timeout , loop = loop , executor = executor , echo = echo , after_created = after_created , ** kwargs ) )
Accepts an ODBC connection string and returns a new Connection object .
59,759
async def close ( self ) : if not self . _conn : return c = await self . _execute ( self . _conn . close ) self . _conn = None return c
Close pyodbc connection
59,760
async def execute ( self , sql , * args ) : _cursor = await self . _execute ( self . _conn . execute , sql , * args ) connection = self cursor = Cursor ( _cursor , connection , echo = self . _echo ) return cursor
Create a new Cursor object call its execute method and return it .
59,761
def getinfo ( self , type_ ) : fut = self . _execute ( self . _conn . getinfo , type_ ) return fut
Returns general information about the driver and data source associated with a connection by calling SQLGetInfo and returning its results . See Microsoft s SQLGetInfo documentation for the types of information available .
59,762
def add_output_converter ( self , sqltype , func ) : fut = self . _execute ( self . _conn . add_output_converter , sqltype , func ) return fut
Register an output converter function that will be called whenever a value with the given SQL type is read from the database .
59,763
def set_attr ( self , attr_id , value ) : fut = self . _execute ( self . _conn . set_attr , attr_id , value ) return fut
Calls SQLSetConnectAttr with the given values .
59,764
def _request_get ( self , path , params = None , json = True , url = BASE_URL ) : url = urljoin ( url , path ) headers = self . _get_request_headers ( ) response = requests . get ( url , params = params , headers = headers ) if response . status_code >= 500 : backoff = self . _initial_backoff for _ in range ( self . _max_retries ) : time . sleep ( backoff ) backoff_response = requests . get ( url , params = params , headers = headers , timeout = DEFAULT_TIMEOUT ) if backoff_response . status_code < 500 : response = backoff_response break backoff *= 2 response . raise_for_status ( ) if json : return response . json ( ) else : return response
Perform a HTTP GET request .
59,765
def _request_post ( self , path , data = None , params = None , url = BASE_URL ) : url = urljoin ( url , path ) headers = self . _get_request_headers ( ) response = requests . post ( url , json = data , params = params , headers = headers , timeout = DEFAULT_TIMEOUT ) response . raise_for_status ( ) if response . status_code == 200 : return response . json ( )
Perform a HTTP POST request ..
59,766
def _request_delete ( self , path , params = None , url = BASE_URL ) : url = urljoin ( url , path ) headers = self . _get_request_headers ( ) response = requests . delete ( url , params = params , headers = headers , timeout = DEFAULT_TIMEOUT ) response . raise_for_status ( ) if response . status_code == 200 : return response . json ( )
Perform a HTTP DELETE request .
59,767
def parse ( cls , signed_request , application_secret_key ) : def decode ( encoded ) : padding = '=' * ( len ( encoded ) % 4 ) return base64 . urlsafe_b64decode ( encoded + padding ) try : encoded_signature , encoded_payload = ( str ( string ) for string in signed_request . split ( '.' , 2 ) ) signature = decode ( encoded_signature ) signed_request_data = json . loads ( decode ( encoded_payload ) . decode ( 'utf-8' ) ) except ( TypeError , ValueError ) : raise SignedRequestError ( "Signed request had a corrupt payload" ) if signed_request_data . get ( 'algorithm' , '' ) . upper ( ) != 'HMAC-SHA256' : raise SignedRequestError ( "Signed request is using an unknown algorithm" ) expected_signature = hmac . new ( application_secret_key . encode ( 'utf-8' ) , msg = encoded_payload . encode ( 'utf-8' ) , digestmod = hashlib . sha256 ) . digest ( ) if signature != expected_signature : raise SignedRequestError ( "Signed request signature mismatch" ) return signed_request_data
Parse a signed request returning a dictionary describing its payload .
59,768
def generate ( self ) : payload = { 'algorithm' : 'HMAC-SHA256' } if self . data : payload [ 'app_data' ] = self . data if self . page : payload [ 'page' ] = { } if self . page . id : payload [ 'page' ] [ 'id' ] = self . page . id if self . page . is_liked : payload [ 'page' ] [ 'liked' ] = self . page . is_liked if self . page . is_admin : payload [ 'page' ] [ 'admin' ] = self . page . is_admin if self . user : payload [ 'user' ] = { } if self . user . country : payload [ 'user' ] [ 'country' ] = self . user . country if self . user . locale : payload [ 'user' ] [ 'locale' ] = self . user . locale if self . user . age : payload [ 'user' ] [ 'age' ] = { 'min' : self . user . age [ 0 ] , 'max' : self . user . age [ - 1 ] } if self . user . oauth_token : if self . user . oauth_token . token : payload [ 'oauth_token' ] = self . user . oauth_token . token if self . user . oauth_token . expires_at is None : payload [ 'expires_in' ] = 0 else : payload [ 'expires_in' ] = int ( time . mktime ( self . user . oauth_token . expires_at . timetuple ( ) ) ) if self . user . oauth_token . issued_at : payload [ 'issued_at' ] = int ( time . mktime ( self . user . oauth_token . issued_at . timetuple ( ) ) ) if self . user . id : payload [ 'user_id' ] = self . user . id encoded_payload = base64 . urlsafe_b64encode ( json . dumps ( payload , separators = ( ',' , ':' ) ) . encode ( 'utf-8' ) ) encoded_signature = base64 . urlsafe_b64encode ( hmac . new ( self . application_secret_key . encode ( 'utf-8' ) , encoded_payload , hashlib . sha256 ) . digest ( ) ) return '%(signature)s.%(payload)s' % { 'signature' : encoded_signature , 'payload' : encoded_payload }
Generate a signed request from this instance .
59,769
def for_application ( self , id , secret_key , api_version = None ) : from facepy . utils import get_application_access_token access_token = get_application_access_token ( id , secret_key , api_version = api_version ) return GraphAPI ( access_token , version = api_version )
Initialize GraphAPI with an OAuth access token for an application .
59,770
def get ( self , path = '' , page = False , retry = 3 , ** options ) : response = self . _query ( method = 'GET' , path = path , data = options , page = page , retry = retry ) if response is False : raise FacebookError ( 'Could not get "%s".' % path ) return response
Get an item from the Graph API .
59,771
def post ( self , path = '' , retry = 0 , ** data ) : response = self . _query ( method = 'POST' , path = path , data = data , retry = retry ) if response is False : raise FacebookError ( 'Could not post to "%s"' % path ) return response
Post an item to the Graph API .
59,772
def search ( self , term , type = 'place' , page = False , retry = 3 , ** options ) : if type != 'place' : raise ValueError ( 'Unsupported type "%s". The only supported type is "place" since Graph API 2.0.' % type ) options = dict ( { 'q' : term , 'type' : type , } , ** options ) response = self . _query ( 'GET' , 'search' , options , page , retry ) return response
Search for an item in the Graph API .
59,773
def batch ( self , requests ) : for request in requests : if 'body' in request : request [ 'body' ] = urlencode ( request [ 'body' ] ) def _grouper ( complete_list , n = 1 ) : for i in range ( 0 , len ( complete_list ) , n ) : yield complete_list [ i : i + n ] responses = [ ] for group in _grouper ( requests , 50 ) : responses += self . post ( batch = json . dumps ( group ) ) for response , request in zip ( responses , requests ) : if not response : yield None continue try : yield self . _parse ( response [ 'body' ] ) except FacepyError as exception : exception . request = request yield exception
Make a batch request .
59,774
def _parse ( self , data ) : if type ( data ) == type ( bytes ( ) ) : try : data = data . decode ( 'utf-8' ) except UnicodeDecodeError : return data try : data = json . loads ( data , parse_float = Decimal ) except ValueError : return data if type ( data ) is dict : if 'error' in data : error = data [ 'error' ] if error . get ( 'type' ) == "OAuthException" : exception = OAuthError else : exception = FacebookError raise exception ( ** self . _get_error_params ( data ) ) if 'error_msg' in data : raise FacebookError ( ** self . _get_error_params ( data ) ) return data
Parse the response from Facebook s Graph API .
59,775
def get_extended_access_token ( access_token , application_id , application_secret_key , api_version = None ) : graph = GraphAPI ( version = api_version ) response = graph . get ( path = 'oauth/access_token' , client_id = application_id , client_secret = application_secret_key , grant_type = 'fb_exchange_token' , fb_exchange_token = access_token ) try : components = parse_qs ( response ) except AttributeError : return response [ 'access_token' ] , None token = components [ 'access_token' ] [ 0 ] try : expires_at = datetime . now ( ) + timedelta ( seconds = int ( components [ 'expires' ] [ 0 ] ) ) except KeyError : expires_at = None return token , expires_at
Get an extended OAuth access token .
59,776
def get_application_access_token ( application_id , application_secret_key , api_version = None ) : graph = GraphAPI ( version = api_version ) response = graph . get ( path = 'oauth/access_token' , client_id = application_id , client_secret = application_secret_key , grant_type = 'client_credentials' ) try : data = parse_qs ( response ) try : return data [ 'access_token' ] [ 0 ] except KeyError : raise GraphAPI . FacebookError ( 'No access token given' ) except AttributeError : return response [ 'access_token' ] , None
Get an OAuth access token for the given application .
59,777
def locked_get_or_set ( self , key , value_creator , version = None , expire = None , id = None , lock_key = None , timeout = DEFAULT_TIMEOUT ) : if lock_key is None : lock_key = 'get_or_set:' + key val = self . get ( key , version = version ) if val is not None : return val with self . lock ( lock_key , expire = expire , id = id ) : val = self . get ( key , version = version ) if val is not None : return val val = value_creator ( ) if val is None : raise ValueError ( '`value_creator` must return a value' ) self . set ( key , val , timeout = timeout , version = version ) return val
Fetch a given key from the cache . If the key does not exist the key is added and set to the value returned when calling value_creator . The creator function is invoked inside of a lock .
59,778
def _eval_script ( redis , script_id , * keys , ** kwargs ) : args = kwargs . pop ( 'args' , ( ) ) if kwargs : raise TypeError ( "Unexpected keyword arguments %s" % kwargs . keys ( ) ) try : return redis . evalsha ( SCRIPTS [ script_id ] , len ( keys ) , * keys + args ) except NoScriptError : logger . info ( "%s not cached." , SCRIPTS [ script_id + 2 ] ) return redis . eval ( SCRIPTS [ script_id + 1 ] , len ( keys ) , * keys + args )
Tries to call EVALSHA with the hash and then if it fails calls regular EVAL with the script .
59,779
def reset ( self ) : _eval_script ( self . _client , RESET , self . _name , self . _signal ) self . _delete_signal ( )
Forcibly deletes the lock . Use this with care .
59,780
def extend ( self , expire = None ) : if expire is None : if self . _expire is not None : expire = self . _expire else : raise TypeError ( "To extend a lock 'expire' must be provided as an " "argument to extend() method or at initialization time." ) error = _eval_script ( self . _client , EXTEND , self . _name , args = ( expire , self . _id ) ) if error == 1 : raise NotAcquired ( "Lock %s is not acquired or it already expired." % self . _name ) elif error == 2 : raise NotExpirable ( "Lock %s has no assigned expiration time" % self . _name ) elif error : raise RuntimeError ( "Unsupported error code %s from EXTEND script" % error )
Extends expiration time of the lock .
59,781
def _lock_renewer ( lockref , interval , stop ) : log = getLogger ( "%s.lock_refresher" % __name__ ) while not stop . wait ( timeout = interval ) : log . debug ( "Refreshing lock" ) lock = lockref ( ) if lock is None : log . debug ( "The lock no longer exists, " "stopping lock refreshing" ) break lock . extend ( expire = lock . _expire ) del lock log . debug ( "Exit requested, stopping lock refreshing" )
Renew the lock key in redis every interval seconds for as long as self . _lock_renewal_thread . should_exit is False .
59,782
def _start_lock_renewer ( self ) : if self . _lock_renewal_thread is not None : raise AlreadyStarted ( "Lock refresh thread already started" ) logger . debug ( "Starting thread to refresh lock every %s seconds" , self . _lock_renewal_interval ) self . _lock_renewal_stop = threading . Event ( ) self . _lock_renewal_thread = threading . Thread ( group = None , target = self . _lock_renewer , kwargs = { 'lockref' : weakref . ref ( self ) , 'interval' : self . _lock_renewal_interval , 'stop' : self . _lock_renewal_stop } ) self . _lock_renewal_thread . setDaemon ( True ) self . _lock_renewal_thread . start ( )
Starts the lock refresher thread .
59,783
def _stop_lock_renewer ( self ) : if self . _lock_renewal_thread is None or not self . _lock_renewal_thread . is_alive ( ) : return logger . debug ( "Signalling the lock refresher to stop" ) self . _lock_renewal_stop . set ( ) self . _lock_renewal_thread . join ( ) self . _lock_renewal_thread = None logger . debug ( "Lock refresher has stopped" )
Stop the lock renewer .
59,784
def release ( self ) : if self . _lock_renewal_thread is not None : self . _stop_lock_renewer ( ) logger . debug ( "Releasing %r." , self . _name ) error = _eval_script ( self . _client , UNLOCK , self . _name , self . _signal , args = ( self . _id , ) ) if error == 1 : raise NotAcquired ( "Lock %s is not acquired or it already expired." % self . _name ) elif error : raise RuntimeError ( "Unsupported error code %s from EXTEND script." % error ) else : self . _delete_signal ( )
Releases the lock that was acquired with the same object .
59,785
def get_detail ( self , course_id ) : resp = self . _requester . get ( urljoin ( self . _base_url , '/api/courses/v1/courses/{course_key}/' . format ( course_key = course_id ) ) ) resp . raise_for_status ( ) return CourseDetail ( resp . json ( ) )
Fetches course details .
59,786
def get_user_info ( self ) : resp = self . requester . get ( urljoin ( self . base_url , '/api/mobile/v0.5/my_user_info' ) ) resp . raise_for_status ( ) return Info ( resp . json ( ) )
Returns a UserInfo object for the logged in user .
59,787
def course_blocks ( self , course_id , username ) : resp = self . requester . get ( urljoin ( self . base_url , '/api/courses/v1/blocks/' ) , params = { "depth" : "all" , "username" : username , "course_id" : course_id , "requested_fields" : "children,display_name,id,type,visible_to_staff_only" , } ) resp . raise_for_status ( ) return Structure ( resp . json ( ) )
Fetches course blocks .
59,788
def get_student_current_grade ( self , username , course_id ) : resp = self . requester . get ( urljoin ( self . base_url , '/api/grades/v1/courses/{course_key}/?username={username}' . format ( username = username , course_key = course_id ) ) ) resp . raise_for_status ( ) return CurrentGrade ( resp . json ( ) [ 0 ] )
Returns an CurrentGrade object for the user in a course
59,789
def get_student_current_grades ( self , username , course_ids = None ) : if course_ids is None : enrollments_client = CourseEnrollments ( self . requester , self . base_url ) enrollments = enrollments_client . get_student_enrollments ( ) course_ids = list ( enrollments . get_enrolled_course_ids ( ) ) all_current_grades = [ ] for course_id in course_ids : try : all_current_grades . append ( self . get_student_current_grade ( username , course_id ) ) except HTTPError as error : if error . response . status_code >= 500 : raise return CurrentGradesByUser ( all_current_grades )
Returns a CurrentGradesByUser object with the user current grades .
59,790
def get_course_current_grades ( self , course_id ) : resp = self . requester . get ( urljoin ( self . base_url , '/api/grades/v1/courses/{course_key}/' . format ( course_key = course_id ) ) ) resp . raise_for_status ( ) resp_json = resp . json ( ) if 'results' in resp_json : grade_entries = [ CurrentGrade ( entry ) for entry in resp_json [ "results" ] ] while resp_json [ 'next' ] is not None : resp = self . requester . get ( resp_json [ 'next' ] ) resp . raise_for_status ( ) resp_json = resp . json ( ) grade_entries . extend ( ( CurrentGrade ( entry ) for entry in resp_json [ "results" ] ) ) else : grade_entries = [ CurrentGrade ( entry ) for entry in resp_json ] return CurrentGradesByCourse ( grade_entries )
Returns a CurrentGradesByCourse object for all users in the specified course .
59,791
def get_requester ( self ) : session = requests . session ( ) session . headers . update ( { 'Authorization' : 'Bearer {}' . format ( self . credentials [ 'access_token' ] ) } ) old_request = session . request def patched_request ( * args , ** kwargs ) : return old_request ( * args , timeout = self . timeout , ** kwargs ) session . request = patched_request return session
Returns an object to make authenticated requests . See python requests for the API .
59,792
def create ( self , master_course_id , coach_email , max_students_allowed , title , modules = None ) : payload = { 'master_course_id' : master_course_id , 'coach_email' : coach_email , 'max_students_allowed' : max_students_allowed , 'display_name' : title , } if modules is not None : payload [ 'course_modules' ] = modules resp = self . requester . post ( parse . urljoin ( self . base_url , '/api/ccx/v0/ccx/' ) , json = payload ) try : resp . raise_for_status ( ) except : log . error ( resp . json ( ) ) raise return resp . json ( ) [ 'ccx_course_id' ]
Creates a CCX
59,793
def _get_enrollments_list_page ( self , params = None ) : req_url = urljoin ( self . base_url , self . enrollment_list_url ) resp = self . requester . get ( req_url , params = params ) resp . raise_for_status ( ) resp_json = resp . json ( ) results = resp_json [ 'results' ] next_url_str = resp_json . get ( 'next' ) cursor = None qstr_cursor = None if next_url_str : next_url = urlparse ( next_url_str ) qstr = parse_qs ( next_url . query ) qstr_cursor = qstr . get ( 'cursor' ) if qstr_cursor and isinstance ( qstr_cursor , list ) : cursor = qstr_cursor [ 0 ] return results , cursor
Submit request to retrieve enrollments list .
59,794
def get_enrollments ( self , course_id = None , usernames = None ) : params = { } if course_id is not None : params [ 'course_id' ] = course_id if usernames is not None and isinstance ( usernames , list ) : params [ 'username' ] = ',' . join ( usernames ) done = False while not done : enrollments , next_cursor = self . _get_enrollments_list_page ( params ) for enrollment in enrollments : yield Enrollment ( enrollment ) if next_cursor : params [ 'cursor' ] = next_cursor else : done = True
List all course enrollments .
59,795
def get_student_enrollments ( self ) : resp = self . requester . get ( urljoin ( self . base_url , self . enrollment_url ) ) resp . raise_for_status ( ) return Enrollments ( resp . json ( ) )
Returns an Enrollments object with the user enrollments
59,796
def create_audit_student_enrollment ( self , course_id ) : audit_enrollment = { "mode" : "audit" , "course_details" : { "course_id" : course_id } } resp = self . requester . post ( urljoin ( self . base_url , self . enrollment_url ) , json = audit_enrollment ) resp . raise_for_status ( ) return Enrollment ( resp . json ( ) )
Creates an audit enrollment for the user in a given course
59,797
def get_student_certificate ( self , username , course_id ) : resp = self . requester . get ( urljoin ( self . base_url , '/api/certificates/v0/certificates/{username}/courses/{course_key}/' . format ( username = username , course_key = course_id ) ) ) resp . raise_for_status ( ) return Certificate ( resp . json ( ) )
Returns an Certificate object with the user certificates
59,798
def get_student_certificates ( self , username , course_ids = None ) : if course_ids is None : enrollments_client = CourseEnrollments ( self . requester , self . base_url ) enrollments = enrollments_client . get_student_enrollments ( ) course_ids = list ( enrollments . get_enrolled_course_ids ( ) ) all_certificates = [ ] for course_id in course_ids : try : all_certificates . append ( self . get_student_certificate ( username , course_id ) ) except HTTPError as error : if error . response . status_code >= 500 : raise return Certificates ( all_certificates )
Returns an Certificates object with the user certificates
59,799
def get_colors ( img ) : w , h = img . size return [ color [ : 3 ] for count , color in img . convert ( 'RGB' ) . getcolors ( w * h ) ]
Returns a list of all the image s colors .