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 gdal_nodata_mask(pcl, pcsl, tirs_arr): """ Given a boolean potential cloud layer, a potential cloud shadow layer and a thermal band Calculate the GDAL-style uint8 mask """
tirs_mask = np.isnan(tirs_arr) | (tirs_arr == 0) return ((~(pcl | pcsl | tirs_mask)) * 255).astype('uint8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _transstat(status, grouppath, dictpath, line): """Executes processing steps when reading a line"""
if status == 0: raise MTLParseError( "Status should not be '%s' after reading line:\n%s" % (STATUSCODE[status], line)) elif status == 1: currentdict = dictpath[-1] currentgroup = _getgroupname(line) grouppath.append(currentgroup) currentdict[currentgroup] = {} dictpath.append(currentdict[currentgroup]) elif status == 2: currentdict = dictpath[-1] newkey, newval = _getmetadataitem(line) # USGS has started quoting the scene center time. If this # happens strip quotes before post processing. if newkey == 'SCENE_CENTER_TIME' and newval.startswith('"') \ and newval.endswith('"'): # logging.warning('Strip quotes off SCENE_CENTER_TIME.') newval = newval[1:-1] currentdict[newkey] = _postprocess(newval) elif status == 3: oldgroup = _getendgroupname(line) if oldgroup != grouppath[-1]: raise MTLParseError( "Reached line '%s' while reading group '%s'." % (line.strip(), grouppath[-1])) del grouppath[-1] del dictpath[-1] try: currentgroup = grouppath[-1] except IndexError: currentgroup = None elif status == 4: if grouppath: raise MTLParseError( "Reached end before end of group '%s'" % grouppath[-1]) return grouppath, dictpath
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _postprocess(valuestr): """ Takes value as str, returns str, int, float, date, datetime, or time """
# USGS has started quoting time sometimes. Grr, strip quotes in this case intpattern = re.compile(r'^\-?\d+$') floatpattern = re.compile(r'^\-?\d+\.\d+(E[+-]?\d\d+)?$') datedtpattern = '%Y-%m-%d' datedttimepattern = '%Y-%m-%dT%H:%M:%SZ' timedtpattern = '%H:%M:%S.%f' timepattern = re.compile(r'^\d{2}:\d{2}:\d{2}(\.\d{6})?') if valuestr.startswith('"') and valuestr.endswith('"'): # it's a string return valuestr[1:-1] elif re.match(intpattern, valuestr): # it's an integer return int(valuestr) elif re.match(floatpattern, valuestr): # floating point number return float(valuestr) # now let's try the datetime objects; throws exception if it doesn't match try: return datetime.datetime.strptime(valuestr, datedtpattern).date() except ValueError: pass try: return datetime.datetime.strptime(valuestr, datedttimepattern) except ValueError: pass # time parsing is complicated: Python's datetime module only accepts # fractions of a second only up to 6 digits mat = re.match(timepattern, valuestr) if mat: test = mat.group(0) try: return datetime.datetime.strptime(test, timedtpattern).time() except ValueError: pass # If we get here, we still haven't returned anything. logging.info( "The value %s couldn't be parsed as " % valuestr + "int, float, date, time, datetime. Returning it as string.") return valuestr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tox_get_python_executable(envconfig): """Return a python executable for the given python base name. The first plugin/hook which returns an executable path will determine it. ``envconfig`` is the testenv configuration which contains per-testenv configuration, notably the ``.envname`` and ``.basepython`` setting. """
try: # pylint: disable=no-member pyenv = (getattr(py.path.local.sysfind('pyenv'), 'strpath', 'pyenv') or 'pyenv') cmd = [pyenv, 'which', envconfig.basepython] pipe = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) out, err = pipe.communicate() except OSError: err = '\'pyenv\': command not found' LOG.warning( "pyenv doesn't seem to be installed, you probably " "don't want this plugin installed either." ) else: if pipe.poll() == 0: return out.strip() else: if not envconfig.tox_pyenv_fallback: raise PyenvWhichFailed(err) LOG.debug("`%s` failed thru tox-pyenv plugin, falling back. " "STDERR: \"%s\" | To disable this behavior, set " "tox_pyenv_fallback=False in your tox.ini or use " " --tox-pyenv-no-fallback on the command line.", ' '.join([str(x) for x in cmd]), 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 quote(myitem, elt=True): '''URL encode string''' if elt and '<' in myitem and len(myitem) > 24 and myitem.find(']]>') == -1: return '<![CDATA[%s]]>' % (myitem) else: myitem = myitem.replace('&', '&amp;').\ replace('<', '&lt;').replace(']]>', ']]&gt;') if not elt: myitem = myitem.replace('"', '&quot;') return myitem
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _doPrep(field_dict): """ _doPrep is makes changes in-place. Do some prep work converting python types into formats that Salesforce will accept. This includes converting lists of strings to "apple;orange;pear". Dicts will be converted to embedded objects None or empty list values will be Null-ed """
fieldsToNull = [] for key, value in field_dict.items(): if value is None: fieldsToNull.append(key) field_dict[key] = [] if hasattr(value, '__iter__'): if len(value) == 0: fieldsToNull.append(key) elif isinstance(value, dict): innerCopy = copy.deepcopy(value) _doPrep(innerCopy) field_dict[key] = innerCopy else: field_dict[key] = ";".join(value) if 'fieldsToNull' in field_dict: raise ValueError( "fieldsToNull should be populated by the client, not the caller." ) field_dict['fieldsToNull'] = fieldsToNull
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _prepareSObjects(sObjects): '''Prepare a SObject''' sObjectsCopy = copy.deepcopy(sObjects) if isinstance(sObjectsCopy, dict): # If root element is a dict, then this is a single object not an array _doPrep(sObjectsCopy) else: # else this is an array, and each elelment should be prepped. for listitems in sObjectsCopy: _doPrep(listitems) return sObjectsCopy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queryTypesDescriptions(self, types): """ Given a list of types, construct a dictionary such that each key is a type, and each value is the corresponding sObject for that type. """
types = list(types) if types: types_descs = self.describeSObjects(types) else: types_descs = [] return dict(map(lambda t, d: (t, d), types, types_descs))
<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_token(self): """Create a session protection token for this client. This method generates a session protection token for the cilent, which consists in a hash of the user agent and the IP address. This method can be overriden by subclasses to implement different token generation algorithms. """
user_agent = request.headers.get('User-Agent') if user_agent is None: # pragma: no cover user_agent = 'no user agent' user_agent = user_agent.encode('utf-8') base = self._get_remote_addr() + b'|' + user_agent h = sha256() h.update(base) return h.hexdigest()
<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_session(self, response): """Clear the session. This method is invoked when the session is found to be invalid. Subclasses can override this method to implement a custom session reset. """
session.clear() # if flask-login is installed, we try to clear the # "remember me" cookie, just in case it is set if 'flask_login' in sys.modules: remember_cookie = current_app.config.get('REMEMBER_COOKIE', 'remember_token') response.set_cookie(remember_cookie, '', expires=0, max_age=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 haikunate(self, delimiter='-', token_length=4, token_hex=False, token_chars='0123456789'): """ Generate heroku-like random names to use in your python applications :param delimiter: Delimiter :param token_length: TokenLength :param token_hex: TokenHex :param token_chars: TokenChars :type delimiter: str :type token_length: int :type token_hex: bool :type token_chars: str :return: heroku-like random string :rtype: str """
if token_hex: token_chars = '0123456789abcdef' adjective = self._random_element(self._adjectives) noun = self._random_element(self._nouns) token = ''.join(self._random_element(token_chars) for _ in range(token_length)) sections = [adjective, noun, token] return delimiter.join(filter(None, sections))
<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_parser_class(): """ Returns the parser according to the system platform """
global distro if distro == 'Linux': Parser = parser.LinuxParser if not os.path.exists(Parser.get_command()[0]): Parser = parser.UnixIPParser elif distro in ['Darwin', 'MacOSX']: Parser = parser.MacOSXParser elif distro == 'Windows': # For some strange reason, Windows will always be win32, see: # https://stackoverflow.com/a/2145582/405682 Parser = parser.WindowsParser else: Parser = parser.NullParser Log.error("Unknown distro type '%s'." % distro) Log.debug("Distro detected as '%s'" % distro) Log.debug("Using '%s'" % Parser) return Parser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_interface(ifconfig=None, route_output=None): """ Return just the default interface device dictionary. :param ifconfig: For mocking actual command output :param route_output: For mocking actual command output """
global Parser return Parser(ifconfig=ifconfig)._default_interface(route_output=route_output)
<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(self, ifconfig=None): # noqa: max-complexity=12 """ Parse ifconfig output into self._interfaces. Optional Arguments: ifconfig The data (stdout) from the ifconfig command. Default is to call exec_cmd(self.get_command()). """
if not ifconfig: ifconfig, __, __ = exec_cmd(self.get_command()) self.ifconfig_data = ifconfig cur = None patterns = self.get_patterns() for line in self.ifconfig_data.splitlines(): for pattern in patterns: m = re.match(pattern, line) if not m: continue groupdict = m.groupdict() # Special treatment to trigger which interface we're # setting for if 'device' is in the line. Presumably the # device of the interface is within the first line of the # device block. if 'device' in groupdict: cur = groupdict['device'] self.add_device(cur) elif cur is None: raise RuntimeError( "Got results that don't belong to a device" ) for k, v in groupdict.items(): if k in self._interfaces[cur]: if self._interfaces[cur][k] is None: self._interfaces[cur][k] = v elif hasattr(self._interfaces[cur][k], 'append'): self._interfaces[cur][k].append(v) elif self._interfaces[cur][k] == v: # Silently ignore if the it's the same value as last. Example: Multiple # inet4 addresses, result in multiple netmasks. Cardinality mismatch continue else: raise RuntimeError( "Tried to add {}={} multiple times to {}, it was already: {}".format( k, v, cur, self._interfaces[cur][k] ) ) else: self._interfaces[cur][k] = v # Copy the first 'inet4' ip address to 'inet' for backwards compatibility for device, device_dict in self._interfaces.items(): if len(device_dict['inet4']) > 0: device_dict['inet'] = device_dict['inet4'][0] # fix it up self._interfaces = self.alter(self._interfaces)
<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(self, line_number): """Return the needle positions or None. :param int line_number: the number of the line :rtype: list :return: the needle positions for a specific line specified by :paramref:`line_number` or :obj:`None` if no were given """
if line_number not in self._get_cache: self._get_cache[line_number] = self._get(line_number) return self._get_cache[line_number]
<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_bytes(self, line_number): """Get the bytes representing needle positions or None. :param int line_number: the line number to take the bytes from :rtype: bytes :return: the bytes that represent the message or :obj:`None` if no data is there for the line. Depending on the :attr:`machine`, the length and result may vary. """
if line_number not in self._needle_position_bytes_cache: line = self._get(line_number) if line is None: line_bytes = None else: line_bytes = self._machine.needle_positions_to_bytes(line) self._needle_position_bytes_cache[line_number] = line_bytes return self._needle_position_bytes_cache[line_number]
<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_line_configuration_message(self, line_number): """Return the cnfLine content without id for the line. :param int line_number: the number of the line :rtype: bytes :return: a cnfLine message without id as defined in :ref:`cnfLine` """
if line_number not in self._line_configuration_message_cache: line_bytes = self.get_bytes(line_number) if line_bytes is not None: line_bytes = bytes([line_number & 255]) + line_bytes line_bytes += bytes([self.is_last(line_number)]) line_bytes += crc8(line_bytes).digest() self._line_configuration_message_cache[line_number] = line_bytes del line_bytes line = self._line_configuration_message_cache[line_number] if line is None: # no need to cache a lot of empty lines line = (bytes([line_number & 255]) + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01') line += crc8(line).digest() return line
<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_message_type(file): """Read the message type from a file."""
message_byte = file.read(1) if message_byte == b'': return ConnectionClosed message_number = message_byte[0] return _message_types.get(message_number, UnknownMessage)
<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(self): """Read the line number."""
self._line_number = next_line( self._communication.last_requested_line_number, self._file.read(1)[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 send(self): """Send this message to the controller."""
self._file.write(self.as_bytes()) self._file.write(b'\r\n')
<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(self, left_end_needle, right_end_needle): """Initialize the StartRequest with start and stop needle. :raises TypeError: if the arguments are not integers :raises ValueError: if the values do not match the :ref:`specification <m4-01>` """
if not isinstance(left_end_needle, int): raise TypeError(_left_end_needle_error_message(left_end_needle)) if left_end_needle < 0 or left_end_needle > 198: raise ValueError(_left_end_needle_error_message(left_end_needle)) if not isinstance(right_end_needle, int): raise TypeError(_right_end_needle_error_message(right_end_needle)) if right_end_needle < 1 or right_end_needle > 199: raise ValueError(_right_end_needle_error_message(right_end_needle)) self._left_end_needle = left_end_needle self._right_end_needle = right_end_needle
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def content_bytes(self): """Return the start and stop needle."""
get_message = \ self._communication.needle_positions.get_line_configuration_message return get_message(self._line_number)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sum_all(iterable, start): """Sum up an iterable starting with a start value. In contrast to :func:`sum`, this also works on other types like :class:`lists <list>` and :class:`sets <set>`. """
if hasattr(start, "__add__"): for value in iterable: start += value else: for value in iterable: start |= value return start
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_line(last_line, next_line_8bit): """Compute the next line based on the last line and a 8bit next line. The behaviour of the function is specified in :ref:`reqline`. :param int last_line: the last line that was processed :param int next_line_8bit: the lower 8 bits of the next line :return: the next line closest to :paramref:`last_line` .. seealso:: :ref:`reqline` """
# compute the line without the lowest byte base_line = last_line - (last_line & 255) # compute the three different lines line = base_line + next_line_8bit lower_line = line - 256 upper_line = line + 256 # compute the next line if last_line - lower_line <= line - last_line: return lower_line if upper_line - last_line < last_line - line: return upper_line return line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def camel_case_to_under_score(camel_case_name): """Return the underscore name of a camel case name. :param str camel_case_name: a name in camel case such as ``"ACamelCaseName"`` :return: the name using underscores, e.g. ``"a_camel_case_name"`` :rtype: str """
result = [] for letter in camel_case_name: if letter.lower() != letter: result.append("_" + letter.lower()) else: result.append(letter.lower()) if result[0].startswith("_"): result[0] = result[0][1:] return "".join(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _message_received(self, message): """Notify the observers about the received message."""
with self.lock: self._state.receive_message(message) for callable in chain(self._on_message_received, self._on_message): callable(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 receive_message(self): """Receive a message from the file."""
with self.lock: assert self.can_receive_messages() message_type = self._read_message_type(self._file) message = message_type(self._file, self) self._message_received(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 can_receive_messages(self): """Whether tihs communication is ready to receive messages.] :rtype: bool .. code:: python assert not communication.can_receive_messages() communication.start() assert communication.can_receive_messages() communication.stop() assert not communication.can_receive_messages() """
with self.lock: return not self._state.is_waiting_for_start() and \ not self._state.is_connection_closed()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Stop the communication with the shield."""
with self.lock: self._message_received(ConnectionClosed(self._file, self))
<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, host_message_class, *args): """Send a host message. :param type host_message_class: a subclass of :class:`AYABImterface.communication.host_messages.Message` :param args: additional arguments that shall be passed to the :paramref:`host_message_class` as arguments """
message = host_message_class(self._file, self, *args) with self.lock: message.send() for callable in self._on_message: callable(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 parallelize(self, seconds_to_wait=2): """Start a parallel thread for receiving messages. If :meth:`start` was no called before, start will be called in the thread. The thread calls :meth:`receive_message` until the :attr:`state` :meth:`~AYABInterface.communication.states.State.is_connection_closed`. :param float seconds_to_wait: A time in seconds to wait with the parallel execution. This is useful to allow the controller time to initialize. .. seealso:: :attr:`lock`, :meth:`runs_in_parallel` """
with self.lock: thread = Thread(target=self._parallel_receive_loop, args=(seconds_to_wait,)) thread.deamon = True thread.start() self._thread = thread
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parallel_receive_loop(self, seconds_to_wait): """Run the receiving in parallel."""
sleep(seconds_to_wait) with self._lock: self._number_of_threads_receiving_messages += 1 try: with self._lock: if self.state.is_waiting_for_start(): self.start() while True: with self.lock: if self.state.is_connection_closed(): return self.receive_message() finally: with self._lock: self._number_of_threads_receiving_messages -= 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 _next(self, state_class, *args): """Transition into the next state. :param type state_class: a subclass of :class:`State`. It is intialized with the communication object and :paramref:`args` :param args: additional arguments """
self._communication.state = state_class(self._communication, *args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_information_confirmation(self, message): """A InformationConfirmation is received. If :meth:`the api version is supported <AYABInterface.communication.Communication.api_version_is_supported>`, the communication object transitions into a :class:`InitializingMachine`, if unsupported, into a :class:`UnsupportedApiVersion` """
if message.api_version_is_supported(): self._next(InitializingMachine) else: self._next(UnsupportedApiVersion) self._communication.controller = 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 receive_start_confirmation(self, message): """Receive a StartConfirmation message. :param message: a :class:`StartConfirmation <AYABInterface.communication.hardware_messages.StartConfirmation>` message If the message indicates success, the communication object transitions into :class:`KnittingStarted` or else, into :class:`StartingFailed`. """
if message.is_success(): self._next(KnittingStarted) else: self._next(StartingFailed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enter(self): """Send a StartRequest."""
self._communication.send(StartRequest, self._communication.left_end_needle, self._communication.right_end_needle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enter(self): """Send a LineConfirmation to the controller. When this state is entered, a :class:`AYABInterface.communication.host_messages.LineConfirmation` is sent to the controller. Also, the :attr:`last line requested <AYABInterface.communication.Communication.last_requested_line_number>` is set. """
self._communication.last_requested_line_number = self._line_number self._communication.send(LineConfirmation, self._line_number)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def colors_to_needle_positions(rows): """Convert rows to needle positions. :return: :rtype: list """
needles = [] for row in rows: colors = set(row) if len(colors) == 1: needles.append([NeedlePositions(row, tuple(colors), False)]) elif len(colors) == 2: color1, color2 = colors if color1 != row[0]: color1, color2 = color2, color1 needles_ = _row_color(row, color1) needles.append([NeedlePositions(needles_, (color1, color2), True)]) else: colors = [] for color in row: if color not in colors: colors.append(color) needles_ = [] for color in colors: needles_.append(NeedlePositions(_row_color(row, color), (color,), False)) needles.append(needles_) return needles
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check(self): """Check for validity. :raises ValueError: - if not all lines are as long as the :attr:`number of needles <AYABInterface.machines.Machine.number_of_needles>` - if the contents of the rows are not :attr:`needle positions <AYABInterface.machines.Machine.needle_positions>` """
# TODO: This violates the law of demeter. # The architecture should be changed that this check is either # performed by the machine or by the unity of machine and # carriage. expected_positions = self._machine.needle_positions expected_row_length = self._machine.number_of_needles for row_index, row in enumerate(self._rows): if len(row) != expected_row_length: message = _ROW_LENGTH_ERROR_MESSAGE.format( row_index, len(row), expected_row_length) raise ValueError(message) for needle_index, needle_position in enumerate(row): if needle_position not in expected_positions: message = _NEEDLE_POSITION_ERROR_MESSAGE.format( row_index, needle_index, repr(needle_position), ", ".join(map(repr, expected_positions))) raise ValueError(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 get_row(self, index, default=None): """Return the row at the given index or the default value."""
if not isinstance(index, int) or index < 0 or index >= len(self._rows): return default return self._rows[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 row_completed(self, index): """Mark the row at index as completed. .. seealso:: :meth:`completed_row_indices` This method notifies the obsevrers from :meth:`on_row_completed`. """
self._completed_rows.append(index) for row_completed in self._on_row_completed: row_completed(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 communicate_through(self, file): """Setup communication through a file. :rtype: AYABInterface.communication.Communication """
if self._communication is not None: raise ValueError("Already communicating.") self._communication = communication = Communication( file, self._get_needle_positions, self._machine, [self._on_message_received], right_end_needle=self.right_end_needle, left_end_needle=self.left_end_needle) return communication
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def actions(self): """A list of actions to perform. :return: a list of :class:`AYABInterface.actions.Action` """
actions = [] do = actions.append # determine the number of colors colors = self.colors # rows and colors movements = ( MoveCarriageToTheRight(KnitCarriage()), MoveCarriageToTheLeft(KnitCarriage())) rows = self._rows first_needles = self._get_row_needles(0) # handle switches if len(colors) == 1: actions.extend([ SwitchOffMachine(), SwitchCarriageToModeNl()]) else: actions.extend([ SwitchCarriageToModeKc(), SwitchOnMachine()]) # move needles do(MoveNeedlesIntoPosition("B", first_needles)) do(MoveCarriageOverLeftHallSensor()) # use colors if len(colors) == 1: do(PutColorInNutA(colors[0])) if len(colors) == 2: do(PutColorInNutA(colors[0])) do(PutColorInNutB(colors[1])) # knit for index, row in enumerate(rows): do(movements[index & 1]) return actions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def needle_positions_to_bytes(self, needle_positions): """Convert the needle positions to the wire format. This conversion is used for :ref:`cnfline`. :param needle_positions: an iterable over :attr:`needle_positions` of length :attr:`number_of_needles` :rtype: bytes """
bit = self.needle_positions assert len(bit) == 2 max_length = len(needle_positions) assert max_length == self.number_of_needles result = [] for byte_index in range(0, max_length, 8): byte = 0 for bit_index in range(8): index = byte_index + bit_index if index >= max_length: break needle_position = needle_positions[index] if bit.index(needle_position) == 1: byte |= 1 << bit_index result.append(byte) if byte_index >= max_length: break result.extend(b"\x00" * (25 - len(result))) return bytes(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name(self): """The identifier of the machine."""
name = self.__class__.__name__ for i, character in enumerate(name): if character.isdigit(): return name[:i] + "-" + name[i:] return 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 _id(self): """What this object is equal to."""
return (self.__class__, self.number_of_needles, self.needle_positions, self.left_end_needle)
<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_chapter(self, c): """ Add a Chapter to your epub. Args: c (Chapter): A Chapter object representing your chapter. Raises: TypeError: Raised if a Chapter object isn't supplied to this method. """
try: assert type(c) == chapter.Chapter except AssertionError: raise TypeError('chapter must be of type Chapter') chapter_file_output = os.path.join(self.OEBPS_DIR, self.current_chapter_path) c._replace_images_in_chapter(self.OEBPS_DIR) c.write(chapter_file_output) self._increase_current_chapter_number() self.chapters.append(c)
<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_epub(self, output_directory, epub_name=None): """ Create an epub file from this object. Args: output_directory (str): Directory to output the epub file to epub_name (Option[str]): The file name of your epub. This should not contain .epub at the end. If this argument is not provided, defaults to the title of the epub. """
def createTOCs_and_ContentOPF(): for epub_file, name in ((self.toc_html, 'toc.html'), (self.toc_ncx, 'toc.ncx'), (self.opf, 'content.opf'),): epub_file.add_chapters(self.chapters) epub_file.write(os.path.join(self.OEBPS_DIR, name)) def create_zip_archive(epub_name): try: assert isinstance(epub_name, basestring) or epub_name is None except AssertionError: raise TypeError('epub_name must be string or None') if epub_name is None: epub_name = self.title epub_name = ''.join([c for c in epub_name if c.isalpha() or c.isdigit() or c == ' ']).rstrip() epub_name_with_path = os.path.join(output_directory, epub_name) try: os.remove(os.path.join(epub_name_with_path, '.zip')) except OSError: pass shutil.make_archive(epub_name_with_path, 'zip', self.EPUB_DIR) return epub_name_with_path + '.zip' def turn_zip_into_epub(zip_archive): epub_full_name = zip_archive.strip('.zip') + '.epub' try: os.remove(epub_full_name) except OSError: pass os.rename(zip_archive, epub_full_name) return epub_full_name createTOCs_and_ContentOPF() epub_path = turn_zip_into_epub(create_zip_archive(epub_name)) return epub_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 save_image(image_url, image_directory, image_name): """ Saves an online image from image_url to image_directory with the name image_name. Returns the extension of the image saved, which is determined dynamically. Args: image_url (str): The url of the image. image_directory (str): The directory to save the image in. image_name (str): The file name to save the image as. Raises: ImageErrorException: Raised if unable to save the image at image_url """
image_type = get_image_type(image_url) if image_type is None: raise ImageErrorException(image_url) full_image_file_name = os.path.join(image_directory, image_name + '.' + image_type) # If the image is present on the local filesystem just copy it if os.path.exists(image_url): shutil.copy(image_url, full_image_file_name) return image_type try: # urllib.urlretrieve(image_url, full_image_file_name) with open(full_image_file_name, 'wb') as f: user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0' request_headers = {'User-Agent': user_agent} requests_object = requests.get(image_url, headers=request_headers) try: content = requests_object.content # Check for empty response f.write(content) except AttributeError: raise ImageErrorException(image_url) except IOError: raise ImageErrorException(image_url) return image_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 _replace_image(image_url, image_tag, ebook_folder, image_name=None): """ Replaces the src of an image to link to the local copy in the images folder of the ebook. Tightly coupled with bs4 package. Args: image_url (str): The url of the image. image_tag (bs4.element.Tag): The bs4 tag containing the image. ebook_folder (str): The directory where the ebook files are being saved. This must contain a subdirectory called "images". image_name (Option[str]): The short name to save the image as. Should not contain a directory or an extension. """
try: assert isinstance(image_tag, bs4.element.Tag) except AssertionError: raise TypeError("image_tag cannot be of type " + str(type(image_tag))) if image_name is None: image_name = str(uuid.uuid4()) try: image_full_path = os.path.join(ebook_folder, 'images') assert os.path.exists(image_full_path) image_extension = save_image(image_url, image_full_path, image_name) image_tag['src'] = 'images' + '/' + image_name + '.' + image_extension except ImageErrorException: image_tag.decompose() except AssertionError: raise ValueError('%s doesn\'t exist or doesn\'t contain a subdirectory images' % ebook_folder) except TypeError: image_tag.decompose()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, file_name): """ Writes the chapter object to an xhtml file. Args: file_name (str): The full name of the xhtml file to save to. """
try: assert file_name[-6:] == '.xhtml' except (AssertionError, IndexError): raise ValueError('filename must end with .xhtml') with open(file_name, 'wb') as f: f.write(self.content.encode('utf-8'))
<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_chapter_from_url(self, url, title=None): """ Creates a Chapter object from a url. Pulls the webpage from the given url, sanitizes it using the clean_function method, and saves it as the content of the created chapter. Basic webpage loaded before any javascript executed. Args: url (string): The url to pull the content of the created Chapter from title (Option[string]): The title of the created Chapter. By default, this is None, in which case the title will try to be inferred from the webpage at the url. Returns: Chapter: A chapter object whose content is the webpage at the given url and whose title is that provided or inferred from the url Raises: ValueError: Raised if unable to connect to url supplied """
try: request_object = requests.get(url, headers=self.request_headers, allow_redirects=False) except (requests.exceptions.MissingSchema, requests.exceptions.ConnectionError): raise ValueError("%s is an invalid url or no network connection" % url) except requests.exceptions.SSLError: raise ValueError("Url %s doesn't have valid SSL certificate" % url) unicode_string = request_object.text return self.create_chapter_from_string(unicode_string, url, title)
<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_chapter_from_file(self, file_name, url=None, title=None): """ Creates a Chapter object from an html or xhtml file. Sanitizes the file's content using the clean_function method, and saves it as the content of the created chapter. Args: file_name (string): The file_name containing the html or xhtml content of the created Chapter url (Option[string]): A url to infer the title of the chapter from title (Option[string]): The title of the created Chapter. By default, this is None, in which case the title will try to be inferred from the webpage at the url. Returns: Chapter: A chapter object whose content is the given file and whose title is that provided or inferred from the url """
with codecs.open(file_name, 'r', encoding='utf-8') as f: content_string = f.read() return self.create_chapter_from_string(content_string, url, title)
<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_chapter_from_string(self, html_string, url=None, title=None): """ Creates a Chapter object from a string. Sanitizes the string using the clean_function method, and saves it as the content of the created chapter. Args: html_string (string): The html or xhtml content of the created Chapter url (Option[string]): A url to infer the title of the chapter from title (Option[string]): The title of the created Chapter. By default, this is None, in which case the title will try to be inferred from the webpage at the url. Returns: Chapter: A chapter object whose content is the given string and whose title is that provided or inferred from the url """
clean_html_string = self.clean_function(html_string) clean_xhtml_string = clean.html_to_xhtml(clean_html_string) if title: pass else: try: root = BeautifulSoup(html_string, 'html.parser') title_node = root.title if title_node is not None: title = unicode(title_node.string) else: raise ValueError except (IndexError, ValueError): title = 'Ebook Chapter' return Chapter(clean_xhtml_string, title, url)
<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_html_from_fragment(tag): """ Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not Args: tag: a bs4.element.Tag Returns:" bs4.element.Tag: A bs4 tag representing a full html document """
try: assert isinstance(tag, bs4.element.Tag) except AssertionError: raise TypeError try: assert tag.find_all('body') == [] except AssertionError: raise ValueError soup = BeautifulSoup('<html><head></head><body></body></html>', 'html.parser') soup.body.append(tag) return soup
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def condense(input_string): """ Trims leadings and trailing whitespace between tags in an html document Args: input_string: A (possible unicode) string representing HTML. Returns: A (possibly unicode) string representing HTML. Raises: TypeError: Raised if input_string isn't a unicode string or string. """
try: assert isinstance(input_string, basestring) except AssertionError: raise TypeError removed_leading_whitespace = re.sub('>\s+', '>', input_string).strip() removed_trailing_whitespace = re.sub('\s+<', '<', removed_leading_whitespace).strip() return removed_trailing_whitespace
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html_to_xhtml(html_unicode_string): """ Converts html to xhtml Args: html_unicode_string: A (possible unicode) string representing HTML. Returns: A (possibly unicode) string representing XHTML. Raises: TypeError: Raised if input_string isn't a unicode string or string. """
try: assert isinstance(html_unicode_string, basestring) except AssertionError: raise TypeError root = BeautifulSoup(html_unicode_string, 'html.parser') # Confirm root node is html try: assert root.html is not None except AssertionError: raise ValueError(''.join(['html_unicode_string cannot be a fragment.', 'string is the following: %s', unicode(root)])) # Add xmlns attribute to html node root.html['xmlns'] = 'http://www.w3.org/1999/xhtml' unicode_string = unicode(root.prettify(encoding='utf-8', formatter='html'), encoding='utf-8') # Close singleton tag_dictionary for tag in constants.SINGLETON_TAG_LIST: unicode_string = unicode_string.replace( '<' + tag + '/>', '<' + tag + ' />') return unicode_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 _merge_dicts(self, dict1, dict2, path=[]): "merges dict2 into dict1" for key in dict2: if key in dict1: if isinstance(dict1[key], dict) and isinstance(dict2[key], dict): self._merge_dicts(dict1[key], dict2[key], path + [str(key)]) elif dict1[key] != dict2[key]: if self._options.get('allowmultioptions', True): if not isinstance(dict1[key], list): dict1[key] = [dict1[key]] if not isinstance(dict2[key], list): dict2[key] = [dict2[key]] dict1[key] = self._merge_lists(dict1[key], dict2[key]) else: if self._options.get('mergeduplicateoptions', False): dict1[key] = dict2[key] else: raise error.ApacheConfigError('Duplicate option "%s" prohibited' % '.'.join(path + [str(key)])) else: dict1[key] = dict2[key] return dict1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def t_multiline_NEWLINE(self, t): r'\r\n|\n|\r' if t.lexer.multiline_newline_seen: return self.t_multiline_OPTION_AND_VALUE(t) t.lexer.multiline_newline_seen = 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 set_default(cls, name): """Replaces the current application default depot"""
if name not in cls._depots: raise RuntimeError('%s depot has not been configured' % (name,)) cls._default_depot = 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 get(cls, name=None): """Gets the application wide depot instance. Might return ``None`` if :meth:`configure` has not been called yet. """
if name is None: name = cls._default_depot name = cls.resolve_alias(name) # resolve alias return cls._depots.get(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 get_file(cls, path): """Retrieves a file by storage name and fileid in the form of a path Path is expected to be ``storage_name/fileid``. """
depot_name, file_id = path.split('/', 1) depot = cls.get(depot_name) return depot.get(file_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure(cls, name, config, prefix='depot.'): """Configures an application depot. This configures the application wide depot from a settings dictionary. The settings dictionary is usually loaded from an application configuration file where all the depot options are specified with a given ``prefix``. The default ``prefix`` is *depot.*, the minimum required setting is ``depot.backend`` which specified the required backend for files storage. Additional options depend on the choosen backend. """
if name in cls._depots: raise RuntimeError('Depot %s has already been configured' % (name,)) if cls._default_depot is None: cls._default_depot = name cls._depots[name] = cls.from_config(config, prefix) return cls._depots[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 make_middleware(cls, app, **options): """Creates the application WSGI middleware in charge of serving local files. A Depot middleware is required if your application wants to serve files from storages that don't directly provide and HTTP interface like :class:`depot.io.local.LocalFileStorage` and :class:`depot.io.gridfs.GridFSStorage` """
from depot.middleware import DepotMiddleware mw = DepotMiddleware(app, **options) cls.set_middleware(mw) return mw
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_config(cls, config, prefix='depot.'): """Creates a new depot from a settings dictionary. Behaves like the :meth:`configure` method but instead of configuring the application depot it creates a new one each time. """
config = config or {} # Get preferred storage backend backend = config.get(prefix + 'backend', 'depot.io.local.LocalFileStorage') # Get all options prefixlen = len(prefix) options = dict((k[prefixlen:], config[k]) for k in config.keys() if k.startswith(prefix)) # Backend is already passed as a positional argument options.pop('backend', None) return cls._new(backend, **options)
<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(cls): """This is only for testing pourposes, resets the DepotManager status This is to simplify writing test fixtures, resets the DepotManager global status and removes the informations related to the current configured depots and middleware. """
cls._default_depot = None cls._depots = {} cls._middleware = None cls._aliases = {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_email_address(cls, email): """Return the user object whose email address is ``email``."""
return DBSession.query(cls).filter_by(email_address=email).first()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_user_name(cls, username): """Return the user object whose user name is ``username``."""
return DBSession.query(cls).filter_by(user_name=username).first()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_password(self, password): """ Check the password against existing credentials. :param password: the password that was provided by the user to try and authenticate. This is the clear text version that we will need to match against the hashed one in the database. :type password: unicode object. :return: Whether the password is valid. :rtype: bool """
hash = sha256() hash.update((password + self.password[:64]).encode('utf-8')) return self.password[64:] == hash.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_from_content(content): """Provides a real file object from file content Converts ``FileStorage``, ``FileIntent`` and ``bytes`` to an actual file. """
f = content if isinstance(content, cgi.FieldStorage): f = content.file elif isinstance(content, FileIntent): f = content._fileobj elif isinstance(content, byte_string): f = SpooledTemporaryFile(INMEMORY_FILESIZE) f.write(content) f.seek(0) return f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fileinfo(fileobj, filename=None, content_type=None, existing=None): """Tries to extract from the given input the actual file object, filename and content_type This is used by the create and replace methods to correctly deduce their parameters from the available information when possible. """
return _FileInfo(fileobj, filename, content_type).get_info(existing)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login(self, came_from=lurl('/')): """Start the user login."""
login_counter = request.environ.get('repoze.who.logins', 0) if login_counter > 0: flash(_('Wrong credentials'), 'warning') return dict(page='login', login_counter=str(login_counter), came_from=came_from)
<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_login(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """
if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) redirect(came_from)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_rewrites(date_classes, rules): """ Return a list of date elements by applying rewrites to the initial date element list """
for rule in rules: date_classes = rule.execute(date_classes) return date_classes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _most_restrictive(date_elems): """ Return the date_elem that has the most restrictive range from date_elems """
most_index = len(DATE_ELEMENTS) for date_elem in date_elems: if date_elem in DATE_ELEMENTS and DATE_ELEMENTS.index(date_elem) < most_index: most_index = DATE_ELEMENTS.index(date_elem) if most_index < len(DATE_ELEMENTS): return DATE_ELEMENTS[most_index] else: raise KeyError('No least restrictive date element found')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, elem_list): """ If condition, return a new elem_list provided by executing action. """
if self.condition.is_true(elem_list): return self.action.act(elem_list) else: return elem_list
<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(find_seq, elem_list): """ Return the first position in elem_list where find_seq starts """
seq_pos = 0 for index, elem in enumerate(elem_list): if Sequence.match(elem, find_seq[seq_pos]): seq_pos += 1 if seq_pos == len(find_seq): # found matching sequence return index - seq_pos + 1 else: # exited sequence seq_pos = 0 raise LookupError('Failed to find sequence in elem_list')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ms_game_main(board_width, board_height, num_mines, port, ip_add): """Main function for Mine Sweeper Game. Parameters board_width : int the width of the board (> 0) board_height : int the height of the board (> 0) num_mines : int the number of mines, cannot be larger than (board_width x board_height) port : int UDP port number, default is 5678 ip_add : string the ip address for receiving the command, default is localhost. """
ms_game = MSGame(board_width, board_height, num_mines, port=port, ip_add=ip_add) ms_app = QApplication([]) ms_window = QWidget() ms_window.setAutoFillBackground(True) ms_window.setWindowTitle("Mine Sweeper") ms_layout = QGridLayout() ms_window.setLayout(ms_layout) fun_wg = gui.ControlWidget() grid_wg = gui.GameWidget(ms_game, fun_wg) remote_thread = gui.RemoteControlThread() def update_grid_remote(move_msg): """Update grid from remote control.""" if grid_wg.ms_game.game_status == 2: grid_wg.ms_game.play_move_msg(str(move_msg)) grid_wg.update_grid() remote_thread.transfer.connect(update_grid_remote) def reset_button_state(): """Reset button state.""" grid_wg.reset_game() fun_wg.reset_button.clicked.connect(reset_button_state) ms_layout.addWidget(fun_wg, 0, 0) ms_layout.addWidget(grid_wg, 1, 0) remote_thread.control_start(grid_wg.ms_game) ms_window.show() ms_app.exec_()
<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_new_game(self, with_tcp=True): """Init a new game. Parameters board : MSBoard define a new board. game_status : int define the game status: 0: lose, 1: win, 2: playing moves : int how many moves carried out. """
self.board = self.create_board(self.board_width, self.board_height, self.num_mines) self.game_status = 2 self.num_moves = 0 self.move_history = [] if with_tcp is True: # init TCP communication. self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcp_socket.bind((self.TCP_IP, self.TCP_PORT)) self.tcp_socket.listen(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 check_move(self, move_type, move_x, move_y): """Check if a move is valid. If the move is not valid, then shut the game. If the move is valid, then setup a dictionary for the game, and update move counter. TODO: maybe instead of shut the game, can end the game or turn it into a valid move? Parameters move_type : string one of four move types: "click", "flag", "unflag", "question" move_x : int X position of the move move_y : int Y position of the move """
if move_type not in self.move_types: raise ValueError("This is not a valid move!") if move_x < 0 or move_x >= self.board_width: raise ValueError("This is not a valid X position of the move!") if move_y < 0 or move_y >= self.board_height: raise ValueError("This is not a valid Y position of the move!") move_des = {} move_des["move_type"] = move_type move_des["move_x"] = move_x move_des["move_y"] = move_y self.num_moves += 1 return move_des
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def play_move(self, move_type, move_x, move_y): """Updat board by a given move. Parameters move_type : string one of four move types: "click", "flag", "unflag", "question" move_x : int X position of the move move_y : int Y position of the move """
# record the move if self.game_status == 2: self.move_history.append(self.check_move(move_type, move_x, move_y)) else: self.end_game() # play the move, update the board if move_type == "click": self.board.click_field(move_x, move_y) elif move_type == "flag": self.board.flag_field(move_x, move_y) elif move_type == "unflag": self.board.unflag_field(move_x, move_y) elif move_type == "question": self.board.question_field(move_x, move_y) # check the status, see if end the game if self.board.check_board() == 0: self.game_status = 0 # game loses # self.print_board() self.end_game() elif self.board.check_board() == 1: self.game_status = 1 # game wins # self.print_board() self.end_game() elif self.board.check_board() == 2: self.game_status = 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 parse_move(self, move_msg): """Parse a move from a string. Parameters move_msg : string a valid message should be in: "[move type]: [X], [Y]" Returns ------- """
# TODO: some condition check type_idx = move_msg.index(":") move_type = move_msg[:type_idx] pos_idx = move_msg.index(",") move_x = int(move_msg[type_idx+1:pos_idx]) move_y = int(move_msg[pos_idx+1:]) return move_type, move_x, move_y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def play_move_msg(self, move_msg): """Another play move function for move message. Parameters move_msg : string a valid message should be in: "[move type]: [X], [Y]" """
move_type, move_x, move_y = self.parse_move(move_msg) self.play_move(move_type, move_x, move_y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tcp_accept(self): """Waiting for a TCP connection."""
self.conn, self.addr = self.tcp_socket.accept() print("[MESSAGE] The connection is established at: ", self.addr) self.tcp_send("> ")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tcp_receive(self): """Receive data from TCP port."""
data = self.conn.recv(self.BUFFER_SIZE) if type(data) != str: # Python 3 specific data = data.decode("utf-8") return str(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 init_board(self): """Init a valid board by given settings. Parameters mine_map : numpy.ndarray the map that defines the mine 0 is empty, 1 is mine info_map : numpy.ndarray the map that presents to gamer 0-8 is number of mines in srrounding. 9 is flagged field. 10 is questioned field. 11 is undiscovered field. 12 is a mine field. """
self.mine_map = np.zeros((self.board_height, self.board_width), dtype=np.uint8) idx_list = np.random.permutation(self.board_width*self.board_height) idx_list = idx_list[:self.num_mines] for idx in idx_list: idx_x = int(idx % self.board_width) idx_y = int(idx / self.board_width) self.mine_map[idx_y, idx_x] = 1 self.info_map = np.ones((self.board_height, self.board_width), dtype=np.uint8)*11
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def click_field(self, move_x, move_y): """Click one grid by given position."""
field_status = self.info_map[move_y, move_x] # can only click blank region if field_status == 11: if self.mine_map[move_y, move_x] == 1: self.info_map[move_y, move_x] = 12 else: # discover the region. self.discover_region(move_x, move_y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover_region(self, move_x, move_y): """Discover region from given location."""
field_list = deque([(move_y, move_x)]) while len(field_list) != 0: field = field_list.popleft() (tl_idx, br_idx, region_sum) = self.get_region(field[1], field[0]) if region_sum == 0: self.info_map[field[0], field[1]] = region_sum # get surrounding to queue region_mat = self.info_map[tl_idx[0]:br_idx[0]+1, tl_idx[1]:br_idx[1]+1] x_list, y_list = np.nonzero(region_mat == 11) for x_idx, y_idx in zip(x_list, y_list): field_temp = (x_idx+max(field[0]-1, 0), y_idx+max(field[1]-1, 0)) if field_temp not in field_list: field_list.append(field_temp) elif region_sum > 0: self.info_map[field[0], field[1]] = region_sum
<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_region(self, move_x, move_y): """Get region around a location."""
top_left = (max(move_y-1, 0), max(move_x-1, 0)) bottom_right = (min(move_y+1, self.board_height-1), min(move_x+1, self.board_width-1)) region_sum = self.mine_map[top_left[0]:bottom_right[0]+1, top_left[1]:bottom_right[1]+1].sum() return top_left, bottom_right, region_sum
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flag_field(self, move_x, move_y): """Flag a grid by given position."""
field_status = self.info_map[move_y, move_x] # a questioned or undiscovered field if field_status != 9 and (field_status == 10 or field_status == 11): self.info_map[move_y, move_x] = 9
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unflag_field(self, move_x, move_y): """Unflag or unquestion a grid by given position."""
field_status = self.info_map[move_y, move_x] if field_status == 9 or field_status == 10: self.info_map[move_y, move_x] = 11
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def question_field(self, move_x, move_y): """Question a grid by given position."""
field_status = self.info_map[move_y, move_x] # a questioned or undiscovered field if field_status != 10 and (field_status == 9 or field_status == 11): self.info_map[move_y, move_x] = 10
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_board(self): """Check the board status and give feedback."""
num_mines = np.sum(self.info_map == 12) num_undiscovered = np.sum(self.info_map == 11) num_questioned = np.sum(self.info_map == 10) if num_mines > 0: return 0 elif np.array_equal(self.info_map == 9, self.mine_map): return 1 elif num_undiscovered > 0 or num_questioned > 0: return 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 board_msg(self): """Structure a board as in print_board."""
board_str = "s\t\t" for i in xrange(self.board_width): board_str += str(i)+"\t" board_str = board_str.expandtabs(4)+"\n\n" for i in xrange(self.board_height): temp_line = str(i)+"\t\t" for j in xrange(self.board_width): if self.info_map[i, j] == 9: temp_line += "@\t" elif self.info_map[i, j] == 10: temp_line += "?\t" elif self.info_map[i, j] == 11: temp_line += "*\t" elif self.info_map[i, j] == 12: temp_line += "!\t" else: temp_line += str(self.info_map[i, j])+"\t" board_str += temp_line.expandtabs(4)+"\n" return board_str
<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_ui(self): """Setup control widget UI."""
self.control_layout = QHBoxLayout() self.setLayout(self.control_layout) self.reset_button = QPushButton() self.reset_button.setFixedSize(40, 40) self.reset_button.setIcon(QtGui.QIcon(WIN_PATH)) self.game_timer = QLCDNumber() self.game_timer.setStyleSheet("QLCDNumber {color: red;}") self.game_timer.setFixedWidth(100) self.move_counter = QLCDNumber() self.move_counter.setStyleSheet("QLCDNumber {color: red;}") self.move_counter.setFixedWidth(100) self.control_layout.addWidget(self.game_timer) self.control_layout.addWidget(self.reset_button) self.control_layout.addWidget(self.move_counter)
<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_ui(self): """Init game interface."""
board_width = self.ms_game.board_width board_height = self.ms_game.board_height self.create_grid(board_width, board_height) self.time = 0 self.timer = QtCore.QTimer() self.timer.timeout.connect(self.timing_game) self.timer.start(1000)
<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_grid(self, grid_width, grid_height): """Create a grid layout with stacked widgets. Parameters grid_width : int the width of the grid grid_height : int the height of the grid """
self.grid_layout = QGridLayout() self.setLayout(self.grid_layout) self.grid_layout.setSpacing(1) self.grid_wgs = {} for i in xrange(grid_height): for j in xrange(grid_width): self.grid_wgs[(i, j)] = FieldWidget() self.grid_layout.addWidget(self.grid_wgs[(i, j)], i, j)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timing_game(self): """Timing game."""
self.ctrl_wg.game_timer.display(self.time) self.time += 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 reset_game(self): """Reset game board."""
self.ms_game.reset_game() self.update_grid() self.time = 0 self.timer.start(1000)
<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_grid(self): """Update grid according to info map."""
info_map = self.ms_game.get_info_map() for i in xrange(self.ms_game.board_height): for j in xrange(self.ms_game.board_width): self.grid_wgs[(i, j)].info_label(info_map[i, j]) self.ctrl_wg.move_counter.display(self.ms_game.num_moves) if self.ms_game.game_status == 2: self.ctrl_wg.reset_button.setIcon(QtGui.QIcon(CONTINUE_PATH)) elif self.ms_game.game_status == 1: self.ctrl_wg.reset_button.setIcon(QtGui.QIcon(WIN_PATH)) self.timer.stop() elif self.ms_game.game_status == 0: self.ctrl_wg.reset_button.setIcon(QtGui.QIcon(LOSE_PATH)) self.timer.stop()