idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
23,900 | def _dissect_msg ( self , match ) : recvfrom = match . group ( 1 ) frame = bytes . fromhex ( match . group ( 2 ) ) if recvfrom == 'E' : _LOGGER . warning ( "Received erroneous message, ignoring: %s" , frame ) return ( None , None , None , None , None ) msgtype = self . _get_msgtype ( frame [ 0 ] ) if msgtype in ( READ_... | Split messages into bytes and return a tuple of bytes . |
23,901 | def _get_u16 ( self , msb , lsb ) : buf = struct . pack ( '>BB' , self . _get_u8 ( msb ) , self . _get_u8 ( lsb ) ) return int ( struct . unpack ( '>H' , buf ) [ 0 ] ) | Convert 2 bytes into an unsigned int . |
23,902 | def _get_s16 ( self , msb , lsb ) : buf = struct . pack ( '>bB' , self . _get_s8 ( msb ) , self . _get_u8 ( lsb ) ) return int ( struct . unpack ( '>h' , buf ) [ 0 ] ) | Convert 2 bytes into a signed int . |
23,903 | async def _report ( self ) : while True : oldstatus = dict ( self . status ) stat = await self . _updateq . get ( ) if self . _update_cb is not None and oldstatus != stat : self . loop . create_task ( self . _update_cb ( dict ( stat ) ) ) | Call _update_cb with the status dict as an argument whenever a status update occurs . |
23,904 | async def set_update_cb ( self , cb ) : if self . _report_task is not None and not self . _report_task . cancelled ( ) : self . loop . create_task ( self . _report_task . cancel ( ) ) self . _update_cb = cb if cb is not None : self . _report_task = self . loop . create_task ( self . _report ( ) ) | Register the update callback . |
23,905 | async def issue_cmd ( self , cmd , value , retry = 3 ) : async with self . _cmd_lock : if not self . connected : _LOGGER . debug ( "Serial transport closed, not sending command %s" , cmd ) return while not self . _cmdq . empty ( ) : _LOGGER . debug ( "Clearing leftover message from command queue:" " %s" , await self . ... | Issue a command then await and return the return value . |
23,906 | def get_target_temp ( self ) : if not self . _connected : return temp_ovrd = self . _protocol . status . get ( DATA_ROOM_SETPOINT_OVRD ) if temp_ovrd : return temp_ovrd return self . _protocol . status . get ( DATA_ROOM_SETPOINT ) | Get the target temperature . |
23,907 | async def get_reports ( self ) : cmd = OTGW_CMD_REPORT reports = { } for value in OTGW_REPORTS . keys ( ) : ret = await self . _wait_for_cmd ( cmd , value ) if ret is None : reports [ value ] = None continue reports [ value ] = ret [ 2 : ] status = { OTGW_ABOUT : reports . get ( OTGW_REPORT_ABOUT ) , OTGW_BUILD : repor... | Update the pyotgw object with the information from all of the PR commands and return the updated status dict . |
23,908 | async def add_alternative ( self , alt , timeout = OTGW_DEFAULT_TIMEOUT ) : cmd = OTGW_CMD_ADD_ALT alt = int ( alt ) if alt < 1 or alt > 255 : return None ret = await self . _wait_for_cmd ( cmd , alt , timeout ) if ret is not None : return int ( ret ) | Add the specified Data - ID to the list of alternative commands to send to the boiler instead of a Data - ID that is known to be unsupported by the boiler . Alternative Data - IDs will always be sent to the boiler in a Read - Data request message with the data - value set to zero . The table of alternative Data - IDs i... |
23,909 | async def del_alternative ( self , alt , timeout = OTGW_DEFAULT_TIMEOUT ) : cmd = OTGW_CMD_DEL_ALT alt = int ( alt ) if alt < 1 or alt > 255 : return None ret = await self . _wait_for_cmd ( cmd , alt , timeout ) if ret is not None : return int ( ret ) | Remove the specified Data - ID from the list of alternative commands . Only one occurrence is deleted . If the Data - ID appears multiple times in the list of alternative commands this command must be repeated to delete all occurrences . The table of alternative Data - IDs is stored in non - volatile memory so it will ... |
23,910 | async def add_unknown_id ( self , unknown_id , timeout = OTGW_DEFAULT_TIMEOUT ) : cmd = OTGW_CMD_UNKNOWN_ID unknown_id = int ( unknown_id ) if unknown_id < 1 or unknown_id > 255 : return None ret = await self . _wait_for_cmd ( cmd , unknown_id , timeout ) if ret is not None : return int ( ret ) | Inform the gateway that the boiler doesn t support the specified Data - ID even if the boiler doesn t indicate that by returning an Unknown - DataId response . Using this command allows the gateway to send an alternative Data - ID to the boiler instead . Return the added ID or None on failure . |
23,911 | async def del_unknown_id ( self , unknown_id , timeout = OTGW_DEFAULT_TIMEOUT ) : cmd = OTGW_CMD_KNOWN_ID unknown_id = int ( unknown_id ) if unknown_id < 1 or unknown_id > 255 : return None ret = await self . _wait_for_cmd ( cmd , unknown_id , timeout ) if ret is not None : return int ( ret ) | Start forwarding the specified Data - ID to the boiler again . This command resets the counter used to determine if the specified Data - ID is supported by the boiler . Return the ID that was marked as supported or None on failure . |
23,912 | async def set_max_ch_setpoint ( self , temperature , timeout = OTGW_DEFAULT_TIMEOUT ) : cmd = OTGW_CMD_SET_MAX status = { } ret = await self . _wait_for_cmd ( cmd , temperature , timeout ) if ret is None : return ret = float ( ret ) status [ DATA_MAX_CH_SETPOINT ] = ret self . _update_status ( status ) return ret | Set the maximum central heating setpoint . This command is only available with boilers that support this function . Return the newly accepted setpoint or None on failure . |
23,913 | async def set_dhw_setpoint ( self , temperature , timeout = OTGW_DEFAULT_TIMEOUT ) : cmd = OTGW_CMD_SET_WATER status = { } ret = await self . _wait_for_cmd ( cmd , temperature , timeout ) if ret is None : return ret = float ( ret ) status [ DATA_DHW_SETPOINT ] = ret self . _update_status ( status ) return ret | Set the domestic hot water setpoint . This command is only available with boilers that support this function . Return the newly accepted setpoint or None on failure . |
23,914 | async def set_max_relative_mod ( self , max_mod , timeout = OTGW_DEFAULT_TIMEOUT ) : if isinstance ( max_mod , int ) and not 0 <= max_mod <= 100 : return None cmd = OTGW_CMD_MAX_MOD status = { } ret = await self . _wait_for_cmd ( cmd , max_mod , timeout ) if ret not in [ '-' , None ] : ret = int ( ret ) if ret == '-' :... | Override the maximum relative modulation from the thermostat . Valid values are 0 through 100 . Clear the setting by specifying a non - numeric value . Return the newly accepted value - if a previous value was cleared or None on failure . |
23,915 | async def set_control_setpoint ( self , setpoint , timeout = OTGW_DEFAULT_TIMEOUT ) : cmd = OTGW_CMD_CONTROL_SETPOINT status = { } ret = await self . _wait_for_cmd ( cmd , setpoint , timeout ) if ret is None : return ret = float ( ret ) status [ DATA_CONTROL_SETPOINT ] = ret self . _update_status ( status ) return ret | Manipulate the control setpoint being sent to the boiler . Set to 0 to pass along the value specified by the thermostat . Return the newly accepted value or None on failure . |
23,916 | async def _send_report ( self , status ) : if len ( self . _notify ) > 0 : asyncio . gather ( * [ coro ( dict ( status ) ) for coro in self . _notify ] , loop = self . loop ) | Call all subscribed coroutines in _notify whenever a status update occurs . |
23,917 | async def _poll_gpio ( self , poll , interval = 10 ) : if poll and self . _gpio_task is None : async def polling_routine ( interval ) : while True : try : pios = None ret = await self . _wait_for_cmd ( OTGW_CMD_REPORT , OTGW_REPORT_GPIO_STATES ) if ret : pios = ret [ 2 : ] status = { OTGW_GPIO_A_STATE : int ( pios [ 0 ... | Start or stop polling GPIO states . |
23,918 | def _update_status ( self , update ) : if isinstance ( update , dict ) : self . _protocol . status . update ( update ) self . _protocol . _updateq . put_nowait ( self . _protocol . status ) | Update the status dict and push it to subscribers . |
23,919 | def write_dockerfile ( self , output_dir ) : if not os . path . exists ( output_dir ) : os . makedirs ( output_dir ) lines = [ ] for istep , step in enumerate ( self . steps ) : if istep == 0 : lines . extend ( step . dockerfile_lines ) else : lines . extend ( step . dockerfile_lines [ 1 : ] ) path = os . path . join (... | Used only to write a Dockerfile that will NOT be built by docker - make |
23,920 | def build ( self , client , nobuild = False , usecache = True , pull = False ) : if not nobuild : self . update_source_images ( client , usecache = usecache , pull = pull ) width = utils . get_console_width ( ) cprint ( '\n' + '=' * width , color = 'white' , attrs = [ 'bold' ] ) line = 'STARTING BUILD for "%s" (image d... | Drives the build of the final image - get the list of steps and execute them . |
23,921 | def finalizenames ( self , client , finalimage ) : client . api . tag ( finalimage , * self . targetname . split ( ':' ) ) cprint ( 'Tagged final image as "%s"' % self . targetname , 'green' ) if not self . keepbuildtags : print ( 'Untagging intermediate containers:' , end = '' ) for step in self . steps : client . api... | Tag the built image with its final name and untag intermediate containers |
23,922 | def _resolve_squash_cache ( self , client ) : from . staging import BUILD_CACHEDIR history = client . api . history ( self . buildname ) comment = history [ 0 ] . get ( 'Comment' , '' ) . split ( ) if len ( comment ) != 4 or comment [ 0 ] != 'merge' or comment [ 2 ] != 'to' : print ( 'WARNING: failed to parse this imag... | Currently doing a squash basically negates the cache for any subsequent layers . But we can work around this by A ) checking if the cache was successful for the _unsquashed_ version of the image and B ) if so re - using an older squashed version of the image . |
23,923 | def dockerfile_lines ( self ) : w1 = colored ( 'WARNING: this build includes files that are built in other images!!! The generated' '\n Dockerfile must be built in a directory that contains' ' the file/directory:' , 'red' , attrs = [ 'bold' ] ) w2 = colored ( ' ' + self . sourcepath , 'red' ) w3 = ( col... | Used only when printing dockerfiles not for building |
23,924 | def _check_yaml_and_paths ( ymlfilepath , yamldefs ) : relpath = os . path . relpath ( ymlfilepath ) if '/' not in relpath : relpath = './%s' % relpath pathroot = os . path . abspath ( os . path . dirname ( ymlfilepath ) ) for imagename , defn in iteritems ( yamldefs ) : if imagename == '_SOURCES_' : yamldefs [ '_SOURC... | Checks YAML for errors and resolves all paths |
23,925 | def generate_build ( self , image , targetname , rebuilds = None , cache_repo = '' , cache_tag = '' , buildargs = None , ** kwargs ) : from_image = self . get_external_base_image ( image ) if cache_repo or cache_tag : cache_from = utils . generate_name ( image , cache_repo , cache_tag ) else : cache_from = None if from... | Separate the build into a series of one or more intermediate steps . Each specified build directory gets its own step |
23,926 | def sort_dependencies ( self , image , dependencies = None ) : if dependencies is None : dependencies = OrderedDict ( ) if image in dependencies : return requires = self . ymldefs [ image ] . get ( 'requires' , [ ] ) for dep in requires : self . sort_dependencies ( dep , dependencies ) dependencies [ image ] = None ret... | Topologically sort the docker commands by their requirements |
23,927 | def get_external_base_image ( self , image , stack = None ) : if stack is None : stack = list ( ) mydef = self . ymldefs [ image ] if image in stack : stack . append ( image ) raise errors . CircularDependencyError ( 'Circular dependency found:\n' + '->' . join ( stack ) ) stack . append ( image ) if 'FROM' in mydef an... | Makes sure that this image has exactly one unique external base image |
23,928 | def stage ( self , startimage , newimage ) : client = utils . get_client ( ) cprint ( ' Copying file from "%s:/%s" \n to "%s://%s/"' % ( self . sourceimage , self . sourcepath , startimage , self . destpath ) , 'blue' ) cachedir = self . _setcache ( client ) cacherelpath = os . path . relpath ( cachedi... | Copies the file from source to target |
23,929 | def _runargs ( argstring ) : import shlex parser = cli . make_arg_parser ( ) args = parser . parse_args ( shlex . split ( argstring ) ) run ( args ) | Entrypoint for debugging |
23,930 | def lookup ( source , keys , fallback = None ) : try : for key in keys : source = source [ key ] return source except ( KeyError , AttributeError , TypeError ) : return fallback | Traverses the source looking up each key . Returns None if can t find anything instead of raising an exception . |
23,931 | def run ( self ) : while True : try : try : name , value , valueType , stamp = self . queue . get ( ) except TypeError : break self . log ( name , value , valueType , stamp ) finally : self . queue . task_done ( ) | Run the thread . |
23,932 | def connect ( self ) : if self . sock is not None : return backoff = 0.01 while True : try : sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) sock . settimeout ( 5 ) sock . connect ( ( self . host , self . port ) ) self . sock = sock return except socket . error : time . sleep ( random . uniform ( 0 ,... | Connects to the Graphite server if not already connected . |
23,933 | def disconnect ( self ) : if self . sock is not None : try : self . sock . close ( ) except socket . error : pass finally : self . sock = None | Disconnect from the Graphite server if connected . |
23,934 | def _sendMsg ( self , msg ) : if not self . sock : self . connect ( ) if not isinstance ( msg , binary_type ) : msg = msg . encode ( "UTF-8" ) backoff = 0.001 while True : try : self . sock . sendall ( msg ) break except socket . error : log . warning ( 'Graphite connection error' , exc_info = True ) self . disconnect ... | Send a line to graphite . Retry with exponential backoff . |
23,935 | def log ( self , name , value , valueType = None , stamp = None ) : if type ( value ) == float : form = "%s%s %2.2f %d\n" else : form = "%s%s %s %d\n" if valueType is not None and len ( valueType ) > 0 and valueType [ 0 ] != '.' : valueType = '.' + valueType if not stamp : stamp = time . time ( ) self . _sendMsg ( form... | Log a named numeric value . The value type may be value count or None . |
23,936 | def enqueue ( self , name , value , valueType = None , stamp = None ) : if self . maxQueueSize and self . queue . qsize ( ) > self . maxQueueSize : return self . queue . put ( ( name , value , valueType , stamp ) ) | Enqueue a call to log . |
23,937 | def update ( self , function ) : with self . lock : oldValue = self . value self . value = function ( oldValue ) return oldValue , self . value | Atomically apply function to the value and return the old and new values . |
23,938 | def tick ( self ) : count = self . _uncounted . getAndSet ( 0 ) instantRate = float ( count ) / self . interval if self . _initialized : self . rate += ( self . alpha * ( instantRate - self . rate ) ) else : self . rate = instantRate self . _initialized = True | Updates rates and decays |
23,939 | def statsId ( obj ) : if hasattr ( obj , ID_KEY ) : return getattr ( obj , ID_KEY ) newId = next ( NEXT_ID ) setattr ( obj , ID_KEY , newId ) return newId | Gets a unique ID for each object . |
23,940 | def filterCollapsedItems ( data ) : return ( ( key , value ) for key , value in six . iteritems ( data ) if not ( isinstance ( value , StatContainer ) and value . isCollapsed ( ) ) ) | Return a filtered iteration over a list of items . |
23,941 | def dumpStatsTo ( filename ) : with open ( filename , 'w' ) as f : latest = getStats ( ) latest [ 'last-updated' ] = time . time ( ) json . dump ( getStats ( ) , f , cls = StatContainerEncoder ) | Writes the stats dict to filanem |
23,942 | def collection ( path , * stats ) : def initMethod ( self ) : init ( self , path ) attributes = { '__init__' : initMethod } for stat in stats : attributes [ stat . getName ( ) ] = stat newClass = type ( 'Stats:%s' % path , ( object , ) , attributes ) instance = newClass ( ) for stat in stats : default = stat . _getInit... | Creates a named stats collection object . |
23,943 | def reset ( cls ) : cls . stats = StatContainer ( ) cls . parentMap = { } cls . containerMap = { } cls . subId = 0 for stat in gc . get_objects ( ) : if isinstance ( stat , Stat ) : stat . _aggregators = { } | Resets the static state . Should only be called by tests . |
23,944 | def init ( cls , obj , context ) : addr = statsId ( obj ) if addr not in cls . containerMap : cls . containerMap [ addr ] = cls . __getStatContainer ( context ) return cls . containerMap [ addr ] | Implementation of init . |
23,945 | def initChild ( cls , obj , name , subContext , parent = None ) : addr = statsId ( obj ) if addr not in cls . containerMap : if not parent : f = inspect . currentframe ( ) while not cls . __getSelf ( f ) : f = f . f_back this = cls . __getSelf ( f ) f = f . f_back while cls . __getSelf ( f ) == this or not cls . __getS... | Implementation of initChild . |
23,946 | def __getStatContainer ( cls , context , parent = None ) : container = parent if container is None : container = cls . stats if context is not None : context = str ( context ) . lstrip ( '/' ) for key in context . split ( '/' ) : container . setdefault ( key , StatContainer ( ) ) container = container [ key ] return co... | Get the stat container for the given context under the given parent . |
23,947 | def getStat ( cls , obj , name ) : objClass = type ( obj ) for theClass in objClass . __mro__ : if theClass == object : break for value in theClass . __dict__ . values ( ) : if isinstance ( value , Stat ) and value . getName ( ) == name : return value | Gets the stat for the given object with the given name or None if no such stat exists . |
23,948 | def getAggregator ( cls , instanceId , name ) : parent = cls . parentMap . get ( instanceId ) while parent : stat = cls . getStat ( parent , name ) if stat : return stat , parent parent = cls . parentMap . get ( statsId ( parent ) ) | Gets the aggregate stat for the given stat . |
23,949 | def _aggregate ( self , instanceId , container , value , subKey = None ) : if instanceId not in self . _aggregators : self . _aggregators [ instanceId ] = _Stats . getAggregator ( instanceId , self . __name ) aggregator = self . _aggregators [ instanceId ] if aggregator : oldValue = container . get ( self . __name ) if... | Performs stat aggregation . |
23,950 | def updateItem ( self , instance , subKey , value ) : instanceId = statsId ( instance ) container = _Stats . getContainerForObject ( instanceId ) self . _aggregate ( instanceId , container , value , subKey ) | Updates a child value . Must be called before the update has actually occurred . |
23,951 | def incr ( self , item , value ) : if item in self : old = UserDict . __getitem__ ( self , item ) else : old = 0.0 self [ item ] = old + value | Increment a key by the given amount . |
23,952 | def addSource ( self , source , data ) : self . _aggregate ( source , self . _aggregators , data , self . _result ) | Adds the given source s stats . |
23,953 | def addJsonDirectory ( self , directory , test = None ) : for filename in os . listdir ( directory ) : try : fullPath = os . path . join ( directory , filename ) if not test or test ( filename , fullPath ) : with open ( fullPath ) as f : jsonData = json . load ( f ) name , _ = os . path . splitext ( filename ) self . a... | Adds data from json files in the given directory . |
23,954 | def mean ( self ) : if len ( self ) == 0 : return float ( 'NaN' ) arr = self . samples ( ) return sum ( arr ) / float ( len ( arr ) ) | Return the sample mean . |
23,955 | def stddev ( self ) : if len ( self ) < 2 : return float ( 'NaN' ) try : arr = self . samples ( ) mean = sum ( arr ) / len ( arr ) bigsum = 0.0 for x in arr : bigsum += ( x - mean ) ** 2 return sqrt ( bigsum / ( len ( arr ) - 1 ) ) except ZeroDivisionError : return float ( 'NaN' ) | Return the sample standard deviation . |
23,956 | def clear ( self ) : self . __init__ ( size = self . size , alpha = self . alpha , clock = self . clock ) | Clear the samples . |
23,957 | def update ( self , value ) : super ( ExponentiallyDecayingReservoir , self ) . update ( value ) timestamp = self . clock . time ( ) self . __rescaleIfNeeded ( ) priority = self . __weight ( timestamp - self . startTime ) / random . random ( ) self . count += 1 if ( self . count <= self . size ) : self . values [ prior... | Adds an old value with a fixed timestamp to the reservoir . |
23,958 | def clear ( self ) : for i in range ( len ( self . sample ) ) : self . sample [ i ] = 0.0 self . count = 0 | Clear the sample . |
23,959 | def update ( self , value ) : super ( UniformSample , self ) . update ( value ) self . count += 1 c = self . count if c < len ( self . sample ) : self . sample [ c - 1 ] = value else : r = random . randint ( 0 , c ) if r < len ( self . sample ) : self . sample [ r ] = value | Add a value to the sample . |
23,960 | def _forbidden ( self , path , value ) : if path [ 0 ] == '/' : path = path [ 1 : ] for rule in reversed ( self . rules ) : if isinstance ( rule [ 1 ] , six . string_types ) : if fnmatch ( path , rule [ 1 ] ) : return not rule [ 0 ] elif rule [ 1 ] ( path , value ) : return not rule [ 0 ] return True | Is a stat forbidden? Goes through the rules to find one that applies . Chronologically newer rules are higher - precedence than older ones . If no rule applies the stat is forbidden by default . |
23,961 | def _pruned ( self , path ) : if path [ 0 ] == '/' : path = path [ 1 : ] for rule in reversed ( self . pruneRules ) : if isinstance ( rule , six . string_types ) : if fnmatch ( path , rule ) : return True elif rule ( path ) : return True return False | Is a stat tree node pruned? Goes through the list of prune rules to find one that applies . Chronologically newer rules are higher - precedence than older ones . If no rule applies the stat is not pruned by default . |
23,962 | def push ( self , statsDict = None , prefix = None , path = None ) : if statsDict is None : statsDict = scales . getStats ( ) prefix = prefix or self . prefix path = path or '/' for name , value in list ( statsDict . items ( ) ) : name = str ( name ) subpath = os . path . join ( path , name ) if self . _pruned ( subpat... | Push stat values out to Graphite . |
23,963 | def run ( self ) : self . graphite . start ( ) while True : log . debug ( 'Graphite pusher is sleeping for %d seconds' , self . period ) time . sleep ( self . period ) log . debug ( 'Pushing stats to Graphite' ) try : self . push ( ) log . debug ( 'Done pushing stats to Graphite' ) except : log . exception ( 'Exception... | Loop forever pushing out stats . |
23,964 | def installStatsLoop ( statsFile , statsDelay ) : def dumpStats ( ) : scales . dumpStatsTo ( statsFile ) reactor . callLater ( statsDelay , dumpStats ) def startStats ( ) : reactor . callLater ( statsDelay , dumpStats ) reactor . callWhenRunning ( startStats ) | Installs an interval loop that dumps stats to a file . |
23,965 | def runQuery ( statDict , query ) : parts = [ x . strip ( ) for x in OPERATOR . split ( query ) ] assert len ( parts ) in ( 1 , 3 ) queryKey = parts [ 0 ] result = { } for key , value in six . iteritems ( statDict ) : if key == queryKey : if len ( parts ) == 3 : op = OPERATORS [ parts [ 1 ] ] try : queryValue = type ( ... | Filters for the given query . |
23,966 | def htmlHeader ( output , path , serverName , query = None ) : if path and path != '/' : output . write ( '<title>%s - Status: %s</title>' % ( serverName , path ) ) else : output . write ( '<title>%s - Status</title>' % serverName ) output . write ( ) output . write ( '<h1 style="margin: 0">Stats</h1>' ) output . write... | Writes an HTML header . |
23,967 | def htmlFormat ( output , pathParts = ( ) , statDict = None , query = None ) : statDict = statDict or scales . getStats ( ) if query : statDict = runQuery ( statDict , query ) _htmlRenderDict ( pathParts , statDict , output ) | Formats as HTML writing to the given object . |
23,968 | def _htmlRenderDict ( pathParts , statDict , output ) : keys = list ( statDict . keys ( ) ) keys . sort ( ) links = [ ] output . write ( '<div class="level">' ) for key in keys : keyStr = cgi . escape ( _utf8str ( key ) ) value = statDict [ key ] if hasattr ( value , '__call__' ) : value = value ( ) if hasattr ( value ... | Render a dictionary as a table - recursing as necessary . |
23,969 | def jsonFormat ( output , statDict = None , query = None , pretty = False ) : statDict = statDict or scales . getStats ( ) if query : statDict = runQuery ( statDict , query ) indent = 2 if pretty else None try : serialized = json . dumps ( statDict , cls = scales . StatContainerEncoder , indent = indent ) except Unicod... | Formats as JSON writing to the given object . |
23,970 | def RepeatTimer ( interval , function , iterations = 0 , * args , ** kwargs ) : def __repeat_timer ( interval , function , iterations , args , kwargs ) : count = 0 while iterations <= 0 or count < iterations : sleep ( interval ) function ( * args , ** kwargs ) count += 1 return start_new_thread ( __repeat_timer , ( int... | Repeating timer . Returns a thread id . |
23,971 | def get_config ( context ) : conf_vars = [ 'disqus_developer' , 'disqus_identifier' , 'disqus_url' , 'disqus_title' , 'disqus_category_id' ] js = '\tvar {} = "{}";' output = [ js . format ( item , context [ item ] ) for item in conf_vars if item in context ] return '\n' . join ( output ) | Return the formatted javascript for any disqus config variables . |
23,972 | def disqus_show_comments ( context , shortname = '' ) : shortname = getattr ( settings , 'DISQUS_WEBSITE_SHORTNAME' , shortname ) return { 'shortname' : shortname , 'config' : get_config ( context ) , } | Return the HTML code to display DISQUS comments . |
23,973 | def add_item ( self , title , link , description , author_email = None , author_name = None , author_link = None , pubdate = None , comments = None , unique_id = None , enclosure = None , categories = ( ) , item_copyright = None , ttl = None , ** kwargs ) : to_unicode = lambda s : force_text ( s , strings_only = True )... | Adds an item to the feed . All args are expected to be Python Unicode objects except pubdate which is a datetime . datetime object and enclosure which is an instance of the Enclosure class . |
23,974 | def call ( method , data , post = False ) : url = "%s%s" % ( 'http://disqus.com/api/' , method ) if post : url += "/" data = urlencode ( data ) else : url += "?%s" % urlencode ( data ) data = '' res = json . load ( urlopen ( url , data ) ) if not res [ 'succeeded' ] : raise CommandError ( "'%s' failed: %s\nData: %s" % ... | Calls method from the DISQUS API with data either in POST or GET . Returns deserialized JSON response . |
23,975 | def _get_comments_to_export ( self , last_export_id = None ) : qs = comments . get_model ( ) . objects . order_by ( 'pk' ) . filter ( is_public = True , is_removed = False ) if last_export_id is not None : print ( "Resuming after comment %s" % str ( last_export_id ) ) qs = qs . filter ( id__gt = last_export_id ) return... | Return comments which should be exported . |
23,976 | def _get_last_state ( self , state_file ) : state = None fp = open ( state_file ) try : state = int ( fp . read ( ) ) print ( "Found previous state: %d" % ( state , ) ) finally : fp . close ( ) return state | Checks the given path for the last exported comment s id |
23,977 | def _save_state ( self , state_file , last_pk ) : fp = open ( state_file , 'w+' ) try : fp . write ( str ( last_pk ) ) finally : fp . close ( ) | Saves the last_pk into the given state_file |
23,978 | def _get_request ( self , request_url , request_method , ** params ) : if request_method == 'GET' : if params : request_url += '&%s' % urlencode ( params ) request = Request ( request_url ) elif request_method == 'POST' : request = Request ( request_url , urlencode ( params , doseq = 1 ) ) return request | Return a Request object that has the GET parameters attached to the url or the POST data attached to the object . |
23,979 | def call ( self , method , ** params ) : url = self . api_url % method request = self . _get_request ( url , self . METHODS [ method ] , ** params ) try : response = urlopen ( request ) except URLError : raise else : response_json = json . loads ( response . read ( ) ) if not response_json [ 'succeeded' ] : raise Disqu... | Call the DISQUS API and return the json response . URLError is raised when the request failed . DisqusException is raised when the query didn t succeed . |
23,980 | def init_app ( app ) : config = EmailsConfig ( app ) app . extensions = getattr ( app , 'extensions' , { } ) app . extensions [ 'emails' ] = config return config | Initialize flask application . It creates EmailsConfig object and saves it in app . extensions . |
23,981 | def send ( self , smtp = None , ** kw ) : smtp_options = { } smtp_options . update ( self . config . smtp_options ) if smtp : smtp_options . update ( smtp ) return super ( Message , self ) . send ( smtp = smtp_options , ** kw ) | Sends message . |
23,982 | def options ( self ) : config = self . _config o = { } o . update ( self . _default_smtp_options ) o . update ( self . _default_message_options ) o . update ( self . _default_backend_options ) o . update ( get_namespace ( config , 'EMAIL_' , valid_keys = o . keys ( ) ) ) o [ 'port' ] = int ( o [ 'port' ] ) o [ 'timeout... | Reads all EMAIL_ options and set default values . |
23,983 | def smtp_options ( self ) : o = { } options = self . options for key in self . _default_smtp_options : if key in options : o [ key ] = options [ key ] o [ 'user' ] = o . pop ( 'host_user' , None ) o [ 'password' ] = o . pop ( 'host_password' , None ) o [ 'tls' ] = o . pop ( 'use_tls' , False ) o [ 'ssl' ] = o . pop ( '... | Convert config namespace to emails . backend . SMTPBackend namespace Returns dict for SMTPFactory |
23,984 | def message_options ( self ) : o = { } options = self . options for key in self . _default_message_options : if key in options : o [ key ] = options [ key ] return o | Convert config namespace to emails . Message namespace |
23,985 | def start ( self ) -> None : session = self . client . create_session ( self . kind , self . proxy_user , self . jars , self . py_files , self . files , self . driver_memory , self . driver_cores , self . executor_memory , self . executor_cores , self . num_executors , self . archives , self . queue , self . name , sel... | Create the remote Spark session and wait for it to be ready . |
23,986 | def state ( self ) -> SessionState : if self . session_id is None : raise ValueError ( "session not yet started" ) session = self . client . get_session ( self . session_id ) if session is None : raise ValueError ( "session not found - it may have been shut down" ) return session . state | The state of the managed Spark session . |
23,987 | def close ( self ) -> None : if self . session_id is not None : self . client . delete_session ( self . session_id ) self . client . close ( ) | Kill the managed Spark session . |
23,988 | def run ( self , code : str ) -> Output : output = self . _execute ( code ) if self . echo and output . text : print ( output . text ) if self . check : output . raise_for_status ( ) return output | Run some code in the managed Spark session . |
23,989 | def read ( self , dataframe_name : str ) -> pandas . DataFrame : code = serialise_dataframe_code ( dataframe_name , self . kind ) output = self . _execute ( code ) output . raise_for_status ( ) if output . text is None : raise RuntimeError ( "statement had no text output" ) return deserialise_dataframe ( output . text ... | Evaluate and retrieve a Spark dataframe in the managed session . |
23,990 | def read_sql ( self , code : str ) -> pandas . DataFrame : if self . kind != SessionKind . SQL : raise ValueError ( "not a SQL session" ) output = self . _execute ( code ) output . raise_for_status ( ) if output . json is None : raise RuntimeError ( "statement had no JSON output" ) return dataframe_from_json_output ( o... | Evaluate a Spark SQL satatement and retrieve the result . |
23,991 | def server_version ( self ) -> Version : if self . _server_version_cache is None : data = self . _client . get ( "/version" ) self . _server_version_cache = Version ( data [ "version" ] ) return self . _server_version_cache | Get the version of Livy running on the server . |
23,992 | def list_sessions ( self ) -> List [ Session ] : data = self . _client . get ( "/sessions" ) return [ Session . from_json ( item ) for item in data [ "sessions" ] ] | List all the active sessions in Livy . |
23,993 | def create_session ( self , kind : SessionKind , proxy_user : str = None , jars : List [ str ] = None , py_files : List [ str ] = None , files : List [ str ] = None , driver_memory : str = None , driver_cores : int = None , executor_memory : str = None , executor_cores : int = None , num_executors : int = None , archiv... | Create a new session in Livy . |
23,994 | def list_statements ( self , session_id : int ) -> List [ Statement ] : response = self . _client . get ( f"/sessions/{session_id}/statements" ) return [ Statement . from_json ( session_id , data ) for data in response [ "statements" ] ] | Get all the statements in a session . |
23,995 | def create_statement ( self , session_id : int , code : str , kind : StatementKind = None ) -> Statement : data = { "code" : code } if kind is not None : if self . legacy_server ( ) : LOGGER . warning ( "statement kind ignored on Livy<0.5.0" ) data [ "kind" ] = kind . value response = self . _client . post ( f"/session... | Run a statement in a session . |
23,996 | def get_statement ( self , session_id : int , statement_id : int ) -> Statement : response = self . _client . get ( f"/sessions/{session_id}/statements/{statement_id}" ) return Statement . from_json ( session_id , response ) | Get information about a statement in a session . |
23,997 | def lattice ( lattice , filename , directory , render , view , ** kwargs ) : dot = graphviz . Digraph ( name = lattice . __class__ . __name__ , comment = repr ( lattice ) , filename = filename , directory = directory , node_attr = dict ( shape = 'circle' , width = '.25' , style = 'filled' , label = '' ) , edge_attr = d... | Return graphviz source for visualizing the lattice graph . |
23,998 | def load ( cls , filename , encoding ) : if encoding is None : encoding = cls . encoding with io . open ( filename , 'r' , encoding = encoding ) as fd : source = fd . read ( ) if cls . normalize_newlines : source = source . replace ( '\r\n' , '\n' ) . replace ( '\r' , '\n' ) return cls . loads ( source ) | Load and parse serialized objects properties bools from file . |
23,999 | def dump ( cls , filename , objects , properties , bools , encoding ) : if encoding is None : encoding = cls . encoding source = cls . dumps ( objects , properties , bools ) if PY2 : source = unicode ( source ) with io . open ( filename , 'w' , encoding = encoding ) as fd : fd . write ( source ) | Write serialized objects properties bools to file . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.