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 SHA...
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: ...
<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....
<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: :pa...
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....
<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...
# 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...
<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'): ...
<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 Objec...
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.', cont...
<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...
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=conta...
<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, ...
<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: ...
<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 repo...
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, ...
<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 ...
<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 sh...
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 Ite...
<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_...
<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=s...
<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 ...
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) ...
<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(*...
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 #...
<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: ...
<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 amoun...
# 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_inde...
<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 ...
# 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) ...
<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.LRR...
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...
<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:`~alarmdeco...
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 :retur...
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}'.fo...
<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.Invali...
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] == ...
<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, dependin...
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) exce...
<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.CloseC...
<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 = '' sel...
<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...
<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.fil...
<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...
<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. ''' ...
<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 ...
<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...
<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...
<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.In...
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 mess...
<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_...
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 pref...
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(da...
<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...
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.a...
<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...
# 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) ...
<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:`~alarmdecod...
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 = No...
<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.me...
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:`~alarmdeco...
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.messag...
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 == 'M...
<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 sta...
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(mess...
<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 :...
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_statu...
<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 :typ...
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_statu...
<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...
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._alar...
<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: messag...
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 =...
<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 ...
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...
<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 ...
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_st...
<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 ...
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("S...
<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 :retur...
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: ...
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:c...
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 m...
<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 ad...
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...
<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: ...
<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...
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 :rai...
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() ...
<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 virtua...
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=BAUDRA...
<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 de...
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): ...
<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 a...
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 :...
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` :return...
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) ...
<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...
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 specifie...
<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 = 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...
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...
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 strin...
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 res...
<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)) ...
<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 a...
<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': nam...
<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) 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:...
<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 ...
<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 ...
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 strin...
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 t...
<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:`~alarmdeco...
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(q...
<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 ...
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 cl...