{"messages": [{"role": "user", "content": "Write Python code that implements formats.py from ataylor32/django (path: django/conf/locale/ml/formats.py)."}, {"role": "assistant", "content": "# django/conf/locale/ml/formats.py (from ataylor32/django, license: bsd-3-clause)\n\n# -*- encoding: utf-8 -*-\n# This file is distributed under the same license as the Django package.\n#\nfrom __future__ import unicode_literals\n\n# The *_FORMAT strings use the Django date format syntax,\n# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\nDATE_FORMAT = 'N j, Y'\nTIME_FORMAT = 'P'\nDATETIME_FORMAT = 'N j, Y, P'\nYEAR_MONTH_FORMAT = 'F Y'\nMONTH_DAY_FORMAT = 'F j'\nSHORT_DATE_FORMAT = 'm/d/Y'\nSHORT_DATETIME_FORMAT = 'm/d/Y P'\nFIRST_DAY_OF_WEEK = 0 # Sunday\n\n# The *_INPUT_FORMATS strings use the Python strftime format syntax,\n# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior\n# Kept ISO formats as they are in first position\nDATE_INPUT_FORMATS = [\n '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'\n # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'\n # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'\n # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'\n # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'\n]\nDATETIME_INPUT_FORMATS = [\n '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'\n '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200'\n '%Y-%m-%d %H:%M', # '2006-10-25 14:30'\n '%Y-%m-%d', # '2006-10-25'\n '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'\n '%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200'\n '%m/%d/%Y %H:%M', # '10/25/2006 14:30'\n '%m/%d/%Y', # '10/25/2006'\n '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'\n '%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200'\n '%m/%d/%y %H:%M', # '10/25/06 14:30'\n '%m/%d/%y', # '10/25/06'\n]\nDECIMAL_SEPARATOR = '.'\nTHOUSAND_SEPARATOR = ','\nNUMBER_GROUPING = 3"}]}
{"messages": [{"role": "user", "content": "Write Python code that implements piblinker.py from minosg/piblinker (path: piblinker.py)."}, {"role": "assistant", "content": "# piblinker.py (from minosg/piblinker, license: lgpl-2.1)\n\n#!/usr/bin/env python\n\n\"\"\"blinky.py: A small library that uses wiriping pi access to raspbery pi GPIO\n ports,aimed at providing a simple notification interface\"\"\"\n\n__author__ = \"minos197@gmail.com\"\n__license__ = \"LGPL\"\n__version__ = \"0.0.1\"\n__email__ = \"Minos Galanakis\"\n__project__ = \"smartpi\"\n__date__ = \"01-06-2015\"\n\nimport io\nimport time\nimport fcntl\nimport serial\nimport struct\nfrom subprocess import Popen, PIPE\nfrom colorlogger import CLogger\nfrom functools import wraps\nfrom pidaemon import start_daemon, kill_daemon, normal_start\n\ndef blinker(color, period=0.2, times=3):\n \"\"\" Decorator that allows modular output formating for PiLogger \"\"\"\n\n def blinker_decorator(func):\n @wraps(func)\n def func_wrapper(class_obj, message):\n # Blinke the LED before printing sdout\n class_obj.blink(color, times, period)\n return func(class_obj, color, message)\n return func_wrapper\n return blinker_decorator\n\nclass PiBlinkerError(Exception):\n __module__ = 'exceptions'\n\nclass PiBlinker():\n\n def __init__(self):\n raise ValueError('PiBlinker is not meant to be instantiated')\n\n @classmethod\n def setup(self,\n log_level=\"ver_debug\",\n log_label=\"PiBlinker\",\n log_path=None,\n log_colors=None):\n\n \"\"\" Module Init.\"\"\"\n # Map a color to GPIO.BCM PIN\n self.LEDS = {\"RED\": [17],\n \"GREEN\": [18],\n \"BLUE\": [27],\n \"PURPLE\": [17, 27],\n \"YELLOW\": [17, 18],\n \"CYAN\": [18, 27],\n \"WHITE\": [17, 18, 27]}\n\n self.last_mode = 0\n # Configure the GPIO ports in hardware\n map(self.run, [(x % v) for n in self.LEDS.values()\n for v in n\n for x in [\"gpio export %d out\",\n \"gpio -g mode %d out\"]])\n\n self.i2c_devices = {}\n\n # Assosiate log levels with colors\n if not log_colors:\n log_colors = {\"base_color\": \"CYAN\",\n \"info\": \"HBLUE\",\n \"warning\": \"YELLOW\",\n \"error\": \"RED\",\n \"debug\": \"GREEN\",\n \"ver_debug\": \"GREEN\"}\n\n # Initalise the logging module\n CLogger.setup(log_label, log_level, log_path, log_colors)\n return self\n\n @staticmethod\n def run(cmd):\n \"\"\" Execute shell command in detached mdoe.\"\"\"\n proc = Popen([cmd], stdout=PIPE, stderr=PIPE, shell=True)\n ret, err = proc.communicate()\n if err:\n # ignore warnings in error stream\n if \"Warning\" in err:\n CLogger.warning(err.strip())\n return err\n raise PiBlinkerError(err)\n else:\n return ret\n\n @classmethod\n def set_led(self, led, mode):\n \"\"\" Set an LED to one of the supported states.\"\"\"\n\n if led not in self.LEDS.keys():\n return\n mlist = {\"ON\": 1, \"OFF\": 0, \"Toggle\": -1}\n # convert input to a numerical mode\n try:\n md = mode if mode not in mlist\\\n else {k: v for k, v in mlist.iteritems()}[mode]\n except KeyError:\n raise PiBlinkerError(\"Mode %s is not reognised\" % mode)\n\n # Toggle the led if required\n led_state = md if md >= 0 else (self.last_mode + 1) % 2\n\n # Toggle the GPIO\n map(self.run, [\"gpio -g write %d %d\" % (led_no, led_state) for\n led_no in self.LEDS[led]])\n self.last_mode = led_state\n\n @classmethod\n def blink(self, led, times, delay=1):\n \"\"\" Blink an LED n number of times.\"\"\"\n\n # Make sure led is uppercase\n led = led.upper()\n if led not in self.LEDS.keys():\n return\n\n mode = 0\n count = 1\n while (count <= times * 2):\n self.set_led(led, mode)\n time.sleep(delay)\n mode = (mode + 1) % 2\n count += 1\n self.set_led(led, mode)\n\n @classmethod\n def led_print(self, color, text):\n \"\"\" Print a debug message and notify the user with the LED.\"\"\"\n\n eval(\"self.%s\" % color.lower())(text)\n\n @classmethod\n def led_bcast(self, data):\n \"\"\" Broadcast a number through led brings \"\"\"\n import re\n\n # separate the numbers in the string ie 192.168.3.1 will become array\n data = map(int, filter(lambda x: x, re.split(r'\\D', data)))\n\n # Separate the digits to a three color tuple\n data = map(lambda x: (x/100, (x % 100)/10, (x % 10)), data)\n\n for red_cnt, green_cnt, blue_cnt in data:\n self.blink(\"GREEN\", 1, 1)\n time.sleep(0.5)\n self.blink(\"RED\", red_cnt, 0.2)\n time.sleep(0.5)\n self.blink(\"GREEN\", green_cnt, 0.2)\n time.sleep(0.5)\n self.blink(\"BLUE\", blue_cnt, 0.2)\n time.sleep(0.5)\n self.blink(\"RED\", 1, 1)\n\n @classmethod\n @blinker(\"RED\")\n def red(self, *args):\n \"\"\" Print a debug message and notify the user with the LED.\"\"\"\n\n color, message = args\n print\"|%s|> %s\" % (color, message)\n\n @classmethod\n @blinker(\"GREEN\")\n def green(self, *args):\n \"\"\" Print a debug message and notify the user with the LED.\"\"\"\n\n color, message = args\n print\"|%s|> %s\" % (color, message)\n\n @classmethod\n @blinker(\"BLUE\")\n def blue(self, *args):\n \"\"\" Print a debug message and notify the user with the LED.\"\"\"\n\n color, message = args\n print\"|%s|> %s\" % (color, message)\n\n @classmethod\n @blinker(\"RED\")\n def error(self, *args):\n \"\"\" Print a debug message and notify the user with the LED.\"\"\"\n\n CLogger.error(args[-1])\n\n @classmethod\n @blinker(\"BLUE\")\n def info(self, *args):\n \"\"\" Print a debug message and notify the user with the LED.\"\"\"\n\n CLogger.info(args[-1])\n\n @classmethod\n @blinker(\"RED\")\n def warning(self, *args):\n \"\"\" Print a debug message and notify the user with the LED.\"\"\"\n\n CLogger.warning(args[-1])\n\n @classmethod\n @blinker(\"GREEN\")\n def debug(self, *args):\n \"\"\" Print a debug message and notify the user with the LED.\"\"\"\n\n CLogger.debug(args[-1])\n\n @classmethod\n def uart_open(self, port=\"/dev/ttyAMA0\", baud=9600, time_out=None):\n \"\"\"Open the Serial Channel\"\"\"\n\n try:\n self.uart = serial.Serial(port, baud, timeout=time_out)\n except serial.SerialException:\n print \"** Failed to initialize serial, check your port.** \"\n raise ValueError\n\n @classmethod\n def uart_activate(self):\n \"\"\" Spam UART port untill it receives an ACK \"\"\"\n\n self.uart_open()\n countr = 0\n # Test with a not supported command\n t_char = \"O\"\n while True:\n self.uart.write(t_char)\n if self.uart.inWaiting():\n repl = self.uart.read(2)\n if repl == \"OK\":\n print \"UART Activated\"\n else:\n print \"UART was already enabled\"\n break\n elif countr == 99:\n # Test with a supported command to see if activated\n t_char = \"2\"\n elif countr > 100:\n break\n\n time.sleep(0.05)\n countr += 1\n\n @classmethod\n def uart_read(self, target=\"ADC\"):\n \"\"\"Read the register through uart\"\"\"\n\n cmd = {\"ADC\": \"2\", \"PIN\": \"1\"}\n\n if target in cmd.keys():\n self.uart.write(cmd[target])\n return self.uart.readline()[:-1]\n\n @classmethod\n def uart_close(self):\n \"\"\"Close the serial channel\"\"\"\n self.uart.close()\n\n @classmethod\n def i2c_open_file(self, slave_id, bus=1):\n \"\"\"Open the I2C channel for raw byte comms\"\"\"\n\n if slave_id in self.i2c_devices.keys():\n print \"Device %d already open\" % slave_id\n return\n\n # Open the file descriptors\n read_ch = io.open(\"/dev/i2c-\"+str(bus), \"rb\", buffering=0)\n write_ch = io.open(\"/dev/i2c-\"+str(bus), \"wb\", buffering=0)\n\n # Set the register\n fcntl.ioctl(read_ch, 0x0703, slave_id)\n fcntl.ioctl(write_ch, 0x0703, slave_id)\n\n # store it to an internal dict\n self.i2c_devices[slave_id] = (read_ch, write_ch)\n # return the file descriptors if the user wants to manually drive them\n return (read_ch, write_ch)\n\n @classmethod\n def i2c_write_as(self, slave_id, format, data):\n \"\"\"Write the data formatted using struct pack,\n Format needs to be specified\"\"\"\n\n try:\n wb_file = self.i2c_devices[slave_id][1]\n wb_file.write(struct.pack(format, data))\n except KeyError:\n print \"Device %d does not exist\" % slave_id\n except struct.error:\n print \"Pack Error make sure the data fits the format structure\"\n except:\n raise IOError\n\n @classmethod\n def i2c_read_as(self, slave_id, format, byte_no):\n try:\n rb_file = self.i2c_devices[slave_id][0]\n return struct.unpack(format, rb_file.read(byte_no))\n except KeyError:\n print \"Device %d does not exit\" % slave_id\n except struct.error:\n print \"Pack Error make sure the data fits the format structure\"\n except:\n raise IOError\n\n @classmethod\n def i2c_close(self, slave_id):\n \"\"\"Close the file descriptors associated to the slave channel\"\"\"\n try:\n self.i2c_devices.pop(slave_id)\n except KeyError:\n print \"Device %d does not exit\" % slave_id\n\n @classmethod\n def demux(self, data):\n \"\"\" For efficiency purposes 10Bit ADC are muxed GPIO state.\"\"\"\n\n adc_val = data & 0x3FF\n pin_val = (data >> 15)\n return (adc_val, pin_val)\n\n @classmethod\n def i2c_read_adc(self, slave_id):\n \"\"\"Reads data as returned from a 10Bit ADC sampling operation\"\"\"\n\n return self.demux(self.i2c_read_as(slave_id, '>H', 2)[0])[0]\n\n @classmethod\n def i2c_read_pin(self, slave_id):\n \"\"\"Reads data as returned from a 10Bit ADC sampling operation\"\"\"\n\n return self.demux(self.i2c_read_as(slave_id, '>H', 2)[0])[1]\n\n @classmethod\n def test_hardware(self):\n \"\"\" Detect hardware shield's presense \"\"\"\n\n detected = False\n\n try:\n self.uart_open(time_out=2)\n reading = self.uart_read(\"ADC\")\n if len(reading):\n detected = True\n except:\n pass\n try:\n readf, writef = self.i2c_open_file(0x04, 1)\n self.i2c_read_as(04, \">H\", 2)\n self.i2c_close(0x04)\n detected = True\n except:\n pass\n return detected\n\nif __name__ == \"__main__\":\n\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-t\", \"--test\", help=\"Test Hardware, select from [all,\\\n i2c, led, log, poll, uart]\", dest='test')\n parser.add_argument(\"-a\", \"--activate\", help=\"Activate UART mode\\\n after a reset\", action=\"store_true\")\n parser.add_argument(\"-d\", \"--daemon\", help=\"Start a button monitor daemon\",\n action=\"store_true\")\n parser.add_argument(\"-nd\", \"--nodaemon\", help=\"Start monitor without\\\n daemon context used in conjuction with wrappers\",\n action=\"store_true\")\n parser.add_argument(\"-b1\", \"--button1\", help=\"Bind script to button1\",\n dest='button1')\n parser.add_argument(\"-b2\", \"--button2\", help=\"Bind script to button2\",\n dest='button2')\n parser.add_argument(\"-u\", \"--user\", help=\"Select different user\\\n to run script as\")\n parser.add_argument(\"-s\", \"--sudopass\", help=\"Set optional sudo password\\\n for elevated priviledges\")\n parser.add_argument(\"-k\", \"--kill\", help=\"increase output verbosity\",\n action=\"store_true\")\n parser.add_argument(\"-i\", \"--blinkip\", help=\"increase output verbosity\",\n action=\"store_true\")\n\n args = parser.parse_args()\n mode = 0\n pb = PiBlinker.setup()\n if args.daemon or args.nodaemon:\n arguments = [args.button1, args.button2, args.user, args.sudopass]\n if args.nodaemon:\n normal_start(*arguments)\n else:\n start_daemon(*arguments)\n elif args.kill:\n kill_daemon()\n elif args.activate:\n pb.uart_activate()\n elif args.blinkip:\n pb.led_bcast(pb.run(\"hostname -I\"))\n elif args.test:\n if args.test == \"all\":\n pb.red(\"This is important\")\n pb.green(\"This worked\")\n pb.blue(\"This you should know\")\n\n readf, writef = pb.i2c_open_file(0x04, 1)\n # read two bytes using the direct file descriptor\n print \"|RAW ADC|>\", repr(readf.read(2))\n\n # read a 2byte uint8_t variable\n print \"|DEC ADC|>\", pb.i2c_read_as(04, \">H\", 2)[0]\n pb.i2c_close(0x04)\n\n pb.info(\"This is an info\")\n pb.warning(\"This is a warning\")\n pb.error(\"This is an error\")\n pb.debug(\"This is debug\")\n\n elif args.test == \"i2c\":\n readf, writef = pb.i2c_open_file(0x04, 1)\n\n # read two bytes using the direct file descriptor\n print \"|RAW ADC|>\", repr(readf.read(2))\n\n # read a 2byte uint8_t variable\n print \"|DEC ADC|>\", pb.i2c_read_as(04, \">H\", 2)[0]\n pb.i2c_close(0x04)\n\n elif args.test == \"poll\":\n\n readf, writef = pb.i2c_open_file(0x04, 1)\n try:\n while True:\n\n # Read using read ADC\n print \"| ADC:\", pb.i2c_read_adc(0x04), \"| PIN: \",\\\n pb.i2c_read_pin(0x04), \"|\"\n time.sleep(0.2)\n except KeyboardInterrupt:\n pass\n pb.i2c_close(0x04)\n\n elif args.test == \"uart\":\n pb.uart_open()\n print \"ADC:\", pb.uart_read(\"ADC\")\n print \"PIN:\", pb.uart_read(\"PIN\")\n pb.uart_close()\n\n elif args.test == \"led\":\n pb.led_print(\"RED\", \"This is RED\")\n pb.led_print(\"GREEN\", \"This is GREEN\")\n pb.led_print(\"BLUE\", \"This is BLUE\")\n\n elif args.test == \"log\":\n pb.info(\"This is an info\")\n pb.warning(\"This is a warning\")\n pb.error(\"This is an error\")\n pb.debug(\"This is debug\")\n\n else:\n parser.print_help()"}]}
{"messages": [{"role": "user", "content": "Write Python code that implements _reflect.py from pyblish/pyblish-starter (path: pyblish_starter/vendor/jsonschema/_reflect.py)."}, {"role": "assistant", "content": "# pyblish_starter/vendor/jsonschema/_reflect.py (from pyblish/pyblish-starter, license: mit)\n\n# -*- test-case-name: twisted.test.test_reflect -*-\n# Copyright (c) Twisted Matrix Laboratories.\n# See LICENSE for details.\n\n\"\"\"\nStandardized versions of various cool and/or strange things that you can do\nwith Python's reflection capabilities.\n\"\"\"\n\nimport sys\n\nfrom .compat import PY3\n\nclass _NoModuleFound(Exception):\n \"\"\"\n No module was found because none exists.\n \"\"\"\n\nclass InvalidName(ValueError):\n \"\"\"\n The given name is not a dot-separated list of Python objects.\n \"\"\"\n\nclass ModuleNotFound(InvalidName):\n \"\"\"\n The module associated with the given name doesn't exist and it can't be\n imported.\n \"\"\"\n\nclass ObjectNotFound(InvalidName):\n \"\"\"\n The object associated with the given name doesn't exist and it can't be\n imported.\n \"\"\"\n\nif PY3:\n def reraise(exception, traceback):\n raise exception.with_traceback(traceback)\nelse:\n exec(\"\"\"def reraise(exception, traceback):\n raise exception.__class__, exception, traceback\"\"\")\n\nreraise.__doc__ = \"\"\"\nRe-raise an exception, with an optional traceback, in a way that is compatible\nwith both Python 2 and Python 3.\n\nNote that on Python 3, re-raised exceptions will be mutated, with their\nC{__traceback__} attribute being set.\n\n@param exception: The exception instance.\n@param traceback: The traceback to use, or C{None} indicating a new traceback.\n\"\"\"\n\ndef _importAndCheckStack(importName):\n \"\"\"\n Import the given name as a module, then walk the stack to determine whether\n the failure was the module not existing, or some code in the module (for\n example a dependent import) failing. This can be helpful to determine\n whether any actual application code was run. For example, to distiguish\n administrative error (entering the wrong module name), from programmer\n error (writing buggy code in a module that fails to import).\n\n @param importName: The name of the module to import.\n @type importName: C{str}\n @raise Exception: if something bad happens. This can be any type of\n exception, since nobody knows what loading some arbitrary code might\n do.\n @raise _NoModuleFound: if no module was found.\n \"\"\"\n try:\n return __import__(importName)\n except ImportError:\n excType, excValue, excTraceback = sys.exc_info()\n while excTraceback:\n execName = excTraceback.tb_frame.f_globals[\"__name__\"]\n # in Python 2 execName is None when an ImportError is encountered,\n # where in Python 3 execName is equal to the importName.\n if execName is None or execName == importName:\n reraise(excValue, excTraceback)\n excTraceback = excTraceback.tb_next\n raise _NoModuleFound()\n\ndef namedAny(name):\n \"\"\"\n Retrieve a Python object by its fully qualified name from the global Python\n module namespace. The first part of the name, that describes a module,\n will be discovered and imported. Each subsequent part of the name is\n treated as the name of an attribute of the object specified by all of the\n name which came before it. For example, the fully-qualified name of this\n object is 'twisted.python.reflect.namedAny'.\n\n @type name: L{str}\n @param name: The name of the object to return.\n\n @raise InvalidName: If the name is an empty string, starts or ends with\n a '.', or is otherwise syntactically incorrect.\n\n @raise ModuleNotFound: If the name is syntactically correct but the\n module it specifies cannot be imported because it does not appear to\n exist.\n\n @raise ObjectNotFound: If the name is syntactically correct, includes at\n least one '.', but the module it specifies cannot be imported because\n it does not appear to exist.\n\n @raise AttributeError: If an attribute of an object along the way cannot be\n accessed, or a module along the way is not found.\n\n @return: the Python object identified by 'name'.\n \"\"\"\n if not name:\n raise InvalidName('Empty module name')\n\n names = name.split('.')\n\n # if the name starts or ends with a '.' or contains '..', the __import__\n # will raise an 'Empty module name' error. This will provide a better error\n # message.\n if '' in names:\n raise InvalidName(\n \"name must be a string giving a '.'-separated list of Python \"\n \"identifiers, not %r\" % (name,))\n\n topLevelPackage = None\n moduleNames = names[:]\n while not topLevelPackage:\n if moduleNames:\n trialname = '.'.join(moduleNames)\n try:\n topLevelPackage = _importAndCheckStack(trialname)\n except _NoModuleFound:\n moduleNames.pop()\n else:\n if len(names) == 1:\n raise ModuleNotFound(\"No module named %r\" % (name,))\n else:\n raise ObjectNotFound('%r does not name an object' % (name,))\n\n obj = topLevelPackage\n for n in names[1:]:\n obj = getattr(obj, n)\n\n return obj"}]}
{"messages": [{"role": "user", "content": "Write Python code that implements configHandler.py from Balannen/LSMASOMM (path: atom3/Kernel/ColoredText/configHandler.py)."}, {"role": "assistant", "content": "# atom3/Kernel/ColoredText/configHandler.py (from Balannen/LSMASOMM, license: gpl-3.0)\n\n\"\"\"Provides access to stored IDLE configuration information.\n\nRefer to the comments at the beginning of config-main.def for a description of\nthe available configuration files and the design implemented to update user\nconfiguration information. In particular, user configuration choices which\nduplicate the defaults will be removed from the user's configuration files,\nand if a file becomes empty, it will be deleted.\n\nThe contents of the user files may be altered using the Options/Configure IDLE\nmenu to access the configuration GUI (configDialog.py), or manually.\n\nThroughout this module there is an emphasis on returning useable defaults\nwhen a problem occurs in returning a requested configuration value back to\nidle. This is to allow IDLE to continue to function in spite of errors in\nthe retrieval of config information. When a default is returned instead of\na requested config value, a message is printed to stderr to aid in\nconfiguration problem notification and resolution.\n\n\"\"\"\nimport os\nimport sys\nimport string\nfrom ConfigParser import ConfigParser, NoOptionError, NoSectionError\n\nclass InvalidConfigType(Exception): pass\nclass InvalidConfigSet(Exception): pass\nclass InvalidFgBg(Exception): pass\nclass InvalidTheme(Exception): pass\n\nclass IdleConfParser(ConfigParser):\n \"\"\"\n A ConfigParser specialised for idle configuration file handling\n \"\"\"\n def __init__(self, cfgFile, cfgDefaults=None):\n \"\"\"\n cfgFile - string, fully specified configuration file name\n \"\"\"\n self.file=cfgFile\n ConfigParser.__init__(self,defaults=cfgDefaults)\n\n def Get(self, section, option, type=None, default=None):\n \"\"\"\n Get an option value for given section/option or return default.\n If type is specified, return as type.\n \"\"\"\n if type=='bool':\n getVal=self.getboolean\n elif type=='int':\n getVal=self.getint\n else:\n getVal=self.get\n if self.has_option(section,option):\n #return getVal(section, option, raw, vars, default)\n return getVal(section, option)\n else:\n return default\n\n def GetOptionList(self,section):\n \"\"\"\n Get an option list for given section\n \"\"\"\n if self.has_section(section):\n return self.options(section)\n else: #return a default value\n return []\n\n def Load(self):\n \"\"\"\n Load the configuration file from disk\n \"\"\"\n self.read(self.file)\n\nclass IdleUserConfParser(IdleConfParser):\n \"\"\"\n IdleConfigParser specialised for user configuration handling.\n \"\"\"\n\n def AddSection(self,section):\n \"\"\"\n if section doesn't exist, add it\n \"\"\"\n if not self.has_section(section):\n self.add_section(section)\n\n def RemoveEmptySections(self):\n \"\"\"\n remove any sections that have no options\n \"\"\"\n for section in self.sections():\n if not self.GetOptionList(section):\n self.remove_section(section)\n\n def IsEmpty(self):\n \"\"\"\n Remove empty sections and then return 1 if parser has no sections\n left, else return 0.\n \"\"\"\n self.RemoveEmptySections()\n if self.sections():\n return 0\n else:\n return 1\n\n def RemoveOption(self,section,option):\n \"\"\"\n If section/option exists, remove it.\n Returns 1 if option was removed, 0 otherwise.\n \"\"\"\n if self.has_section(section):\n return self.remove_option(section,option)\n\n def SetOption(self,section,option,value):\n \"\"\"\n Sets option to value, adding section if required.\n Returns 1 if option was added or changed, otherwise 0.\n \"\"\"\n if self.has_option(section,option):\n if self.get(section,option)==value:\n return 0\n else:\n self.set(section,option,value)\n return 1\n else:\n if not self.has_section(section):\n self.add_section(section)\n self.set(section,option,value)\n return 1\n\n def RemoveFile(self):\n \"\"\"\n Removes the user config file from disk if it exists.\n \"\"\"\n if os.path.exists(self.file):\n os.remove(self.file)\n\n def Save(self):\n \"\"\"Update user configuration file.\n\n Remove empty sections. If resulting config isn't empty, write the file\n to disk. If config is empty, remove the file from disk if it exists.\n\n \"\"\"\n if not self.IsEmpty():\n cfgFile=open(self.file,'w')\n self.write(cfgFile)\n else:\n self.RemoveFile()\n\nclass IdleConf:\n \"\"\"\n holds config parsers for all idle config files:\n default config files\n (idle install dir)/config-main.def\n (idle install dir)/config-extensions.def\n (idle install dir)/config-highlight.def\n (idle install dir)/config-keys.def\n user config files\n (user home dir)/.idlerc/config-main.cfg\n (user home dir)/.idlerc/config-extensions.cfg\n (user home dir)/.idlerc/config-highlight.cfg\n (user home dir)/.idlerc/config-keys.cfg\n \"\"\"\n def __init__(self):\n self.defaultCfg={}\n self.userCfg={}\n self.cfg={}\n self.CreateConfigHandlers()\n self.LoadCfgFiles()\n #self.LoadCfg()\n\n def CreateConfigHandlers(self):\n \"\"\"\n set up a dictionary of config parsers for default and user\n configurations respectively\n \"\"\"\n #build idle install path\n if __name__ != '__main__': # we were imported\n idleDir=os.path.dirname(__file__)\n else: # we were exec'ed (for testing only)\n idleDir=os.path.abspath(sys.path[0])\n userDir=self.GetUserCfgDir()\n configTypes=('main','extensions','highlight','keys')\n defCfgFiles={}\n usrCfgFiles={}\n for cfgType in configTypes: #build config file names\n defCfgFiles[cfgType]=os.path.join(idleDir,'config-'+cfgType+'.def')\n usrCfgFiles[cfgType]=os.path.join(userDir,'config-'+cfgType+'.cfg')\n for cfgType in configTypes: #create config parsers\n self.defaultCfg[cfgType]=IdleConfParser(defCfgFiles[cfgType])\n self.userCfg[cfgType]=IdleUserConfParser(usrCfgFiles[cfgType])\n\n def GetUserCfgDir(self):\n \"\"\"\n Creates (if required) and returns a filesystem directory for storing\n user config files.\n \"\"\"\n cfgDir='.idlerc'\n userDir=os.path.expanduser('~')\n if userDir != '~': #'HOME' exists as a key in os.environ\n if not os.path.exists(userDir):\n warn=('\\n Warning: HOME environment variable points to\\n '+\n userDir+'\\n but the path does not exist.\\n')\n sys.stderr.write(warn)\n userDir='~'\n if userDir=='~': #we still don't have a home directory\n #traditionally idle has defaulted to os.getcwd(), is this adeqate?\n userDir = os.getcwd() #hack for no real homedir\n userDir=os.path.join(userDir,cfgDir)\n if not os.path.exists(userDir):\n try: #make the config dir if it doesn't exist yet\n os.mkdir(userDir)\n except IOError:\n warn=('\\n Warning: unable to create user config directory\\n '+\n userDir+'\\n')\n sys.stderr.write(warn)\n return userDir\n\n def GetOption(self, configType, section, option, default=None, type=None):\n \"\"\"\n Get an option value for given config type and given general\n configuration section/option or return a default. If type is specified,\n return as type. Firstly the user configuration is checked, with a\n fallback to the default configuration, and a final 'catch all'\n fallback to a useable passed-in default if the option isn't present in\n either the user or the default configuration.\n configType must be one of ('main','extensions','highlight','keys')\n If a default is returned a warning is printed to stderr.\n \"\"\"\n if self.userCfg[configType].has_option(section,option):\n return self.userCfg[configType].Get(section, option, type=type)\n elif self.defaultCfg[configType].has_option(section,option):\n return self.defaultCfg[configType].Get(section, option, type=type)\n else: #returning default, print warning\n warning=('\\n Warning: configHandler.py - IdleConf.GetOption -\\n'+\n ' problem retrieving configration option '+`option`+'\\n'+\n ' from section '+`section`+'.\\n'+\n ' returning default value: '+`default`+'\\n')\n sys.stderr.write(warning)\n return default\n\n def GetSectionList(self, configSet, configType):\n \"\"\"\n Get a list of sections from either the user or default config for\n the given config type.\n configSet must be either 'user' or 'default'\n configType must be one of ('main','extensions','highlight','keys')\n \"\"\"\n if not (configType in ('main','extensions','highlight','keys')):\n raise InvalidConfigType, 'Invalid configType specified'\n if configSet == 'user':\n cfgParser=self.userCfg[configType]\n elif configSet == 'default':\n cfgParser=self.defaultCfg[configType]\n else:\n raise InvalidConfigSet, 'Invalid configSet specified'\n return cfgParser.sections()\n\n def GetHighlight(self, theme, element, fgBg=None):\n \"\"\"\n return individual highlighting theme elements.\n fgBg - string ('fg'or'bg') or None, if None return a dictionary\n containing fg and bg colours (appropriate for passing to Tkinter in,\n e.g., a tag_config call), otherwise fg or bg colour only as specified.\n \"\"\"\n if self.defaultCfg['highlight'].has_section(theme):\n themeDict=self.GetThemeDict('default',theme)\n else:\n themeDict=self.GetThemeDict('user',theme)\n fore=themeDict[element+'-foreground']\n if element=='cursor': #there is no config value for cursor bg\n back=themeDict['normal-background']\n else:\n back=themeDict[element+'-background']\n highlight={\"foreground\": fore,\"background\": back}\n if not fgBg: #return dict of both colours\n return highlight\n else: #return specified colour only\n if fgBg == 'fg':\n return highlight[\"foreground\"]\n if fgBg == 'bg':\n return highlight[\"background\"]\n else:\n raise InvalidFgBg, 'Invalid fgBg specified'\n\n def GetThemeDict(self,type,themeName):\n \"\"\"\n type - string, 'default' or 'user' theme type\n themeName - string, theme name\n Returns a dictionary which holds {option:value} for each element\n in the specified theme. Values are loaded over a set of ultimate last\n fallback defaults to guarantee that all theme elements are present in\n a newly created theme.\n \"\"\"\n if type == 'user':\n cfgParser=self.userCfg['highlight']\n elif type == 'default':\n cfgParser=self.defaultCfg['highlight']\n else:\n raise InvalidTheme, 'Invalid theme type specified'\n #foreground and background values are provded for each theme element\n #(apart from cursor) even though all these values are not yet used\n #by idle, to allow for their use in the future. Default values are\n #generally black and white.\n theme={ 'normal-foreground':'#000000',\n 'normal-background':'#ffffff',\n 'keyword-foreground':'#000000',\n 'keyword-background':'#ffffff',\n 'comment-foreground':'#000000',\n 'comment-background':'#ffffff',\n 'string-foreground':'#000000',\n 'string-background':'#ffffff',\n 'definition-foreground':'#000000',\n 'definition-background':'#ffffff',\n 'hilite-foreground':'#000000',\n 'hilite-background':'gray',\n 'break-foreground':'#ffffff',\n 'break-background':'#000000',\n 'hit-foreground':'#ffffff',\n 'hit-background':'#000000',\n 'error-foreground':'#ffffff',\n 'error-background':'#000000',\n #cursor (only foreground can be set)\n 'cursor-foreground':'#000000',\n #shell window\n 'stdout-foreground':'#000000',\n 'stdout-background':'#ffffff',\n 'stderr-foreground':'#000000',\n 'stderr-background':'#ffffff',\n 'console-foreground':'#000000',\n 'console-background':'#ffffff' }\n for element in theme.keys():\n if not cfgParser.has_option(themeName,element):\n #we are going to return a default, print warning\n warning=('\\n Warning: configHandler.py - IdleConf.GetThemeDict'+\n ' -\\n problem retrieving theme element '+`element`+\n '\\n from theme '+`themeName`+'.\\n'+\n ' returning default value: '+`theme[element]`+'\\n')\n sys.stderr.write(warning)\n colour=cfgParser.Get(themeName,element,default=theme[element])\n theme[element]=colour\n return theme\n\n def CurrentTheme(self):\n \"\"\"\n Returns the name of the currently active theme\n \"\"\"\n return self.GetOption('main','Theme','name',default='')\n\n def CurrentKeys(self):\n \"\"\"\n Returns the name of the currently active key set\n \"\"\"\n return self.GetOption('main','Keys','name',default='')\n\n def GetExtensions(self, activeOnly=1):\n \"\"\"\n Gets a list of all idle extensions declared in the config files.\n activeOnly - boolean, if true only return active (enabled) extensions\n \"\"\"\n extns=self.RemoveKeyBindNames(\n self.GetSectionList('default','extensions'))\n userExtns=self.RemoveKeyBindNames(\n self.GetSectionList('user','extensions'))\n for extn in userExtns:\n if extn not in extns: #user has added own extension\n extns.append(extn)\n if activeOnly:\n activeExtns=[]\n for extn in extns:\n if self.GetOption('extensions',extn,'enable',default=1,\n type='bool'):\n #the extension is enabled\n activeExtns.append(extn)\n return activeExtns\n else:\n return extns\n\n def RemoveKeyBindNames(self,extnNameList):\n #get rid of keybinding section names\n names=extnNameList\n kbNameIndicies=[]\n for name in names:\n if name.endswith('_bindings') or name.endswith('_cfgBindings'):\n kbNameIndicies.append(names.index(name))\n kbNameIndicies.sort()\n kbNameIndicies.reverse()\n for index in kbNameIndicies: #delete each keybinding section name\n del(names[index])\n return names\n\n def GetExtnNameForEvent(self,virtualEvent):\n \"\"\"\n Returns the name of the extension that virtualEvent is bound in, or\n None if not bound in any extension.\n virtualEvent - string, name of the virtual event to test for, without\n the enclosing '<< >>'\n \"\"\"\n extName=None\n vEvent='<<'+virtualEvent+'>>'\n for extn in self.GetExtensions(activeOnly=0):\n for event in self.GetExtensionKeys(extn).keys():\n if event == vEvent:\n extName=extn\n return extName\n\n def GetExtensionKeys(self,extensionName):\n \"\"\"\n returns a dictionary of the configurable keybindings for a particular\n extension,as they exist in the dictionary returned by GetCurrentKeySet;\n that is, where previously used bindings are disabled.\n \"\"\"\n keysName=extensionName+'_cfgBindings'\n activeKeys=self.GetCurrentKeySet()\n extKeys={}\n if self.defaultCfg['extensions'].has_section(keysName):\n eventNames=self.defaultCfg['extensions'].GetOptionList(keysName)\n for eventName in eventNames:\n event='<<'+eventName+'>>'\n binding=activeKeys[event]\n extKeys[event]=binding\n return extKeys\n\n def __GetRawExtensionKeys(self,extensionName):\n \"\"\"\n returns a dictionary of the configurable keybindings for a particular\n extension, as defined in the configuration files, or an empty dictionary\n if no bindings are found\n \"\"\"\n keysName=extensionName+'_cfgBindings'\n extKeys={}\n if self.defaultCfg['extensions'].has_section(keysName):\n eventNames=self.defaultCfg['extensions'].GetOptionList(keysName)\n for eventName in eventNames:\n binding=self.GetOption('extensions',keysName,\n eventName,default='').split()\n event='<<'+eventName+'>>'\n extKeys[event]=binding\n return extKeys\n\n def GetExtensionBindings(self,extensionName):\n \"\"\"\n Returns a dictionary of all the event bindings for a particular\n extension. The configurable keybindings are returned as they exist in\n the dictionary returned by GetCurrentKeySet; that is, where re-used\n keybindings are disabled.\n \"\"\"\n bindsName=extensionName+'_bindings'\n extBinds=self.GetExtensionKeys(extensionName)\n #add the non-configurable bindings\n if self.defaultCfg['extensions'].has_section(bindsName):\n eventNames=self.defaultCfg['extensions'].GetOptionList(bindsName)\n for eventName in eventNames:\n binding=self.GetOption('extensions',bindsName,\n eventName,default='').split()\n event='<<'+eventName+'>>'\n extBinds[event]=binding\n\n return extBinds\n\n def GetKeyBinding(self, keySetName, eventStr):\n \"\"\"\n returns the keybinding for a specific event.\n keySetName - string, name of key binding set\n eventStr - string, the virtual event we want the binding for,\n represented as a string, eg. '<{{ varvalue }}
{% endif %}'\n>>> t = template.Template(s)\n\n(t is now a compiled template, and its render() method can be called multiple\ntimes with multiple contexts)\n\n>>> c = template.Context({'test':True, 'varvalue': 'Hello'})\n>>> t.render(c)\nu'Hello
'\n>>> c = template.Context({'test':False, 'varvalue': 'Hello'})\n>>> t.render(c)\nu''\n\"\"\"\n\n# Template lexing symbols\nfrom django.template.base import (ALLOWED_VARIABLE_CHARS, BLOCK_TAG_END,\n BLOCK_TAG_START, COMMENT_TAG_END, COMMENT_TAG_START,\n FILTER_ARGUMENT_SEPARATOR, FILTER_SEPARATOR, SINGLE_BRACE_END,\n SINGLE_BRACE_START, TOKEN_BLOCK, TOKEN_COMMENT, TOKEN_TEXT, TOKEN_VAR,\n TRANSLATOR_COMMENT_MARK, UNKNOWN_SOURCE, VARIABLE_ATTRIBUTE_SEPARATOR,\n VARIABLE_TAG_END, VARIABLE_TAG_START, filter_re, tag_re)\n\n# Exceptions\nfrom django.template.base import (ContextPopException, InvalidTemplateLibrary,\n TemplateDoesNotExist, TemplateEncodingError, TemplateSyntaxError,\n VariableDoesNotExist)\n\n# Template parts\nfrom django.template.base import (Context, FilterExpression, Lexer, Node,\n NodeList, Parser, RequestContext, Origin, StringOrigin, Template,\n TextNode, Token, TokenParser, Variable, VariableNode, constant_string,\n filter_raw_string)\n\n# Compiling templates\nfrom django.template.base import (compile_string, resolve_variable,\n unescape_string_literal, generic_tag_compiler)\n\n# Library management\nfrom django.template.base import (Library, add_to_builtins, builtins,\n get_library, get_templatetags_modules, get_text_list, import_library,\n libraries)\n\n__all__ = ('Template', 'Context', 'RequestContext', 'compile_string')"}]}
{"messages": [{"role": "user", "content": "Write Python code that implements basic_ftpd.py from leiferikb/bitpop (path: src/third_party/pyftpdlib/src/demo/basic_ftpd.py)."}, {"role": "assistant", "content": "# src/third_party/pyftpdlib/src/demo/basic_ftpd.py (from leiferikb/bitpop, license: gpl-3.0)\n\n#!/usr/bin/env python\n# $Id: basic_ftpd.py 977 2012-01-22 23:05:09Z g.rodola $\n\n# pyftpdlib is released under the MIT license, reproduced below:\n# ======================================================================\n# Copyright (C) 2007-2012 Giampaolo Rodola'