text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _chunk_putter(self, uri, open_file, headers=None): """Make many PUT request for a single chunked object. Objects that are processed by this method have a SHA256 hash appended to the name as well as a count for object indexing which starts at 0. To make a PUT request pass, ``url`` :param uri: ``str`` :param open_file: ``object`` :param headers: ``dict`` """
count = 0 dynamic_hash = hashlib.sha256(self.job_args.get('container')) dynamic_hash = dynamic_hash.hexdigest() while True: # Read in a chunk of an open file file_object = open_file.read(self.job_args.get('chunk_size')) if not file_object: break # When a chuck is present store it as BytesIO with io.BytesIO(file_object) as file_object: # store the parsed URI for the chunk chunk_uri = urlparse.urlparse( '%s.%s.%s' % ( uri.geturl(), dynamic_hash, count ) ) # Increment the count as soon as it is used count += 1 # Check if the read chunk already exists sync = self._sync_check( uri=chunk_uri, headers=headers, file_object=file_object ) if not sync: continue # PUT the chunk _resp = self.http.put( url=chunk_uri, body=file_object, headers=headers ) self._resp_exception(resp=_resp) LOG.debug(_resp.__dict__)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _putter(self, uri, headers, local_object=None): """Place object into the container. :param uri: :param headers: :param local_object: """
if not local_object: return self.http.put(url=uri, headers=headers) with open(local_object, 'rb') as f_open: large_object_size = self.job_args.get('large_object_size') if not large_object_size: large_object_size = 5153960756 if os.path.getsize(local_object) > large_object_size: # Remove the manifest entry while working with chunks manifest = headers.pop('X-Object-Manifest') # Feed the open file through the chunk process self._chunk_putter( uri=uri, open_file=f_open, headers=headers ) # Upload the 0 byte object with the manifest path headers.update({'X-Object-Manifest': manifest}) return self.http.put(url=uri, headers=headers) else: if self.job_args.get('sync'): sync = self._sync_check( uri=uri, headers=headers, local_object=local_object ) if not sync: return None return self.http.put( url=uri, body=f_open, headers=headers )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _header_poster(self, uri, headers): """POST Headers on a specified object in the container. :param uri: ``str`` :param headers: ``dict`` """
resp = self.http.post(url=uri, body=None, headers=headers) self._resp_exception(resp=resp) return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _obj_index(self, uri, base_path, marked_path, headers, spr=False): """Return an index of objects from within the container. :param uri: :param base_path: :param marked_path: :param headers: :param spr: "single page return" Limit the returned data to one page :type spr: ``bol`` :return: """
object_list = list() l_obj = None container_uri = uri.geturl() while True: marked_uri = urlparse.urljoin(container_uri, marked_path) resp = self.http.get(url=marked_uri, headers=headers) self._resp_exception(resp=resp) return_list = resp.json() if spr: return return_list time_offset = self.job_args.get('time_offset') for obj in return_list: if time_offset: # Get the last_modified data from the Object. time_delta = cloud_utils.TimeDelta( job_args=self.job_args, last_modified=time_offset ) if time_delta: object_list.append(obj) else: object_list.append(obj) if object_list: last_obj_in_list = object_list[-1].get('name') else: last_obj_in_list = None if l_obj == last_obj_in_list: return object_list else: l_obj = last_obj_in_list marked_path = self._last_marker( base_path=base_path, last_object=l_obj )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _list_getter(self, uri, headers, last_obj=None, spr=False): """Get a list of all objects in a container. :param uri: :param headers: :return list: :param spr: "single page return" Limit the returned data to one page :type spr: ``bol`` """
# Quote the file path. base_path = marked_path = ('%s?limit=10000&format=json' % uri.path) if last_obj: marked_path = self._last_marker( base_path=base_path, last_object=cloud_utils.quoter(last_obj) ) file_list = self._obj_index( uri=uri, base_path=base_path, marked_path=marked_path, headers=headers, spr=spr ) LOG.debug( 'Found [ %d ] entries(s) at [ %s ]', len(file_list), uri.geturl() ) if spr: return file_list else: return cloud_utils.unique_list_dicts( dlist=file_list, key='name' )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resp_exception(self, resp): """If we encounter an exception in our upload. we will look at how we can attempt to resolve the exception. :param resp: """
message = [ 'Url: [ %s ] Reason: [ %s ] Request: [ %s ] Status Code: [ %s ]. ', resp.url, resp.reason, resp.request, resp.status_code ] # Check to make sure we have all the bits needed if not hasattr(resp, 'status_code'): message[0] += 'No Status to check. Turbolift will retry...' raise exceptions.SystemProblem(message) elif resp is None: message[0] += 'No response information. Turbolift will retry...' raise exceptions.SystemProblem(message) elif resp.status_code == 401: message[0] += ( 'Turbolift experienced an Authentication issue. Turbolift' ' will retry...' ) self.job_args.update(auth.authenticate(self.job_args)) raise exceptions.SystemProblem(message) elif resp.status_code == 404: message[0] += 'Item not found.' LOG.debug(*message) elif resp.status_code == 409: message[0] += ( 'Request Conflict. Turbolift is abandoning this...' ) elif resp.status_code == 413: return_headers = resp.headers retry_after = return_headers.get('retry_after', 10) cloud_utils.stupid_hack(wait=retry_after) message[0] += ( 'The System encountered an API limitation and will' ' continue in [ %s ] Seconds' % retry_after ) raise exceptions.SystemProblem(message) elif resp.status_code == 502: message[0] += ( 'Failure making Connection. Turbolift will retry...' ) raise exceptions.SystemProblem(message) elif resp.status_code == 503: cloud_utils.stupid_hack(wait=10) message[0] += 'SWIFT-API FAILURE' raise exceptions.SystemProblem(message) elif resp.status_code == 504: cloud_utils.stupid_hack(wait=10) message[0] += 'Gateway Failure.' raise exceptions.SystemProblem(message) elif resp.status_code >= 300: message[0] += 'General exception.' raise exceptions.SystemProblem(message) else: LOG.debug(*message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_items(self, url, container=None, last_obj=None, spr=False): """Builds a long list of objects found in a container. NOTE: This could be millions of Objects. :param url: :param container: :param last_obj: :param spr: "single page return" Limit the returned data to one page :type spr: ``bol`` :return None | list: """
headers, container_uri = self._return_base_data( url=url, container=container ) if container: resp = self._header_getter(uri=container_uri, headers=headers) if resp.status_code == 404: LOG.info('Container [ %s ] not found.', container) return [resp] return self._list_getter( uri=container_uri, headers=headers, last_obj=last_obj, spr=spr )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_object(self, url, container, container_object, object_headers, container_headers): """Update an existing object in a swift container. This method will place new headers on an existing object or container. :param url: :param container: :param container_object: """
headers, container_uri = self._return_base_data( url=url, container=container, container_object=container_object, container_headers=container_headers, object_headers=object_headers, ) return self._header_poster( uri=container_uri, headers=headers )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def container_cdn_command(self, url, container, container_object, cdn_headers): """Command your CDN enabled Container. :param url: :param container: """
headers, container_uri = self._return_base_data( url=url, container=container, container_object=container_object, object_headers=cdn_headers ) if self.job_args.get('purge'): return self._deleter( uri=container_uri, headers=headers ) else: return self._header_poster( uri=container_uri, headers=headers )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put_container(self, url, container, container_headers=None): """Create a container if it is not Found. :param url: :param container: """
headers, container_uri = self._return_base_data( url=url, container=container, container_headers=container_headers ) resp = self._header_getter( uri=container_uri, headers=headers ) if resp.status_code == 404: return self._putter(uri=container_uri, headers=headers) else: return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put_object(self, url, container, container_object, local_object, object_headers, meta=None): """This is the Sync method which uploads files to the swift repository if they are not already found. If a file "name" is found locally and in the swift repository an MD5 comparison is done between the two files. If the MD5 is miss-matched the local file is uploaded to the repository. If custom meta data is specified, and the object exists the method will put the metadata onto the object. :param url: :param container: :param container_object: """
headers, container_uri = self._return_base_data( url=url, container=container, container_object=container_object, container_headers=object_headers, object_headers=meta ) return self._putter( uri=container_uri, headers=headers, local_object=local_object )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_items(self, url, container, container_object, local_object): """Get an objects from a container. :param url: :param container: """
headers, container_uri = self._return_base_data( url=url, container=container, container_object=container_object ) return self._getter( uri=container_uri, headers=headers, local_object=local_object )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_items(self, url, container, container_object=None): """Deletes an objects in a container. :param url: :param container: """
headers, container_uri = self._return_base_data( url=url, container=container, container_object=container_object ) return self._deleter(uri=container_uri, headers=headers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_bmu(self, activations): """Get indices of bmus, sorted by their distance from input."""
# If the neural gas is a recursive neural gas, we need reverse argsort. if self.argfunc == 'argmax': activations = -activations sort = np.argsort(activations, 1) return sort.argsort()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calculate_influence(self, influence_lambda): """Calculate the ranking influence."""
return np.exp(-np.arange(self.num_neurons) / influence_lambda)[:, None]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_params(self, constants): """Update the params."""
constants = np.max(np.min(constants, 1)) self.params['r']['value'] = max([self.params['r']['value'], constants]) epsilon = constants / self.params['r']['value'] influence = self._calculate_influence(epsilon) # Account for learning rate return influence * epsilon
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _shuffle_items(items, bucket_key=None, disable=None, seed=None, session=None): """ Shuffles a list of `items` in place. If `bucket_key` is None, items are shuffled across the entire list. `bucket_key` is an optional function called for each item in `items` to calculate the key of bucket in which the item falls. Bucket defines the boundaries across which items will not be shuffled. `disable` is a function that takes an item and returns a falsey value if this item is ok to be shuffled. It returns a truthy value otherwise and the truthy value is used as part of the item's key when determining the bucket it belongs to. """
if seed is not None: random.seed(seed) # If `bucket_key` is falsey, shuffle is global. if not bucket_key and not disable: random.shuffle(items) return def get_full_bucket_key(item): assert bucket_key or disable if bucket_key and disable: return ItemKey(bucket=bucket_key(item, session), disabled=disable(item, session)) elif disable: return ItemKey(disabled=disable(item, session)) else: return ItemKey(bucket=bucket_key(item, session)) # For a sequence of items A1, A2, B1, B2, C1, C2, # where key(A1) == key(A2) == key(C1) == key(C2), # items A1, A2, C1, and C2 will end up in the same bucket. buckets = OrderedDict() for item in items: full_bucket_key = get_full_bucket_key(item) if full_bucket_key not in buckets: buckets[full_bucket_key] = [] buckets[full_bucket_key].append(item) # Shuffle inside a bucket bucket_keys = list(buckets.keys()) for full_bucket_key in buckets.keys(): if full_bucket_key.bucket == FAILED_FIRST_LAST_FAILED_BUCKET_KEY: # Do not shuffle the last failed bucket continue if not full_bucket_key.disabled: random.shuffle(buckets[full_bucket_key]) # Shuffle buckets # Only the first bucket can be FAILED_FIRST_LAST_FAILED_BUCKET_KEY if bucket_keys and bucket_keys[0].bucket == FAILED_FIRST_LAST_FAILED_BUCKET_KEY: new_bucket_keys = list(buckets.keys())[1:] random.shuffle(new_bucket_keys) new_bucket_keys.insert(0, bucket_keys[0]) else: new_bucket_keys = list(buckets.keys()) random.shuffle(new_bucket_keys) items[:] = [item for bk in new_bucket_keys for item in buckets[bk]] return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bucket_type_key(bucket_type): """ Registers a function that calculates test item key for the specified bucket type. """
def decorator(f): @functools.wraps(f) def wrapped(item, session): key = f(item) if session is not None: for handler in session.random_order_bucket_type_key_handlers: key = handler(item, key) return key bucket_type_keys[bucket_type] = wrapped return wrapped return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unsigned_request(self, path, payload=None): """ generic bitpay usigned wrapper passing a payload will do a POST, otherwise a GET """
headers = {"content-type": "application/json", "accept": "application/json", "X-accept-version": "2.0.0"} try: if payload: response = requests.post(self.uri + path, verify=self.verify, data=json.dumps(payload), headers=headers) else: response = requests.get(self.uri + path, verify=self.verify, headers=headers) except Exception as pro: raise BitPayConnectionError('Connection refused') return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Example application that watches for an event from a specific RF device. This feature allows you to watch for events from RF devices if you have an RF receiver. This is useful in the case of internal sensors, which don't emit a FAULT if the sensor is tripped and the panel is armed STAY. It also will monitor sensors that aren't configured. NOTE: You must have an RF receiver installed and enabled in your panel for RFX messages to be seen. """
try: # Retrieve the first USB device device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handler and open the device device.on_rfx_message += handle_rfx with device.open(baudrate=BAUDRATE): while True: time.sleep(1) except Exception as ex: print('Exception:', ex)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_rfx(sender, message): """ Handles RF message events from the AlarmDecoder. """
# Check for our target serial number and loop if message.serial_number == RF_DEVICE_SERIAL_NUMBER and message.loop[0] == True: print(message.serial_number, 'triggered loop #1')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fire(self, *args, **kwargs): """Fire event and call all handler functions You can call EventHandler object itself like e(*args, **kwargs) instead of e.fire(*args, **kwargs). """
for func in self._getfunctionlist(): if type(func) == EventHandler: func.fire(*args, **kwargs) else: func(self.obj, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Example application that opens a serial device and prints messages to the terminal. """
try: # Retrieve the specified serial device. device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handler and open the device device.on_message += handle_message # Override the default SerialDevice baudrate since we're using a USB device # over serial in this example. with device.open(baudrate=BAUDRATE): while True: time.sleep(1) except Exception as ex: print('Exception:', ex)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_ssl(self): """ Initializes our device as an SSL connection. :raises: :py:class:`~alarmdecoder.util.CommError` """
if not have_openssl: raise ImportError('SSL sockets have been disabled due to missing requirement: pyopenssl.') try: ctx = SSL.Context(SSL.TLSv1_METHOD) if isinstance(self.ssl_key, crypto.PKey): ctx.use_privatekey(self.ssl_key) else: ctx.use_privatekey_file(self.ssl_key) if isinstance(self.ssl_certificate, crypto.X509): ctx.use_certificate(self.ssl_certificate) else: ctx.use_certificate_file(self.ssl_certificate) if isinstance(self.ssl_ca, crypto.X509): store = ctx.get_cert_store() store.add_cert(self.ssl_ca) else: ctx.load_verify_locations(self.ssl_ca, None) verify_method = SSL.VERIFY_PEER if (self._ssl_allow_self_signed): verify_method = SSL.VERIFY_NONE ctx.set_verify(verify_method, self._verify_ssl_callback) self._device = SSL.Connection(ctx, self._device) except SSL.Error as err: raise CommError('Error setting up SSL connection.', err)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_best_frequencies(self): """ Returns the best n_local_max frequencies """
return self.freq[self.best_local_optima], self.per[self.best_local_optima]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finetune_best_frequencies(self, fresolution=1e-5, n_local_optima=10): """ Computes the selected criterion over a grid of frequencies around a specified amount of local optima of the periodograms. This function is intended for additional fine tuning of the results obtained with grid_search """
# Find the local optima local_optima_index = [] for k in range(1, len(self.per)-1): if self.per[k-1] < self.per[k] and self.per[k+1] < self.per[k]: local_optima_index.append(k) local_optima_index = np.array(local_optima_index) if(len(local_optima_index) < n_local_optima): print("Warning: Not enough local maxima found in the periodogram, skipping finetuning") return # Keep only n_local_optima best_local_optima = local_optima_index[np.argsort(self.per[local_optima_index])][::-1] if n_local_optima > 0: best_local_optima = best_local_optima[:n_local_optima] else: best_local_optima = best_local_optima[0] # Do finetuning around each local optima for j in range(n_local_optima): freq_fine = self.freq[best_local_optima[j]] - self.fres_grid for k in range(0, int(2.0*self.fres_grid/fresolution)): cost = self.compute_metric(freq_fine) if cost > self.per[best_local_optima[j]]: self.per[best_local_optima[j]] = cost self.freq[best_local_optima[j]] = freq_fine freq_fine += fresolution # Sort them in descending order idx = np.argsort(self.per[best_local_optima])[::-1] if n_local_optima > 0: self.best_local_optima = best_local_optima[idx] else: self.best_local_optima = best_local_optima
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, message): """ Updates the states in the primary AlarmDecoder object based on the LRR message provided. :param message: LRR message object :type message: :py:class:`~alarmdecoder.messages.LRRMessage` """
# Firmware version < 2.2a.8.6 if message.version == 1: if message.event_type == 'ALARM_PANIC': self._alarmdecoder._update_panic_status(True) elif message.event_type == 'CANCEL': self._alarmdecoder._update_panic_status(False) # Firmware version >= 2.2a.8.6 elif message.version == 2: source = message.event_source if source == LRR_EVENT_TYPE.CID: self._handle_cid_message(message) elif source == LRR_EVENT_TYPE.DSC: self._handle_dsc_message(message) elif source == LRR_EVENT_TYPE.ADEMCO: self._handle_ademco_message(message) elif source == LRR_EVENT_TYPE.ALARMDECODER: self._handle_alarmdecoder_message(message) elif source == LRR_EVENT_TYPE.UNKNOWN: self._handle_unknown_message(message) else: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_cid_message(self, message): """ Handles ContactID LRR events. :param message: LRR message object :type message: :py:class:`~alarmdecoder.messages.LRRMessage` """
status = self._get_event_status(message) if status is None: return if message.event_code in LRR_FIRE_EVENTS: if message.event_code == LRR_CID_EVENT.OPENCLOSE_CANCEL_BY_USER: status = False self._alarmdecoder._update_fire_status(status=status) if message.event_code in LRR_ALARM_EVENTS: kwargs = {} field_name = 'zone' if not status: field_name = 'user' kwargs[field_name] = int(message.event_data) self._alarmdecoder._update_alarm_status(status=status, **kwargs) if message.event_code in LRR_POWER_EVENTS: self._alarmdecoder._update_power_status(status=status) if message.event_code in LRR_BYPASS_EVENTS: self._alarmdecoder._update_zone_bypass_status(status=status, zone=int(message.event_data)) if message.event_code in LRR_BATTERY_EVENTS: self._alarmdecoder._update_battery_status(status=status) if message.event_code in LRR_PANIC_EVENTS: if message.event_code == LRR_CID_EVENT.OPENCLOSE_CANCEL_BY_USER: status = False self._alarmdecoder._update_panic_status(status=status) if message.event_code in LRR_ARM_EVENTS: # NOTE: status on OPENCLOSE messages is backwards. status_stay = (message.event_status == LRR_EVENT_STATUS.RESTORE \ and message.event_code in LRR_STAY_EVENTS) if status_stay: status = False else: status = not status self._alarmdecoder._update_armed_status(status=status, status_stay=status_stay)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_event_status(self, message): """ Retrieves the boolean status of an LRR message. :param message: LRR message object :type message: :py:class:`~alarmdecoder.messages.LRRMessage` :returns: Boolean indicating whether the event was triggered or restored. """
status = None if message.event_status == LRR_EVENT_STATUS.TRIGGER: status = True elif message.event_status == LRR_EVENT_STATUS.RESTORE: status = False return status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_all(pattern=None): """ Returns all serial ports present. :param pattern: pattern to search for when retrieving serial ports :type pattern: string :returns: list of devices :raises: :py:class:`~alarmdecoder.util.CommError` """
devices = [] try: if pattern: devices = serial.tools.list_ports.grep(pattern) else: devices = serial.tools.list_ports.comports() except serial.SerialException as err: raise CommError('Error enumerating serial devices: {0}'.format(str(err)), err) return devices
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_message(self, data): """ Parse the message from the device. :param data: message data :type data: string :raises: :py:class:`~alarmdecoder.util.InvalidMessageError` """
match = self._regex.match(str(data)) if match is None: raise InvalidMessageError('Received invalid message: {0}'.format(data)) header, self.bitfield, self.numeric_code, self.panel_data, alpha = match.group(1, 2, 3, 4, 5) is_bit_set = lambda bit: not self.bitfield[bit] == "0" self.ready = is_bit_set(1) self.armed_away = is_bit_set(2) self.armed_home = is_bit_set(3) self.backlight_on = is_bit_set(4) self.programming_mode = is_bit_set(5) self.beeps = int(self.bitfield[6], 16) self.zone_bypassed = is_bit_set(7) self.ac_power = is_bit_set(8) self.chime_on = is_bit_set(9) self.alarm_event_occurred = is_bit_set(10) self.alarm_sounding = is_bit_set(11) self.battery_low = is_bit_set(12) self.entry_delay_off = is_bit_set(13) self.fire_alarm = is_bit_set(14) self.check_zone = is_bit_set(15) self.perimeter_only = is_bit_set(16) self.system_fault = is_bit_set(17) if self.bitfield[18] in list(PANEL_TYPES): self.panel_type = PANEL_TYPES[self.bitfield[18]] # pos 20-21 - Unused. self.text = alpha.strip('"') self.mask = int(self.panel_data[3:3+8], 16) if self.panel_type in (ADEMCO, DSC): if int(self.panel_data[19:21], 16) & 0x01 > 0: # Current cursor location on the alpha display. self.cursor_location = int(self.panel_data[21:23], 16)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_numeric_code(self, force_hex=False): """ Parses and returns the numeric code as an integer. The numeric code can be either base 10 or base 16, depending on where the message came from. :param force_hex: force the numeric code to be processed as base 16. :type force_hex: boolean :raises: ValueError """
code = None got_error = False if not force_hex: try: code = int(self.numeric_code) except ValueError: got_error = True if force_hex or got_error: try: code = int(self.numeric_code, 16) except ValueError: raise return code
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def LoadCHM(self, archiveName): '''Loads a CHM archive. This function will also call GetArchiveInfo to obtain information such as the index file name and the topics file. It returns 1 on success, and 0 if it fails. ''' if self.filename is not None: self.CloseCHM() self.file = chmlib.chm_open(archiveName) if self.file is None: return 0 self.filename = archiveName self.GetArchiveInfo() return 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def CloseCHM(self): '''Closes the CHM archive. This function will close the CHM file, if it is open. All variables are also reset. ''' if self.filename is not None: chmlib.chm_close(self.file) self.file = None self.filename = '' self.title = "" self.home = "/" self.index = None self.topics = None self.encoding = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def GetTopicsTree(self): '''Reads and returns the topics tree. This auxiliary function reads and returns the topics tree file contents for the CHM archive. ''' if self.topics is None: return None if self.topics: res, ui = chmlib.chm_resolve_object(self.file, self.topics) if (res != chmlib.CHM_RESOLVE_SUCCESS): return None size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length) if (size == 0): sys.stderr.write('GetTopicsTree: file size = 0\n') return None return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def GetIndex(self): '''Reads and returns the index tree. This auxiliary function reads and returns the index tree file contents for the CHM archive. ''' if self.index is None: return None if self.index: res, ui = chmlib.chm_resolve_object(self.file, self.index) if (res != chmlib.CHM_RESOLVE_SUCCESS): return None size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length) if (size == 0): sys.stderr.write('GetIndex: file size = 0\n') return None return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ResolveObject(self, document): '''Tries to locate a document in the archive. This function tries to locate the document inside the archive. It returns a tuple where the first element is zero if the function was successful, and the second is the UnitInfo for that document. The UnitInfo is used to retrieve the document contents ''' if self.file: path = os.path.abspath(document) return chmlib.chm_resolve_object(self.file, path) else: return (1, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def RetrieveObject(self, ui, start=-1, length=-1): '''Retrieves the contents of a document. This function takes a UnitInfo and two optional arguments, the first being the start address and the second is the length. These define the amount of data to be read from the archive. ''' if self.file and ui: if length == -1: len = ui.length else: len = length if start == -1: st = 0l else: st = long(start) return chmlib.chm_retrieve_object(self.file, ui, st, len) else: return (0, '')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def Search(self, text, wholewords=0, titleonly=0): '''Performs full-text search on the archive. The first parameter is the word to look for, the second indicates if the search should be for whole words only, and the third parameter indicates if the search should be restricted to page titles. This method will return a tuple, the first item indicating if the search results were partial, and the second item being a dictionary containing the results.''' if text and text != '' and self.file: return extra.search(self.file, text, wholewords, titleonly) else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def GetEncoding(self): '''Returns a string that can be used with the codecs python package to encode or decode the files in the chm archive. If an error is found, or if it is not possible to find the encoding, None is returned.''' if self.encoding: vals = string.split(self.encoding, ',') if len(vals) > 2: try: return charset_table[int(vals[2])] except KeyError: pass return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Example application that opens a device that has been exposed to the network with ser2sock or similar serial-to-IP software. """
try: # Retrieve an AD2 device that has been exposed with ser2sock on localhost:10000. device = AlarmDecoder(SocketDevice(interface=(HOSTNAME, PORT))) # Set up an event handler and open the device device.on_message += handle_message with device.open(): while True: time.sleep(1) except Exception as ex: print('Exception:', ex)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_message(self, data): """ Parse the raw message from the device. :param data: message data :type data: string :raises: :py:class:`~alarmdecoder.util.InvalidMessageError` """
try: header, values = data.split(':') address, channel, value = values.split(',') self.address = int(address) self.channel = int(channel) self.value = int(value) except ValueError: raise InvalidMessageError('Received invalid message: {0}'.format(data)) if header == '!EXP': self.type = ExpanderMessage.ZONE elif header == '!REL': self.type = ExpanderMessage.RELAY else: raise InvalidMessageError('Unknown expander message header: {0}'.format(data))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_event_description(event_type, event_code): """ Retrieves the human-readable description of an LRR event. :param event_type: Base LRR event type. Use LRR_EVENT_TYPE.* :type event_type: int :param event_code: LRR event code :type event_code: int :returns: string """
description = 'Unknown' lookup_map = LRR_TYPE_MAP.get(event_type, None) if lookup_map is not None: description = lookup_map.get(event_code, description) return description
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_event_source(prefix): """ Retrieves the LRR_EVENT_TYPE corresponding to the prefix provided.abs :param prefix: Prefix to convert to event type :type prefix: string :returns: int """
source = LRR_EVENT_TYPE.UNKNOWN if prefix == 'CID': source = LRR_EVENT_TYPE.CID elif prefix == 'DSC': source = LRR_EVENT_TYPE.DSC elif prefix == 'AD2': source = LRR_EVENT_TYPE.ALARMDECODER elif prefix == 'ADEMCO': source = LRR_EVENT_TYPE.ADEMCO return source
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, data): """ Sends data to the `AlarmDecoder`_ device. :param data: data to send :type data: string """
if self._device: if isinstance(data, str): data = str.encode(data) # Hack to support unicode under Python 2.x if sys.version_info < (3,): if isinstance(data, unicode): data = bytes(data) self._device.write(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config_string(self): """ Build a configuration string that's compatible with the AlarmDecoder configuration command from the current values in the object. :returns: string """
config_entries = [] # HACK: This is ugly.. but I can't think of an elegant way of doing it. config_entries.append(('ADDRESS', '{0}'.format(self.address))) config_entries.append(('CONFIGBITS', '{0:x}'.format(self.configbits))) config_entries.append(('MASK', '{0:x}'.format(self.address_mask))) config_entries.append(('EXP', ''.join(['Y' if z else 'N' for z in self.emulate_zone]))) config_entries.append(('REL', ''.join(['Y' if r else 'N' for r in self.emulate_relay]))) config_entries.append(('LRR', 'Y' if self.emulate_lrr else 'N')) config_entries.append(('DEDUPLICATE', 'Y' if self.deduplicate else 'N')) config_entries.append(('MODE', list(PANEL_TYPES)[list(PANEL_TYPES.values()).index(self.mode)])) config_entries.append(('COM', 'Y' if self.emulate_com else 'N')) config_string = '&'.join(['='.join(t) for t in config_entries]) return '&'.join(['='.join(t) for t in config_entries])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fault_zone(self, zone, simulate_wire_problem=False): """ Faults a zone if we are emulating a zone expander. :param zone: zone to fault :type zone: int :param simulate_wire_problem: Whether or not to simulate a wire fault :type simulate_wire_problem: bool """
# Allow ourselves to also be passed an address/channel combination # for zone expanders. # # Format (expander index, channel) if isinstance(zone, tuple): expander_idx, channel = zone zone = self._zonetracker.expander_to_zone(expander_idx, channel) status = 2 if simulate_wire_problem else 1 self.send("L{0:02}{1}\r".format(zone, status))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wire_events(self): """ Wires up the internal device events. """
self._device.on_open += self._on_open self._device.on_close += self._on_close self._device.on_read += self._on_read self._device.on_write += self._on_write self._zonetracker.on_fault += self._on_zone_fault self._zonetracker.on_restore += self._on_zone_restore
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_message(self, data): """ Parses keypad messages from the panel. :param data: keypad data to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.Message` """
try: data = data.decode('utf-8') except: raise InvalidMessageError('Decode failed for message: {0}'.format(data)) if data is not None: data = data.lstrip('\0') if data is None or data == '': raise InvalidMessageError() msg = None header = data[0:4] if header[0] != '!' or header == '!KPM': msg = self._handle_keypad_message(data) elif header == '!EXP' or header == '!REL': msg = self._handle_expander_message(data) elif header == '!RFX': msg = self._handle_rfx(data) elif header == '!LRR': msg = self._handle_lrr(data) elif header == '!AUI': msg = self._handle_aui(data) elif data.startswith('!Ready'): self.on_boot() elif data.startswith('!CONFIG'): self._handle_config(data) elif data.startswith('!VER'): self._handle_version(data) elif data.startswith('!Sending'): self._handle_sending(data) return msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_keypad_message(self, data): """ Handle keypad messages. :param data: keypad message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.Message` """
msg = Message(data) if self._internal_address_mask & msg.mask > 0: if not self._ignore_message_states: self._update_internal_states(msg) self.on_message(message=msg) return msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_expander_message(self, data): """ Handle expander messages. :param data: expander message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.ExpanderMessage` """
msg = ExpanderMessage(data) self._update_internal_states(msg) self.on_expander_message(message=msg) return msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_rfx(self, data): """ Handle RF messages. :param data: RF message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.RFMessage` """
msg = RFMessage(data) self.on_rfx_message(message=msg) return msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_lrr(self, data): """ Handle Long Range Radio messages. :param data: LRR message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.LRRMessage` """
msg = LRRMessage(data) if not self._ignore_lrr_states: self._lrr_system.update(msg) self.on_lrr_message(message=msg) return msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_aui(self, data): """ Handle AUI messages. :param data: RF message to parse :type data: string :returns: :py:class`~alarmdecoder.messages.AUIMessage` """
msg = AUIMessage(data) self.on_aui_message(message=msg) return msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_version(self, data): """ Handles received version data. :param data: Version string to parse :type data: string """
_, version_string = data.split(':') version_parts = version_string.split(',') self.serial_number = version_parts[0] self.version_number = version_parts[1] self.version_flags = version_parts[2]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_config(self, data): """ Handles received configuration data. :param data: Configuration string to parse :type data: string """
_, config_string = data.split('>') for setting in config_string.split('&'): key, val = setting.split('=') if key == 'ADDRESS': self.address = int(val) elif key == 'CONFIGBITS': self.configbits = int(val, 16) elif key == 'MASK': self.address_mask = int(val, 16) elif key == 'EXP': self.emulate_zone = [val[z] == 'Y' for z in list(range(5))] elif key == 'REL': self.emulate_relay = [val[r] == 'Y' for r in list(range(4))] elif key == 'LRR': self.emulate_lrr = (val == 'Y') elif key == 'DEDUPLICATE': self.deduplicate = (val == 'Y') elif key == 'MODE': self.mode = PANEL_TYPES[val] elif key == 'COM': self.emulate_com = (val == 'Y') self.on_config_received()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_sending(self, data): """ Handles results of a keypress send. :param data: Sending string to parse :type data: string """
matches = re.match('^!Sending(\.{1,5})done.*', data) if matches is not None: good_send = False if len(matches.group(1)) < 5: good_send = True self.on_sending_received(status=good_send, message=data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_internal_states(self, message): """ Updates internal device states. :param message: :py:class:`~alarmdecoder.messages.Message` to update internal states with :type message: :py:class:`~alarmdecoder.messages.Message`, :py:class:`~alarmdecoder.messages.ExpanderMessage`, :py:class:`~alarmdecoder.messages.LRRMessage`, or :py:class:`~alarmdecoder.messages.RFMessage` """
if isinstance(message, Message) and not self._ignore_message_states: self._update_armed_ready_status(message) self._update_power_status(message) self._update_chime_status(message) self._update_alarm_status(message) self._update_zone_bypass_status(message) self._update_battery_status(message) self._update_fire_status(message) elif isinstance(message, ExpanderMessage): self._update_expander_status(message) self._update_zone_tracker(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_power_status(self, message=None, status=None): """ Uses the provided message to update the AC power state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: power status, overrides message bits. :type status: bool :returns: bool indicating the new status """
power_status = status if isinstance(message, Message): power_status = message.ac_power if power_status is None: return if power_status != self._power_status: self._power_status, old_status = power_status, self._power_status if old_status is not None: self.on_power_changed(status=self._power_status) return self._power_status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_chime_status(self, message=None, status=None): """ Uses the provided message to update the Chime state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: chime status, overrides message bits. :type status: bool :returns: bool indicating the new status """
chime_status = status if isinstance(message, Message): chime_status = message.chime_on if chime_status is None: return if chime_status != self._chime_status: self._chime_status, old_status = chime_status, self._chime_status if old_status is not None: self.on_chime_changed(status=self._chime_status) return self._chime_status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_alarm_status(self, message=None, status=None, zone=None, user=None): """ Uses the provided message to update the alarm state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: alarm status, overrides message bits. :type status: bool :param user: user associated with alarm event :type user: string :returns: bool indicating the new status """
alarm_status = status alarm_zone = zone if isinstance(message, Message): alarm_status = message.alarm_sounding alarm_zone = message.parse_numeric_code() if alarm_status != self._alarm_status: self._alarm_status, old_status = alarm_status, self._alarm_status if old_status is not None or status is not None: if self._alarm_status: self.on_alarm(zone=alarm_zone) else: self.on_alarm_restored(zone=alarm_zone, user=user) return self._alarm_status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_zone_bypass_status(self, message=None, status=None, zone=None): """ Uses the provided message to update the zone bypass state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: bypass status, overrides message bits. :type status: bool :param zone: zone associated with bypass event :type zone: int Zone can be None if LRR CID Bypass checking is disabled or we do not know what zones but know something is bypassed. """
bypass_status = status if isinstance(message, Message): bypass_status = message.zone_bypassed if bypass_status is None: return old_bypass_status = self._bypass_status.get(zone, None) if bypass_status != old_bypass_status: if bypass_status == False and zone is None: self._bypass_status = {} else: self._bypass_status[zone] = bypass_status if old_bypass_status is not None or message is None or (old_bypass_status is None and bypass_status is True): self.on_bypass(status=bypass_status, zone=zone) return bypass_status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_armed_status(self, message=None, status=None, status_stay=None): """ Uses the provided message to update the armed state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: armed status, overrides message bits :type status: bool :param status_stay: armed stay status, overrides message bits :type status_stay: bool :returns: bool indicating the new status """
arm_status = status stay_status = status_stay if isinstance(message, Message): arm_status = message.armed_away stay_status = message.armed_home if arm_status is None or stay_status is None: return self._armed_status, old_status = arm_status, self._armed_status self._armed_stay, old_stay = stay_status, self._armed_stay if arm_status != old_status or stay_status != old_stay: if old_status is not None or message is None: if self._armed_status or self._armed_stay: self.on_arm(stay=stay_status) else: self.on_disarm() return self._armed_status or self._armed_stay
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_battery_status(self, message=None, status=None): """ Uses the provided message to update the battery state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: battery status, overrides message bits :type status: bool :returns: boolean indicating the new status """
battery_status = status if isinstance(message, Message): battery_status = message.battery_low if battery_status is None: return last_status, last_update = self._battery_status if battery_status == last_status: self._battery_status = (last_status, time.time()) else: if battery_status is True or time.time() > last_update + self._battery_timeout: self._battery_status = (battery_status, time.time()) self.on_low_battery(status=battery_status) return self._battery_status[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_fire_status(self, message=None, status=None): """ Uses the provided message to update the fire alarm state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: fire status, overrides message bits :type status: bool :returns: boolean indicating the new status """
fire_status = status last_status = self._fire_status if isinstance(message, Message): # Quirk in Ademco panels. The fire bit drops on "SYSTEM LO BAT" messages. # FIXME: does not support non english panels. if self.mode == ADEMCO and message.text.startswith("SYSTEM"): fire_status = last_status else: fire_status = message.fire_alarm if fire_status is None: return if fire_status != self._fire_status: self._fire_status, old_status = fire_status, self._fire_status if old_status is not None: self.on_fire(status=self._fire_status) return self._fire_status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_panic_status(self, status=None): """ Updates the panic status of the alarm panel. :param status: status to use to update :type status: boolean :returns: boolean indicating the new status """
if status is None: return if status != self._panic_status: self._panic_status, old_status = status, self._panic_status if old_status is not None: self.on_panic(status=self._panic_status) return self._panic_status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_expander_status(self, message): """ Uses the provided message to update the expander states. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.ExpanderMessage` :returns: boolean indicating the new status """
if message.type == ExpanderMessage.RELAY: self._relay_status[(message.address, message.channel)] = message.value self.on_relay_changed(message=message) return self._relay_status[(message.address, message.channel)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _on_open(self, sender, *args, **kwargs): """ Internal handler for opening the device. """
self.get_config() self.get_version() self.on_open()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _on_read(self, sender, *args, **kwargs): """ Internal handler for reading from the device. """
data = kwargs.get('data', None) self.on_read(data=data) self._handle_message(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _on_write(self, sender, *args, **kwargs): """ Internal handler for writing to the device. """
self.on_write(data=kwargs.get('data', None))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, message): """ Update zone statuses based on the current message. :param message: message to use to update the zone tracking :type message: :py:class:`~alarmdecoder.messages.Message` or :py:class:`~alarmdecoder.messages.ExpanderMessage` """
if isinstance(message, ExpanderMessage): zone = -1 if message.type == ExpanderMessage.ZONE: zone = self.expander_to_zone(message.address, message.channel, self.alarmdecoder_object.mode) if zone != -1: status = Zone.CLEAR if message.value == 1: status = Zone.FAULT elif message.value == 2: status = Zone.CHECK # NOTE: Expander zone faults are handled differently than # regular messages. We don't include them in # self._zones_faulted because they are not reported # by the panel in it's rolling list of faults. try: self._update_zone(zone, status=status) except IndexError: self._add_zone(zone, status=status, expander=True) else: # Panel is ready, restore all zones. # # NOTE: This will need to be updated to support panels with # multiple partitions. In it's current state a ready on # partition #1 will end up clearing all zones, even if they # exist elsewhere and it shouldn't. # # NOTE: SYSTEM messages provide inconsistent ready statuses. This # may need to be extended later for other panels. if message.ready and not message.text.startswith("SYSTEM"): for zone in self._zones_faulted: self._update_zone(zone, Zone.CLEAR) self._last_zone_fault = 0 # Process fault elif self.alarmdecoder_object.mode != DSC and (message.check_zone or message.text.startswith("FAULT") or message.text.startswith("ALARM")): zone = message.parse_numeric_code() # NOTE: Odd case for ECP failures. Apparently they report as # zone 191 (0xBF) regardless of whether or not the # 3-digit mode is enabled... so we have to pull it out # of the alpha message. if zone == 191: zone_regex = re.compile('^CHECK (\d+).*$') match = zone_regex.match(message.text) if match is None: return zone = match.group(1) # Add new zones and clear expired ones. if zone in self._zones_faulted: self._update_zone(zone) self._clear_zones(zone) else: status = Zone.FAULT if message.check_zone: status = Zone.CHECK self._add_zone(zone, status=status) self._zones_faulted.append(zone) self._zones_faulted.sort() # Save our spot for the next message. self._last_zone_fault = zone self._clear_expired_zones()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expander_to_zone(self, address, channel, panel_type=ADEMCO): """ Convert an address and channel into a zone number. :param address: expander address :type address: int :param channel: channel :type channel: int :returns: zone number associated with an address and channel """
zone = -1 if panel_type == ADEMCO: # TODO: This is going to need to be reworked to support the larger # panels without fixed addressing on the expanders. idx = address - 7 # Expanders start at address 7. zone = address + channel + (idx * 7) + 1 elif panel_type == DSC: zone = (address * 8) + channel return zone
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clear_zones(self, zone): """ Clear all expired zones from our status list. :param zone: current zone being processed :type zone: int """
cleared_zones = [] found_last_faulted = found_current = at_end = False # First pass: Find our start spot. it = iter(self._zones_faulted) try: while not found_last_faulted: z = next(it) if z == self._last_zone_fault: found_last_faulted = True break except StopIteration: at_end = True # Continue until we find our end point and add zones in # between to our clear list. try: while not at_end and not found_current: z = next(it) if z == zone: found_current = True break else: cleared_zones += [z] except StopIteration: pass # Second pass: roll through the list again if we didn't find # our end point and remove everything until we do. if not found_current: it = iter(self._zones_faulted) try: while not found_current: z = next(it) if z == zone: found_current = True break else: cleared_zones += [z] except StopIteration: pass # Actually remove the zones and trigger the restores. for z in cleared_zones: self._update_zone(z, Zone.CLEAR)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clear_expired_zones(self): """ Update zone status for all expired zones. """
zones = [] for z in list(self._zones.keys()): zones += [z] for z in zones: if self._zones[z].status != Zone.CLEAR and self._zone_expired(z): self._update_zone(z, Zone.CLEAR)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_zone(self, zone, name='', status=Zone.CLEAR, expander=False): """ Adds a zone to the internal zone list. :param zone: zone number :type zone: int :param name: human readable zone name :type name: string :param status: zone status :type status: int """
if not zone in self._zones: self._zones[zone] = Zone(zone=zone, name=name, status=None, expander=expander) self._update_zone(zone, status=status)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_zone(self, zone, status=None): """ Updates a zones status. :param zone: zone number :type zone: int :param status: zone status :type status: int :raises: IndexError """
if not zone in self._zones: raise IndexError('Zone does not exist and cannot be updated: %d', zone) old_status = self._zones[zone].status if status is None: status = old_status self._zones[zone].status = status self._zones[zone].timestamp = time.time() if status == Zone.CLEAR: if zone in self._zones_faulted: self._zones_faulted.remove(zone) self.on_restore(zone=zone) else: if old_status != status and status is not None: self.on_fault(zone=zone)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _zone_expired(self, zone): """ Determine if a zone is expired or not. :param zone: zone number :type zone: int :returns: whether or not the zone is expired """
return (time.time() > self._zones[zone].timestamp + Zonetracker.EXPIRE) and self._zones[zone].expander is False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Example application that periodically faults a virtual zone and then restores it. This is an advanced feature that allows you to emulate a virtual zone. When the AlarmDecoder is configured to emulate a zone expander we can fault and restore those zones programmatically at will. These events can also be seen by others, such as home automation platforms which allows you to connect other devices or services and monitor them as you would any physical zone. For example, you could connect a ZigBee device and receiver and fault or restore it's zone(s) based on the data received. In order for this to happen you need to perform a couple configuration steps: 1. Enable zone expander emulation on your AlarmDecoder device by hitting '!' in a terminal and going through the prompts. 2. Enable the zone expander in your panel programming. """
try: # Retrieve the first USB device device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handlers and open the device device.on_zone_fault += handle_zone_fault device.on_zone_restore += handle_zone_restore with device.open(baudrate=BAUDRATE): last_update = time.time() while True: if time.time() - last_update > WAIT_TIME: last_update = time.time() device.fault_zone(TARGET_ZONE) time.sleep(1) except Exception as ex: print('Exception:', ex)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bytes_available(device): """ Determines the number of bytes available for reading from an AlarmDecoder device :param device: the AlarmDecoder device :type device: :py:class:`~alarmdecoder.devices.Device` :returns: int """
bytes_avail = 0 if isinstance(device, alarmdecoder.devices.SerialDevice): if hasattr(device._device, "in_waiting"): bytes_avail = device._device.in_waiting else: bytes_avail = device._device.inWaiting() elif isinstance(device, alarmdecoder.devices.SocketDevice): bytes_avail = 4096 return bytes_avail
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bytes_hack(buf): """ Hacky workaround for old installs of the library on systems without python-future that were keeping the 2to3 update from working after auto-update. """
ub = None if sys.version_info > (3,): ub = buf else: ub = bytes(buf) return ub
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_firmware_file(file_path): """ Reads a firmware file into a dequeue for processing. :param file_path: Path to the firmware file :type file_path: string :returns: deque """
data_queue = deque() with open(file_path) as firmware_handle: for line in firmware_handle: line = line.rstrip() if line != '' and line[0] == ':': data_queue.append(line + "\r") return data_queue
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(device): """ Reads data from the specified device. :param device: the AlarmDecoder device :type device: :py:class:`~alarmdecoder.devices.Device` :returns: string """
response = None bytes_avail = bytes_available(device) if isinstance(device, alarmdecoder.devices.SerialDevice): response = device._device.read(bytes_avail) elif isinstance(device, alarmdecoder.devices.SocketDevice): response = device._device.recv(bytes_avail) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload(device, file_path, progress_callback=None, debug=False): """ Uploads firmware to an `AlarmDecoder`_ device. :param file_path: firmware file path :type file_path: string :param progress_callback: callback function used to report progress :type progress_callback: function :raises: :py:class:`~alarmdecoder.util.NoDeviceError`, :py:class:`~alarmdecoder.util.TimeoutError` """
def progress_stage(stage, **kwargs): """Callback to update progress for the specified stage.""" if progress_callback is not None: progress_callback(stage, **kwargs) return stage if device is None: raise NoDeviceError('No device specified for firmware upload.') fds = [device._device.fileno()] # Read firmware file into memory try: write_queue = read_firmware_file(file_path) except IOError as err: stage = progress_stage(Firmware.STAGE_ERROR, error=str(err)) return data_read = '' got_response = False running = True stage = progress_stage(Firmware.STAGE_START) if device.is_reader_alive(): # Close the reader thread and wait for it to die, otherwise # it interferes with our reading. device.stop_reader() while device._read_thread.is_alive(): stage = progress_stage(Firmware.STAGE_WAITING) time.sleep(0.5) time.sleep(3) try: while running: rr, wr, _ = select.select(fds, fds, [], 0.5) if len(rr) != 0: response = Firmware.read(device) for c in response: # HACK: Python 3 / PySerial hack. if isinstance(c, int): c = chr(c) if c == '\xff' or c == '\r': # HACK: odd case for our mystery \xff byte. # Boot started, start looking for the !boot message if data_read.startswith("!sn"): stage = progress_stage(Firmware.STAGE_BOOT) # Entered bootloader upload mode, start uploading elif data_read.startswith("!load"): got_response = True stage = progress_stage(Firmware.STAGE_UPLOADING) # Checksum error elif data_read == '!ce': running = False raise UploadChecksumError("Checksum error in {0}".format(file_path)) # Bad data elif data_read == '!no': running = False raise UploadError("Incorrect data sent to bootloader.") # Firmware upload complete elif data_read == '!ok': running = False stage = progress_stage(Firmware.STAGE_DONE) # All other responses are valid during upload. else: got_response = True if stage == Firmware.STAGE_UPLOADING: progress_stage(stage) data_read = '' elif c == '\n': pass else: data_read += c if len(wr) != 0: # Reboot device if stage in [Firmware.STAGE_START, Firmware.STAGE_WAITING]: device.write('=') stage = progress_stage(Firmware.STAGE_WAITING_ON_LOADER) # Enter bootloader elif stage == Firmware.STAGE_BOOT: device.write('=') stage = progress_stage(Firmware.STAGE_LOAD) # Upload firmware elif stage == Firmware.STAGE_UPLOADING: if len(write_queue) > 0 and got_response == True: got_response = False device.write(write_queue.popleft()) except UploadError as err: stage = progress_stage(Firmware.STAGE_ERROR, error=str(err)) else: stage = progress_stage(Firmware.STAGE_DONE)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_device(device_args): """ Creates an AlarmDecoder from the specified USB device arguments. :param device_args: Tuple containing information on the USB device to open. :type device_args: Tuple (vid, pid, serialnumber, interface_count, description) """
device = AlarmDecoder(USBDevice.find(device_args)) device.on_message += handle_message device.open() return device
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode(cls, string, errors='strict'): """Return the encoded version of a string. :param string: The input string to encode. :type string: `basestring` :param errors: The error handling scheme. Only 'strict' is supported. :type errors: `basestring` :return: Tuple of encoded string and number of input bytes consumed. :rtype: `tuple` (`unicode`, `int`) """
if errors != 'strict': raise UnicodeError('Unsupported error handling {0}'.format(errors)) unicode_string = cls._ensure_unicode_string(string) encoded = unicode_string.translate(cls._encoding_table) return encoded, len(string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(cls, string, errors='strict'): """Return the decoded version of a string. :param string: The input string to decode. :type string: `basestring` :param errors: The error handling scheme. Only 'strict' is supported. :type errors: `basestring` :return: Tuple of decoded string and number of input bytes consumed. :rtype: `tuple` (`unicode`, `int`) """
if errors != 'strict': raise UnicodeError('Unsupported error handling {0}'.format(errors)) unicode_string = cls._ensure_unicode_string(string) decoded = unicode_string.translate(cls._decoding_table) return decoded, len(string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_function(cls, encoding): """Search function to find 'rotunicode' codec."""
if encoding == cls._codec_name: return codecs.CodecInfo( name=cls._codec_name, encode=cls.encode, decode=cls.decode, ) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ensure_unicode_string(string): """Returns a unicode string for string. :param string: The input string. :type string: `basestring` :returns: A unicode string. :rtype: `unicode` """
if not isinstance(string, six.text_type): string = string.decode('utf-8') return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get(url, params=None): """HTTP GET request."""
try: response = requests.get(url, params=params) response.raise_for_status() # If JSON fails, return raw data # (e.g. when downloading CSV job logs). try: return response.json() except ValueError: return response.text except NameError: url = '{0}?{1}'.format(url, urllib.urlencode(params)) return json.loads(urllib2.urlopen(url).read().decode(ENCODING))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post(url, data, content_type, params=None): """HTTP POST request."""
try: response = requests.post(url, params=params, data=data, headers={ 'Content-Type': content_type, }) response.raise_for_status() return response.json() except NameError: url = '{0}?{1}'.format(url, urllib.urlencode(params)) req = urllib2.Request(url, data.encode(ENCODING), { 'Content-Type': content_type, }) return json.loads(urllib2.urlopen(req).read().decode(ENCODING))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def api(self, name, url, **kwargs): """Generic API method."""
if name not in self._apis: raise ValueError('API name must be one of {0}, not {1!r}.'.format( tuple(self._apis), name)) fields = kwargs.get('fields') timeout = kwargs.get('timeout') text = kwargs.get('text') html = kwargs.get('html') if text and html: raise ValueError(u'Both `text` and `html` arguments provided!') params = {'url': url, 'token': self._token} if timeout: params['timeout'] = timeout if fields: if not isinstance(fields, str): fields = ','.join(sorted(fields)) params['fields'] = fields url = self.endpoint(name) if text or html: content_type = html and 'text/html' or 'text/plain' return self._post(url, text or html, content_type, params=params) return self._get(url, params=params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crawl(self, urls, name='crawl', api='analyze', **kwargs): """Crawlbot API. Returns a diffbot.Job object to check and retrieve crawl status. """
# If multiple seed URLs are specified, join with whitespace. if isinstance(urls, list): urls = ' '.join(urls) url = self.endpoint('crawl') process_url = self.endpoint(api) params = { 'token': self._token, 'seeds': urls, 'name': name, 'apiUrl': process_url, } # Add any additional named parameters as accepted by Crawlbot params['maxToCrawl'] = 10 params.update(kwargs) self._get(url, params=params) return Job(self._token, name, self._version)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_lrr_message(sender, message): """ Handles message events from the AlarmDecoder. """
print(sender, message.partition, message.event_type, message.event_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Example application that sends an email when an alarm event is detected. """
try: # Retrieve the first USB device device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE)) # Set up an event handler and open the device device.on_alarm += handle_alarm with device.open(baudrate=BAUDRATE): while True: time.sleep(1) except Exception as ex: print('Exception:', ex)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_alarm(sender, **kwargs): """ Handles alarm events from the AlarmDecoder. """
zone = kwargs.pop('zone', None) text = "Alarm: Zone {0}".format(zone) # Build the email message msg = MIMEText(text) msg['Subject'] = SUBJECT msg['From'] = FROM_ADDRESS msg['To'] = TO_ADDRESS s = smtplib.SMTP(SMTP_SERVER) # Authenticate if needed if SMTP_USERNAME is not None: s.login(SMTP_USERNAME, SMTP_PASSWORD) # Send the email s.sendmail(FROM_ADDRESS, TO_ADDRESS, msg.as_string()) s.quit() print('sent alarm email:', text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """ Example application that opens a device that has been exposed to the network with ser2sock and SSL encryption and authentication. """
try: # Retrieve an AD2 device that has been exposed with ser2sock on localhost:10000. ssl_device = SocketDevice(interface=('localhost', 10000)) # Enable SSL and set the certificates to be used. # # The key/cert attributes can either be a filesystem path or an X509/PKey # object from pyopenssl. ssl_device.ssl = True ssl_device.ssl_ca = SSL_CA # CA certificate ssl_device.ssl_key = SSL_KEY # Client private key ssl_device.ssl_certificate = SSL_CERT # Client certificate device = AlarmDecoder(ssl_device) # Set up an event handler and open the device device.on_message += handle_message with device.open(): while True: time.sleep(1) except Exception as ex: print('Exception:', ex)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ruencode(string, extension=False): """Encode a string using 'rotunicode' codec. :param string: The input string to encode. :type string: `basestring` :param extension: True if the entire input string should be encoded. False to split the input string using :func:`os.path.splitext` and encode only the file name portion keeping the extension as is. :type extension: `bool` :return: Encoded string. :rtype: `unicode` """
if extension: file_name = string file_ext = '' else: file_name, file_ext = splitext(string) encoded_value, _ = _ROT_UNICODE.encode(file_name) return encoded_value + file_ext
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_escape_sequences(string): """Parse a string for possible escape sequences. Sample usage: 'foo\nbar' 'foo\\u0256' :param string: Any string. :type string: `basestring` :raises: :class:`ValueError` if a backslash character is found, but it doesn't form a proper escape sequence with the character(s) that follow. :return: The parsed string. Will parse the standard escape sequences, and also basic \\uxxxx escape sequences. \\uxxxxxxxxxx escape sequences are not currently supported. :rtype: `unicode` """
string = safe_unicode(string) characters = [] i = 0 string_len = len(string) while i < string_len: character = string[i] if character == '\\': # Figure out the size of the escape sequence. Most escape sequences # are two characters (e.g. '\\' and 'n'), with the sole exception # being \uxxxx escape sequences, which are six characters. if string[(i + 1):(i + 2)] == 'u': offset = 6 else: offset = 2 try: # `json.decoder.scanstring()` mostly does what we want, but it # also does some stuff that we don't want, like parsing quote # characters. This will mess us up. The iteration and scanning # within this loop is meant to isolate the escape sequences, so # that we'll always be calling it with something like # >>> scanstring('"\n"', 1) # or # >>> scanstring('"\u0256"', 1) # The 1 refers to the location of the first character after the # open quote character. json_string = '"' + string[i:(i + offset)] + '"' character = scanstring(json_string, 1)[0] characters.append(character) i += offset except ValueError: # If an exception was raised, raise a new `ValueError`. The # reason we don't re-raise the original exception is because, # in Python 3, it is a custom JSON `ValueError` subclass. We # don't want to raise a JSON error from a function that has # nothing to do with JSON, so we create a new `ValueError`. The # error message is also nonsensical to the caller, in all # cases. raise_from(ValueError(string), None) else: characters.append(character) i += 1 return ''.join(characters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_all(cls, vid=None, pid=None): """ Returns all FTDI devices matching our vendor and product IDs. :returns: list of devices :raises: :py:class:`~alarmdecoder.util.CommError` """
if not have_pyftdi: raise ImportError('The USBDevice class has been disabled due to missing requirement: pyftdi or pyusb.') cls.__devices = [] query = cls.PRODUCT_IDS if vid and pid: query = [(vid, pid)] try: cls.__devices = Ftdi.find_all(query, nocache=True) except (usb.core.USBError, FtdiError) as err: raise CommError('Error enumerating AD2USB devices: {0}'.format(str(err)), err) return cls.__devices
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_detection(cls, on_attached=None, on_detached=None): """ Starts the device detection thread. :param on_attached: function to be called when a device is attached **Callback definition:** *def callback(thread, device)* :type on_attached: function :param on_detached: function to be called when a device is detached **Callback definition:** *def callback(thread, device)* :type on_detached: function """
if not have_pyftdi: raise ImportError('The USBDevice class has been disabled due to missing requirement: pyftdi or pyusb.') cls.__detect_thread = USBDevice.DetectThread(on_attached, on_detached) try: cls.find_all() except CommError: pass cls.__detect_thread.start()