idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
8,600
async def request ( self , method , url , params = None , headers = None , data = None , json = None , token_refresh_attempts = 2 , * * kwargs ) : if all ( [ data , json ] ) : msg = ( '"data" and "json" request parameters can not be used ' 'at the same time' ) logging . warn ( msg ) raise exceptions . GCPHTTPError ( ms...
Make an asynchronous HTTP request .
746
6
8,601
async def get_json ( self , url , json_callback = None , * * kwargs ) : if not json_callback : json_callback = json . loads response = await self . request ( method = 'get' , url = url , * * kwargs ) return json_callback ( response )
Get a URL and return its JSON response .
67
9
8,602
async def get_all ( self , url , params = None ) : if not params : params = { } items = [ ] next_page_token = None while True : if next_page_token : params [ 'pageToken' ] = next_page_token response = await self . get_json ( url , params = params ) items . append ( response ) next_page_token = response . get ( 'nextPag...
Aggregate data from all pages of an API query .
106
11
8,603
def check_config ( ) : configfile = ConfigFile ( ) global data if data . keys ( ) > 0 : # FIXME: run a better check of this file print ( "gitberg config file exists" ) print ( "\twould you like to edit your gitberg config file?" ) else : print ( "No config found" ) print ( "\twould you like to create a gitberg config f...
Report if there is an existing config file
231
8
8,604
async def main ( ) : async with aiohttp . ClientSession ( ) as session : data = Luftdaten ( SENSOR_ID , loop , session ) await data . get_data ( ) if not await data . validate_sensor ( ) : print ( "Station is not available:" , data . sensor_id ) return if data . values and data . meta : # Print the sensor values print ...
Sample code to retrieve the data .
131
7
8,605
async def list_instances ( self , project , page_size = 100 , instance_filter = None ) : url = ( f'{self.BASE_URL}{self.api_version}/projects/{project}' '/aggregated/instances' ) params = { 'maxResults' : page_size } if instance_filter : params [ 'filter' ] = instance_filter responses = await self . list_all ( url , pa...
Fetch all instances in a GCE project .
119
10
8,606
def infer_alpha_chain ( beta ) : if beta . gene . startswith ( "DRB" ) : return AlleleName ( species = "HLA" , gene = "DRA1" , allele_family = "01" , allele_code = "01" ) elif beta . gene . startswith ( "DPB" ) : # Most common alpha chain for DP is DPA*01:03 but we really # need to change this logic to use a lookup tab...
Given a parsed beta chain of a class II MHC infer the most frequent corresponding alpha chain .
233
19
8,607
def create_ticket ( subject , tags , ticket_body , requester_email = None , custom_fields = [ ] ) : payload = { 'ticket' : { 'subject' : subject , 'comment' : { 'body' : ticket_body } , 'group_id' : settings . ZENDESK_GROUP_ID , 'tags' : tags , 'custom_fields' : custom_fields } } if requester_email : payload [ 'ticket'...
Create a new Zendesk ticket
234
8
8,608
def message ( message , title = '' ) : return backend_api . opendialog ( "message" , dict ( message = message , title = title ) )
Display a message
35
3
8,609
def ask_file ( message = 'Select file for open.' , default = '' , title = '' , save = False ) : return backend_api . opendialog ( "ask_file" , dict ( message = message , default = default , title = title , save = save ) )
A dialog to get a file name . The default argument specifies a file path .
62
16
8,610
def ask_folder ( message = 'Select folder.' , default = '' , title = '' ) : return backend_api . opendialog ( "ask_folder" , dict ( message = message , default = default , title = title ) )
A dialog to get a directory name . Returns the name of a directory or None if user chose to cancel . If the default argument specifies a directory name and that directory exists then the dialog box will start with that directory .
52
44
8,611
def ask_ok_cancel ( message = '' , default = 0 , title = '' ) : return backend_api . opendialog ( "ask_ok_cancel" , dict ( message = message , default = default , title = title ) )
Display a message with choices of OK and Cancel .
55
10
8,612
def ask_yes_no ( message = '' , default = 0 , title = '' ) : return backend_api . opendialog ( "ask_yes_no" , dict ( message = message , default = default , title = title ) )
Display a message with choices of Yes and No .
53
10
8,613
def register ( self , receiver_id , receiver ) : assert receiver_id not in self . receivers self . receivers [ receiver_id ] = receiver ( receiver_id )
Register a receiver .
36
4
8,614
def get ( self , sched_rule_id ) : path = '/' . join ( [ 'schedulerule' , sched_rule_id ] ) return self . rachio . get ( path )
Retrieve the information for a scheduleRule entity .
45
10
8,615
def parse ( self , message , schema ) : func = { 'audit-log' : self . _parse_audit_log_msg , 'event' : self . _parse_event_msg , } [ schema ] return func ( message )
Parse message according to schema .
54
7
8,616
def start ( self , zone_id , duration ) : path = 'zone/start' payload = { 'id' : zone_id , 'duration' : duration } return self . rachio . put ( path , payload )
Start a zone .
49
4
8,617
def startMultiple ( self , zones ) : path = 'zone/start_multiple' payload = { 'zones' : zones } return self . rachio . put ( path , payload )
Start multiple zones .
41
4
8,618
def get ( self , zone_id ) : path = '/' . join ( [ 'zone' , zone_id ] ) return self . rachio . get ( path )
Retrieve the information for a zone entity .
38
9
8,619
def start ( self ) : zones = [ { "id" : data [ 0 ] , "duration" : data [ 1 ] , "sortOrder" : count } for ( count , data ) in enumerate ( self . _zones , 1 ) ] self . _api . startMultiple ( zones )
Start the schedule .
64
4
8,620
def clean_translation ( self ) : translation = self . cleaned_data [ 'translation' ] if self . instance and self . instance . content_object : # do not allow string longer than translatable field obj = self . instance . content_object field = obj . _meta . get_field ( self . instance . field ) max_length = field . max_...
Do not allow translations longer than the max_lenght of the field to be translated .
186
19
8,621
def _get_merge_rules ( properties , path = None ) : if path is None : path = ( ) for key , value in properties . items ( ) : new_path = path + ( key , ) types = _get_types ( value ) # `omitWhenMerged` supersedes all other rules. # See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#omit-when-merged if v...
Yields merge rules as key - value pairs in which the first element is a JSON path as a tuple and the second element is a list of merge properties whose values are true .
509
37
8,622
def get_merge_rules ( schema = None ) : schema = schema or get_release_schema_url ( get_tags ( ) [ - 1 ] ) if isinstance ( schema , dict ) : deref_schema = jsonref . JsonRef . replace_refs ( schema ) else : deref_schema = _get_merge_rules_from_url_or_path ( schema ) return dict ( _get_merge_rules ( deref_schema [ 'prop...
Returns merge rules as key - value pairs in which the key is a JSON path as a tuple and the value is a list of merge properties whose values are true .
114
33
8,623
def unflatten ( processed , merge_rules ) : unflattened = OrderedDict ( ) for key in processed : current_node = unflattened for end , part in enumerate ( key , 1 ) : # If this is a path to an item of an array. # See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#identifier-merge if isinstance ( part , ...
Unflattens a processed object into a JSON object .
455
12
8,624
def merge ( releases , schema = None , merge_rules = None ) : if not merge_rules : merge_rules = get_merge_rules ( schema ) merged = OrderedDict ( { ( 'tag' , ) : [ 'compiled' ] } ) for release in sorted ( releases , key = lambda release : release [ 'date' ] ) : release = release . copy ( ) ocid = release [ 'ocid' ] da...
Merges a list of releases into a compiledRelease .
270
11
8,625
def merge_versioned ( releases , schema = None , merge_rules = None ) : if not merge_rules : merge_rules = get_merge_rules ( schema ) merged = OrderedDict ( ) for release in sorted ( releases , key = lambda release : release [ 'date' ] ) : release = release . copy ( ) # Don't version the OCID. ocid = release . pop ( 'o...
Merges a list of releases into a versionedRelease .
304
12
8,626
def chunks ( items , size ) : return [ items [ i : i + size ] for i in range ( 0 , len ( items ) , size ) ]
Split list into chunks of the given size . Original order is preserved .
33
14
8,627
def login ( self ) : _LOGGER . debug ( "Attempting to login to ZoneMinder" ) login_post = { 'view' : 'console' , 'action' : 'login' } if self . _username : login_post [ 'username' ] = self . _username if self . _password : login_post [ 'password' ] = self . _password req = requests . post ( urljoin ( self . _server_url...
Login to the ZoneMinder API .
246
8
8,628
def _zm_request ( self , method , api_url , data = None , timeout = DEFAULT_TIMEOUT ) -> dict : try : # Since the API uses sessions that expire, sometimes we need to # re-auth if the call fails. for _ in range ( ZoneMinder . LOGIN_RETRIES ) : req = requests . request ( method , urljoin ( self . _server_url , api_url ) ...
Perform a request to the ZoneMinder API .
225
11
8,629
def get_monitors ( self ) -> List [ Monitor ] : raw_monitors = self . _zm_request ( 'get' , ZoneMinder . MONITOR_URL ) if not raw_monitors : _LOGGER . warning ( "Could not fetch monitors from ZoneMinder" ) return [ ] monitors = [ ] for raw_result in raw_monitors [ 'monitors' ] : _LOGGER . debug ( "Initializing camera %...
Get a list of Monitors from the ZoneMinder API .
131
13
8,630
def get_run_states ( self ) -> List [ RunState ] : raw_states = self . get_state ( 'api/states.json' ) if not raw_states : _LOGGER . warning ( "Could not fetch runstates from ZoneMinder" ) return [ ] run_states = [ ] for i in raw_states [ 'states' ] : raw_state = i [ 'State' ] _LOGGER . info ( "Initializing runstate %s...
Get a list of RunStates from the ZoneMinder API .
133
13
8,631
def get_active_state ( self ) -> Optional [ str ] : for state in self . get_run_states ( ) : if state . active : return state . name return None
Get the name of the active run state from the ZoneMinder API .
39
15
8,632
def set_active_state ( self , state_name ) : _LOGGER . info ( 'Setting ZoneMinder run state to state %s' , state_name ) return self . _zm_request ( 'GET' , 'api/states/change/{}.json' . format ( state_name ) , timeout = 120 )
Set the ZoneMinder run state to the given state name via ZM API .
73
17
8,633
def is_available ( self ) -> bool : status_response = self . get_state ( 'api/host/daemonCheck.json' ) if not status_response : return False return status_response . get ( 'result' ) == 1
Indicate if this ZoneMinder service is currently available .
53
12
8,634
def _build_server_url ( server_host , server_path ) -> str : server_url = urljoin ( server_host , server_path ) if server_url [ - 1 ] == '/' : return server_url return '{}/' . format ( server_url )
Build the server url making sure it ends in a trailing slash .
63
13
8,635
def get ( self , flex_sched_rule_id ) : path = '/' . join ( [ 'flexschedulerule' , flex_sched_rule_id ] ) return self . rachio . get ( path )
Retrieve the information for a flexscheduleRule entity .
52
12
8,636
def upload_all_books ( book_id_start , book_id_end , rdf_library = None ) : # TODO refactor appname into variable logger . info ( "starting a gitberg mass upload: {0} -> {1}" . format ( book_id_start , book_id_end ) ) for book_id in range ( int ( book_id_start ) , int ( book_id_end ) + 1 ) : cache = { } errors = 0 try ...
Uses the fetch make push subcommands to mirror Project Gutenberg to a github3 api
227
18
8,637
def upload_list ( book_id_list , rdf_library = None ) : with open ( book_id_list , 'r' ) as f : cache = { } for book_id in f : book_id = book_id . strip ( ) try : if int ( book_id ) in missing_pgid : print ( u'missing\t{}' . format ( book_id ) ) continue upload_book ( book_id , rdf_library = rdf_library , cache = cache...
Uses the fetch make push subcommands to add a list of pg books
161
16
8,638
def translate ( self ) : translations = [ ] for lang in settings . LANGUAGES : # do not create an translations for default language. # we will use the original model for this if lang [ 0 ] == self . _get_default_language ( ) : continue # create translations for all fields of each language if self . translatable_slug is...
Create all translations objects for this Translatable instance .
189
10
8,639
def translations_objects ( self , lang ) : return Translation . objects . filter ( object_id = self . id , content_type = ContentType . objects . get_for_model ( self ) , lang = lang )
Return the complete list of translation objects of a Translatable instance
47
12
8,640
def translations ( self , lang ) : key = self . _get_translations_cache_key ( lang ) trans_dict = cache . get ( key , { } ) if self . translatable_slug is not None : if self . translatable_slug not in self . translatable_fields : self . translatable_fields = self . translatable_fields + ( self . translatable_slug , ) i...
Return the list of translation strings of a Translatable instance in a dictionary form
160
15
8,641
def get_translation_obj ( self , lang , field , create = False ) : trans = None try : trans = Translation . objects . get ( object_id = self . id , content_type = ContentType . objects . get_for_model ( self ) , lang = lang , field = field , ) except Translation . DoesNotExist : if create : trans = Translation . object...
Return the translation object of an specific field in a Translatable istance
122
15
8,642
def get_translation ( self , lang , field ) : # Read from cache key = self . _get_translation_cache_key ( lang , field ) trans = cache . get ( key , '' ) if not trans : trans_obj = self . get_translation_obj ( lang , field ) trans = getattr ( trans_obj , 'translation' , '' ) # if there's no translation text fall back t...
Return the translation string of an specific field in a Translatable istance
119
15
8,643
def set_translation ( self , lang , field , text ) : # Do not allow user to set a translations in the default language auto_slug_obj = None if lang == self . _get_default_language ( ) : raise CanNotTranslate ( _ ( 'You are not supposed to translate the default language. ' 'Use the model fields for translations in defau...
Store a translation string in the specified field for a Translatable istance
325
15
8,644
def translations_link ( self ) : translation_type = ContentType . objects . get_for_model ( Translation ) link = urlresolvers . reverse ( 'admin:%s_%s_changelist' % ( translation_type . app_label , translation_type . model ) , ) object_type = ContentType . objects . get_for_model ( self ) link += '?content_type__id__ex...
Print on admin change list the link to see all translations for this object
134
14
8,645
def comparison_callback ( sender , instance , * * kwargs ) : if validate_instance ( instance ) and settings . AUTOMATED_LOGGING [ 'to_database' ] : try : old = sender . objects . get ( pk = instance . pk ) except Exception : return None try : mdl = ContentType . objects . get_for_model ( instance ) cur , ins = old . __...
Comparing old and new object to determin which fields changed how
631
12
8,646
def save_callback ( sender , instance , created , update_fields , * * kwargs ) : if validate_instance ( instance ) : status = 'add' if created is True else 'change' change = '' if status == 'change' and 'al_chl' in instance . __dict__ . keys ( ) : changelog = instance . al_chl . modification change = ' to following cha...
Save object & link logging entry
114
6
8,647
def requires_refcount ( cls , func ) : @ functools . wraps ( func ) def requires_active_handle ( * args , * * kwargs ) : if cls . refcount ( ) == 0 : raise NoHandleException ( ) # You probably want to encase your code in a 'with LibZFSHandle():' block... return func ( * args , * * kwargs ) return requires_active_handle
The requires_refcount decorator adds a check prior to call func to verify that there is an active handle . if there is no such handle a NoHandleException exception is thrown .
96
37
8,648
def auto ( cls , func ) : @ functools . wraps ( func ) def auto_claim_handle ( * args , * * kwargs ) : with cls ( ) : return func ( * args , * * kwargs ) return auto_claim_handle
The auto decorator wraps func in a context manager so that a handle is obtained .
59
17
8,649
def get_gpubsub_publisher ( config , metrics , changes_channel , * * kw ) : builder = gpubsub_publisher . GPubsubPublisherBuilder ( config , metrics , changes_channel , * * kw ) return builder . build_publisher ( )
Get a GPubsubPublisher client .
61
8
8,650
def get_reconciler ( config , metrics , rrset_channel , changes_channel , * * kw ) : builder = reconciler . GDNSReconcilerBuilder ( config , metrics , rrset_channel , changes_channel , * * kw ) return builder . build_reconciler ( )
Get a GDNSReconciler client .
71
10
8,651
def get_authority ( config , metrics , rrset_channel , * * kwargs ) : builder = authority . GCEAuthorityBuilder ( config , metrics , rrset_channel , * * kwargs ) return builder . build_authority ( )
Get a GCEAuthority client .
58
8
8,652
async def refresh_token ( self ) : url , headers , body = self . _setup_token_request ( ) request_id = uuid . uuid4 ( ) logging . debug ( _utils . REQ_LOG_FMT . format ( request_id = request_id , method = 'POST' , url = url , kwargs = None ) ) async with self . _session . post ( url , headers = headers , data = body ) ...
Refresh oauth access token attached to this HTTP session .
335
12
8,653
def get ( self , dev_id ) : path = '/' . join ( [ 'device' , dev_id ] ) return self . rachio . get ( path )
Retrieve the information for a device entity .
38
9
8,654
def getEvent ( self , dev_id , starttime , endtime ) : path = 'device/%s/event?startTime=%s&endTime=%s' % ( dev_id , starttime , endtime ) return self . rachio . get ( path )
Retrieve events for a device entity .
62
8
8,655
def getForecast ( self , dev_id , units ) : assert units in [ 'US' , 'METRIC' ] , 'units must be either US or METRIC' path = 'device/%s/forecast?units=%s' % ( dev_id , units ) return self . rachio . get ( path )
Retrieve current and predicted forecast .
73
7
8,656
def stopWater ( self , dev_id ) : path = 'device/stop_water' payload = { 'id' : dev_id } return self . rachio . put ( path , payload )
Stop all watering on device .
44
6
8,657
def rainDelay ( self , dev_id , duration ) : path = 'device/rain_delay' payload = { 'id' : dev_id , 'duration' : duration } return self . rachio . put ( path , payload )
Rain delay device .
53
4
8,658
def on ( self , dev_id ) : path = 'device/on' payload = { 'id' : dev_id } return self . rachio . put ( path , payload )
Turn ON all features of the device .
41
8
8,659
def off ( self , dev_id ) : path = 'device/off' payload = { 'id' : dev_id } return self . rachio . put ( path , payload )
Turn OFF all features of the device .
41
8
8,660
def create_wallet ( self , master_secret = b"" ) : master_secret = deserialize . bytes_str ( master_secret ) bip32node = control . create_wallet ( self . testnet , master_secret = master_secret ) return bip32node . hwif ( as_private = True )
Create a BIP0032 - style hierarchical wallet .
69
11
8,661
def create_key ( self , master_secret = b"" ) : master_secret = deserialize . bytes_str ( master_secret ) bip32node = control . create_wallet ( self . testnet , master_secret = master_secret ) return bip32node . wif ( )
Create new private key and return in wif format .
63
11
8,662
def confirms ( self , txid ) : txid = deserialize . txid ( txid ) return self . service . confirms ( txid )
Returns number of confirms or None if unpublished .
32
9
8,663
def get_time_period ( value ) : for time_period in TimePeriod : if time_period . period == value : return time_period raise ValueError ( '{} is not a valid TimePeriod' . format ( value ) )
Get the corresponding TimePeriod from the value .
53
10
8,664
def update_monitor ( self ) : result = self . _client . get_state ( self . _monitor_url ) self . _raw_result = result [ 'monitor' ]
Update the monitor and monitor status from the ZM server .
39
12
8,665
def function ( self , new_function ) : self . _client . change_state ( self . _monitor_url , { 'Monitor[Function]' : new_function . value } )
Set the MonitorState of this Monitor .
40
8
8,666
def is_recording ( self ) -> Optional [ bool ] : status_response = self . _client . get_state ( 'api/monitors/alarm/id:{}/command:status.json' . format ( self . _monitor_id ) ) if not status_response : _LOGGER . warning ( 'Could not get status for monitor {}' . format ( self . _monitor_id ) ) return None status = statu...
Indicate if this Monitor is currently recording .
139
9
8,667
def is_available ( self ) -> bool : status_response = self . _client . get_state ( 'api/monitors/daemonStatus/id:{}/daemon:zmc.json' . format ( self . _monitor_id ) ) if not status_response : _LOGGER . warning ( 'Could not get availability for monitor {}' . format ( self . _monitor_id ) ) return False # Monitor_Status ...
Indicate if this Monitor is currently available .
167
9
8,668
def get_events ( self , time_period , include_archived = False ) -> Optional [ int ] : date_filter = '1%20{}' . format ( time_period . period ) if time_period == TimePeriod . ALL : # The consoleEvents API uses DATE_SUB, so give it # something large date_filter = '100%20year' archived_filter = '/Archived=:0' if include_...
Get the number of events that have occurred on this Monitor .
206
12
8,669
def _build_image_url ( self , monitor , mode ) -> str : query = urlencode ( { 'mode' : mode , 'buffer' : monitor [ 'StreamReplayBuffer' ] , 'monitor' : monitor [ 'Id' ] , } ) url = '{zms_url}?{query}' . format ( zms_url = self . _client . get_zms_url ( ) , query = query ) _LOGGER . debug ( 'Monitor %s %s URL (without a...
Build and return a ZoneMinder camera image url .
145
11
8,670
def askopenfile ( mode = "r" , * * options ) : filename = askopenfilename ( * * options ) if filename : return open ( filename , mode ) return None
Ask for a filename to open and returned the opened file
38
11
8,671
def askopenfiles ( mode = "r" , * * options ) : files = askopenfilenames ( * * options ) if files : ofiles = [ ] for filename in files : ofiles . append ( open ( filename , mode ) ) files = ofiles return files
Ask for multiple filenames and return the open file objects
59
12
8,672
def asksaveasfile ( mode = "w" , * * options ) : filename = asksaveasfilename ( * * options ) if filename : return open ( filename , mode ) return None
Ask for a filename to save as and returned the opened file
40
12
8,673
def spaced_coordinate ( name , keys , ordered = True ) : def validate ( self ) : """Raise a ValueError if the instance's keys are incorrect""" if set ( keys ) != set ( self ) : raise ValueError ( '{} needs keys {} and got {}' . format ( type ( self ) . __name__ , keys , tuple ( self ) ) ) new_class = type ( name , ( Co...
Create a subclass of Coordinate instances of which must have exactly the given keys .
120
16
8,674
def norm ( self , order = 2 ) : return ( sum ( val ** order for val in abs ( self ) . values ( ) ) ) ** ( 1 / order )
Find the vector norm with the given order of the values
36
11
8,675
def jsonify ( o , max_depth = - 1 , parse_enums = PARSE_KEEP ) : if max_depth == 0 : return o max_depth -= 1 if isinstance ( o , dict ) : keyattrs = getattr ( o . __class__ , '_altnames' , { } ) def _getter ( key , value ) : key = keyattrs . get ( key , key ) other = getattr ( o , key , value ) if callable ( other ) : ...
Walks through object o and attempts to get the property instead of the key if available . This means that for our VDev objects we can easily get a dict of all the parsed values .
312
38
8,676
def copy_files ( self ) : files = [ u'LICENSE' , u'CONTRIBUTING.rst' ] this_dir = dirname ( abspath ( __file__ ) ) for _file in files : sh . cp ( '{0}/templates/{1}' . format ( this_dir , _file ) , '{0}/' . format ( self . book . local_path ) ) # copy metadata rdf file if self . book . meta . rdf_path : # if None, meta...
Copy the LICENSE and CONTRIBUTING files to each folder repo Generate covers if needed . Dump the metadata .
228
25
8,677
def _collate_data ( collation , first_axis , second_axis ) : if first_axis not in collation : collation [ first_axis ] = { } collation [ first_axis ] [ "create" ] = 0 collation [ first_axis ] [ "modify" ] = 0 collation [ first_axis ] [ "delete" ] = 0 first = collation [ first_axis ] first [ second_axis ] = first [ seco...
Collects information about the number of edit actions belonging to keys in a supplied dictionary of object or changeset ids .
114
24
8,678
def extract_changesets ( objects ) : def add_changeset_info ( collation , axis , item ) : """ """ if axis not in collation : collation [ axis ] = { } first = collation [ axis ] first [ "id" ] = axis first [ "username" ] = item [ "username" ] first [ "uid" ] = item [ "uid" ] first [ "timestamp" ] = item [ "timestamp" ] ...
Provides information about each changeset present in an OpenStreetMap diff file .
302
16
8,679
def to_str ( obj ) : if isinstance ( obj , str ) : return obj if isinstance ( obj , unicode ) : return obj . encode ( 'utf-8' ) return str ( obj )
convert a object to string
45
6
8,680
def get_managed_zone ( self , zone ) : if zone . endswith ( '.in-addr.arpa.' ) : return self . reverse_prefix + '-' . join ( zone . split ( '.' ) [ - 5 : - 3 ] ) return self . forward_prefix + '-' . join ( zone . split ( '.' ) [ : - 1 ] )
Get the GDNS managed zone name for a DNS zone .
81
12
8,681
async def get_records_for_zone ( self , dns_zone , params = None ) : managed_zone = self . get_managed_zone ( dns_zone ) url = f'{self._base_url}/managedZones/{managed_zone}/rrsets' if not params : params = { } if 'fields' not in params : # Get only the fields we care about params [ 'fields' ] = ( 'rrsets/name,rrsets/k...
Get all resource record sets for a managed zone using the DNS zone .
256
14
8,682
async def is_change_done ( self , zone , change_id ) : zone_id = self . get_managed_zone ( zone ) url = f'{self._base_url}/managedZones/{zone_id}/changes/{change_id}' resp = await self . get_json ( url ) return resp [ 'status' ] == self . DNS_CHANGES_DONE
Check if a DNS change has completed .
91
8
8,683
async def publish_changes ( self , zone , changes ) : zone_id = self . get_managed_zone ( zone ) url = f'{self._base_url}/managedZones/{zone_id}/changes' resp = await self . request ( 'post' , url , json = changes ) return json . loads ( resp ) [ 'id' ]
Post changes to a zone .
81
6
8,684
def leave ( self , reason = None , message = None ) : # see https://github.com/crossbario/autobahn-python/issues/605 return self . _async_session . leave ( reason = reason , log_message = message )
Actively close this WAMP session .
56
8
8,685
def call ( self , procedure , * args , * * kwargs ) : return self . _async_session . call ( procedure , * args , * * kwargs )
Call a remote procedure .
39
5
8,686
def register ( self , endpoint , procedure = None , options = None ) : def proxy_endpoint ( * args , * * kwargs ) : return self . _callbacks_runner . put ( partial ( endpoint , * args , * * kwargs ) ) return self . _async_session . register ( proxy_endpoint , procedure = procedure , options = options )
Register a procedure for remote calling .
81
7
8,687
def publish ( self , topic , * args , * * kwargs ) : return self . _async_session . publish ( topic , * args , * * kwargs )
Publish an event to a topic .
39
8
8,688
def subscribe ( self , handler , topic = None , options = None ) : def proxy_handler ( * args , * * kwargs ) : return self . _callbacks_runner . put ( partial ( handler , * args , * * kwargs ) ) return self . _async_session . subscribe ( proxy_handler , topic = topic , options = options )
Subscribe to a topic for receiving events .
79
8
8,689
def b58encode ( val , charset = DEFAULT_CHARSET ) : def _b58encode_int ( int_ , default = bytes ( [ charset [ 0 ] ] ) ) : if not int_ and default : return default output = b'' while int_ : int_ , idx = divmod ( int_ , base ) output = charset [ idx : idx + 1 ] + output return output if not isinstance ( val , bytes ) : r...
Encode input to base58check encoding .
299
9
8,690
def b58decode ( val , charset = DEFAULT_CHARSET ) : def _b58decode_int ( val ) : output = 0 for char in val : output = output * base + charset . index ( char ) return output if isinstance ( val , str ) : val = val . encode ( ) if isinstance ( charset , str ) : charset = charset . encode ( ) base = len ( charset ) if no...
Decode base58check encoded input to original raw bytes .
215
12
8,691
def wait_for_edge ( self ) : GPIO . remove_event_detect ( self . _pin ) GPIO . wait_for_edge ( self . _pin , self . _edge )
This will remove remove any callbacks you might have specified
42
11
8,692
def request_finished_callback ( sender , * * kwargs ) : logger = logging . getLogger ( __name__ ) level = settings . AUTOMATED_LOGGING [ 'loglevel' ] [ 'request' ] user = get_current_user ( ) uri , application , method , status = get_current_environ ( ) excludes = settings . AUTOMATED_LOGGING [ 'exclude' ] [ 'request' ...
This function logs if the user acceses the page
249
11
8,693
def request_exception ( sender , request , * * kwargs ) : if not isinstance ( request , WSGIRequest ) : logger = logging . getLogger ( __name__ ) level = CRITICAL if request . status_code <= 500 else WARNING logger . log ( level , '%s exception occured (%s)' , request . status_code , request . reason_phrase ) else : lo...
Automated request exception logging .
115
6
8,694
def source_start ( base = '' , book_id = 'book' ) : repo_htm_path = "{book_id}-h/{book_id}-h.htm" . format ( book_id = book_id ) possible_paths = [ "book.asciidoc" , repo_htm_path , "{}-0.txt" . format ( book_id ) , "{}-8.txt" . format ( book_id ) , "{}.txt" . format ( book_id ) , "{}-pdf.pdf" . format ( book_id ) , ] ...
chooses a starting source file in the base directory for id = book_id
173
16
8,695
def pretty_dump ( fn ) : @ wraps ( fn ) def pretty_dump_wrapper ( * args , * * kwargs ) : response . content_type = "application/json; charset=utf-8" return json . dumps ( fn ( * args , * * kwargs ) , # sort_keys=True, indent = 4 , separators = ( ',' , ': ' ) ) return pretty_dump_wrapper
Decorator used to output prettified JSON .
94
10
8,696
def decode_json_body ( ) : raw_data = request . body . read ( ) try : return json . loads ( raw_data ) except ValueError as e : raise HTTPError ( 400 , e . __str__ ( ) )
Decode bottle . request . body to JSON .
51
10
8,697
def handle_type_error ( fn ) : @ wraps ( fn ) def handle_type_error_wrapper ( * args , * * kwargs ) : def any_match ( string_list , obj ) : return filter ( lambda x : x in obj , string_list ) try : return fn ( * args , * * kwargs ) except TypeError as e : message = e . __str__ ( ) str_list = [ "takes exactly" , "got an...
Convert TypeError to bottle . HTTPError with 400 code and message about wrong parameters .
160
18
8,698
def json_to_params ( fn = None , return_json = True ) : def json_to_params_decorator ( fn ) : @ handle_type_error @ wraps ( fn ) def json_to_params_wrapper ( * args , * * kwargs ) : data = decode_json_body ( ) if type ( data ) in [ tuple , list ] : args = list ( args ) + data elif type ( data ) == dict : # transport on...
Convert JSON in the body of the request to the parameters for the wrapped function .
262
17
8,699
def json_to_data ( fn = None , return_json = True ) : def json_to_data_decorator ( fn ) : @ handle_type_error @ wraps ( fn ) def get_data_wrapper ( * args , * * kwargs ) : kwargs [ "data" ] = decode_json_body ( ) if not return_json : return fn ( * args , * * kwargs ) return encode_json_body ( fn ( * args , * * kwargs )...
Decode JSON from the request and add it as data parameter for wrapped function .
155
16