idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
43,100
def add_static_url ( self , url_path , directory , endpoint = None , roles = None ) : url_path = self . static_url_path + "/" + url_path + "/<path:filename>" self . add_url_rule ( url_path , endpoint = endpoint , view_func = partial ( send_file_from_directory , directory = directory ) , roles = roles , ) self . add_acc...
Add a new url rule for static files .
43,101
def _message_send ( self , connection ) : sender = current_app . config [ "MAIL_SENDER" ] if not self . extra_headers : self . extra_headers = { } self . extra_headers [ "Sender" ] = sender connection . send ( self , sender )
Send a single message instance .
43,102
def _filter_metadata_for_connection ( target , connection , ** kw ) : engine = connection . engine . name default_engines = ( engine , ) tables = target if isinstance ( target , sa . Table ) else kw . get ( "tables" , [ ] ) for table in tables : indexes = list ( table . indexes ) for idx in indexes : if engine not in i...
Listener to control what indexes get created .
43,103
def url_for ( obj , ** kw ) : if isinstance ( obj , str ) : return flask_url_for ( obj , ** kw ) try : return current_app . default_view . url_for ( obj , ** kw ) except KeyError : if hasattr ( obj , "_url" ) : return obj . _url elif hasattr ( obj , "url" ) : return obj . url raise BuildError ( repr ( obj ) , kw , "GET...
Polymorphic variant of Flask s url_for function .
43,104
def send_file_from_directory ( filename , directory , app = None ) : if app is None : app = current_app cache_timeout = app . get_send_file_max_age ( filename ) return send_from_directory ( directory , filename , cache_timeout = cache_timeout )
Helper to add static rules like in abilian . app . app .
43,105
def get_model_changes ( entity_type , year = None , month = None , day = None , hour = None , since = None ) : query = AuditEntry . query if since : query = query . filter ( AuditEntry . happened_at >= since ) if year : query = query . filter ( extract ( "year" , AuditEntry . happened_at ) == year ) if month : query = ...
Get models modified at the given date with the Audit service .
43,106
def get_columns_diff ( changes ) : for change in changes : change . diff = [ ] elt_changes = change . get_changes ( ) if elt_changes : change . diff = elt_changes . columns return changes
Add the changed columns as a diff attribute .
43,107
def _has_argument ( func ) : if hasattr ( inspect , 'signature' ) : sig = inspect . signature ( func ) return bool ( sig . parameters ) else : return bool ( inspect . getargspec ( func ) . args )
Test whether a function expects an argument .
43,108
def get_context ( self , template ) : context = { } for regex , context_generator in self . contexts : if re . match ( regex , template . name ) : if inspect . isfunction ( context_generator ) : if _has_argument ( context_generator ) : context . update ( context_generator ( template ) ) else : context . update ( contex...
Get the context for a template .
43,109
def get_rule ( self , template_name ) : for regex , render_func in self . rules : if re . match ( regex , template_name ) : return render_func raise ValueError ( "no matching rule" )
Find a matching compilation rule for a function .
43,110
def is_partial ( self , filename ) : return any ( ( x . startswith ( "_" ) for x in filename . split ( os . path . sep ) ) )
Check if a file is a partial .
43,111
def is_template ( self , filename ) : if self . is_partial ( filename ) : return False if self . is_ignored ( filename ) : return False if self . is_static ( filename ) : return False return True
Check if a file is a template .
43,112
def _ensure_dir ( self , template_name ) : head = os . path . dirname ( template_name ) if head : file_dirpath = os . path . join ( self . outpath , head ) if not os . path . exists ( file_dirpath ) : os . makedirs ( file_dirpath )
Ensure the output directory for a template exists .
43,113
def render ( self , use_reloader = False ) : self . render_templates ( self . templates ) self . copy_static ( self . static_names ) if use_reloader : self . logger . info ( "Watching '%s' for changes..." % self . searchpath ) self . logger . info ( "Press Ctrl+C to stop." ) Reloader ( self ) . watch ( )
Generate the site .
43,114
def register_jinja_loaders ( self , * loaders ) : if not hasattr ( self , "_jinja_loaders" ) : raise ValueError ( "Cannot register new jinja loaders after first template rendered" ) self . _jinja_loaders . extend ( loaders )
Register one or many jinja2 . Loader instances for templates lookup .
43,115
def render ( args ) : srcpath = ( os . path . join ( os . getcwd ( ) , 'templates' ) if args [ '--srcpath' ] is None else args [ '--srcpath' ] if os . path . isabs ( args [ '--srcpath' ] ) else os . path . join ( os . getcwd ( ) , args [ '--srcpath' ] ) ) if not os . path . isdir ( srcpath ) : print ( "The templates di...
Render a site .
43,116
def indexable_role ( principal ) : principal = unwrap ( principal ) if hasattr ( principal , "is_anonymous" ) and principal . is_anonymous : principal = Anonymous if isinstance ( principal , Role ) : return f"role:{principal.name}" elif isinstance ( principal , User ) : fmt = "user:{:d}" elif isinstance ( principal , G...
Return a string suitable for query against allowed_roles_and_users field .
43,117
def to_text ( self , digest , blob , mime_type ) : if mime_type . startswith ( "image/" ) : return "" cache_key = "txt:" + digest text = self . cache . get ( cache_key ) if text : return text for handler in self . handlers : if handler . accept ( mime_type , "text/plain" ) : text = handler . convert ( blob ) self . cac...
Convert a file to plain text .
43,118
def has_image ( self , digest , mime_type , index , size = 500 ) : cache_key = f"img:{index}:{size}:{digest}" return mime_type . startswith ( "image/" ) or cache_key in self . cache
Tell if there is a preview image .
43,119
def get_image ( self , digest , blob , mime_type , index , size = 500 ) : if mime_type . startswith ( "image/" ) : return "" cache_key = f"img:{index}:{size}:{digest}" return self . cache . get ( cache_key )
Return an image for the given content only if it already exists in the image cache .
43,120
def to_image ( self , digest , blob , mime_type , index , size = 500 ) : if mime_type . startswith ( "image/" ) : return "" cache_key = f"img:{index}:{size}:{digest}" converted = self . cache . get ( cache_key ) if converted : return converted for handler in self . handlers : if handler . accept ( mime_type , "image/jp...
Convert a file to a list of images .
43,121
def get_metadata ( self , digest , content , mime_type ) : if mime_type . startswith ( "image/" ) : img = Image . open ( BytesIO ( content ) ) ret = { } if not hasattr ( img , "_getexif" ) : return { } info = img . _getexif ( ) if not info : return { } for tag , value in info . items ( ) : decoded = TAGS . get ( tag , ...
Get a dictionary representing the metadata embedded in the given content .
43,122
def ToByteArray ( self ) : lc = self . InternalEncodeLc ( ) out = bytearray ( 4 ) out [ 0 ] = self . cla out [ 1 ] = self . ins out [ 2 ] = self . p1 out [ 3 ] = self . p2 if self . data : out . extend ( lc ) out . extend ( self . data ) out . extend ( [ 0x00 , 0x00 ] ) else : out . extend ( [ 0x00 , 0x00 , 0x00 ] ) re...
Serialize the command .
43,123
def _BuildPluginRequest ( self , app_id , challenge_data , origin ) : client_data_map = { } encoded_challenges = [ ] app_id_hash_encoded = self . _Base64Encode ( self . _SHA256 ( app_id ) ) for challenge_item in challenge_data : key = challenge_item [ 'key' ] key_handle_encoded = self . _Base64Encode ( key . key_handle...
Builds a JSON request in the form that the plugin expects .
43,124
def _BuildAuthenticatorResponse ( self , app_id , client_data , plugin_response ) : encoded_client_data = self . _Base64Encode ( client_data ) signature_data = str ( plugin_response [ 'signatureData' ] ) key_handle = str ( plugin_response [ 'keyHandle' ] ) response = { 'clientData' : encoded_client_data , 'signatureDat...
Builds the response to return to the caller .
43,125
def _CallPlugin ( self , cmd , input_json ) : input_length = len ( input_json ) length_bytes_le = struct . pack ( '<I' , input_length ) request = length_bytes_le + input_json . encode ( ) sign_process = subprocess . Popen ( cmd , stdin = subprocess . PIPE , stdout = subprocess . PIPE ) stdout = sign_process . communica...
Calls the plugin and validates the response .
43,126
def InternalInit ( self ) : self . cid = UsbHidTransport . U2FHID_BROADCAST_CID nonce = bytearray ( os . urandom ( 8 ) ) r = self . InternalExchange ( UsbHidTransport . U2FHID_INIT , nonce ) if len ( r ) < 17 : raise errors . HidError ( 'unexpected init reply len' ) if r [ 0 : 8 ] != nonce : raise errors . HidError ( '...
Initializes the device and obtains channel id .
43,127
def InternalExchange ( self , cmd , payload_in ) : self . logger . debug ( 'payload: ' + str ( list ( payload_in ) ) ) payload = bytearray ( ) payload [ : ] = payload_in for _ in range ( 2 ) : self . InternalSend ( cmd , payload ) ret_cmd , ret_payload = self . InternalRecv ( ) if ret_cmd == UsbHidTransport . U2FHID_ER...
Sends and receives a message from the device .
43,128
def InternalSend ( self , cmd , payload ) : length_to_send = len ( payload ) max_payload = self . packet_size - 7 first_frame = payload [ 0 : max_payload ] first_packet = UsbHidTransport . InitPacket ( self . packet_size , self . cid , cmd , len ( payload ) , first_frame ) del payload [ 0 : max_payload ] length_to_send...
Sends a message to the device including fragmenting it .
43,129
def InternalRecv ( self ) : first_read = self . InternalReadFrame ( ) first_packet = UsbHidTransport . InitPacket . FromWireFormat ( self . packet_size , first_read ) data = first_packet . payload to_read = first_packet . size - len ( first_packet . payload ) seq = 0 while to_read > 0 : next_read = self . InternalReadF...
Receives a message from the device including defragmenting it .
43,130
def InternalPlatformSwitch ( funcname , * args , ** kwargs ) : clz = None if sys . platform . startswith ( 'linux' ) : from pyu2f . hid import linux clz = linux . LinuxHidDevice elif sys . platform . startswith ( 'win32' ) : from pyu2f . hid import windows clz = windows . WindowsHidDevice elif sys . platform . startswi...
Determine on a platform - specific basis which module to use .
43,131
def GetJson ( self ) : server_challenge_b64 = base64 . urlsafe_b64encode ( self . raw_server_challenge ) . decode ( ) server_challenge_b64 = server_challenge_b64 . rstrip ( '=' ) return json . dumps ( { 'typ' : self . typ , 'challenge' : server_challenge_b64 , 'origin' : self . origin } , sort_keys = True )
Returns JSON version of ClientData compatible with FIDO spec .
43,132
def GetValueLength ( rd , pos ) : rd = bytearray ( rd ) key = rd [ pos ] if key == LONG_ITEM_ENCODING : if pos + 1 < len ( rd ) : return ( 3 , rd [ pos + 1 ] ) else : raise errors . HidError ( 'Malformed report descriptor' ) else : code = key & 0x03 if code <= 0x02 : return ( 1 , code ) elif code == 0x03 : return ( 1 ,...
Get value length for a key in rd .
43,133
def ReadLsbBytes ( rd , offset , value_size ) : encoding = None if value_size == 1 : encoding = '<B' elif value_size == 2 : encoding = '<H' elif value_size == 4 : encoding = '<L' else : raise errors . HidError ( 'Invalid value size specified' ) ret , = struct . unpack ( encoding , rd [ offset : offset + value_size ] ) ...
Reads value_size bytes from rd at offset least signifcant byte first .
43,134
def ParseReportDescriptor ( rd , desc ) : rd = bytearray ( rd ) pos = 0 report_count = None report_size = None usage_page = None usage = None while pos < len ( rd ) : key = rd [ pos ] key_size , value_length = GetValueLength ( rd , pos ) if key & REPORT_DESCRIPTOR_KEY_MASK == INPUT_ITEM : if report_count and report_siz...
Parse the binary report descriptor .
43,135
def FillDeviceAttributes ( device , descriptor ) : attributes = HidAttributes ( ) result = hid . HidD_GetAttributes ( device , ctypes . byref ( attributes ) ) if not result : raise ctypes . WinError ( ) buf = ctypes . create_string_buffer ( 1024 ) result = hid . HidD_GetProductString ( device , buf , 1024 ) if not resu...
Fill out the attributes of the device .
43,136
def FillDeviceCapabilities ( device , descriptor ) : preparsed_data = PHIDP_PREPARSED_DATA ( 0 ) ret = hid . HidD_GetPreparsedData ( device , ctypes . byref ( preparsed_data ) ) if not ret : raise ctypes . WinError ( ) try : caps = HidCapabilities ( ) ret = hid . HidP_GetCaps ( preparsed_data , ctypes . byref ( caps ) ...
Fill out device capabilities .
43,137
def OpenDevice ( path , enum = False ) : desired_access = GENERIC_WRITE | GENERIC_READ share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE if enum : desired_access = 0 h = kernel32 . CreateFileA ( path , desired_access , share_mode , None , OPEN_EXISTING , 0 , None ) if h == INVALID_HANDLE_VALUE : raise ctypes . WinError (...
Open the device and return a handle to it .
43,138
def GetLocalU2FInterface ( origin = socket . gethostname ( ) ) : hid_transports = hidtransport . DiscoverLocalHIDU2FDevices ( ) for t in hid_transports : try : return U2FInterface ( security_key = hardware . SecurityKey ( transport = t ) , origin = origin ) except errors . UnsupportedVersionException : pass raise error...
Obtains a U2FInterface for the first valid local U2FHID device found .
43,139
def Register ( self , app_id , challenge , registered_keys ) : client_data = model . ClientData ( model . ClientData . TYP_REGISTRATION , challenge , self . origin ) challenge_param = self . InternalSHA256 ( client_data . GetJson ( ) ) app_param = self . InternalSHA256 ( app_id ) for key in registered_keys : try : if k...
Registers app_id with the security key .
43,140
def Authenticate ( self , app_id , challenge , registered_keys ) : client_data = model . ClientData ( model . ClientData . TYP_AUTHENTICATION , challenge , self . origin ) app_param = self . InternalSHA256 ( app_id ) challenge_param = self . InternalSHA256 ( client_data . GetJson ( ) ) num_invalid_keys = 0 for key in r...
Authenticates app_id with the security key .
43,141
def CmdRegister ( self , challenge_param , app_param ) : self . logger . debug ( 'CmdRegister' ) if len ( challenge_param ) != 32 or len ( app_param ) != 32 : raise errors . InvalidRequestError ( ) body = bytearray ( challenge_param + app_param ) response = self . InternalSendApdu ( apdu . CommandApdu ( 0 , apdu . CMD_...
Register security key .
43,142
def CmdAuthenticate ( self , challenge_param , app_param , key_handle , check_only = False ) : self . logger . debug ( 'CmdAuthenticate' ) if len ( challenge_param ) != 32 or len ( app_param ) != 32 : raise errors . InvalidRequestError ( ) control = 0x07 if check_only else 0x03 body = bytearray ( challenge_param + app_...
Attempt to obtain an authentication signature .
43,143
def CmdVersion ( self ) : self . logger . debug ( 'CmdVersion' ) response = self . InternalSendApdu ( apdu . CommandApdu ( 0 , apdu . CMD_VERSION , 0x00 , 0x00 ) ) if not response . IsSuccess ( ) : raise errors . ApduError ( response . sw1 , response . sw2 ) return response . body
Obtain the version of the device and test transport format .
43,144
def InternalSendApdu ( self , apdu_to_send ) : response = None if not self . use_legacy_format : response = apdu . ResponseApdu ( self . transport . SendMsgBytes ( apdu_to_send . ToByteArray ( ) ) ) if response . sw1 == 0x67 and response . sw2 == 0x00 : self . use_legacy_format = True return self . InternalSendApdu ( a...
Send an APDU to the device .
43,145
def GetDeviceIntProperty ( dev_ref , key ) : cf_key = CFStr ( key ) type_ref = iokit . IOHIDDeviceGetProperty ( dev_ref , cf_key ) cf . CFRelease ( cf_key ) if not type_ref : return None if cf . CFGetTypeID ( type_ref ) != cf . CFNumberGetTypeID ( ) : raise errors . OsHidError ( 'Expected number type, got {}' . format ...
Reads int property from the HID device .
43,146
def GetDeviceStringProperty ( dev_ref , key ) : cf_key = CFStr ( key ) type_ref = iokit . IOHIDDeviceGetProperty ( dev_ref , cf_key ) cf . CFRelease ( cf_key ) if not type_ref : return None if cf . CFGetTypeID ( type_ref ) != cf . CFStringGetTypeID ( ) : raise errors . OsHidError ( 'Expected string type, got {}' . form...
Reads string property from the HID device .
43,147
def GetDevicePath ( device_handle ) : io_service_obj = iokit . IOHIDDeviceGetService ( device_handle ) str_buffer = ctypes . create_string_buffer ( DEVICE_PATH_BUFFER_SIZE ) iokit . IORegistryEntryGetPath ( io_service_obj , K_IO_SERVICE_PLANE , str_buffer ) return str_buffer . value
Obtains the unique path for the device .
43,148
def HidReadCallback ( read_queue , result , sender , report_type , report_id , report , report_length ) : del result , sender , report_type , report_id incoming_bytes = [ report [ i ] for i in range ( report_length ) ] read_queue . put ( incoming_bytes )
Handles incoming IN report from HID device .
43,149
def DeviceReadThread ( hid_device ) : hid_device . run_loop_ref = cf . CFRunLoopGetCurrent ( ) if not hid_device . run_loop_ref : logger . error ( 'Failed to get current run loop' ) return iokit . IOHIDDeviceScheduleWithRunLoop ( hid_device . device_handle , hid_device . run_loop_ref , K_CF_RUNLOOP_DEFAULT_MODE ) run_l...
Binds a device to the thread s run loop then starts the run loop .
43,150
def change_view ( self , * args , ** kwargs ) : Hierarchy . init_hierarchy ( self ) self . hierarchy . hook_change_view ( self , args , kwargs ) return super ( HierarchicalModelAdmin , self ) . change_view ( * args , ** kwargs )
Renders detailed model edit page .
43,151
def action_checkbox ( self , obj ) : if getattr ( obj , Hierarchy . UPPER_LEVEL_MODEL_ATTR , False ) : return '' return super ( HierarchicalModelAdmin , self ) . action_checkbox ( obj )
Renders checkboxes .
43,152
def get_queryset ( self , request ) : self . _hierarchy . hook_get_queryset ( self , request ) return super ( HierarchicalChangeList , self ) . get_queryset ( request )
Constructs a query set .
43,153
def get_results ( self , request ) : super ( HierarchicalChangeList , self ) . get_results ( request ) self . _hierarchy . hook_get_results ( self )
Gets query set results .
43,154
def check_field_exists ( self , field_name ) : if not settings . DEBUG : return try : self . lookup_opts . get_field ( field_name ) except FieldDoesNotExist as e : raise AdmirarchyConfigurationError ( e )
Implements field exists check for debugging purposes .
43,155
def init_hierarchy ( cls , model_admin ) : hierarchy = getattr ( model_admin , 'hierarchy' ) if hierarchy : if not isinstance ( hierarchy , Hierarchy ) : hierarchy = AdjacencyList ( ) else : hierarchy = NoHierarchy ( ) model_admin . hierarchy = hierarchy
Initializes model admin with hierarchy data .
43,156
def get_pid_from_request ( cls , changelist , request ) : val = request . GET . get ( cls . PARENT_ID_QS_PARAM , False ) pid = val or None try : del changelist . params [ cls . PARENT_ID_QS_PARAM ] except KeyError : pass return pid
Gets parent ID from query string .
43,157
def read_file ( fpath ) : with io . open ( os . path . join ( PATH_BASE , fpath ) ) as f : return f . read ( )
Reads a file within package directories .
43,158
def get_version ( ) : contents = read_file ( os . path . join ( 'admirarchy' , '__init__.py' ) ) version = re . search ( 'VERSION = \(([^)]+)\)' , contents ) version = version . group ( 1 ) . replace ( ', ' , '.' ) . strip ( ) return version
Returns version number without module import ( which can lead to ImportError if some dependencies are unavailable before install .
43,159
def process_update ( self , update ) : data = json . loads ( update ) NetworkTables . getEntry ( data [ "k" ] ) . setValue ( data [ "v" ] )
Process an incoming update from a remote NetworkTables
43,160
def _send_update ( self , data ) : if isinstance ( data , dict ) : data = json . dumps ( data ) self . update_callback ( data )
Send a NetworkTables update via the stored send_update callback
43,161
def _nt_on_change ( self , key , value , isNew ) : self . _send_update ( { "k" : key , "v" : value , "n" : isNew } )
NetworkTables global listener callback
43,162
def close ( self ) : NetworkTables . removeGlobalListener ( self . _nt_on_change ) NetworkTables . removeConnectionListener ( self . _nt_connected )
Clean up NetworkTables listeners
43,163
def select_station ( candidates , coverage_range = None , min_fraction_coverage = 0.9 , distance_warnings = ( 50000 , 200000 ) , rank = 1 , ) : def _test_station ( station ) : if coverage_range is None : return True , [ ] else : start_date , end_date = coverage_range try : tempC , warnings = eeweather . mockable . load...
Select a station from a list of candidates that meets given data quality criteria .
43,164
def _load_isd_station_metadata ( download_path ) : from shapely . geometry import Point isd_history = pd . read_csv ( os . path . join ( download_path , "isd-history.csv" ) , dtype = str , parse_dates = [ "BEGIN" , "END" ] , ) hasGEO = ( isd_history . LAT . notnull ( ) & isd_history . LON . notnull ( ) & ( isd_history ...
Collect metadata for US isd stations .
43,165
def _load_isd_file_metadata ( download_path , isd_station_metadata ) : isd_inventory = pd . read_csv ( os . path . join ( download_path , "isd-inventory.csv" ) , dtype = str ) station_keep = [ usaf in isd_station_metadata for usaf in isd_inventory . USAF ] isd_inventory = isd_inventory [ station_keep ] year_keep = isd_...
Collect data counts for isd files .
43,166
def build_metadata_db ( zcta_geometry = False , iecc_climate_zone_geometry = True , iecc_moisture_regime_geometry = True , ba_climate_zone_geometry = True , ca_climate_zone_geometry = True , ) : try : import shapely except ImportError : raise ImportError ( "Loading polygons requires shapely." ) try : from bs4 import Be...
Build database of metadata from primary sources .
43,167
def json ( self ) : return { "elevation" : self . elevation , "latitude" : self . latitude , "longitude" : self . longitude , "icao_code" : self . icao_code , "name" : self . name , "quality" : self . quality , "wban_ids" : self . wban_ids , "recent_wban_id" : self . recent_wban_id , "climate_zones" : { "iecc_climate_z...
Return a JSON - serializeable object containing station metadata .
43,168
def get_isd_filenames ( self , year = None , with_host = False ) : return get_isd_filenames ( self . usaf_id , year , with_host = with_host )
Get filenames of raw ISD station data .
43,169
def get_gsod_filenames ( self , year = None , with_host = False ) : return get_gsod_filenames ( self . usaf_id , year , with_host = with_host )
Get filenames of raw GSOD station data .
43,170
def execute ( self , input_data ) : if ( input_data [ 'meta' ] [ 'type_tag' ] != 'pdf' ) : return { 'error' : self . __class__ . __name__ + ': called on ' + input_data [ 'meta' ] [ 'type_tag' ] } view = { } view [ 'strings' ] = input_data [ 'strings' ] [ 'string_list' ] [ : 5 ] view . update ( input_data [ 'meta' ] ) r...
Execute the ViewPDF worker
43,171
def add_node ( self , node_id , name , labels ) : if node_id not in self . node_cache : self . workbench . add_node ( node_id , name , labels ) self . node_cache . add ( node_id )
Cache aware add_node
43,172
def add_rel ( self , source_id , target_id , rel ) : if ( source_id , target_id ) not in self . rel_cache : self . workbench . add_rel ( source_id , target_id , rel ) self . rel_cache . add ( ( source_id , target_id ) )
Cache aware add_rel
43,173
def run ( ) : args = client_helper . grab_server_args ( ) workbench = zerorpc . Client ( timeout = 300 , heartbeat = 60 ) workbench . connect ( 'tcp://' + args [ 'server' ] + ':' + args [ 'port' ] ) print workbench . help ( ) print workbench . help ( 'basic' ) print workbench . help ( 'commands' ) print workbench . hel...
This client calls a bunch of help commands from workbench
43,174
def execute ( self , input_data ) : string_output = input_data [ 'strings' ] [ 'string_list' ] flatten = ' ' . join ( string_output ) urls = self . url_match . findall ( flatten ) return { 'url_list' : urls }
Execute the URL worker
43,175
def r_to_s ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : class ReprToStr ( str ) : def __repr__ ( self ) : return str ( self ) return ReprToStr ( func ( * args , ** kwargs ) ) return wrapper
Decorator method for Workbench methods returning a str
43,176
def all_files_in_directory ( path ) : file_list = [ ] for dirname , dirnames , filenames in os . walk ( path ) : for filename in filenames : file_list . append ( os . path . join ( dirname , filename ) ) return file_list
Recursively ist all files under a directory
43,177
def run ( ) : args = client_helper . grab_server_args ( ) workbench = zerorpc . Client ( timeout = 300 , heartbeat = 60 ) workbench . connect ( 'tcp://' + args [ 'server' ] + ':' + args [ 'port' ] ) data_dir = os . path . join ( os . path . dirname ( os . path . realpath ( __file__ ) ) , '../data' ) file_list = all_fil...
This client pushes a big directory of different files into Workbench .
43,178
def load_all_plugins ( self ) : self . plugin_path = os . path . realpath ( self . plugin_dir ) sys . path . append ( self . plugin_dir ) print '<<< Plugin Manager >>>' for f in [ os . path . join ( self . plugin_dir , child ) for child in os . listdir ( self . plugin_dir ) ] : if '.DS_Store' in f or '__init__.py' in f...
Load all the plugins in the plugin directory
43,179
def remove_plugin ( self , f ) : if f . endswith ( '.py' ) : plugin_name = os . path . splitext ( os . path . basename ( f ) ) [ 0 ] print '- %s %sREMOVED' % ( plugin_name , color . Red ) print '\t%sNote: still in memory, restart Workbench to remove...%s' % ( color . Yellow , color . Normal )
Remvoing a deleted plugin .
43,180
def add_plugin ( self , f ) : if f . endswith ( '.py' ) : plugin_name = os . path . splitext ( os . path . basename ( f ) ) [ 0 ] if plugin_name in sys . modules : try : handler = reload ( sys . modules [ plugin_name ] ) print '\t- %s %sRELOAD%s' % ( plugin_name , color . Yellow , color . Normal ) except ImportError , ...
Adding and verifying plugin .
43,181
def store_sample ( self , sample_bytes , filename , type_tag ) : if len ( filename ) > 1000 : print 'switched bytes/filename... %s %s' % ( sample_bytes [ : 100 ] , filename [ : 100 ] ) exit ( 1 ) sample_info = { } sample_info [ 'md5' ] = hashlib . md5 ( sample_bytes ) . hexdigest ( ) if self . has_sample ( sample_info ...
Store a sample into the datastore .
43,182
def sample_storage_size ( self ) : try : coll_stats = self . database . command ( 'collStats' , 'fs.chunks' ) sample_storage_size = coll_stats [ 'size' ] / 1024.0 / 1024.0 return sample_storage_size except pymongo . errors . OperationFailure : return 0
Get the storage size of the samples storage collection .
43,183
def expire_data ( self ) : while self . sample_storage_size ( ) > self . samples_cap : record = self . database [ self . sample_collection ] . find ( ) . sort ( 'import_time' , pymongo . ASCENDING ) . limit ( 1 ) [ 0 ] self . remove_sample ( record [ 'md5' ] )
Expire data within the samples collection .
43,184
def remove_sample ( self , md5 ) : record = self . database [ self . sample_collection ] . find_one ( { 'md5' : md5 } ) if not record : return print 'Deleting sample: %s (%.2f MB)...' % ( record [ 'md5' ] , record [ 'length' ] / 1024.0 / 1024.0 ) self . database [ self . sample_collection ] . remove ( { 'md5' : record ...
Delete a specific sample
43,185
def clean_for_serialization ( self , data ) : if isinstance ( data , dict ) : for k in data . keys ( ) : if ( k . startswith ( '__' ) ) : del data [ k ] elif isinstance ( data [ k ] , bson . objectid . ObjectId ) : del data [ k ] elif isinstance ( data [ k ] , datetime . datetime ) : data [ k ] = data [ k ] . isoformat...
Clean data in preparation for serialization .
43,186
def clean_for_storage ( self , data ) : data = self . data_to_unicode ( data ) if isinstance ( data , dict ) : for k in dict ( data ) . keys ( ) : if k == '_id' : del data [ k ] continue if '.' in k : new_k = k . replace ( '.' , '_' ) data [ new_k ] = data [ k ] del data [ k ] k = new_k if isinstance ( data [ k ] , dic...
Clean data in preparation for storage .
43,187
def get_sample ( self , md5 ) : if len ( md5 ) < 32 : md5 = self . get_full_md5 ( md5 , self . sample_collection ) sample_info = self . database [ self . sample_collection ] . find_one ( { 'md5' : md5 } ) if not sample_info : return None try : grid_fs_id = sample_info [ '__grid_fs' ] sample_info = self . clean_for_seri...
Get the sample from the data store .
43,188
def has_sample ( self , md5 ) : sample = self . get_sample ( md5 ) return True if sample else False
Checks if data store has this sample .
43,189
def _list_samples ( self , predicate = None ) : cursor = self . database [ self . sample_collection ] . find ( predicate , { '_id' : 0 , 'md5' : 1 } ) return [ item [ 'md5' ] for item in cursor ]
List all samples that meet the predicate or all if predicate is not specified .
43,190
def tag_match ( self , tags = None ) : if 'tags' not in self . database . collection_names ( ) : print 'Warning: Searching on non-existance tags collection' return None if not tags : cursor = self . database [ 'tags' ] . find ( { } , { '_id' : 0 , 'md5' : 1 } ) else : cursor = self . database [ 'tags' ] . find ( { 'tag...
List all samples that match the tags or all if tags are not specified .
43,191
def store_work_results ( self , results , collection , md5 ) : results [ 'md5' ] = md5 results [ '__time_stamp' ] = datetime . datetime . utcnow ( ) if 'mod_time' not in results : results [ 'mod_time' ] = results [ '__time_stamp' ] try : self . database [ collection ] . update ( { 'md5' : md5 } , self . clean_for_stora...
Store the output results of the worker .
43,192
def clear_worker_output ( self ) : print 'Dropping all of the worker output collections... Whee!' all_c = self . database . collection_names ( ) try : all_c . remove ( 'system.indexes' ) all_c . remove ( 'fs.chunks' ) all_c . remove ( 'fs.files' ) all_c . remove ( 'sample_set' ) all_c . remove ( 'tags' ) all_c . remove...
Drops all of the worker output collections
43,193
def periodic_ops ( self ) : if ( time . time ( ) - self . last_ops_run ) < 30 : return try : self . last_ops_run = time . time ( ) print 'Running Periodic Ops' all_c = self . database . collection_names ( ) try : all_c . remove ( 'system.indexes' ) all_c . remove ( 'fs.chunks' ) all_c . remove ( 'fs.files' ) all_c . re...
Run periodic operations on the the data store . Operations like making sure collections are capped and indexes are set up .
43,194
def to_unicode ( self , s ) : if isinstance ( s , unicode ) : return s if isinstance ( s , str ) : return unicode ( s , errors = 'ignore' ) return s
Convert an elementary datatype to unicode .
43,195
def data_to_unicode ( self , data ) : if isinstance ( data , dict ) : return { self . to_unicode ( k ) : self . to_unicode ( v ) for k , v in data . iteritems ( ) } if isinstance ( data , list ) : return [ self . to_unicode ( l ) for l in data ] else : return self . to_unicode ( data )
Recursively convert a list or dictionary to unicode .
43,196
def grab_server_args ( ) : workbench_conf = ConfigParser . ConfigParser ( ) config_path = os . path . join ( os . path . dirname ( os . path . realpath ( __file__ ) ) , 'config.ini' ) workbench_conf . read ( config_path ) server = workbench_conf . get ( 'workbench' , 'server_uri' ) port = workbench_conf . get ( 'workbe...
Grab server info from configuration file
43,197
def _make_attachment ( self , attachment , str_encoding = None ) : is_inline_image = False if isinstance ( attachment , MIMEBase ) : name = attachment . get_filename ( ) content = attachment . get_payload ( decode = True ) mimetype = attachment . get_content_type ( ) if attachment . get_content_maintype ( ) == 'image' ...
Returns EmailMessage . attachments item formatted for sending with Mailjet
43,198
def index_data ( self , data , index_name , doc_type ) : if not isinstance ( data , dict ) : raise RuntimeError ( 'Index failed, data needs to be a dict!' ) try : self . els_search . index ( index = index_name , doc_type = doc_type , body = data ) except Exception , error : print 'Index failed: %s' % str ( error ) rais...
Take an arbitrary dictionary of data and index it with ELS .
43,199
def search ( self , index_name , query ) : try : results = self . els_search . search ( index = index_name , body = query ) return results except Exception , error : error_str = 'Query failed: %s\n' % str ( error ) error_str += '\nIs there a dynamic script in the query?, see www.elasticsearch.org' print error_str raise...
Search the given index_name with the given ELS query .