idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
11,500
def build_options ( self ) : if self . version . build_metadata : return set ( self . version . build_metadata . split ( '.' ) ) else : return set ( )
The package build options .
11,501
def clearSelection ( self ) : first = None editors = self . editors ( ) for editor in editors : if not editor . selectedText ( ) : continue first = first or editor editor . backspace ( ) for editor in editors : editor . setFocus ( ) if first : first . setFocus ( )
Clears the selected text for this edit .
11,502
def cut ( self ) : text = self . selectedText ( ) for editor in self . editors ( ) : editor . cut ( ) QtGui . QApplication . clipboard ( ) . setText ( text )
Cuts the text from the serial to the clipboard .
11,503
def goBack ( self ) : index = self . indexOf ( self . currentEditor ( ) ) if index == - 1 : return previous = self . editorAt ( index - 1 ) if previous : previous . setFocus ( ) previous . setCursorPosition ( self . sectionLength ( ) )
Moves the cursor to the end of the previous editor
11,504
def goForward ( self ) : index = self . indexOf ( self . currentEditor ( ) ) if index == - 1 : return next = self . editorAt ( index + 1 ) if next : next . setFocus ( ) next . setCursorPosition ( 0 )
Moves the cursor to the beginning of the next editor .
11,505
def selectAll ( self ) : self . blockEditorHandling ( True ) for editor in self . editors ( ) : editor . selectAll ( ) self . blockEditorHandling ( False )
Selects the text within all the editors .
11,506
async def disable ( self , reason = None ) : params = { "enable" : True , "reason" : reason } response = await self . _api . put ( "/v1/agent/maintenance" , params = params ) return response . status == 200
Enters maintenance mode
11,507
async def enable ( self , reason = None ) : params = { "enable" : False , "reason" : reason } response = await self . _api . put ( "/v1/agent/maintenance" , params = params ) return response . status == 200
Resumes normal operation
11,508
def parse_datetime ( dt ) : d = datetime . strptime ( dt [ : - 1 ] , ISOFORMAT ) if dt [ - 1 : ] == 'Z' : return timezone ( 'utc' ) . localize ( d ) else : return d
Parse an ISO datetime which Python does buggily .
11,509
def refreshRecords ( self ) : table_type = self . tableType ( ) if ( not table_type ) : self . _records = RecordSet ( ) return False search = nativestring ( self . uiSearchTXT . text ( ) ) query = self . query ( ) . copy ( ) terms , search_query = Q . fromSearch ( search ) if ( search_query ) : query &= search_query se...
Refreshes the records being loaded by this browser .
11,510
def refreshResults ( self ) : if ( self . currentMode ( ) == XOrbBrowserWidget . Mode . Detail ) : self . refreshDetails ( ) elif ( self . currentMode ( ) == XOrbBrowserWidget . Mode . Card ) : self . refreshCards ( ) else : self . refreshThumbnails ( )
Joins together the queries from the fixed system the search and the query builder to generate a query for the browser to display .
11,511
def refreshCards ( self ) : cards = self . cardWidget ( ) factory = self . factory ( ) self . setUpdatesEnabled ( False ) self . blockSignals ( True ) cards . setUpdatesEnabled ( False ) cards . blockSignals ( True ) cards . clear ( ) QApplication . instance ( ) . processEvents ( ) if ( self . isGroupingActive ( ) ) : ...
Refreshes the results for the cards view of the browser .
11,512
def refreshDetails ( self ) : tree = self . uiRecordsTREE tree . blockSignals ( True ) tree . setRecordSet ( self . records ( ) ) tree . blockSignals ( False )
Refreshes the results for the details view of the browser .
11,513
def refreshThumbnails ( self ) : widget = self . thumbnailWidget ( ) widget . setUpdatesEnabled ( False ) widget . blockSignals ( True ) widget . clear ( ) widget . setIconSize ( self . thumbnailSize ( ) ) factory = self . factory ( ) if ( self . isGroupingActive ( ) ) : grouping = self . records ( ) . grouped ( ) for ...
Refreshes the thumbnails view of the browser .
11,514
def showGroupMenu ( self ) : group_active = self . isGroupingActive ( ) group_by = self . groupBy ( ) menu = XMenu ( self ) menu . setTitle ( 'Grouping Options' ) menu . setShowTitle ( True ) menu . addAction ( 'Edit Advanced Grouping' ) menu . addSeparator ( ) action = menu . addAction ( 'No Grouping' ) action . setCh...
Displays the group menu to the user for modification .
11,515
def get_settings ( ) : s = getattr ( settings , 'CLAMAV_UPLOAD' , { } ) s = { 'CONTENT_TYPE_CHECK_ENABLED' : s . get ( 'CONTENT_TYPE_CHECK_ENABLED' , False ) , 'LAST_HANDLER' : getattr ( settings , 'FILE_UPLOAD_HANDLERS' ) [ - 1 ] } return s
This function returns a dict containing default settings
11,516
def clear ( self ) : self . _xroot = ElementTree . Element ( 'settings' ) self . _xroot . set ( 'version' , '1.0' ) self . _xstack = [ self . _xroot ]
Clears the settings for this XML format .
11,517
def clear ( self ) : if self . _customFormat : self . _customFormat . clear ( ) else : super ( XSettings , self ) . clear ( )
Clears out all the settings for this instance .
11,518
def endGroup ( self ) : if self . _customFormat : self . _customFormat . endGroup ( ) else : super ( XSettings , self ) . endGroup ( )
Ends the current group of xml data .
11,519
def load ( self ) : if self . _customFormat and os . path . exists ( self . fileName ( ) ) : self . _customFormat . load ( self . fileName ( ) )
Loads the settings from disk for this XSettings object if it is a custom format .
11,520
def sync ( self ) : if self . _customFormat : self . _customFormat . save ( self . fileName ( ) ) else : super ( XSettings , self ) . sync ( )
Syncs the information for this settings out to the file system .
11,521
def clear ( self ) : layout = self . _entryWidget . layout ( ) for i in range ( layout . count ( ) - 1 ) : widget = layout . itemAt ( i ) . widget ( ) widget . close ( )
Clears out the widgets for this query builder .
11,522
def moveDown ( self , entry ) : if not entry : return entries = self . entries ( ) next = entries [ entries . index ( entry ) + 1 ] entry_q = entry . query ( ) next_q = next . query ( ) next . setQuery ( entry_q ) entry . setQuery ( next_q )
Moves the current query down one entry .
11,523
def _selectTree ( self ) : self . uiGanttTREE . blockSignals ( True ) self . uiGanttTREE . clearSelection ( ) for item in self . uiGanttVIEW . scene ( ) . selectedItems ( ) : item . treeItem ( ) . setSelected ( True ) self . uiGanttTREE . blockSignals ( False )
Matches the tree selection to the views selection .
11,524
def _selectView ( self ) : scene = self . uiGanttVIEW . scene ( ) scene . blockSignals ( True ) scene . clearSelection ( ) for item in self . uiGanttTREE . selectedItems ( ) : item . viewItem ( ) . setSelected ( True ) scene . blockSignals ( False ) curr_item = self . uiGanttTREE . currentItem ( ) vitem = curr_item . v...
Matches the view selection to the trees selection .
11,525
def _updateViewRect ( self ) : if not self . updatesEnabled ( ) : return header_h = self . _cellHeight * 2 rect = self . uiGanttVIEW . scene ( ) . sceneRect ( ) sbar_max = self . uiGanttTREE . verticalScrollBar ( ) . maximum ( ) sbar_max += self . uiGanttTREE . viewport ( ) . height ( ) + header_h widget_max = self . u...
Updates the view rect to match the current tree value .
11,526
def syncView ( self ) : if not self . updatesEnabled ( ) : return for item in self . topLevelItems ( ) : try : item . syncView ( recursive = True ) except AttributeError : continue
Syncs all the items to the view .
11,527
def get_data_path ( package , resource ) : loader = pkgutil . get_loader ( package ) if loader is None or not hasattr ( loader , 'get_data' ) : raise PackageResourceError ( "Failed to load package: '{0}'" . format ( package ) ) mod = sys . modules . get ( package ) or loader . load_module ( package ) if mod is None or ...
Return the full file path of a resource of a package .
11,528
def scrollToEnd ( self ) : vsbar = self . verticalScrollBar ( ) vsbar . setValue ( vsbar . maximum ( ) ) hbar = self . horizontalScrollBar ( ) hbar . setValue ( 0 )
Scrolls to the end for this console edit .
11,529
def assignQuery ( self ) : self . uiRecordTREE . setQuery ( self . _queryWidget . query ( ) , autoRefresh = True )
Assigns the query from the query widget to the edit .
11,530
def refresh ( self ) : table = self . tableType ( ) if table : table . markTableCacheExpired ( ) self . uiRecordTREE . searchRecords ( self . uiSearchTXT . text ( ) )
Commits changes stored in the interface to the database .
11,531
def parse ( self , url ) : parsed_url = urlparse . urlparse ( url ) try : default_config = self . CONFIG [ parsed_url . scheme ] except KeyError : raise ValueError ( 'unrecognised URL scheme for {}: {}' . format ( self . __class__ . __name__ , url ) ) handler = self . get_handler_for_scheme ( parsed_url . scheme ) conf...
Return a configuration dict from a URL
11,532
def get_auto_config ( self ) : methods = [ m for m in dir ( self ) if m . startswith ( 'auto_config_' ) ] for method_name in sorted ( methods ) : auto_config_method = getattr ( self , method_name ) url = auto_config_method ( self . env ) if url : return url
Walk over all available auto_config methods passing them the current environment and seeing if they return a configuration URL
11,533
def Process ( self , request , context ) : LOG . debug ( "Process called" ) try : metrics = self . plugin . process ( [ Metric ( pb = m ) for m in request . Metrics ] , ConfigMap ( pb = request . Config ) ) return MetricsReply ( metrics = [ m . pb for m in metrics ] ) except Exception as err : msg = "message: {}\n\nsta...
Dispatches the request to the plugins process method
11,534
async def join ( self , address , * , wan = None ) : response = await self . _api . get ( "/v1/agent/join" , address , params = { "wan" : wan } ) return response . status == 200
Triggers the local agent to join a node
11,535
async def force_leave ( self , node ) : node_id = extract_attr ( node , keys = [ "Node" , "ID" ] ) response = await self . _get ( "/v1/agent/force-leave" , node_id ) return response . status == 200
Forces removal of a node
11,536
def gotoNext ( self ) : index = self . _currentPanel . currentIndex ( ) + 1 if ( self . _currentPanel . count ( ) == index ) : index = 0 self . _currentPanel . setCurrentIndex ( index )
Goes to the next panel tab .
11,537
def gotoPrevious ( self ) : index = self . _currentPanel . currentIndex ( ) - 1 if index < 0 : index = self . _currentPanel . count ( ) - 1 self . _currentPanel . setCurrentIndex ( index )
Goes to the previous panel tab .
11,538
def newPanelTab ( self ) : view = self . _currentPanel . currentView ( ) if view : new_view = view . duplicate ( self . _currentPanel ) self . _currentPanel . addTab ( new_view , new_view . windowTitle ( ) )
Creates a new panel with a copy of the current widget .
11,539
def renamePanel ( self ) : index = self . _currentPanel . currentIndex ( ) title = self . _currentPanel . tabText ( index ) new_title , accepted = QInputDialog . getText ( self , 'Rename Tab' , 'Name:' , QLineEdit . Normal , title ) if accepted : widget = self . _currentPanel . currentView ( ) widget . setWindowTitle (...
Prompts the user for a custom name for the current panel tab .
11,540
def reload ( self ) : enum = self . _enum if not enum : return self . clear ( ) if not self . isRequired ( ) : self . addItem ( '' ) if self . sortByKey ( ) : self . addItems ( sorted ( enum . keys ( ) ) ) else : items = enum . items ( ) items . sort ( key = lambda x : x [ 1 ] ) self . addItems ( map ( lambda x : x [ 0...
Reloads the contents for this box .
11,541
def recalculate ( self ) : scene = self . scene ( ) w = self . calculateSceneWidth ( ) scene . setSceneRect ( 0 , 0 , w , self . height ( ) ) spacing = self . spacing ( ) x = self . width ( ) / 4.0 y = self . height ( ) / 2.0 for item in self . items ( ) : pmap = item . pixmap ( ) item . setPos ( x , y - pmap . height ...
Recalcualtes the slider scene for this widget .
11,542
def _check_token ( self ) : need_token = ( self . _token_info is None or self . auth_handler . is_token_expired ( self . _token_info ) ) if need_token : new_token = self . auth_handler . refresh_access_token ( self . _token_info [ 'refresh_token' ] ) if new_token is None : return self . _token_info = new_token self . _...
Simple Mercedes me API .
11,543
def get_location ( self , car_id ) : _LOGGER . debug ( "get_location for %s called" , car_id ) api_result = self . _retrieve_api_result ( car_id , API_LOCATION ) _LOGGER . debug ( "get_location result: %s" , api_result ) location = Location ( ) for loc_option in LOCATION_OPTIONS : curr_loc_option = api_result . get ( l...
get refreshed location information .
11,544
async def create ( self , token ) : token = encode_token ( token ) response = await self . _api . put ( "/v1/acl/create" , data = token ) return response . body
Creates a new token with a given policy
11,545
async def destroy ( self , token ) : token_id = extract_attr ( token , keys = [ "ID" ] ) response = await self . _api . put ( "/v1/acl/destroy" , token_id ) return response . body
Destroys a given token .
11,546
async def info ( self , token ) : token_id = extract_attr ( token , keys = [ "ID" ] ) response = await self . _api . get ( "/v1/acl/info" , token_id ) meta = extract_meta ( response . headers ) try : result = decode_token ( response . body [ 0 ] ) except IndexError : raise NotFound ( response . body , meta = meta ) ret...
Queries the policy of a given token .
11,547
async def clone ( self , token ) : token_id = extract_attr ( token , keys = [ "ID" ] ) response = await self . _api . put ( "/v1/acl/clone" , token_id ) return consul ( response )
Creates a new token by cloning an existing token
11,548
async def items ( self ) : response = await self . _api . get ( "/v1/acl/list" ) results = [ decode_token ( r ) for r in response . body ] return consul ( results , meta = extract_meta ( response . headers ) )
Lists all the active tokens
11,549
async def replication ( self , * , dc = None ) : params = { "dc" : dc } response = await self . _api . get ( "/v1/acl/replication" , params = params ) return response . body
Checks status of ACL replication
11,550
def make_unique_endings ( strings_collection ) : res = [ ] for i in range ( len ( strings_collection ) ) : hex_code = hex ( consts . String . UNICODE_SPECIAL_SYMBOLS_START + i ) hex_code = r"\U" + "0" * ( 8 - len ( hex_code ) + 2 ) + hex_code [ 2 : ] res . append ( strings_collection [ i ] + hex_code . decode ( "unicod...
Make each string in the collection end with a unique character . Essential for correct builiding of a generalized annotated suffix tree . Returns the updated strings collection encoded in Unicode .
11,551
async def datacenters ( self ) : response = await self . _api . get ( "/v1/coordinate/datacenters" ) return { data [ "Datacenter" ] : data for data in response . body }
Queries for WAN coordinates of Consul servers
11,552
def resizeToContents ( self ) : if self . count ( ) : item = self . item ( self . count ( ) - 1 ) rect = self . visualItemRect ( item ) height = rect . bottom ( ) + 8 height = max ( 28 , height ) self . setFixedHeight ( height ) else : self . setFixedHeight ( self . minimumHeight ( ) )
Resizes the list widget to fit its contents vertically .
11,553
def parse_status_file ( status_file , nas_addr ) : session_users = { } flag1 = False flag2 = False with open ( status_file ) as stlines : for line in stlines : if line . startswith ( "Common Name" ) : flag1 = True continue if line . startswith ( "ROUTING TABLE" ) : flag1 = False continue if line . startswith ( "Virtual...
parse openvpn status log
11,554
def update_status ( dbfile , status_file , nas_addr ) : try : total = 0 params = [ ] for sid , su in parse_status_file ( status_file , nas_addr ) . items ( ) : if 'session_id' in su and 'inbytes' in su and 'outbytes' in su : params . append ( ( su [ 'inbytes' ] , su [ 'outbytes' ] , su [ 'session_id' ] ) ) total += 1 s...
update status db
11,555
def accounting ( dbfile , config ) : try : nas_id = config . get ( 'DEFAULT' , 'nas_id' ) nas_addr = config . get ( 'DEFAULT' , 'nas_addr' ) secret = config . get ( 'DEFAULT' , 'radius_secret' ) radius_addr = config . get ( 'DEFAULT' , 'radius_addr' ) radius_acct_port = config . getint ( 'DEFAULT' , 'radius_acct_port' ...
update radius accounting
11,556
def main ( conf ) : config = init_config ( conf ) nas_addr = config . get ( 'DEFAULT' , 'nas_addr' ) status_file = config . get ( 'DEFAULT' , 'statusfile' ) status_dbfile = config . get ( 'DEFAULT' , 'statusdb' ) nas_coa_port = config . get ( 'DEFAULT' , 'nas_coa_port' ) def do_update_status_task ( ) : d = deferToThrea...
OpenVPN status daemon
11,557
def _filter_by_simple_schema ( self , qs , lookup , sublookup , value , schema ) : value_lookup = 'attrs__value_%s' % schema . datatype if sublookup : value_lookup = '%s__%s' % ( value_lookup , sublookup ) return { 'attrs__schema' : schema , str ( value_lookup ) : value }
Filters given entity queryset by an attribute which is linked to given schema and has given value in the field for schema s datatype .
11,558
def _filter_by_m2m_schema ( self , qs , lookup , sublookup , value , schema , model = None ) : model = model or self . model schemata = dict ( ( s . name , s ) for s in model . get_schemata_for_model ( ) ) try : schema = schemata [ lookup ] except KeyError : raise ValueError ( u'Could not find schema for lookup "%s"' %...
Filters given entity queryset by an attribute which is linked to given many - to - many schema .
11,559
def create ( self , ** kwargs ) : fields = self . model . _meta . get_all_field_names ( ) schemata = dict ( ( s . name , s ) for s in self . model . get_schemata_for_model ( ) ) possible_names = set ( fields ) | set ( schemata . keys ( ) ) wrong_names = set ( kwargs . keys ( ) ) - possible_names if wrong_names : raise ...
Creates entity instance and related Attr instances .
11,560
def removeProfile ( self ) : manager = self . parent ( ) prof = manager . currentProfile ( ) opts = QMessageBox . Yes | QMessageBox . No question = 'Are you sure you want to remove "%s"?' % prof . name ( ) answer = QMessageBox . question ( self , 'Remove Profile' , question , opts ) if ( answer == QMessageBox . Yes ) :...
Removes the current profile from the system .
11,561
def saveProfile ( self ) : manager = self . parent ( ) prof = manager . currentProfile ( ) save_prof = manager . viewWidget ( ) . saveProfile ( ) prof . setXmlElement ( save_prof . xmlElement ( ) )
Saves the current profile to the current settings from the view widget .
11,562
def saveProfileAs ( self ) : name , ok = QInputDialog . getText ( self , 'Create Profile' , 'Name:' ) if ( not name ) : return manager = self . parent ( ) prof = manager . viewWidget ( ) . saveProfile ( ) prof . setName ( nativestring ( name ) ) self . parent ( ) . addProfile ( prof )
Saves the current profile as a new profile to the manager .
11,563
def hexdump ( logger , s , width = 16 , skip = True , hexii = False , begin = 0 , highlight = None ) : r s = _flat ( s ) return '\n' . join ( hexdump_iter ( logger , StringIO ( s ) , width , skip , hexii , begin , highlight ) )
r Return a hexdump - dump of a string .
11,564
def adjustText ( self ) : pos = self . cursorPosition ( ) self . blockSignals ( True ) super ( XLineEdit , self ) . setText ( self . formatText ( self . text ( ) ) ) self . setCursorPosition ( pos ) self . blockSignals ( False )
Updates the text based on the current format options .
11,565
def adjustButtons ( self ) : y = 1 for btn in self . buttons ( ) : btn . setIconSize ( self . iconSize ( ) ) btn . setFixedSize ( QSize ( self . height ( ) - 2 , self . height ( ) - 2 ) ) left_buttons = self . _buttons . get ( Qt . AlignLeft , [ ] ) x = ( self . cornerRadius ( ) / 2.0 ) + 2 for btn in left_buttons : bt...
Adjusts the placement of the buttons for this line edit .
11,566
def adjustTextMargins ( self ) : left_buttons = self . _buttons . get ( Qt . AlignLeft , [ ] ) if left_buttons : bwidth = left_buttons [ - 1 ] . pos ( ) . x ( ) + left_buttons [ - 1 ] . width ( ) - 4 else : bwidth = 0 + ( max ( 8 , self . cornerRadius ( ) ) - 8 ) ico = self . icon ( ) if ico and not ico . isNull ( ) : ...
Adjusts the margins for the text based on the contents to be displayed .
11,567
def clear ( self ) : super ( XLineEdit , self ) . clear ( ) self . textEntered . emit ( '' ) self . textChanged . emit ( '' ) self . textEdited . emit ( '' )
Clears the text from the edit .
11,568
def get ( cap , * args , ** kwargs ) : if 'READTHEDOCS' in os . environ : return '' if kwargs != { } : raise TypeError ( "get(): No such argument %r" % kwargs . popitem ( ) [ 0 ] ) if _cache == { } : try : curses . setupterm ( ) except : pass s = _cache . get ( cap ) if not s : s = curses . tigetstr ( cap ) if s == Non...
Get a terminal capability exposes through the curses module .
11,569
def registerThermostat ( self , thermostat ) : try : type ( thermostat ) == heatmiser . HeatmiserThermostat if thermostat . address in self . thermostats . keys ( ) : raise ValueError ( "Key already present" ) else : self . thermostats [ thermostat . address ] = thermostat except ValueError : pass except Exception as e...
Registers a thermostat with the UH1
11,570
def refresh ( self ) : self . clear ( ) for i , filename in enumerate ( self . filenames ( ) ) : name = '%i. %s' % ( i + 1 , os . path . basename ( filename ) ) action = self . addAction ( name ) action . setData ( wrapVariant ( filename ) )
Clears out the actions for this menu and then loads the files .
11,571
def values ( self , values ) : if isinstance ( values , dict ) : l = [ ] for column in self . _columns : l . append ( values [ column ] ) self . _values . append ( tuple ( l ) ) else : self . _values . append ( values ) return self
The values for insert it can be a dict row or list tuple row .
11,572
def adjustMinimumWidth ( self ) : pw = self . pixmapSize ( ) . width ( ) self . setMinimumWidth ( pw * self . maximum ( ) + 3 * self . maximum ( ) )
Modifies the minimum width to factor in the size of the pixmaps and the number for the maximum .
11,573
def cli ( conf ) : config = init_config ( conf ) nas_id = config . get ( 'DEFAULT' , 'nas_id' ) secret = config . get ( 'DEFAULT' , 'radius_secret' ) nas_addr = config . get ( 'DEFAULT' , 'nas_addr' ) radius_addr = config . get ( 'DEFAULT' , 'radius_addr' ) radius_acct_port = config . getint ( 'DEFAULT' , 'radius_acct_...
OpenVPN client_disconnect method
11,574
def viewAt ( self , point ) : widget = self . childAt ( point ) if widget : return projexui . ancestor ( widget , XView ) else : return None
Looks up the view at the inputed point .
11,575
def draw ( canvas , mol ) : mol . require ( "ScaleAndCenter" ) mlb = mol . size2d [ 2 ] if not mol . atom_count ( ) : return bond_type_fn = { 1 : { 0 : single_bond , 1 : wedged_single , 2 : dashed_wedged_single , 3 : wave_single , } , 2 : { 0 : cw_double , 1 : counter_cw_double , 2 : double_bond , 3 : cross_double } , ...
Draw molecule structure image .
11,576
def smiles_to_compound ( smiles , assign_descriptors = True ) : it = iter ( smiles ) mol = molecule ( ) try : for token in it : mol ( token ) result , _ = mol ( None ) except KeyError as err : raise ValueError ( "Unsupported Symbol: {}" . format ( err ) ) result . graph . remove_node ( 0 ) logger . debug ( result ) if ...
Convert SMILES text to compound object
11,577
def salm2map ( salm , s , lmax , Ntheta , Nphi ) : if Ntheta < 2 or Nphi < 1 : raise ValueError ( "Input values of Ntheta={0} and Nphi={1} " . format ( Ntheta , Nphi ) + "are not allowed; they must be greater than 1 and 0, respectively." ) if lmax < 1 : raise ValueError ( "Input value of lmax={0} " . format ( lmax ) + ...
Convert mode weights of spin - weighted function to values on a grid
11,578
def map2salm ( map , s , lmax ) : import numpy as np map = np . ascontiguousarray ( map , dtype = np . complex128 ) salm = np . empty ( map . shape [ : - 2 ] + ( N_lm ( lmax ) , ) , dtype = np . complex128 ) if map . ndim > 2 : s = np . ascontiguousarray ( s , dtype = np . intc ) if s . ndim != map . ndim - 2 or np . p...
Convert values of spin - weighted function on a grid to mode weights
11,579
def Imm ( extended_map , s , lmax ) : import numpy as np extended_map = np . ascontiguousarray ( extended_map , dtype = np . complex128 ) NImm = ( 2 * lmax + 1 ) ** 2 imm = np . empty ( NImm , dtype = np . complex128 ) _Imm ( extended_map , imm , s , lmax ) return imm
Take the fft of the theta extended map then zero pad and reorganize it
11,580
def _query ( self , url , xpath ) : return self . session . query ( CachedRequest ) . filter ( CachedRequest . url == url ) . filter ( CachedRequest . xpath == xpath )
Base query for an url and xpath
11,581
def get ( self , url , store_on_error = False , xpath = None , rate_limit = None , log_hits = True , log_misses = True ) : try : cached = self . _query ( url , xpath ) . one ( ) if log_hits : config . logger . info ( "Request cache hit: " + url ) if cached . status_code != requests . codes . ok : raise RuntimeError ( "...
Get a URL via the cache .
11,582
def get_timestamp ( self , url , xpath = None ) : if not path . exists ( self . db_path ) : return None if self . _query ( url , xpath ) . count ( ) > 0 : return self . _query ( url , xpath ) . one ( ) . queried_on
Get time stamp of cached query result .
11,583
def set_logger ( self ) : logger = logging . getLogger ( __name__ ) logger . setLevel ( level = logging . INFO ) logger_file = os . path . join ( self . logs_path , 'dingtalk_sdk.logs' ) logger_handler = logging . FileHandler ( logger_file ) logger_handler . setLevel ( logging . INFO ) logger_formatter = logging . Form...
Method to build the base logging system . By default logging level is set to INFO .
11,584
def get_response ( self ) : request = getattr ( requests , self . request_method , None ) if request is None and self . _request_method is None : raise ValueError ( "A effective http request method must be set" ) if self . request_url is None : raise ValueError ( "Fatal error occurred, the class property \"request_url\...
Get the original response of requests
11,585
def sendCommand ( self , ** msg ) : assert 'type' in msg , 'Message type is required.' msg [ 'id' ] = self . next_message_id self . next_message_id += 1 if self . next_message_id >= maxint : self . next_message_id = 1 self . sendMessage ( json . dumps ( msg ) ) return msg [ 'id' ]
Sends a raw command to the Slack server generating a message ID automatically .
11,586
def sendChatMessage ( self , text , id = None , user = None , group = None , channel = None , parse = 'none' , link_names = True , unfurl_links = True , unfurl_media = False , send_with_api = False , icon_emoji = None , icon_url = None , username = None , attachments = None , thread_ts = None , reply_broadcast = False ...
Sends a chat message to a given id user group or channel .
11,587
def run ( ) : options = btoptions . Options ( ) btlog . initialize_logging ( options . log_level , options . log_file ) app = btapp . get_application ( ) app . run ( )
Entry point for the bolt executable .
11,588
def mols_to_file ( mols , path ) : with open ( path , 'w' ) as f : f . write ( mols_to_text ( mols ) )
Save molecules to the SDFile format file
11,589
def listen ( self ) : logger . info ( "Listening on port " + str ( self . listener . listen_port ) ) self . listener . listen ( )
Starts the client listener to listen for server responses .
11,590
def retransmit ( self , data ) : if data [ "method" ] == "REGISTER" : if not self . registered and self . register_retries < self . max_retries : logger . debug ( "<%s> Timeout exceeded. " % str ( self . cuuid ) + "Retransmitting REGISTER request." ) self . register_retries += 1 self . register ( data [ "address" ] , r...
Processes messages that have been delivered from the transport protocol .
11,591
def handle_message ( self , msg , host ) : logger . debug ( "Executing handle_message method." ) response = None if self . encryption and self . server_key : msg_data = unserialize_data ( msg , self . compression , self . encryption ) else : msg_data = unserialize_data ( msg , self . compression ) logger . debug ( "Pac...
Processes messages that have been delivered from the transport protocol
11,592
def autodiscover ( self , autoregister = True ) : logger . debug ( "<%s> Sending autodiscover message to broadcast " "address" % str ( self . cuuid ) ) if not self . listener . listening : logger . warning ( "Neteria client is not listening. The client " "will not be able to process responses from the server" ) message...
This function will send out an autodiscover broadcast to find a Neteria server . Any servers that respond with an OHAI CLIENT packet are servers that we can connect to . Servers that respond are stored in the discovered_servers list .
11,593
def register ( self , address , retry = True ) : logger . debug ( "<%s> Sending REGISTER request to: %s" % ( str ( self . cuuid ) , str ( address ) ) ) if not self . listener . listening : logger . warning ( "Neteria client is not listening." ) message = { "method" : "REGISTER" , "cuuid" : str ( self . cuuid ) } if sel...
This function will send a register packet to the discovered Neteria server .
11,594
def event ( self , event_data , priority = "normal" , event_method = "EVENT" ) : logger . debug ( "event: " + str ( event_data ) ) euuid = uuid . uuid1 ( ) logger . debug ( "<%s> <euuid:%s> Sending event data to server: " "%s" % ( str ( self . cuuid ) , str ( euuid ) , str ( self . server ) ) ) if not self . listener ....
This function will send event packets to the server . This is the main method you would use to send data from your application to the server .
11,595
def legal_check ( self , message ) : if message [ "method" ] == "LEGAL" : logger . debug ( "<%s> <euuid:%s> Event LEGAL" % ( str ( self . cuuid ) , message [ "euuid" ] ) ) logger . debug ( "<%s> <euuid:%s> Removing event from event " "buffer." % ( str ( self . cuuid ) , message [ "euuid" ] ) ) if message [ "priority" ]...
This method handles event legality check messages from the server .
11,596
def search ( self , category = None , cuisine = None , location = ( None , None ) , radius = None , tl_coord = ( None , None ) , br_coord = ( None , None ) , name = None , country = None , locality = None , region = None , postal_code = None , street_address = None , website_url = None , has_menu = None , open_at = Non...
Locu Venue Search API Call Wrapper
11,597
def search_next ( self , obj ) : if 'meta' in obj and 'next' in obj [ 'meta' ] and obj [ 'meta' ] [ 'next' ] != None : uri = self . api_url % obj [ 'meta' ] [ 'next' ] header , content = self . _http_uri_request ( uri ) resp = json . loads ( content ) if not self . _is_http_response_ok ( header ) : error = resp . get (...
Takes the dictionary that is returned by search or search_next function and gets the next batch of results
11,598
def get_details ( self , ids ) : if isinstance ( ids , list ) : if len ( ids ) > 5 : ids = ids [ : 5 ] id_param = ';' . join ( ids ) + '/' else : ids = str ( ids ) id_param = ids + '/' header , content = self . _http_request ( id_param ) resp = json . loads ( content ) if not self . _is_http_response_ok ( header ) : er...
Locu Venue Details API Call Wrapper
11,599
def get_menus ( self , id ) : resp = self . get_details ( [ id ] ) menus = [ ] for obj in resp [ 'objects' ] : if obj [ 'has_menu' ] : menus += obj [ 'menus' ] return menus
Given a venue id returns a list of menus associated with a venue