{"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. '<>'\n \"\"\"\n eventName=eventStr[2:-2] #trim off the angle brackets\n binding=self.GetOption('keys',keySetName,eventName,default='').split()\n return binding\n\n def GetCurrentKeySet(self):\n return self.GetKeySet(self.CurrentKeys())\n\n def GetKeySet(self,keySetName):\n \"\"\"\n Returns a dictionary of: all requested core keybindings, plus the\n keybindings for all currently active extensions. If a binding defined\n in an extension is already in use, that binding is disabled.\n \"\"\"\n keySet=self.GetCoreKeys(keySetName)\n activeExtns=self.GetExtensions(activeOnly=1)\n for extn in activeExtns:\n extKeys=self.__GetRawExtensionKeys(extn)\n if extKeys: #the extension defines keybindings\n for event in extKeys.keys():\n if extKeys[event] in keySet.values():\n #the binding is already in use\n extKeys[event]='' #disable this binding\n keySet[event]=extKeys[event] #add binding\n return keySet\n\n def IsCoreBinding(self,virtualEvent):\n \"\"\"\n returns true if the virtual event is bound in the core idle keybindings.\n virtualEvent - string, name of the virtual event to test for, without\n the enclosing '<< >>'\n \"\"\"\n return ('<<'+virtualEvent+'>>') in self.GetCoreKeys().keys()\n\n def GetCoreKeys(self, keySetName=None):\n \"\"\"\n returns the requested set of core keybindings, with fallbacks if\n required.\n Keybindings loaded from the config file(s) are loaded _over_ these\n defaults, so if there is a problem getting any core binding there will\n be an 'ultimate last resort fallback' to the CUA-ish bindings\n defined here.\n \"\"\"\n keyBindings={\n '<>': ['', ''],\n '<>': ['', ''],\n '<>': ['', ''],\n '<>': ['', ''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': ['', ''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [' '],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': [''],\n '<>': ['']\n }\n if keySetName:\n for event in keyBindings.keys():\n binding=self.GetKeyBinding(keySetName,event)\n if binding:\n keyBindings[event]=binding\n else: #we are going to return a default, print warning\n warning=('\\n Warning: configHandler.py - IdleConf.GetCoreKeys'+\n ' -\\n problem retrieving key binding for event '+\n `event`+'\\n from key set '+`keySetName`+'.\\n'+\n ' returning default value: '+`keyBindings[event]`+'\\n')\n sys.stderr.write(warning)\n return keyBindings\n\n def GetExtraHelpSourceList(self,configSet):\n \"\"\"Fetch list of extra help sources from a given configSet.\n\n Valid configSets are 'user' or 'default'. Return a list of tuples of\n the form (menu_item , path_to_help_file , option), or return the empty\n list. 'option' is the sequence number of the help resource. 'option'\n values determine the position of the menu items on the Help menu,\n therefore the returned list must be sorted by 'option'.\n\n \"\"\"\n helpSources=[]\n if configSet=='user':\n cfgParser=self.userCfg['main']\n elif configSet=='default':\n cfgParser=self.defaultCfg['main']\n else:\n raise InvalidConfigSet, 'Invalid configSet specified'\n options=cfgParser.GetOptionList('HelpFiles')\n for option in options:\n value=cfgParser.Get('HelpFiles',option,default=';')\n if value.find(';')==-1: #malformed config entry with no ';'\n menuItem='' #make these empty\n helpPath='' #so value won't be added to list\n else: #config entry contains ';' as expected\n value=string.split(value,';')\n menuItem=value[0].strip()\n helpPath=value[1].strip()\n if menuItem and helpPath: #neither are empty strings\n helpSources.append( (menuItem,helpPath,option) )\n helpSources.sort(self.__helpsort)\n return helpSources\n\n def __helpsort(self, h1, h2):\n if int(h1[2]) < int(h2[2]):\n return -1\n elif int(h1[2]) > int(h2[2]):\n return 1\n else:\n return 0\n\n def GetAllExtraHelpSourcesList(self):\n \"\"\"\n Returns a list of tuples containing the details of all additional help\n sources configured, or an empty list if there are none. Tuples are of\n the format returned by GetExtraHelpSourceList.\n \"\"\"\n allHelpSources=( self.GetExtraHelpSourceList('default')+\n self.GetExtraHelpSourceList('user') )\n return allHelpSources\n\n def LoadCfgFiles(self):\n \"\"\"\n load all configuration files.\n \"\"\"\n for key in self.defaultCfg.keys():\n self.defaultCfg[key].Load()\n self.userCfg[key].Load() #same keys\n\n def SaveUserCfgFiles(self):\n \"\"\"\n write all loaded user configuration files back to disk\n \"\"\"\n for key in self.userCfg.keys():\n self.userCfg[key].Save()\n\nidleConf=IdleConf()\n\n### module test\nif __name__ == '__main__':\n def dumpCfg(cfg):\n print '\\n',cfg,'\\n'\n for key in cfg.keys():\n sections=cfg[key].sections()\n print key\n print sections\n for section in sections:\n options=cfg[key].options(section)\n print section\n print options\n for option in options:\n print option, '=', cfg[key].Get(section,option)\n dumpCfg(idleConf.defaultCfg)\n dumpCfg(idleConf.userCfg)\n print idleConf.userCfg['main'].Get('Theme','name')\n #print idleConf.userCfg['highlight'].GetDefHighlight('Foo','normal')"}]} {"messages": [{"role": "user", "content": "Write Python code that implements artifact.py from square/pants (path: src/python/pants/cache/artifact.py)."}, {"role": "assistant", "content": "# src/python/pants/cache/artifact.py (from square/pants, license: apache-2.0)\n\n# coding=utf-8\n# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (nested_scopes, generators, division, absolute_import, with_statement,\n print_function, unicode_literals)\n\nimport errno\nimport os\nimport shutil\nimport tarfile\n\nfrom pants.util.contextutil import open_tar\nfrom pants.util.dirutil import safe_mkdir, safe_mkdir_for, safe_walk\n\nclass ArtifactError(Exception):\n pass\n\nclass Artifact(object):\n \"\"\"Represents a set of files in an artifact.\"\"\"\n def __init__(self, artifact_root):\n # All files must be under this root.\n self._artifact_root = artifact_root\n\n # The files known to be in this artifact, relative to artifact_root.\n self._relpaths = set()\n\n def get_paths(self):\n for relpath in self._relpaths:\n yield os.path.join(self._artifact_root, relpath)\n\n def override_paths(self, paths): # Use with care.\n self._relpaths = set([os.path.relpath(path, self._artifact_root) for path in paths])\n\n def collect(self, paths):\n \"\"\"Collect the paths (which must be under artifact root) into this artifact.\"\"\"\n raise NotImplementedError()\n\n def extract(self):\n \"\"\"Extract the files in this artifact to their locations under artifact root.\"\"\"\n raise NotImplementedError()\n\nclass DirectoryArtifact(Artifact):\n \"\"\"An artifact stored as loose files under a directory.\"\"\"\n def __init__(self, artifact_root, directory):\n Artifact.__init__(self, artifact_root)\n self._directory = directory\n\n def collect(self, paths):\n for path in paths or ():\n relpath = os.path.relpath(path, self._artifact_root)\n dst = os.path.join(self._directory, relpath)\n safe_mkdir(os.path.dirname(dst))\n if os.path.isdir(path):\n shutil.copytree(path, dst)\n else:\n shutil.copy(path, dst)\n self._relpaths.add(relpath)\n\n def extract(self):\n for dir_name, _, filenames in safe_walk(self._directory):\n for filename in filenames:\n filename = os.path.join(dir_name, filename)\n relpath = os.path.relpath(filename, self._directory)\n dst = os.path.join(self._artifact_root, relpath)\n safe_mkdir_for(dst)\n shutil.copy(filename, dst)\n self._relpaths.add(relpath)\n\nclass TarballArtifact(Artifact):\n \"\"\"An artifact stored in a tarball.\"\"\"\n def __init__(self, artifact_root, tarfile, compression=9):\n Artifact.__init__(self, artifact_root)\n self._tarfile = tarfile\n self._compression = compression\n\n def collect(self, paths):\n # In our tests, gzip is slightly less compressive than bzip2 on .class files,\n # but decompression times are much faster.\n mode = 'w:gz' if self._compression else 'w'\n\n tar_kwargs = {'dereference': True, 'errorlevel': 2}\n if self._compression:\n tar_kwargs['compresslevel'] = self._compression\n\n with open_tar(self._tarfile, mode, **tar_kwargs) as tarout:\n for path in paths or ():\n # Adds dirs recursively.\n relpath = os.path.relpath(path, self._artifact_root)\n tarout.add(path, relpath)\n self._relpaths.add(relpath)\n\n def extract(self):\n try:\n with open_tar(self._tarfile, 'r', errorlevel=2) as tarin:\n # Note: We create all needed paths proactively, even though extractall() can do this for us.\n # This is because we may be called concurrently on multiple artifacts that share directories,\n # and there will be a race condition inside extractall(): task T1 A) sees that a directory\n # doesn't exist and B) tries to create it. But in the gap between A) and B) task T2 creates\n # the same directory, so T1 throws \"File exists\" in B).\n # This actually happened, and was very hard to debug.\n # Creating the paths here up front allows us to squelch that \"File exists\" error.\n paths = []\n dirs = set()\n for tarinfo in tarin.getmembers():\n paths.append(tarinfo.name)\n if tarinfo.isdir():\n dirs.add(tarinfo.name)\n else:\n dirs.add(os.path.dirname(tarinfo.name))\n for d in dirs:\n try:\n os.makedirs(os.path.join(self._artifact_root, d))\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n tarin.extractall(self._artifact_root)\n self._relpaths.update(paths)\n except tarfile.ReadError as e:\n raise ArtifactError(e.message)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements edit.py from Empeeric/dirometer (path: django/views/generic/edit.py)."}, {"role": "assistant", "content": "# django/views/generic/edit.py (from Empeeric/dirometer, license: mit)\n\nfrom django.forms import models as model_forms\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.http import HttpResponseRedirect\nfrom django.views.generic.base import TemplateResponseMixin, View\nfrom django.views.generic.detail import (SingleObjectMixin,\n SingleObjectTemplateResponseMixin, BaseDetailView)\n\nclass FormMixin(object):\n \"\"\"\n A mixin that provides a way to show and handle a form in a request.\n \"\"\"\n\n initial = {}\n form_class = None\n success_url = None\n\n def get_initial(self):\n \"\"\"\n Returns the initial data to use for forms on this view.\n \"\"\"\n return self.initial\n\n def get_form_class(self):\n \"\"\"\n Returns the form class to use in this view\n \"\"\"\n return self.form_class\n\n def get_form(self, form_class):\n \"\"\"\n Returns an instance of the form to be used in this view.\n \"\"\"\n return form_class(**self.get_form_kwargs())\n\n def get_form_kwargs(self):\n \"\"\"\n Returns the keyword arguments for instanciating the form.\n \"\"\"\n kwargs = {'initial': self.get_initial()}\n if self.request.method in ('POST', 'PUT'):\n kwargs.update({\n 'data': self.request.POST,\n 'files': self.request.FILES,\n })\n return kwargs\n\n def get_context_data(self, **kwargs):\n return kwargs\n\n def get_success_url(self):\n if self.success_url:\n url = self.success_url\n else:\n raise ImproperlyConfigured(\n \"No URL to redirect to. Provide a success_url.\")\n return url\n\n def form_valid(self, form):\n return HttpResponseRedirect(self.get_success_url())\n\n def form_invalid(self, form):\n return self.render_to_response(self.get_context_data(form=form))\n\nclass ModelFormMixin(FormMixin, SingleObjectMixin):\n \"\"\"\n A mixin that provides a way to show and handle a modelform in a request.\n \"\"\"\n\n def get_form_class(self):\n \"\"\"\n Returns the form class to use in this view\n \"\"\"\n if self.form_class:\n return self.form_class\n else:\n if self.model is not None:\n # If a model has been explicitly provided, use it\n model = self.model\n elif hasattr(self, 'object') and self.object is not None:\n # If this view is operating on a single object, use\n # the class of that object\n model = self.object.__class__\n else:\n # Try to get a queryset and extract the model class\n # from that\n model = self.get_queryset().model\n return model_forms.modelform_factory(model)\n\n def get_form_kwargs(self):\n \"\"\"\n Returns the keyword arguments for instanciating the form.\n \"\"\"\n kwargs = super(ModelFormMixin, self).get_form_kwargs()\n kwargs.update({'instance': self.object})\n return kwargs\n\n def get_success_url(self):\n if self.success_url:\n url = self.success_url % self.object.__dict__\n else:\n try:\n url = self.object.get_absolute_url()\n except AttributeError:\n raise ImproperlyConfigured(\n \"No URL to redirect to. Either provide a url or define\"\n \" a get_absolute_url method on the Model.\")\n return url\n\n def form_valid(self, form):\n self.object = form.save()\n return super(ModelFormMixin, self).form_valid(form)\n\n def get_context_data(self, **kwargs):\n context = kwargs\n if self.object:\n context['object'] = self.object\n context_object_name = self.get_context_object_name(self.object)\n if context_object_name:\n context[context_object_name] = self.object\n return context\n\nclass ProcessFormView(View):\n \"\"\"\n A mixin that processes a form on POST.\n \"\"\"\n def get(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n return self.render_to_response(self.get_context_data(form=form))\n\n def post(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n if form.is_valid():\n return self.form_valid(form)\n else:\n return self.form_invalid(form)\n\n # PUT is a valid HTTP verb for creating (with a known URL) or editing an\n # object, note that browsers only support POST for now.\n def put(self, *args, **kwargs):\n return self.post(*args, **kwargs)\n\nclass BaseFormView(FormMixin, ProcessFormView):\n \"\"\"\n A base view for displaying a form\n \"\"\"\n\nclass FormView(TemplateResponseMixin, BaseFormView):\n \"\"\"\n A view for displaying a form, and rendering a template response.\n \"\"\"\n\nclass BaseCreateView(ModelFormMixin, ProcessFormView):\n \"\"\"\n Base view for creating an new object instance.\n\n Using this base class requires subclassing to provide a response mixin.\n \"\"\"\n def get(self, request, *args, **kwargs):\n self.object = None\n return super(BaseCreateView, self).get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n self.object = None\n return super(BaseCreateView, self).post(request, *args, **kwargs)\n\nclass CreateView(SingleObjectTemplateResponseMixin, BaseCreateView):\n \"\"\"\n View for creating an new object instance,\n with a response rendered by template.\n \"\"\"\n template_name_suffix = '_form'\n\nclass BaseUpdateView(ModelFormMixin, ProcessFormView):\n \"\"\"\n Base view for updating an existing object.\n\n Using this base class requires subclassing to provide a response mixin.\n \"\"\"\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n return super(BaseUpdateView, self).get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n return super(BaseUpdateView, self).post(request, *args, **kwargs)\n\nclass UpdateView(SingleObjectTemplateResponseMixin, BaseUpdateView):\n \"\"\"\n View for updating an object,\n with a response rendered by template..\n \"\"\"\n template_name_suffix = '_form'\n\nclass DeletionMixin(object):\n \"\"\"\n A mixin providing the ability to delete objects\n \"\"\"\n success_url = None\n\n def delete(self, request, *args, **kwargs):\n self.object = self.get_object()\n self.object.delete()\n return HttpResponseRedirect(self.get_success_url())\n\n # Add support for browsers which only accept GET and POST for now.\n def post(self, *args, **kwargs):\n return self.delete(*args, **kwargs)\n\n def get_success_url(self):\n if self.success_url:\n return self.success_url\n else:\n raise ImproperlyConfigured(\n \"No URL to redirect to. Provide a success_url.\")\n\nclass BaseDeleteView(DeletionMixin, BaseDetailView):\n \"\"\"\n Base view for deleting an object.\n\n Using this base class requires subclassing to provide a response mixin.\n \"\"\"\n\nclass DeleteView(SingleObjectTemplateResponseMixin, BaseDeleteView):\n \"\"\"\n View for deleting an object retrieved with `self.get_object()`,\n with a response rendered by template.\n \"\"\"\n template_name_suffix = '_confirm_delete'"}]} {"messages": [{"role": "user", "content": "Write Python code that implements scheduler_visualisation_test.py from lungetech/luigi (path: test/scheduler_visualisation_test.py)."}, {"role": "assistant", "content": "# test/scheduler_visualisation_test.py (from lungetech/luigi, license: apache-2.0)\n\n# -*- coding: utf-8 -*-\n#\n# Copyright 2012-2015 Spotify AB\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom __future__ import division\n\nimport os\nimport tempfile\nimport time\nfrom helpers import unittest\n\nimport luigi\nimport luigi.notifications\nimport luigi.scheduler\nimport luigi.six as six\nimport luigi.worker\n\nluigi.notifications.DEBUG = True\n\ntempdir = tempfile.mkdtemp()\n\nclass DummyTask(luigi.Task):\n task_id = luigi.Parameter()\n\n def run(self):\n f = self.output().open('w')\n f.close()\n\n def output(self):\n return luigi.LocalTarget(os.path.join(tempdir, str(self)))\n\nclass FactorTask(luigi.Task):\n product = luigi.Parameter()\n\n def requires(self):\n for factor in range(2, self.product):\n if self.product % factor == 0:\n yield FactorTask(factor)\n yield FactorTask(self.product // factor)\n return\n\n def run(self):\n f = self.output().open('w')\n f.close()\n\n def output(self):\n return luigi.LocalTarget(os.path.join(tempdir, 'luigi_test_factor_%d' % self.product))\n\nclass BadReqTask(luigi.Task):\n succeed = luigi.BoolParameter()\n\n def requires(self):\n assert self.succeed\n yield BadReqTask(False)\n\n def run(self):\n pass\n\n def complete(self):\n return False\n\nclass FailingTask(luigi.Task):\n task_namespace = __name__\n task_id = luigi.Parameter()\n\n def run(self):\n raise Exception(\"Error Message\")\n\nclass OddFibTask(luigi.Task):\n n = luigi.IntParameter()\n done = luigi.BoolParameter(default=True, significant=False)\n\n def requires(self):\n if self.n > 1:\n yield OddFibTask(self.n - 1, self.done)\n yield OddFibTask(self.n - 2, self.done)\n\n def complete(self):\n return self.n % 2 == 0 and self.done\n\n def run(self):\n assert False\n\nclass SchedulerVisualisationTest(unittest.TestCase):\n\n def setUp(self):\n self.scheduler = luigi.scheduler.CentralPlannerScheduler()\n\n def tearDown(self):\n pass\n\n def _assert_complete(self, tasks):\n for t in tasks:\n self.assert_(t.complete())\n\n def _build(self, tasks):\n with luigi.worker.Worker(scheduler=self.scheduler, worker_processes=1) as w:\n for t in tasks:\n w.add(t)\n w.run()\n\n def _remote(self):\n return self.scheduler\n\n def _test_run(self, workers):\n tasks = [DummyTask(i) for i in range(20)]\n self._build(tasks, workers=workers)\n self._assert_complete(tasks)\n\n def test_graph(self):\n start = time.time()\n tasks = [DummyTask(task_id=1), DummyTask(task_id=2)]\n self._build(tasks)\n self._assert_complete(tasks)\n end = time.time()\n\n remote = self._remote()\n graph = remote.graph()\n self.assertEqual(len(graph), 2)\n self.assert_(DummyTask(task_id=1).task_id in graph)\n d1 = graph[DummyTask(task_id=1).task_id]\n self.assertEqual(d1[u'status'], u'DONE')\n self.assertEqual(d1[u'deps'], [])\n self.assertGreaterEqual(d1[u'start_time'], start)\n self.assertLessEqual(d1[u'start_time'], end)\n d2 = graph[DummyTask(task_id=2).task_id]\n self.assertEqual(d2[u'status'], u'DONE')\n self.assertEqual(d2[u'deps'], [])\n self.assertGreaterEqual(d2[u'start_time'], start)\n self.assertLessEqual(d2[u'start_time'], end)\n\n def test_large_graph_truncate(self):\n class LinearTask(luigi.Task):\n idx = luigi.IntParameter()\n\n def requires(self):\n if self.idx > 0:\n yield LinearTask(self.idx - 1)\n\n def complete(self):\n return False\n\n root_task = LinearTask(100)\n\n self.scheduler = luigi.scheduler.CentralPlannerScheduler(max_graph_nodes=10)\n self._build([root_task])\n\n graph = self.scheduler.dep_graph(root_task.task_id)\n self.assertEqual(10, len(graph))\n expected_nodes = [LinearTask(i).task_id for i in range(100, 90, -1)]\n six.assertCountEqual(self, expected_nodes, graph)\n\n def test_large_inverse_graph_truncate(self):\n class LinearTask(luigi.Task):\n idx = luigi.IntParameter()\n\n def requires(self):\n if self.idx > 0:\n yield LinearTask(self.idx - 1)\n\n def complete(self):\n return False\n\n root_task = LinearTask(100)\n\n self.scheduler = luigi.scheduler.CentralPlannerScheduler(max_graph_nodes=10)\n self._build([root_task])\n\n graph = self.scheduler.inverse_dep_graph(LinearTask(0).task_id)\n self.assertEqual(10, len(graph))\n expected_nodes = [LinearTask(i).task_id for i in range(10)]\n six.assertCountEqual(self, expected_nodes, graph)\n\n def test_truncate_graph_with_full_levels(self):\n class BinaryTreeTask(luigi.Task):\n idx = luigi.IntParameter()\n\n def requires(self):\n if self.idx < 100:\n return map(BinaryTreeTask, (self.idx * 2, self.idx * 2 + 1))\n\n root_task = BinaryTreeTask(1)\n\n self.scheduler = luigi.scheduler.CentralPlannerScheduler(max_graph_nodes=10)\n self._build([root_task])\n\n graph = self.scheduler.dep_graph(root_task.task_id)\n self.assertEqual(10, len(graph))\n expected_nodes = [BinaryTreeTask(i).task_id for i in range(1, 11)]\n six.assertCountEqual(self, expected_nodes, graph)\n\n def test_truncate_graph_with_multiple_depths(self):\n class LinearTask(luigi.Task):\n idx = luigi.IntParameter()\n\n def requires(self):\n if self.idx > 0:\n yield LinearTask(self.idx - 1)\n yield LinearTask(0)\n\n def complete(self):\n return False\n\n root_task = LinearTask(100)\n\n self.scheduler = luigi.scheduler.CentralPlannerScheduler(max_graph_nodes=10)\n self._build([root_task])\n\n graph = self.scheduler.dep_graph(root_task.task_id)\n self.assertEqual(10, len(graph))\n expected_nodes = [LinearTask(i).task_id for i in range(100, 91, -1)] +\\\n [LinearTask(0).task_id]\n self.maxDiff = None\n six.assertCountEqual(self, expected_nodes, graph)\n\n def _assert_all_done(self, tasks):\n self._assert_all(tasks, u'DONE')\n\n def _assert_all(self, tasks, status):\n for task in tasks.values():\n self.assertEqual(task[u'status'], status)\n\n def test_dep_graph_single(self):\n self._build([FactorTask(1)])\n remote = self._remote()\n dep_graph = remote.dep_graph(FactorTask(product=1).task_id)\n self.assertEqual(len(dep_graph), 1)\n self._assert_all_done(dep_graph)\n\n d1 = dep_graph.get(FactorTask(product=1).task_id)\n self.assertEqual(type(d1), type({}))\n self.assertEqual(d1[u'deps'], [])\n\n def test_dep_graph_not_found(self):\n self._build([FactorTask(1)])\n remote = self._remote()\n dep_graph = remote.dep_graph(FactorTask(product=5).task_id)\n self.assertEqual(len(dep_graph), 0)\n\n def test_inverse_dep_graph_not_found(self):\n self._build([FactorTask(1)])\n remote = self._remote()\n dep_graph = remote.inverse_dep_graph('FactorTask(product=5)')\n self.assertEqual(len(dep_graph), 0)\n\n def test_dep_graph_tree(self):\n self._build([FactorTask(30)])\n remote = self._remote()\n dep_graph = remote.dep_graph(FactorTask(product=30).task_id)\n self.assertEqual(len(dep_graph), 5)\n self._assert_all_done(dep_graph)\n\n d30 = dep_graph[FactorTask(product=30).task_id]\n self.assertEqual(sorted(d30[u'deps']), sorted([FactorTask(product=15).task_id, FactorTask(product=2).task_id]))\n\n d2 = dep_graph[FactorTask(product=2).task_id]\n self.assertEqual(sorted(d2[u'deps']), [])\n\n d15 = dep_graph[FactorTask(product=15).task_id]\n self.assertEqual(sorted(d15[u'deps']), sorted([FactorTask(product=3).task_id, FactorTask(product=5).task_id]))\n\n d3 = dep_graph[FactorTask(product=3).task_id]\n self.assertEqual(sorted(d3[u'deps']), [])\n\n d5 = dep_graph[FactorTask(product=5).task_id]\n self.assertEqual(sorted(d5[u'deps']), [])\n\n def test_dep_graph_missing_deps(self):\n self._build([BadReqTask(True)])\n dep_graph = self._remote().dep_graph(BadReqTask(succeed=True).task_id)\n self.assertEqual(len(dep_graph), 2)\n\n suc = dep_graph[BadReqTask(succeed=True).task_id]\n self.assertEqual(suc[u'deps'], [BadReqTask(succeed=False).task_id])\n\n fail = dep_graph[BadReqTask(succeed=False).task_id]\n self.assertEqual(fail[u'name'], 'BadReqTask')\n self.assertEqual(fail[u'params'], {'succeed': 'False'})\n self.assertEqual(fail[u'status'], 'UNKNOWN')\n\n def test_dep_graph_diamond(self):\n self._build([FactorTask(12)])\n remote = self._remote()\n dep_graph = remote.dep_graph(FactorTask(product=12).task_id)\n self.assertEqual(len(dep_graph), 4)\n self._assert_all_done(dep_graph)\n\n d12 = dep_graph[FactorTask(product=12).task_id]\n self.assertEqual(sorted(d12[u'deps']), sorted([FactorTask(product=2).task_id, FactorTask(product=6).task_id]))\n\n d6 = dep_graph[FactorTask(product=6).task_id]\n self.assertEqual(sorted(d6[u'deps']), sorted([FactorTask(product=2).task_id, FactorTask(product=3).task_id]))\n\n d3 = dep_graph[FactorTask(product=3).task_id]\n self.assertEqual(sorted(d3[u'deps']), [])\n\n d2 = dep_graph[FactorTask(product=2).task_id]\n self.assertEqual(sorted(d2[u'deps']), [])\n\n def test_dep_graph_skip_done(self):\n task = OddFibTask(9)\n self._build([task])\n remote = self._remote()\n\n task_id = task.task_id\n self.assertEqual(9, len(remote.dep_graph(task_id, include_done=True)))\n\n skip_done_graph = remote.dep_graph(task_id, include_done=False)\n self.assertEqual(5, len(skip_done_graph))\n for task in skip_done_graph.values():\n self.assertNotEqual('DONE', task['status'])\n self.assertLess(len(task['deps']), 2)\n\n def test_inverse_dep_graph_skip_done(self):\n self._build([OddFibTask(9, done=False)])\n self._build([OddFibTask(9, done=True)])\n remote = self._remote()\n\n task_id = OddFibTask(1).task_id\n self.assertEqual(9, len(remote.inverse_dep_graph(task_id, include_done=True)))\n\n skip_done_graph = remote.inverse_dep_graph(task_id, include_done=False)\n self.assertEqual(5, len(skip_done_graph))\n for task in skip_done_graph.values():\n self.assertNotEqual('DONE', task['status'])\n self.assertLess(len(task['deps']), 2)\n\n def test_task_list_single(self):\n self._build([FactorTask(7)])\n remote = self._remote()\n tasks_done = remote.task_list('DONE', '')\n self.assertEqual(len(tasks_done), 1)\n self._assert_all_done(tasks_done)\n\n t7 = tasks_done.get(FactorTask(product=7).task_id)\n self.assertEqual(type(t7), type({}))\n\n self.assertEqual(remote.task_list('', ''), tasks_done)\n self.assertEqual(remote.task_list('FAILED', ''), {})\n self.assertEqual(remote.task_list('PENDING', ''), {})\n\n def test_dep_graph_root_has_display_name(self):\n root_task = FactorTask(12)\n self._build([root_task])\n\n dep_graph = self._remote().dep_graph(root_task.task_id)\n self.assertEqual('FactorTask(product=12)', dep_graph[root_task.task_id]['display_name'])\n\n def test_dep_graph_non_root_nodes_lack_display_name(self):\n root_task = FactorTask(12)\n self._build([root_task])\n\n dep_graph = self._remote().dep_graph(root_task.task_id)\n for task_id, node in dep_graph.items():\n if task_id != root_task.task_id:\n self.assertNotIn('display_name', node)\n\n def test_task_list_failed(self):\n self._build([FailingTask(8)])\n remote = self._remote()\n failed = remote.task_list('FAILED', '')\n self.assertEqual(len(failed), 1)\n\n f8 = failed.get(FailingTask(task_id=8).task_id)\n self.assertEqual(f8[u'status'], u'FAILED')\n\n self.assertEqual(remote.task_list('DONE', ''), {})\n self.assertEqual(remote.task_list('PENDING', ''), {})\n\n def test_task_list_upstream_status(self):\n class A(luigi.ExternalTask):\n pass\n\n class B(luigi.ExternalTask):\n\n def complete(self):\n return True\n\n class C(luigi.Task):\n\n def requires(self):\n return [A(), B()]\n\n class F(luigi.Task):\n\n def run(self):\n raise Exception()\n\n class D(luigi.Task):\n\n def requires(self):\n return [F()]\n\n class E(luigi.Task):\n\n def requires(self):\n return [C(), D()]\n\n self._build([E()])\n remote = self._remote()\n\n done = remote.task_list('DONE', '')\n self.assertEqual(len(done), 1)\n db = done.get(B().task_id)\n self.assertEqual(db['status'], 'DONE')\n\n missing_input = remote.task_list('PENDING', 'UPSTREAM_MISSING_INPUT')\n self.assertEqual(len(missing_input), 2)\n\n pa = missing_input.get(A().task_id)\n self.assertEqual(pa['status'], 'PENDING')\n self.assertEqual(remote._upstream_status(A().task_id, {}), 'UPSTREAM_MISSING_INPUT')\n\n pc = missing_input.get(C().task_id)\n self.assertEqual(pc['status'], 'PENDING')\n self.assertEqual(remote._upstream_status(C().task_id, {}), 'UPSTREAM_MISSING_INPUT')\n\n upstream_failed = remote.task_list('PENDING', 'UPSTREAM_FAILED')\n self.assertEqual(len(upstream_failed), 2)\n pe = upstream_failed.get(E().task_id)\n self.assertEqual(pe['status'], 'PENDING')\n self.assertEqual(remote._upstream_status(E().task_id, {}), 'UPSTREAM_FAILED')\n\n pe = upstream_failed.get(D().task_id)\n self.assertEqual(pe['status'], 'PENDING')\n self.assertEqual(remote._upstream_status(D().task_id, {}), 'UPSTREAM_FAILED')\n\n pending = dict(missing_input)\n pending.update(upstream_failed)\n self.assertEqual(remote.task_list('PENDING', ''), pending)\n self.assertEqual(remote.task_list('PENDING', 'UPSTREAM_RUNNING'), {})\n\n failed = remote.task_list('FAILED', '')\n self.assertEqual(len(failed), 1)\n fd = failed.get(F().task_id)\n self.assertEqual(fd['status'], 'FAILED')\n\n all = dict(pending)\n all.update(done)\n all.update(failed)\n self.assertEqual(remote.task_list('', ''), all)\n self.assertEqual(remote.task_list('RUNNING', ''), {})\n\n def test_task_search(self):\n self._build([FactorTask(8)])\n self._build([FailingTask(8)])\n remote = self._remote()\n all_tasks = remote.task_search('Task')\n self.assertEqual(len(all_tasks), 2)\n self._assert_all(all_tasks['DONE'], 'DONE')\n self._assert_all(all_tasks['FAILED'], 'FAILED')\n\n def test_fetch_error(self):\n self._build([FailingTask(8)])\n remote = self._remote()\n error = remote.fetch_error(FailingTask(task_id=8).task_id)\n self.assertEqual(error[\"taskId\"], FailingTask(task_id=8).task_id)\n self.assertTrue(\"Error Message\" in error[\"error\"])\n self.assertTrue(\"Runtime error\" in error[\"error\"])\n self.assertTrue(\"Traceback\" in error[\"error\"])\n\n def test_inverse_deps(self):\n class X(luigi.Task):\n pass\n\n class Y(luigi.Task):\n\n def requires(self):\n return [X()]\n\n class Z(luigi.Task):\n id = luigi.Parameter()\n\n def requires(self):\n return [Y()]\n\n class ZZ(luigi.Task):\n\n def requires(self):\n return [Z(1), Z(2)]\n\n self._build([ZZ()])\n dep_graph = self._remote().inverse_dep_graph(X().task_id)\n\n def assert_has_deps(task_id, deps):\n self.assertTrue(task_id in dep_graph, '%s not in dep_graph %s' % (task_id, dep_graph))\n task = dep_graph[task_id]\n self.assertEqual(sorted(task['deps']), sorted(deps), '%s does not have deps %s' % (task_id, deps))\n\n assert_has_deps(X().task_id, [Y().task_id])\n assert_has_deps(Y().task_id, [Z(id=1).task_id, Z(id=2).task_id])\n assert_has_deps(Z(id=1).task_id, [ZZ().task_id])\n assert_has_deps(Z(id=2).task_id, [ZZ().task_id])\n assert_has_deps(ZZ().task_id, [])\n\n def test_simple_worker_list(self):\n class X(luigi.Task):\n\n def run(self):\n self._complete = True\n\n def complete(self):\n return getattr(self, '_complete', False)\n\n task_x = X()\n self._build([task_x])\n\n workers = self._remote().worker_list()\n\n self.assertEqual(1, len(workers))\n worker = workers[0]\n self.assertEqual(task_x.task_id, worker['first_task'])\n self.assertEqual(0, worker['num_pending'])\n self.assertEqual(0, worker['num_uniques'])\n self.assertEqual(0, worker['num_running'])\n self.assertEqual(1, worker['workers'])\n\n def test_worker_list_pending_uniques(self):\n class X(luigi.Task):\n\n def complete(self):\n return False\n\n class Y(X):\n\n def requires(self):\n return X()\n\n class Z(Y):\n pass\n\n w1 = luigi.worker.Worker(scheduler=self.scheduler, worker_processes=1)\n w2 = luigi.worker.Worker(scheduler=self.scheduler, worker_processes=1)\n\n w1.add(Y())\n w2.add(Z())\n\n workers = self._remote().worker_list()\n self.assertEqual(2, len(workers))\n for worker in workers:\n self.assertEqual(2, worker['num_pending'])\n self.assertEqual(1, worker['num_uniques'])\n self.assertEqual(0, worker['num_running'])\n\n def test_worker_list_running(self):\n class X(luigi.Task):\n n = luigi.IntParameter()\n\n w = luigi.worker.Worker(worker_id='w', scheduler=self.scheduler, worker_processes=3)\n w.add(X(0))\n w.add(X(1))\n w.add(X(2))\n w.add(X(3))\n\n self.scheduler.get_work(worker='w')\n self.scheduler.get_work(worker='w')\n self.scheduler.get_work(worker='w')\n\n workers = self._remote().worker_list()\n self.assertEqual(1, len(workers))\n worker = workers[0]\n\n self.assertEqual(3, worker['num_running'])\n self.assertEqual(1, worker['num_pending'])\n self.assertEqual(1, worker['num_uniques'])\n\nif __name__ == '__main__':\n unittest.main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements linearize-hashes.py from segwitcoin/SegwitCoin (path: contrib/linearize/linearize-hashes.py)."}, {"role": "assistant", "content": "# contrib/linearize/linearize-hashes.py (from segwitcoin/SegwitCoin, license: mit)\n\n#!/usr/bin/env python3\n#\n# linearize-hashes.py: List blocks in a linear, no-fork version of the chain.\n#\n# Copyright (c) 2013-2016 The Bitcoin Core developers\n# Distributed under the MIT software license, see the accompanying\n# file COPYING or http://www.opensource.org/licenses/mit-license.php.\n#\n\nfrom __future__ import print_function\ntry: # Python 3\n import http.client as httplib\nexcept ImportError: # Python 2\n import httplib\nimport json\nimport re\nimport base64\nimport sys\nimport os\nimport os.path\n\nsettings = {}\n\n##### Switch endian-ness #####\ndef hex_switchEndian(s):\n\t\"\"\" Switches the endianness of a hex string (in pairs of hex chars) \"\"\"\n\tpairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]\n\treturn b''.join(pairList[::-1]).decode()\n\nclass BitcoinRPC:\n\tdef __init__(self, host, port, username, password):\n\t\tauthpair = \"%s:%s\" % (username, password)\n\t\tauthpair = authpair.encode('utf-8')\n\t\tself.authhdr = b\"Basic \" + base64.b64encode(authpair)\n\t\tself.conn = httplib.HTTPConnection(host, port=port, timeout=30)\n\n\tdef execute(self, obj):\n\t\ttry:\n\t\t\tself.conn.request('POST', '/', json.dumps(obj),\n\t\t\t\t{ 'Authorization' : self.authhdr,\n\t\t\t\t 'Content-type' : 'application/json' })\n\t\texcept ConnectionRefusedError:\n\t\t\tprint('RPC connection refused. Check RPC settings and the server status.',\n\t\t\t file=sys.stderr)\n\t\t\treturn None\n\n\t\tresp = self.conn.getresponse()\n\t\tif resp is None:\n\t\t\tprint(\"JSON-RPC: no response\", file=sys.stderr)\n\t\t\treturn None\n\n\t\tbody = resp.read().decode('utf-8')\n\t\tresp_obj = json.loads(body)\n\t\treturn resp_obj\n\n\t@staticmethod\n\tdef build_request(idx, method, params):\n\t\tobj = { 'version' : '1.1',\n\t\t\t'method' : method,\n\t\t\t'id' : idx }\n\t\tif params is None:\n\t\t\tobj['params'] = []\n\t\telse:\n\t\t\tobj['params'] = params\n\t\treturn obj\n\n\t@staticmethod\n\tdef response_is_error(resp_obj):\n\t\treturn 'error' in resp_obj and resp_obj['error'] is not None\n\ndef get_block_hashes(settings, max_blocks_per_call=10000):\n\trpc = BitcoinRPC(settings['host'], settings['port'],\n\t\t\t settings['rpcuser'], settings['rpcpassword'])\n\n\theight = settings['min_height']\n\twhile height < settings['max_height']+1:\n\t\tnum_blocks = min(settings['max_height']+1-height, max_blocks_per_call)\n\t\tbatch = []\n\t\tfor x in range(num_blocks):\n\t\t\tbatch.append(rpc.build_request(x, 'getblockhash', [height + x]))\n\n\t\treply = rpc.execute(batch)\n\t\tif reply is None:\n\t\t\tprint('Cannot continue. Program will halt.')\n\t\t\treturn None\n\n\t\tfor x,resp_obj in enumerate(reply):\n\t\t\tif rpc.response_is_error(resp_obj):\n\t\t\t\tprint('JSON-RPC: error at height', height+x, ': ', resp_obj['error'], file=sys.stderr)\n\t\t\t\texit(1)\n\t\t\tassert(resp_obj['id'] == x) # assume replies are in-sequence\n\t\t\tif settings['rev_hash_bytes'] == 'true':\n\t\t\t\tresp_obj['result'] = hex_switchEndian(resp_obj['result'])\n\t\t\tprint(resp_obj['result'])\n\n\t\theight += num_blocks\n\ndef get_rpc_cookie():\n\t# Open the cookie file\n\twith open(os.path.join(os.path.expanduser(settings['datadir']), '.cookie'), 'r') as f:\n\t\tcombined = f.readline()\n\t\tcombined_split = combined.split(\":\")\n\t\tsettings['rpcuser'] = combined_split[0]\n\t\tsettings['rpcpassword'] = combined_split[1]\n\nif __name__ == '__main__':\n\tif len(sys.argv) != 2:\n\t\tprint(\"Usage: linearize-hashes.py CONFIG-FILE\")\n\t\tsys.exit(1)\n\n\tf = open(sys.argv[1])\n\tfor line in f:\n\t\t# skip comment lines\n\t\tm = re.search('^\\s*#', line)\n\t\tif m:\n\t\t\tcontinue\n\n\t\t# parse key=value lines\n\t\tm = re.search('^(\\w+)\\s*=\\s*(\\S.*)$', line)\n\t\tif m is None:\n\t\t\tcontinue\n\t\tsettings[m.group(1)] = m.group(2)\n\tf.close()\n\n\tif 'host' not in settings:\n\t\tsettings['host'] = '127.0.0.1'\n\tif 'port' not in settings:\n\t\tsettings['port'] = 8332\n\tif 'min_height' not in settings:\n\t\tsettings['min_height'] = 0\n\tif 'max_height' not in settings:\n\t\tsettings['max_height'] = 313000\n\tif 'rev_hash_bytes' not in settings:\n\t\tsettings['rev_hash_bytes'] = 'false'\n\n\tuse_userpass = True\n\tuse_datadir = False\n\tif 'rpcuser' not in settings or 'rpcpassword' not in settings:\n\t\tuse_userpass = False\n\tif 'datadir' in settings and not use_userpass:\n\t\tuse_datadir = True\n\tif not use_userpass and not use_datadir:\n\t\tprint(\"Missing datadir or username and/or password in cfg file\", file=stderr)\n\t\tsys.exit(1)\n\n\tsettings['port'] = int(settings['port'])\n\tsettings['min_height'] = int(settings['min_height'])\n\tsettings['max_height'] = int(settings['max_height'])\n\n\t# Force hash byte format setting to be lowercase to make comparisons easier.\n\tsettings['rev_hash_bytes'] = settings['rev_hash_bytes'].lower()\n\n\t# Get the rpc user and pass from the cookie if the datadir is set\n\tif use_datadir:\n\t\tget_rpc_cookie()\n\n\tget_block_hashes(settings)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements __init__.py from westinedu/newertrends (path: django/template/__init__.py)."}, {"role": "assistant", "content": "# django/template/__init__.py (from westinedu/newertrends, license: bsd-3-clause)\n\n\"\"\"\nThis is the Django template system.\n\nHow it works:\n\nThe Lexer.tokenize() function converts a template string (i.e., a string containing\nmarkup with custom template tags) to tokens, which can be either plain text\n(TOKEN_TEXT), variables (TOKEN_VAR) or block statements (TOKEN_BLOCK).\n\nThe Parser() class takes a list of tokens in its constructor, and its parse()\nmethod returns a compiled template -- which is, under the hood, a list of\nNode objects.\n\nEach Node is responsible for creating some sort of output -- e.g. simple text\n(TextNode), variable values in a given context (VariableNode), results of basic\nlogic (IfNode), results of looping (ForNode), or anything else. The core Node\ntypes are TextNode, VariableNode, IfNode and ForNode, but plugin modules can\ndefine their own custom node types.\n\nEach Node has a render() method, which takes a Context and returns a string of\nthe rendered node. For example, the render() method of a Variable Node returns\nthe variable's value as a string. The render() method of an IfNode returns the\nrendered output of whatever was inside the loop, recursively.\n\nThe Template class is a convenient wrapper that takes care of template\ncompilation and rendering.\n\nUsage:\n\nThe only thing you should ever use directly in this file is the Template class.\nCreate a compiled template object with a template_string, then call render()\nwith a context. In the compilation stage, the TemplateSyntaxError exception\nwill be raised if the template doesn't have proper syntax.\n\nSample code:\n\n>>> from django import template\n>>> s = u'{% if test %}

{{ 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' \n#\n# All Rights Reserved\n#\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation\n# files (the \"Software\"), to deal in the Software without\n# restriction, including without limitation the rights to use,\n# copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n#\n# ======================================================================\n\n\"\"\"A basic FTP server which uses a DummyAuthorizer for managing 'virtual\nusers', setting a limit for incoming connections.\n\"\"\"\n\nimport os\n\nfrom pyftpdlib import ftpserver\n\ndef main():\n # Instantiate a dummy authorizer for managing 'virtual' users\n authorizer = ftpserver.DummyAuthorizer()\n\n # Define a new user having full r/w permissions and a read-only\n # anonymous user\n authorizer.add_user('user', '12345', os.getcwd(), perm='elradfmwM')\n authorizer.add_anonymous(os.getcwd())\n\n # Instantiate FTP handler class\n ftp_handler = ftpserver.FTPHandler\n ftp_handler.authorizer = authorizer\n\n # Define a customized banner (string returned when client connects)\n ftp_handler.banner = \"pyftpdlib %s based ftpd ready.\" %ftpserver.__ver__\n\n # Specify a masquerade address and the range of ports to use for\n # passive connections. Decomment in case you're behind a NAT.\n #ftp_handler.masquerade_address = '151.25.42.11'\n #ftp_handler.passive_ports = range(60000, 65535)\n\n # Instantiate FTP server class and listen to 0.0.0.0:21\n address = ('', 21)\n ftpd = ftpserver.FTPServer(address, ftp_handler)\n\n # set a limit for connections\n ftpd.max_cons = 256\n ftpd.max_cons_per_ip = 5\n\n # start ftp server\n ftpd.serve_forever()\n\nif __name__ == '__main__':\n main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_http.py from Juniper/tempest (path: tempest/tests/lib/common/test_http.py)."}, {"role": "assistant", "content": "# tempest/tests/lib/common/test_http.py (from Juniper/tempest, license: apache-2.0)\n\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom tempest.lib.common import http\nfrom tempest.tests import base\n\nclass TestClosingHttp(base.TestCase):\n def setUp(self):\n super(TestClosingHttp, self).setUp()\n self.cert_none = \"CERT_NONE\"\n self.cert_location = \"/etc/ssl/certs/ca-certificates.crt\"\n\n def test_constructor_invalid_ca_certs_and_timeout(self):\n connection = http.ClosingHttp(\n disable_ssl_certificate_validation=False,\n ca_certs=None,\n timeout=None)\n for attr in ('cert_reqs', 'ca_certs', 'timeout'):\n self.assertNotIn(attr, connection.connection_pool_kw)\n\n def test_constructor_valid_ca_certs(self):\n cert_required = 'CERT_REQUIRED'\n connection = http.ClosingHttp(\n disable_ssl_certificate_validation=False,\n ca_certs=self.cert_location,\n timeout=None)\n self.assertEqual(cert_required,\n connection.connection_pool_kw['cert_reqs'])\n self.assertEqual(self.cert_location,\n connection.connection_pool_kw['ca_certs'])\n self.assertNotIn('timeout',\n connection.connection_pool_kw)\n\n def test_constructor_ssl_cert_validation_disabled(self):\n connection = http.ClosingHttp(\n disable_ssl_certificate_validation=True,\n ca_certs=None,\n timeout=30)\n self.assertEqual(self.cert_none,\n connection.connection_pool_kw['cert_reqs'])\n self.assertEqual(30,\n connection.connection_pool_kw['timeout'])\n self.assertNotIn('ca_certs',\n connection.connection_pool_kw)\n\n def test_constructor_ssl_cert_validation_disabled_and_ca_certs(self):\n connection = http.ClosingHttp(\n disable_ssl_certificate_validation=True,\n ca_certs=self.cert_location,\n timeout=None)\n self.assertNotIn('timeout',\n connection.connection_pool_kw)\n self.assertEqual(self.cert_none,\n connection.connection_pool_kw['cert_reqs'])\n self.assertNotIn('ca_certs',\n connection.connection_pool_kw)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements param_mss_err.py from kisel/trex-core (path: scripts/astf/param_mss_err.py)."}, {"role": "assistant", "content": "# scripts/astf/param_mss_err.py (from kisel/trex-core, license: apache-2.0)\n\nfrom trex_astf_lib.api import *\n\n# IPV6 tunable example \n#\n# ipv6.src_msb\n# ipv6.dst_msb \n# ipv6.enable\n# \n\nclass Prof1():\n def __init__(self):\n pass\n\n def get_profile(self, **kwargs):\n\n # ip generator\n ip_gen_c = ASTFIPGenDist(ip_range=[\"16.0.0.0\", \"16.0.0.255\"], distribution=\"seq\")\n ip_gen_s = ASTFIPGenDist(ip_range=[\"48.0.0.0\", \"48.0.255.255\"], distribution=\"seq\")\n ip_gen = ASTFIPGen(glob=ASTFIPGenGlobal(ip_offset=\"1.0.0.0\"),\n dist_client=ip_gen_c,\n dist_server=ip_gen_s)\n\n c_glob_info = ASTFGlobalInfo()\n c_glob_info.tcp.mss = 1\n\n return ASTFProfile(default_ip_gen=ip_gen,\n # Defaults affects all files\n default_c_glob_info=c_glob_info,\n cap_list=[\n ASTFCapInfo(file=\"../avl/delay_10_http_browsing_0.pcap\", cps=1)\n ]\n )\n\ndef register():\n return Prof1()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements multiplicity.py from edgedb/edgedb (path: edb/edgeql/compiler/inference/multiplicity.py)."}, {"role": "assistant", "content": "# edb/edgeql/compiler/inference/multiplicity.py (from edgedb/edgedb, license: apache-2.0)\n\n#\n# This source file is part of the EdgeDB open source project.\n#\n# Copyright 2020-present MagicStack Inc. and the EdgeDB authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"EdgeQL multiplicity inference.\n\nA top-down multiplicity inferer that traverses the full AST populating\nmultiplicity fields and performing multiplicity checks.\n\"\"\"\n\nfrom __future__ import annotations\nfrom typing import *\n\nimport functools\n\nfrom edb import errors\n\nfrom edb.edgeql import qltypes\n\nfrom edb.schema import pointers as s_pointers\n\nfrom edb.ir import ast as irast\nfrom edb.ir import typeutils as irtyputils\n\nfrom . import cardinality\nfrom . import context as inference_context\n\nZERO = qltypes.Multiplicity.ZERO\nONE = qltypes.Multiplicity.ONE\nMANY = qltypes.Multiplicity.MANY\n\ndef _max_multiplicity(\n args: Iterable[qltypes.Multiplicity]\n) -> qltypes.Multiplicity:\n # Coincidentally, the lexical order of multiplicity is opposite of\n # order of multiplicity values.\n arg_list = list(args)\n if not arg_list:\n return ZERO\n else:\n return min(arg_list)\n\ndef _common_multiplicity(\n args: Iterable[irast.Base],\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n return _max_multiplicity(\n infer_multiplicity(a, scope_tree=scope_tree, ctx=ctx) for a in args)\n\n@functools.singledispatch\ndef _infer_multiplicity(\n ir: irast.Expr,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n # return MANY\n raise ValueError(f'infer_multiplicity: cannot handle {ir!r}')\n\n@_infer_multiplicity.register\ndef __infer_none(\n ir: None,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n # Here for debugging purposes.\n raise ValueError('invalid infer_multiplicity(None, schema) call')\n\n@_infer_multiplicity.register\ndef __infer_statement(\n ir: irast.Statement,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n return infer_multiplicity(\n ir.expr, scope_tree=scope_tree, ctx=ctx)\n\n@_infer_multiplicity.register\ndef __infer_empty_set(\n ir: irast.EmptySet,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n return ZERO\n\n@_infer_multiplicity.register\ndef __infer_type_introspection(\n ir: irast.TypeIntrospection,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n # TODO: The result is always ONE, but we still want to actually\n # introspect the expression. Unfortunately, currently the\n # expression is not available at this stage.\n #\n # E.g. consider:\n # WITH X := Foo {bar := {Bar, Bar}}\n # SELECT INTROSPECT TYPEOF X.bar;\n return ONE\n\ndef _infer_shape(\n ir: irast.Set,\n *,\n is_mutation: bool=False,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> None:\n for shape_set, _ in ir.shape:\n new_scope = cardinality._get_set_scope(shape_set, scope_tree, ctx=ctx)\n if shape_set.expr and shape_set.rptr:\n expr_mult = infer_multiplicity(\n shape_set.expr, scope_tree=new_scope, ctx=ctx)\n\n ptrref = shape_set.rptr.ptrref\n if expr_mult is MANY and irtyputils.is_object(ptrref.out_target):\n raise errors.QueryError(\n f'possibly not a strict set returned by an '\n f'expression for a computable '\n f'{ptrref.shortname.name}.',\n hint=(\n f'Use DISTINCT for the entire computable expression '\n f'to resolve this.'\n ),\n context=shape_set.context\n )\n\n _infer_shape(\n shape_set, is_mutation=is_mutation, scope_tree=scope_tree, ctx=ctx)\n\ndef _infer_set(\n ir: irast.Set,\n *,\n is_mutation: bool=False,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n result = _infer_set_inner(\n ir, is_mutation=is_mutation, scope_tree=scope_tree, ctx=ctx)\n ctx.inferred_multiplicity[ir, scope_tree] = result\n # The shape doesn't affect multiplicity, but requires validation.\n _infer_shape(ir, is_mutation=is_mutation, scope_tree=scope_tree, ctx=ctx)\n\n return result\n\ndef _infer_set_inner(\n ir: irast.Set,\n *,\n is_mutation: bool=False,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n rptr = ir.rptr\n new_scope = cardinality._get_set_scope(ir, scope_tree, ctx=ctx)\n\n if rptr is not None:\n # Validate the source\n infer_multiplicity(rptr.source, scope_tree=new_scope, ctx=ctx)\n\n if ir.expr:\n expr_mult = infer_multiplicity(ir.expr, scope_tree=new_scope, ctx=ctx)\n\n if rptr is not None:\n rptrref = rptr.ptrref\n\n if isinstance(rptr.ptrref, irast.TupleIndirectionPointerRef):\n # All bets are off for tuple elements.\n return MANY\n elif not irtyputils.is_object(ir.typeref):\n # This is not an expression and is some kind of scalar, so\n # multiplicity cannot be guaranteed to be ONE (most scalar\n # expressions don't have an implicit requirement to be sets)\n # unless we also have an exclusive constraint.\n\n if rptr is not None:\n schema = ctx.env.schema\n # We should only have some kind of path terminating in a\n # property here.\n assert isinstance(rptrref, irast.PointerRef)\n ptr = schema.get_by_id(rptrref.id, type=s_pointers.Pointer)\n if ptr.is_exclusive(schema):\n # Got an exclusive constraint\n return ONE\n\n return MANY\n\n else:\n # This is some kind of a link at the end of a path.\n # Therefore the target is a proper set.\n return ONE\n\n elif ir.expr is not None:\n return expr_mult\n\n else:\n # Evidently this is not a pointer, expression, or a scalar.\n # This is an object type and therefore a proper set.\n return ONE\n\n@_infer_multiplicity.register\ndef __infer_func_call(\n ir: irast.FunctionCall,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n # If the function returns a set (for any reason), all bets are off\n # and the maximum multiplicity cannot be inferred.\n card = cardinality.infer_cardinality(\n ir, scope_tree=scope_tree, ctx=ctx)\n\n # We still want to validate the multiplicity of the arguments, though.\n for arg in ir.args:\n infer_multiplicity(arg.expr, scope_tree=scope_tree, ctx=ctx)\n\n if card is not None and card.is_single():\n return ONE\n elif str(ir.func_shortname) == 'std::enumerate':\n # Technically the output of enumerate is always of\n # multiplicity ONE because it's a set of tuples with first\n # elements being guaranteed to be distinct.\n return ONE\n else:\n return MANY\n\n@_infer_multiplicity.register\ndef __infer_oper_call(\n ir: irast.OperatorCall,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n mult = []\n cards = []\n for arg in ir.args:\n cards.append(\n cardinality.infer_cardinality(\n arg.expr, scope_tree=scope_tree, ctx=ctx))\n mult.append(\n infer_multiplicity(\n arg.expr, scope_tree=scope_tree, ctx=ctx))\n\n op_name = str(ir.func_shortname)\n\n if op_name == 'std::UNION':\n # UNION will produce multiplicity MANY unless most or all of\n # the elements multiplicity is ZERO (from an empty set).\n result = ZERO\n for m in mult:\n if m is ONE and result is ZERO:\n result = m\n elif m is ONE and result is not ZERO:\n return MANY\n elif m is MANY:\n return MANY\n return result\n\n elif op_name == 'std::DISTINCT':\n if mult[0] is ZERO:\n return ZERO\n else:\n return ONE\n elif op_name == 'std::IF':\n # If the cardinality of the condition is more than ONE, then\n # the multiplicity cannot be inferred.\n if cards[1].is_single():\n # Now it's just a matter of the multiplicity of the\n # possible results.\n return _max_multiplicity((mult[0], mult[2]))\n else:\n return MANY\n\n else:\n # The rest of the operators (other than UNION, DISTINCT, or\n # IF..ELSE). We can ignore the SET OF args because the results\n # are actually proportional to the element-wise args in our\n # operators.\n result = _max_multiplicity(mult)\n if result is MANY:\n return result\n\n # Even when arguments are of multiplicity ONE, we cannot\n # exclude the possibility of the result being of multiplicity\n # MANY. We need to check that at most one argument has\n # cardinality more than ONE.\n\n if len([card for card in cards if card.is_multi()]) > 1:\n return MANY\n else:\n return result\n\n@_infer_multiplicity.register\ndef __infer_const(\n ir: irast.BaseConstant,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n return ONE\n\n@_infer_multiplicity.register\ndef __infer_param(\n ir: irast.Parameter,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n return ONE\n\n@_infer_multiplicity.register\ndef __infer_const_set(\n ir: irast.ConstantSet,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n if len(ir.elements) == len({el.value for el in ir.elements}):\n return ONE\n else:\n return MANY\n\n@_infer_multiplicity.register\ndef __infer_typecheckop(\n ir: irast.TypeCheckOp,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n # Unless this is a singleton, the multiplicity cannot be assumed to be ONE.\n card = cardinality.infer_cardinality(\n ir, scope_tree=scope_tree, ctx=ctx)\n if card is not None and card.is_single():\n return ONE\n else:\n return MANY\n\n@_infer_multiplicity.register\ndef __infer_typecast(\n ir: irast.TypeCast,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n return infer_multiplicity(\n ir.expr, scope_tree=scope_tree, ctx=ctx,\n )\n\ndef _infer_stmt_multiplicity(\n ir: irast.FilteredStmt,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n result = infer_multiplicity(\n ir.subject if isinstance(ir, irast.MutatingStmt) else ir.result,\n scope_tree=scope_tree,\n ctx=ctx,\n )\n\n # WITH block bindings need to be validated, they don't have to\n # have multiplicity ONE, but their sub-expressions must be valid.\n #\n # Inferring how the FILTER clause affects multiplicity is in\n # general impossible, but we still want to ensure that the FILTER\n # expression has valid multiplicity.\n for part in ir.bindings + [ir.where]:\n if part:\n infer_multiplicity(part, scope_tree=scope_tree, ctx=ctx)\n\n return result\n\ndef _infer_for_multiplicity(\n ir: irast.SelectStmt,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n\n assert ir.iterator_stmt is not None\n itexpr = ir.iterator_stmt.expr\n\n if isinstance(ir.result.expr, irast.SelectStmt):\n union = ir.result.expr\n if (isinstance(union.where, irast.Set) and\n isinstance(union.where.expr, irast.OperatorCall) and\n str(union.where.expr.func_shortname) == 'std::='):\n\n op = union.where.expr\n left, right = (a.expr for a in op.args)\n\n # The iterator set may be wrapped in an `enumerate`, this\n # requires different handling.\n has_enumerate = (\n isinstance(itexpr, irast.SelectStmt) and\n isinstance(itfn := itexpr.result.expr, irast.FunctionCall) and\n str(itfn.func_shortname) == 'std::enumerate'\n )\n\n # First make sure that the cardinality of the FILTER\n # expression is is no more than 1. Then make sure both\n # operands are paths.\n if union.where_card.is_single():\n it = None\n if left.rptr is not None:\n it = right\n elif right.rptr is not None:\n it = left\n\n if it is not None:\n if has_enumerate:\n assert isinstance(itfn, irast.FunctionCall)\n enumerate_mult = infer_multiplicity(\n itfn.args[0].expr, scope_tree=scope_tree, ctx=ctx,\n )\n if (\n enumerate_mult is ONE\n and it.rptr is not None\n and isinstance(\n it.rptr,\n irast.TupleIndirectionPointer\n )\n # Tuple comes from the iterator set\n and it.rptr.source.expr is itexpr\n # the indirection is accessing element 1\n and str(it.rptr.ptrref.name) == '__tuple__::1'\n ):\n return ONE\n elif (it.is_binding and it.expr is itexpr):\n return ONE\n\n elif isinstance(ir.result.expr, irast.InsertStmt):\n # A union of inserts always has multiplicity ONE\n return ONE\n\n return MANY\n\n@_infer_multiplicity.register\ndef __infer_select_stmt(\n ir: irast.SelectStmt,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n result = _infer_stmt_multiplicity(ir, scope_tree=scope_tree, ctx=ctx)\n itmult = None\n\n if ir.iterator_stmt:\n # If this is a FOR, then there's a common pattern which can be\n # detected and the multiplicity of it is ONE. Otherwise it\n # cannot be reliably inferred.\n #\n # The pattern is: FOR x IN {} UNION\n # (SELECT ... FILTER .prop = x) As long as the FILTER has just\n # a single .prop = x expression, this is going to be a bunch\n # of disjoint unions and the final multiplicity will be ONE.\n itmult = infer_multiplicity(\n ir.iterator_stmt, scope_tree=scope_tree, ctx=ctx,\n )\n\n # OFFSET, LIMIT and ORDER BY have already been validated to be\n # singletons, but their sub-expressions (if any) still need to be\n # validated.\n for part in [ir.limit, ir.offset] + [sort.expr for sort in ir.orderby]:\n if part:\n new_scope = cardinality._get_set_scope(part, scope_tree, ctx=ctx)\n infer_multiplicity(part, scope_tree=new_scope, ctx=ctx)\n\n if itmult is not None:\n if itmult is ONE:\n return _infer_for_multiplicity(\n ir, scope_tree=scope_tree, ctx=ctx)\n\n return MANY\n else:\n return result\n\n@_infer_multiplicity.register\ndef __infer_insert_stmt(\n ir: irast.InsertStmt,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n # INSERT will always return a proper set, but we still want to\n # process the sub-expressions.\n infer_multiplicity(\n ir.subject, is_mutation=True, scope_tree=scope_tree, ctx=ctx\n )\n new_scope = cardinality._get_set_scope(ir.result, scope_tree, ctx=ctx)\n infer_multiplicity(\n ir.result, is_mutation=True, scope_tree=new_scope, ctx=ctx\n )\n\n if ir.on_conflict:\n for part in [ir.on_conflict.select_ir, ir.on_conflict.else_ir]:\n if part:\n infer_multiplicity(part, scope_tree=scope_tree, ctx=ctx)\n\n return ONE\n\n@_infer_multiplicity.register\ndef __infer_update_stmt(\n ir: irast.UpdateStmt,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n # Presumably UPDATE will always return a proper set, even if it's\n # fed something with higher multiplicity, but we still want to\n # process the expression being updated.\n infer_multiplicity(\n ir.result, is_mutation=True, scope_tree=scope_tree, ctx=ctx,\n )\n result = _infer_stmt_multiplicity(ir, scope_tree=scope_tree, ctx=ctx)\n if result is ZERO:\n return ZERO\n else:\n return ONE\n\n@_infer_multiplicity.register\ndef __infer_delete_stmt(\n ir: irast.DeleteStmt,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n # Presumably DELETE will always return a proper set, even if it's\n # fed something with higher multiplicity, but we still want to\n # process the expression being deleted.\n infer_multiplicity(\n ir.result, is_mutation=True, scope_tree=scope_tree, ctx=ctx,\n )\n result = _infer_stmt_multiplicity(ir, scope_tree=scope_tree, ctx=ctx)\n if result is ZERO:\n return ZERO\n else:\n return ONE\n\n@_infer_multiplicity.register\ndef __infer_group_stmt(\n ir: irast.GroupStmt,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n raise NotImplementedError\n\n@_infer_multiplicity.register\ndef __infer_slice(\n ir: irast.SliceIndirection,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n # Slice indirection multiplicity is guaranteed to be ONE as long\n # as the cardinality of this expression is at most one, otherwise\n # the results of index indirection can contain values with\n # multiplicity > 1.\n card = cardinality.infer_cardinality(\n ir, scope_tree=scope_tree, ctx=ctx)\n if card is not None and card.is_single():\n return ONE\n else:\n return MANY\n\n@_infer_multiplicity.register\ndef __infer_index(\n ir: irast.IndexIndirection,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n # Index indirection multiplicity is guaranteed to be ONE as long\n # as the cardinality of this expression is at most one, otherwise\n # the results of index indirection can contain values with\n # multiplicity > 1.\n card = cardinality.infer_cardinality(\n ir, scope_tree=scope_tree, ctx=ctx)\n if card is not None and card.is_single():\n return ONE\n else:\n return MANY\n\n@_infer_multiplicity.register\ndef __infer_array(\n ir: irast.Array,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n return _common_multiplicity(ir.elements, scope_tree=scope_tree, ctx=ctx)\n\n@_infer_multiplicity.register\ndef __infer_tuple(\n ir: irast.Tuple,\n *,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n return _common_multiplicity(\n [el.val for el in ir.elements], scope_tree=scope_tree, ctx=ctx\n )\n\ndef infer_multiplicity(\n ir: irast.Base,\n *,\n is_mutation: bool=False,\n scope_tree: irast.ScopeTreeNode,\n ctx: inference_context.InfCtx,\n) -> qltypes.Multiplicity:\n\n result = ctx.inferred_multiplicity.get((ir, scope_tree))\n if result is not None:\n return result\n\n # We can use cardinality as a helper in determining multiplicity,\n # since singletons have multiplicity one.\n card = cardinality.infer_cardinality(\n ir, is_mutation=is_mutation, scope_tree=scope_tree, ctx=ctx)\n\n if isinstance(ir, irast.Set):\n result = _infer_set(\n ir, is_mutation=is_mutation, scope_tree=scope_tree, ctx=ctx,\n )\n else:\n result = _infer_multiplicity(ir, scope_tree=scope_tree, ctx=ctx)\n\n if card is not None and card.is_single():\n # We've validated multiplicity, so now we can just override it\n # safely.\n result = ONE\n\n if result not in {ZERO, ONE, MANY}:\n raise errors.QueryError(\n 'could not determine the multiplicity of '\n 'set produced by expression',\n context=ir.context)\n\n ctx.inferred_multiplicity[ir, scope_tree] = result\n\n return result"}]} {"messages": [{"role": "user", "content": "Write Python code that implements maf_template.py from pfi/maf (path: maf_template.py)."}, {"role": "assistant", "content": "# maf_template.py (from pfi/maf, license: bsd-2-clause)\n\n#!/usr/bin/env python\n# coding: ISO8859-1\n#\n# Copyright (c) 2013, Preferred Infrastructure, Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\nmaf - a waf extension for automation of parameterized computational experiments\n\"\"\"\n\n# NOTE: coding ISO8859-1 is necessary for attaching maflib at the end of this\n# file.\n\nimport os\nimport os.path\nimport shutil\nimport subprocess\nimport sys\nimport tarfile\nimport waflib.Context\nimport waflib.Logs\n\nTAR_NAME = 'maflib.tar'\nNEW_LINE = '#XXX'.encode()\nCARRIAGE_RETURN = '#YYY'.encode()\nARCHIVE_BEGIN = '#==>\\n'.encode()\nARCHIVE_END = '#<==\\n'.encode()\n\nclass _Cleaner:\n def __init__(self, directory):\n self._cwd = os.getcwd()\n self._directory = directory\n\n def __enter__(self):\n self.clean()\n\n def __exit__(self, exc_type, exc_value, traceback):\n os.chdir(self._cwd)\n if exc_type:\n self.clean()\n return False\n\n def clean(self):\n try:\n path = os.path.join(self._directory, 'maflib')\n shutil.rmtree(path)\n except OSError:\n pass\n\ndef _read_archive(filename):\n if filename.endswith('.pyc'):\n filename = filename[:-1]\n\n with open(filename, 'rb') as f:\n while True:\n line = f.readline()\n if not line:\n raise Exception('archive not found')\n if line == ARCHIVE_BEGIN:\n content = f.readline()\n if not content or f.readline() != ARCHIVE_END:\n raise Exception('corrupt archive')\n break\n\n return content[1:-1].replace(NEW_LINE, '\\n'.encode()).replace(\n CARRIAGE_RETURN, '\\r'.encode())\n\ndef unpack_maflib(directory):\n with _Cleaner(directory) as c:\n content = _read_archive(__file__)\n\n os.makedirs(os.path.join(directory, 'maflib'))\n os.chdir(directory)\n\n bz2_name = TAR_NAME + '.bz2'\n with open(bz2_name, 'wb') as f:\n f.write(content)\n\n try:\n t = tarfile.open(bz2_name)\n except:\n try:\n os.system('bunzip2 ' + bz2_name)\n t = tarfile.open(TAR_NAME)\n except:\n raise Exception('Cannot extract maflib. Check that python bz2 module or bunzip2 command is available.')\n\n try:\n t.extractall()\n finally:\n t.close()\n\n try:\n os.remove(bz2_name)\n os.remove(TAR_NAME)\n except:\n pass\n\n maflib_path = os.path.abspath(os.getcwd())\n return maflib_path\n\ndef test_maflib(directory):\n try:\n os.stat(os.path.join(directory, 'maflib'))\n return os.path.abspath(directory)\n except OSError:\n return None\n\ndef find_maflib():\n path = waflib.Context.waf_dir\n if not test_maflib(path):\n unpack_maflib(path)\n return path\n\nfind_maflib()\nimport maflib.core"}]} {"messages": [{"role": "user", "content": "Write Python code that implements db_base_plugin_common.py from eonpatapon/neutron (path: neutron/db/db_base_plugin_common.py)."}, {"role": "assistant", "content": "# neutron/db/db_base_plugin_common.py (from eonpatapon/neutron, license: apache-2.0)\n\n# Copyright (c) 2015 OpenStack Foundation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport functools\n\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom sqlalchemy.orm import exc\n\nfrom neutron.api.v2 import attributes\nfrom neutron.common import constants\nfrom neutron.common import exceptions as n_exc\nfrom neutron.common import utils\nfrom neutron.db import common_db_mixin\nfrom neutron.db import models_v2\n\nLOG = logging.getLogger(__name__)\n\nclass DbBasePluginCommon(common_db_mixin.CommonDbMixin):\n \"\"\"Stores getters and helper methods for db_base_plugin_v2\n\n All private getters and simple helpers like _make_*_dict were moved from\n db_base_plugin_v2.\n More complicated logic and public methods left in db_base_plugin_v2.\n Main purpose of this class is to make getters accessible for Ipam\n backends.\n \"\"\"\n\n @staticmethod\n def _generate_mac():\n return utils.get_random_mac(cfg.CONF.base_mac.split(':'))\n\n @staticmethod\n def _delete_ip_allocation(context, network_id, subnet_id, ip_address):\n\n # Delete the IP address from the IPAllocate table\n LOG.debug(\"Delete allocated IP %(ip_address)s \"\n \"(%(network_id)s/%(subnet_id)s)\",\n {'ip_address': ip_address,\n 'network_id': network_id,\n 'subnet_id': subnet_id})\n context.session.query(models_v2.IPAllocation).filter_by(\n network_id=network_id,\n ip_address=ip_address,\n subnet_id=subnet_id).delete()\n\n @staticmethod\n def _store_ip_allocation(context, ip_address, network_id, subnet_id,\n port_id):\n LOG.debug(\"Allocated IP %(ip_address)s \"\n \"(%(network_id)s/%(subnet_id)s/%(port_id)s)\",\n {'ip_address': ip_address,\n 'network_id': network_id,\n 'subnet_id': subnet_id,\n 'port_id': port_id})\n allocated = models_v2.IPAllocation(\n network_id=network_id,\n port_id=port_id,\n ip_address=ip_address,\n subnet_id=subnet_id\n )\n context.session.add(allocated)\n\n def _make_subnet_dict(self, subnet, fields=None, context=None):\n res = {'id': subnet['id'],\n 'name': subnet['name'],\n 'tenant_id': subnet['tenant_id'],\n 'network_id': subnet['network_id'],\n 'ip_version': subnet['ip_version'],\n 'cidr': subnet['cidr'],\n 'subnetpool_id': subnet.get('subnetpool_id'),\n 'allocation_pools': [{'start': pool['first_ip'],\n 'end': pool['last_ip']}\n for pool in subnet['allocation_pools']],\n 'gateway_ip': subnet['gateway_ip'],\n 'enable_dhcp': subnet['enable_dhcp'],\n 'ipv6_ra_mode': subnet['ipv6_ra_mode'],\n 'ipv6_address_mode': subnet['ipv6_address_mode'],\n 'dns_nameservers': [dns['address']\n for dns in subnet['dns_nameservers']],\n 'host_routes': [{'destination': route['destination'],\n 'nexthop': route['nexthop']}\n for route in subnet['routes']],\n }\n # The shared attribute for a subnet is the same as its parent network\n res['shared'] = self._make_network_dict(subnet.networks,\n context=context)['shared']\n # Call auxiliary extend functions, if any\n self._apply_dict_extend_functions(attributes.SUBNETS, res, subnet)\n return self._fields(res, fields)\n\n def _make_subnetpool_dict(self, subnetpool, fields=None):\n default_prefixlen = str(subnetpool['default_prefixlen'])\n min_prefixlen = str(subnetpool['min_prefixlen'])\n max_prefixlen = str(subnetpool['max_prefixlen'])\n res = {'id': subnetpool['id'],\n 'name': subnetpool['name'],\n 'tenant_id': subnetpool['tenant_id'],\n 'default_prefixlen': default_prefixlen,\n 'min_prefixlen': min_prefixlen,\n 'max_prefixlen': max_prefixlen,\n 'shared': subnetpool['shared'],\n 'prefixes': [prefix['cidr']\n for prefix in subnetpool['prefixes']],\n 'ip_version': subnetpool['ip_version'],\n 'default_quota': subnetpool['default_quota']}\n return self._fields(res, fields)\n\n def _make_port_dict(self, port, fields=None,\n process_extensions=True):\n res = {\"id\": port[\"id\"],\n 'name': port['name'],\n \"network_id\": port[\"network_id\"],\n 'tenant_id': port['tenant_id'],\n \"mac_address\": port[\"mac_address\"],\n \"admin_state_up\": port[\"admin_state_up\"],\n \"status\": port[\"status\"],\n \"fixed_ips\": [{'subnet_id': ip[\"subnet_id\"],\n 'ip_address': ip[\"ip_address\"]}\n for ip in port[\"fixed_ips\"]],\n \"device_id\": port[\"device_id\"],\n \"device_owner\": port[\"device_owner\"]}\n # Call auxiliary extend functions, if any\n if process_extensions:\n self._apply_dict_extend_functions(\n attributes.PORTS, res, port)\n return self._fields(res, fields)\n\n def _get_network(self, context, id):\n try:\n network = self._get_by_id(context, models_v2.Network, id)\n except exc.NoResultFound:\n raise n_exc.NetworkNotFound(net_id=id)\n return network\n\n def _get_subnet(self, context, id):\n try:\n subnet = self._get_by_id(context, models_v2.Subnet, id)\n except exc.NoResultFound:\n raise n_exc.SubnetNotFound(subnet_id=id)\n return subnet\n\n def _get_subnetpool(self, context, id):\n try:\n return self._get_by_id(context, models_v2.SubnetPool, id)\n except exc.NoResultFound:\n raise n_exc.SubnetPoolNotFound(subnetpool_id=id)\n\n def _get_all_subnetpools(self, context):\n # NOTE(tidwellr): see note in _get_all_subnets()\n return context.session.query(models_v2.SubnetPool).all()\n\n def _get_port(self, context, id):\n try:\n port = self._get_by_id(context, models_v2.Port, id)\n except exc.NoResultFound:\n raise n_exc.PortNotFound(port_id=id)\n return port\n\n def _get_dns_by_subnet(self, context, subnet_id):\n dns_qry = context.session.query(models_v2.DNSNameServer)\n return dns_qry.filter_by(subnet_id=subnet_id).all()\n\n def _get_route_by_subnet(self, context, subnet_id):\n route_qry = context.session.query(models_v2.SubnetRoute)\n return route_qry.filter_by(subnet_id=subnet_id).all()\n\n def _get_router_gw_ports_by_network(self, context, network_id):\n port_qry = context.session.query(models_v2.Port)\n return port_qry.filter_by(network_id=network_id,\n device_owner=constants.DEVICE_OWNER_ROUTER_GW).all()\n\n def _get_subnets_by_network(self, context, network_id):\n subnet_qry = context.session.query(models_v2.Subnet)\n return subnet_qry.filter_by(network_id=network_id).all()\n\n def _get_subnets_by_subnetpool(self, context, subnetpool_id):\n subnet_qry = context.session.query(models_v2.Subnet)\n return subnet_qry.filter_by(subnetpool_id=subnetpool_id).all()\n\n def _get_all_subnets(self, context):\n # NOTE(salvatore-orlando): This query might end up putting\n # a lot of stress on the db. Consider adding a cache layer\n return context.session.query(models_v2.Subnet).all()\n\n def _get_subnets(self, context, filters=None, fields=None,\n sorts=None, limit=None, marker=None,\n page_reverse=False):\n marker_obj = self._get_marker_obj(context, 'subnet', limit, marker)\n make_subnet_dict = functools.partial(self._make_subnet_dict,\n context=context)\n return self._get_collection(context, models_v2.Subnet,\n make_subnet_dict,\n filters=filters, fields=fields,\n sorts=sorts,\n limit=limit,\n marker_obj=marker_obj,\n page_reverse=page_reverse)\n\n def _make_network_dict(self, network, fields=None,\n process_extensions=True, context=None):\n res = {'id': network['id'],\n 'name': network['name'],\n 'tenant_id': network['tenant_id'],\n 'admin_state_up': network['admin_state_up'],\n 'mtu': network.get('mtu', constants.DEFAULT_NETWORK_MTU),\n 'status': network['status'],\n 'subnets': [subnet['id']\n for subnet in network['subnets']]}\n # The shared attribute for a network now reflects if the network\n # is shared to the calling tenant via an RBAC entry.\n shared = False\n matches = ('*',) + ((context.tenant_id,) if context else ())\n for entry in network.rbac_entries:\n if (entry.action == 'access_as_shared' and\n entry.target_tenant in matches):\n shared = True\n break\n res['shared'] = shared\n # TODO(pritesh): Move vlan_transparent to the extension module.\n # vlan_transparent here is only added if the vlantransparent\n # extension is enabled.\n if ('vlan_transparent' in network and network['vlan_transparent'] !=\n attributes.ATTR_NOT_SPECIFIED):\n res['vlan_transparent'] = network['vlan_transparent']\n # Call auxiliary extend functions, if any\n if process_extensions:\n self._apply_dict_extend_functions(\n attributes.NETWORKS, res, network)\n return self._fields(res, fields)\n\n def _make_subnet_args(self, detail, subnet, subnetpool_id):\n gateway_ip = str(detail.gateway_ip) if detail.gateway_ip else None\n args = {'tenant_id': detail.tenant_id,\n 'id': detail.subnet_id,\n 'name': subnet['name'],\n 'network_id': subnet['network_id'],\n 'ip_version': subnet['ip_version'],\n 'cidr': str(detail.subnet_cidr),\n 'subnetpool_id': subnetpool_id,\n 'enable_dhcp': subnet['enable_dhcp'],\n 'gateway_ip': gateway_ip}\n if subnet['ip_version'] == 6 and subnet['enable_dhcp']:\n if attributes.is_attr_set(subnet['ipv6_ra_mode']):\n args['ipv6_ra_mode'] = subnet['ipv6_ra_mode']\n if attributes.is_attr_set(subnet['ipv6_address_mode']):\n args['ipv6_address_mode'] = subnet['ipv6_address_mode']\n return args\n\n def _make_fixed_ip_dict(self, ips):\n # Excludes from dict all keys except subnet_id and ip_address\n return [{'subnet_id': ip[\"subnet_id\"],\n 'ip_address': ip[\"ip_address\"]}\n for ip in ips]"}]} {"messages": [{"role": "user", "content": "Write Python code that implements _links_test.py from iMilind/grpc (path: src/python/src/grpc/_adapter/_links_test.py)."}, {"role": "assistant", "content": "# src/python/src/grpc/_adapter/_links_test.py (from iMilind/grpc, license: bsd-3-clause)\n\n# Copyright 2015, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Test of the GRPC-backed ForeLink and RearLink.\"\"\"\n\nimport threading\nimport unittest\n\nfrom grpc._adapter import _proto_scenarios\nfrom grpc._adapter import _test_links\nfrom grpc._adapter import fore\nfrom grpc._adapter import rear\nfrom grpc.framework.base import interfaces\nfrom grpc.framework.foundation import logging_pool\n\n_IDENTITY = lambda x: x\n_TIMEOUT = 2\n\nclass RoundTripTest(unittest.TestCase):\n\n def setUp(self):\n self.fore_link_pool = logging_pool.pool(80)\n self.rear_link_pool = logging_pool.pool(80)\n\n def tearDown(self):\n self.rear_link_pool.shutdown(wait=True)\n self.fore_link_pool.shutdown(wait=True)\n\n def testZeroMessageRoundTrip(self):\n test_operation_id = object()\n test_method = 'test method'\n test_fore_link = _test_links.ForeLink(None, None)\n def rear_action(front_to_back_ticket, fore_link):\n if front_to_back_ticket.kind in (\n interfaces.FrontToBackTicket.Kind.COMPLETION,\n interfaces.FrontToBackTicket.Kind.ENTIRE):\n back_to_front_ticket = interfaces.BackToFrontTicket(\n front_to_back_ticket.operation_id, 0,\n interfaces.BackToFrontTicket.Kind.COMPLETION, None)\n fore_link.accept_back_to_front_ticket(back_to_front_ticket)\n test_rear_link = _test_links.RearLink(rear_action, None)\n\n fore_link = fore.ForeLink(\n self.fore_link_pool, {test_method: None}, {test_method: None}, None, ())\n fore_link.join_rear_link(test_rear_link)\n test_rear_link.join_fore_link(fore_link)\n fore_link.start()\n port = fore_link.port()\n\n rear_link = rear.RearLink(\n 'localhost', port, self.rear_link_pool, {test_method: None},\n {test_method: None}, False, None, None, None)\n rear_link.join_fore_link(test_fore_link)\n test_fore_link.join_rear_link(rear_link)\n rear_link.start()\n\n front_to_back_ticket = interfaces.FrontToBackTicket(\n test_operation_id, 0, interfaces.FrontToBackTicket.Kind.ENTIRE,\n test_method, interfaces.ServicedSubscription.Kind.FULL, None, None,\n _TIMEOUT)\n rear_link.accept_front_to_back_ticket(front_to_back_ticket)\n\n with test_fore_link.condition:\n while (not test_fore_link.tickets or\n test_fore_link.tickets[-1].kind is\n interfaces.BackToFrontTicket.Kind.CONTINUATION):\n test_fore_link.condition.wait()\n\n rear_link.stop()\n fore_link.stop()\n\n with test_fore_link.condition:\n self.assertIs(\n test_fore_link.tickets[-1].kind,\n interfaces.BackToFrontTicket.Kind.COMPLETION)\n\n def testEntireRoundTrip(self):\n test_operation_id = object()\n test_method = 'test method'\n test_front_to_back_datum = b'\\x07'\n test_back_to_front_datum = b'\\x08'\n test_fore_link = _test_links.ForeLink(None, None)\n rear_sequence_number = [0]\n def rear_action(front_to_back_ticket, fore_link):\n if front_to_back_ticket.payload is None:\n payload = None\n else:\n payload = test_back_to_front_datum\n terminal = front_to_back_ticket.kind in (\n interfaces.FrontToBackTicket.Kind.COMPLETION,\n interfaces.FrontToBackTicket.Kind.ENTIRE)\n if payload is not None or terminal:\n if terminal:\n kind = interfaces.BackToFrontTicket.Kind.COMPLETION\n else:\n kind = interfaces.BackToFrontTicket.Kind.CONTINUATION\n back_to_front_ticket = interfaces.BackToFrontTicket(\n front_to_back_ticket.operation_id, rear_sequence_number[0], kind,\n payload)\n rear_sequence_number[0] += 1\n fore_link.accept_back_to_front_ticket(back_to_front_ticket)\n test_rear_link = _test_links.RearLink(rear_action, None)\n\n fore_link = fore.ForeLink(\n self.fore_link_pool, {test_method: _IDENTITY},\n {test_method: _IDENTITY}, None, ())\n fore_link.join_rear_link(test_rear_link)\n test_rear_link.join_fore_link(fore_link)\n fore_link.start()\n port = fore_link.port()\n\n rear_link = rear.RearLink(\n 'localhost', port, self.rear_link_pool, {test_method: _IDENTITY},\n {test_method: _IDENTITY}, False, None, None, None)\n rear_link.join_fore_link(test_fore_link)\n test_fore_link.join_rear_link(rear_link)\n rear_link.start()\n\n front_to_back_ticket = interfaces.FrontToBackTicket(\n test_operation_id, 0, interfaces.FrontToBackTicket.Kind.ENTIRE,\n test_method, interfaces.ServicedSubscription.Kind.FULL, None,\n test_front_to_back_datum, _TIMEOUT)\n rear_link.accept_front_to_back_ticket(front_to_back_ticket)\n\n with test_fore_link.condition:\n while (not test_fore_link.tickets or\n test_fore_link.tickets[-1].kind is not\n interfaces.BackToFrontTicket.Kind.COMPLETION):\n test_fore_link.condition.wait()\n\n rear_link.stop()\n fore_link.stop()\n\n with test_rear_link.condition:\n front_to_back_payloads = tuple(\n ticket.payload for ticket in test_rear_link.tickets\n if ticket.payload is not None)\n with test_fore_link.condition:\n back_to_front_payloads = tuple(\n ticket.payload for ticket in test_fore_link.tickets\n if ticket.payload is not None)\n self.assertTupleEqual((test_front_to_back_datum,), front_to_back_payloads)\n self.assertTupleEqual((test_back_to_front_datum,), back_to_front_payloads)\n\n def _perform_scenario_test(self, scenario):\n test_operation_id = object()\n test_method = scenario.method()\n test_fore_link = _test_links.ForeLink(None, None)\n rear_lock = threading.Lock()\n rear_sequence_number = [0]\n def rear_action(front_to_back_ticket, fore_link):\n with rear_lock:\n if front_to_back_ticket.payload is not None:\n response = scenario.response_for_request(front_to_back_ticket.payload)\n else:\n response = None\n terminal = front_to_back_ticket.kind in (\n interfaces.FrontToBackTicket.Kind.COMPLETION,\n interfaces.FrontToBackTicket.Kind.ENTIRE)\n if response is not None or terminal:\n if terminal:\n kind = interfaces.BackToFrontTicket.Kind.COMPLETION\n else:\n kind = interfaces.BackToFrontTicket.Kind.CONTINUATION\n back_to_front_ticket = interfaces.BackToFrontTicket(\n front_to_back_ticket.operation_id, rear_sequence_number[0], kind,\n response)\n rear_sequence_number[0] += 1\n fore_link.accept_back_to_front_ticket(back_to_front_ticket)\n test_rear_link = _test_links.RearLink(rear_action, None)\n\n fore_link = fore.ForeLink(\n self.fore_link_pool, {test_method: scenario.deserialize_request},\n {test_method: scenario.serialize_response}, None, ())\n fore_link.join_rear_link(test_rear_link)\n test_rear_link.join_fore_link(fore_link)\n fore_link.start()\n port = fore_link.port()\n\n rear_link = rear.RearLink(\n 'localhost', port, self.rear_link_pool,\n {test_method: scenario.serialize_request},\n {test_method: scenario.deserialize_response}, False, None, None, None)\n rear_link.join_fore_link(test_fore_link)\n test_fore_link.join_rear_link(rear_link)\n rear_link.start()\n\n commencement_ticket = interfaces.FrontToBackTicket(\n test_operation_id, 0,\n interfaces.FrontToBackTicket.Kind.COMMENCEMENT, test_method,\n interfaces.ServicedSubscription.Kind.FULL, None, None,\n _TIMEOUT)\n fore_sequence_number = 1\n rear_link.accept_front_to_back_ticket(commencement_ticket)\n for request in scenario.requests():\n continuation_ticket = interfaces.FrontToBackTicket(\n test_operation_id, fore_sequence_number,\n interfaces.FrontToBackTicket.Kind.CONTINUATION, None, None, None,\n request, None)\n fore_sequence_number += 1\n rear_link.accept_front_to_back_ticket(continuation_ticket)\n completion_ticket = interfaces.FrontToBackTicket(\n test_operation_id, fore_sequence_number,\n interfaces.FrontToBackTicket.Kind.COMPLETION, None, None, None, None,\n None)\n fore_sequence_number += 1\n rear_link.accept_front_to_back_ticket(completion_ticket)\n\n with test_fore_link.condition:\n while (not test_fore_link.tickets or\n test_fore_link.tickets[-1].kind is not\n interfaces.BackToFrontTicket.Kind.COMPLETION):\n test_fore_link.condition.wait()\n\n rear_link.stop()\n fore_link.stop()\n\n with test_rear_link.condition:\n requests = tuple(\n ticket.payload for ticket in test_rear_link.tickets\n if ticket.payload is not None)\n with test_fore_link.condition:\n responses = tuple(\n ticket.payload for ticket in test_fore_link.tickets\n if ticket.payload is not None)\n self.assertTrue(scenario.verify_requests(requests))\n self.assertTrue(scenario.verify_responses(responses))\n\n def testEmptyScenario(self):\n self._perform_scenario_test(_proto_scenarios.EmptyScenario())\n\n def testBidirectionallyUnaryScenario(self):\n self._perform_scenario_test(_proto_scenarios.BidirectionallyUnaryScenario())\n\n def testBidirectionallyStreamingScenario(self):\n self._perform_scenario_test(\n _proto_scenarios.BidirectionallyStreamingScenario())\n\nif __name__ == '__main__':\n unittest.main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements comments.py from jarvys/django-1.7-jdb (path: django/contrib/comments/templatetags/comments.py)."}, {"role": "assistant", "content": "# django/contrib/comments/templatetags/comments.py (from jarvys/django-1.7-jdb, license: bsd-3-clause)\n\nfrom django import template\nfrom django.template.loader import render_to_string\nfrom django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib import comments\nfrom django.utils import six\nfrom django.utils.deprecation import RenameMethodsBase, RemovedInDjango18Warning\nfrom django.utils.encoding import smart_text\n\nregister = template.Library()\n\nclass RenameBaseCommentNodeMethods(RenameMethodsBase):\n renamed_methods = (\n ('get_query_set', 'get_queryset', RemovedInDjango18Warning),\n )\n\nclass BaseCommentNode(six.with_metaclass(RenameBaseCommentNodeMethods, template.Node)):\n \"\"\"\n Base helper class (abstract) for handling the get_comment_* template tags.\n Looks a bit strange, but the subclasses below should make this a bit more\n obvious.\n \"\"\"\n\n @classmethod\n def handle_token(cls, parser, token):\n \"\"\"Class method to parse get_comment_list/count/form and return a Node.\"\"\"\n tokens = token.split_contents()\n if tokens[1] != 'for':\n raise template.TemplateSyntaxError(\"Second argument in %r tag must be 'for'\" % tokens[0])\n\n # {% get_whatever for obj as varname %}\n if len(tokens) == 5:\n if tokens[3] != 'as':\n raise template.TemplateSyntaxError(\"Third argument in %r must be 'as'\" % tokens[0])\n return cls(\n object_expr=parser.compile_filter(tokens[2]),\n as_varname=tokens[4],\n )\n\n # {% get_whatever for app.model pk as varname %}\n elif len(tokens) == 6:\n if tokens[4] != 'as':\n raise template.TemplateSyntaxError(\"Fourth argument in %r must be 'as'\" % tokens[0])\n return cls(\n ctype=BaseCommentNode.lookup_content_type(tokens[2], tokens[0]),\n object_pk_expr=parser.compile_filter(tokens[3]),\n as_varname=tokens[5]\n )\n\n else:\n raise template.TemplateSyntaxError(\"%r tag requires 4 or 5 arguments\" % tokens[0])\n\n @staticmethod\n def lookup_content_type(token, tagname):\n try:\n app, model = token.split('.')\n return ContentType.objects.get_by_natural_key(app, model)\n except ValueError:\n raise template.TemplateSyntaxError(\"Third argument in %r must be in the format 'app.model'\" % tagname)\n except ContentType.DoesNotExist:\n raise template.TemplateSyntaxError(\"%r tag has non-existant content-type: '%s.%s'\" % (tagname, app, model))\n\n def __init__(self, ctype=None, object_pk_expr=None, object_expr=None, as_varname=None, comment=None):\n if ctype is None and object_expr is None:\n raise template.TemplateSyntaxError(\"Comment nodes must be given either a literal object or a ctype and object pk.\")\n self.comment_model = comments.get_model()\n self.as_varname = as_varname\n self.ctype = ctype\n self.object_pk_expr = object_pk_expr\n self.object_expr = object_expr\n self.comment = comment\n\n def render(self, context):\n qs = self.get_queryset(context)\n context[self.as_varname] = self.get_context_value_from_queryset(context, qs)\n return ''\n\n def get_queryset(self, context):\n ctype, object_pk = self.get_target_ctype_pk(context)\n if not object_pk:\n return self.comment_model.objects.none()\n\n qs = self.comment_model.objects.filter(\n content_type=ctype,\n object_pk=smart_text(object_pk),\n site__pk=settings.SITE_ID,\n )\n\n # The is_public and is_removed fields are implementation details of the\n # built-in comment model's spam filtering system, so they might not\n # be present on a custom comment model subclass. If they exist, we\n # should filter on them.\n field_names = [f.name for f in self.comment_model._meta.fields]\n if 'is_public' in field_names:\n qs = qs.filter(is_public=True)\n if getattr(settings, 'COMMENTS_HIDE_REMOVED', True) and 'is_removed' in field_names:\n qs = qs.filter(is_removed=False)\n\n return qs\n\n def get_target_ctype_pk(self, context):\n if self.object_expr:\n try:\n obj = self.object_expr.resolve(context)\n except template.VariableDoesNotExist:\n return None, None\n return ContentType.objects.get_for_model(obj), obj.pk\n else:\n return self.ctype, self.object_pk_expr.resolve(context, ignore_failures=True)\n\n def get_context_value_from_queryset(self, context, qs):\n \"\"\"Subclasses should override this.\"\"\"\n raise NotImplementedError('subclasses of BaseCommentNode must provide a get_context_value_from_queryset() method')\n\nclass CommentListNode(BaseCommentNode):\n \"\"\"Insert a list of comments into the context.\"\"\"\n def get_context_value_from_queryset(self, context, qs):\n return list(qs)\n\nclass CommentCountNode(BaseCommentNode):\n \"\"\"Insert a count of comments into the context.\"\"\"\n def get_context_value_from_queryset(self, context, qs):\n return qs.count()\n\nclass CommentFormNode(BaseCommentNode):\n \"\"\"Insert a form for the comment model into the context.\"\"\"\n\n def get_form(self, context):\n obj = self.get_object(context)\n if obj:\n return comments.get_form()(obj)\n else:\n return None\n\n def get_object(self, context):\n if self.object_expr:\n try:\n return self.object_expr.resolve(context)\n except template.VariableDoesNotExist:\n return None\n else:\n object_pk = self.object_pk_expr.resolve(context,\n ignore_failures=True)\n return self.ctype.get_object_for_this_type(pk=object_pk)\n\n def render(self, context):\n context[self.as_varname] = self.get_form(context)\n return ''\n\nclass RenderCommentFormNode(CommentFormNode):\n \"\"\"Render the comment form directly\"\"\"\n\n @classmethod\n def handle_token(cls, parser, token):\n \"\"\"Class method to parse render_comment_form and return a Node.\"\"\"\n tokens = token.split_contents()\n if tokens[1] != 'for':\n raise template.TemplateSyntaxError(\"Second argument in %r tag must be 'for'\" % tokens[0])\n\n # {% render_comment_form for obj %}\n if len(tokens) == 3:\n return cls(object_expr=parser.compile_filter(tokens[2]))\n\n # {% render_comment_form for app.models pk %}\n elif len(tokens) == 4:\n return cls(\n ctype=BaseCommentNode.lookup_content_type(tokens[2], tokens[0]),\n object_pk_expr=parser.compile_filter(tokens[3])\n )\n\n def render(self, context):\n ctype, object_pk = self.get_target_ctype_pk(context)\n if object_pk:\n template_search_list = [\n \"comments/%s/%s/form.html\" % (ctype.app_label, ctype.model),\n \"comments/%s/form.html\" % ctype.app_label,\n \"comments/form.html\"\n ]\n context.push()\n formstr = render_to_string(template_search_list, {\"form\" : self.get_form(context)}, context)\n context.pop()\n return formstr\n else:\n return ''\n\nclass RenderCommentListNode(CommentListNode):\n \"\"\"Render the comment list directly\"\"\"\n\n @classmethod\n def handle_token(cls, parser, token):\n \"\"\"Class method to parse render_comment_list and return a Node.\"\"\"\n tokens = token.split_contents()\n if tokens[1] != 'for':\n raise template.TemplateSyntaxError(\"Second argument in %r tag must be 'for'\" % tokens[0])\n\n # {% render_comment_list for obj %}\n if len(tokens) == 3:\n return cls(object_expr=parser.compile_filter(tokens[2]))\n\n # {% render_comment_list for app.models pk %}\n elif len(tokens) == 4:\n return cls(\n ctype=BaseCommentNode.lookup_content_type(tokens[2], tokens[0]),\n object_pk_expr=parser.compile_filter(tokens[3])\n )\n\n def render(self, context):\n ctype, object_pk = self.get_target_ctype_pk(context)\n if object_pk:\n template_search_list = [\n \"comments/%s/%s/list.html\" % (ctype.app_label, ctype.model),\n \"comments/%s/list.html\" % ctype.app_label,\n \"comments/list.html\"\n ]\n qs = self.get_queryset(context)\n context.push()\n liststr = render_to_string(template_search_list, {\n \"comment_list\" : self.get_context_value_from_queryset(context, qs)\n }, context)\n context.pop()\n return liststr\n else:\n return ''\n\n# We could just register each classmethod directly, but then we'd lose out on\n# the automagic docstrings-into-admin-docs tricks. So each node gets a cute\n# wrapper function that just exists to hold the docstring.\n\n@register.tag\ndef get_comment_count(parser, token):\n \"\"\"\n Gets the comment count for the given params and populates the template\n context with a variable containing that value, whose name is defined by the\n 'as' clause.\n\n Syntax::\n\n {% get_comment_count for [object] as [varname] %}\n {% get_comment_count for [app].[model] [object_id] as [varname] %}\n\n Example usage::\n\n {% get_comment_count for event as comment_count %}\n {% get_comment_count for calendar.event event.id as comment_count %}\n {% get_comment_count for calendar.event 17 as comment_count %}\n\n \"\"\"\n return CommentCountNode.handle_token(parser, token)\n\n@register.tag\ndef get_comment_list(parser, token):\n \"\"\"\n Gets the list of comments for the given params and populates the template\n context with a variable containing that value, whose name is defined by the\n 'as' clause.\n\n Syntax::\n\n {% get_comment_list for [object] as [varname] %}\n {% get_comment_list for [app].[model] [object_id] as [varname] %}\n\n Example usage::\n\n {% get_comment_list for event as comment_list %}\n {% for comment in comment_list %}\n ...\n {% endfor %}\n\n \"\"\"\n return CommentListNode.handle_token(parser, token)\n\n@register.tag\ndef render_comment_list(parser, token):\n \"\"\"\n Render the comment list (as returned by ``{% get_comment_list %}``)\n through the ``comments/list.html`` template\n\n Syntax::\n\n {% render_comment_list for [object] %}\n {% render_comment_list for [app].[model] [object_id] %}\n\n Example usage::\n\n {% render_comment_list for event %}\n\n \"\"\"\n return RenderCommentListNode.handle_token(parser, token)\n\n@register.tag\ndef get_comment_form(parser, token):\n \"\"\"\n Get a (new) form object to post a new comment.\n\n Syntax::\n\n {% get_comment_form for [object] as [varname] %}\n {% get_comment_form for [app].[model] [object_id] as [varname] %}\n \"\"\"\n return CommentFormNode.handle_token(parser, token)\n\n@register.tag\ndef render_comment_form(parser, token):\n \"\"\"\n Render the comment form (as returned by ``{% render_comment_form %}``) through\n the ``comments/form.html`` template.\n\n Syntax::\n\n {% render_comment_form for [object] %}\n {% render_comment_form for [app].[model] [object_id] %}\n \"\"\"\n return RenderCommentFormNode.handle_token(parser, token)\n\n@register.simple_tag\ndef comment_form_target():\n \"\"\"\n Get the target URL for the comment form.\n\n Example::\n\n
\n \"\"\"\n return comments.get_form_target()\n\n@register.simple_tag\ndef get_comment_permalink(comment, anchor_pattern=None):\n \"\"\"\n Get the permalink for a comment, optionally specifying the format of the\n named anchor to be appended to the end of the URL.\n\n Example::\n {% get_comment_permalink comment \"#c%(id)s-by-%(user_name)s\" %}\n \"\"\"\n\n if anchor_pattern:\n return comment.get_absolute_url(anchor_pattern)\n return comment.get_absolute_url()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements msvc9_support.py from spirrello/spirrello-pynet-work (path: applied_python/lib/python2.7/site-packages/setuptools/msvc9_support.py)."}, {"role": "assistant", "content": "# applied_python/lib/python2.7/site-packages/setuptools/msvc9_support.py (from spirrello/spirrello-pynet-work, license: gpl-3.0)\n\ntry:\n import distutils.msvc9compiler\nexcept ImportError:\n pass\n\nunpatched = dict()\n\ndef patch_for_specialized_compiler():\n \"\"\"\n Patch functions in distutils.msvc9compiler to use the standalone compiler\n build for Python (Windows only). Fall back to original behavior when the\n standalone compiler is not available.\n \"\"\"\n if 'distutils' not in globals():\n # The module isn't available to be patched\n return\n\n if unpatched:\n # Already patched\n return\n\n unpatched.update(vars(distutils.msvc9compiler))\n\n distutils.msvc9compiler.find_vcvarsall = find_vcvarsall\n distutils.msvc9compiler.query_vcvarsall = query_vcvarsall\n\ndef find_vcvarsall(version):\n Reg = distutils.msvc9compiler.Reg\n VC_BASE = r'Software\\%sMicrosoft\\DevDiv\\VCForPython\\%0.1f'\n key = VC_BASE % ('', version)\n try:\n # Per-user installs register the compiler path here\n productdir = Reg.get_value(key, \"installdir\")\n except KeyError:\n try:\n # All-user installs on a 64-bit system register here\n key = VC_BASE % ('Wow6432Node\\\\', version)\n productdir = Reg.get_value(key, \"installdir\")\n except KeyError:\n productdir = None\n\n if productdir:\n import os\n vcvarsall = os.path.join(productdir, \"vcvarsall.bat\")\n if os.path.isfile(vcvarsall):\n return vcvarsall\n\n return unpatched['find_vcvarsall'](version)\n\ndef query_vcvarsall(version, *args, **kwargs):\n try:\n return unpatched['query_vcvarsall'](version, *args, **kwargs)\n except distutils.errors.DistutilsPlatformError as exc:\n if exc and \"vcvarsall.bat\" in exc.args[0]:\n message = 'Microsoft Visual C++ %0.1f is required (%s).' % (version, exc.args[0])\n if int(version) == 9:\n # This redirection link is maintained by Microsoft.\n # Contact vspython@microsoft.com if it needs updating.\n raise distutils.errors.DistutilsPlatformError(\n message + ' Get it from http://aka.ms/vcpython27'\n )\n raise distutils.errors.DistutilsPlatformError(message)\n raise"}]} {"messages": [{"role": "user", "content": "Write Python code that implements dmg-license.py from hroncok/horus (path: pkg/darwin/create-dmg/support/dmg-license.py)."}, {"role": "assistant", "content": "# pkg/darwin/create-dmg/support/dmg-license.py (from hroncok/horus, license: gpl-2.0)\n\n#! /usr/bin/env python\n\"\"\"\nThis script adds a license file to a DMG. Requires Xcode and a plain ascii text\nlicense file.\nObviously only runs on a Mac.\n\nCopyright (C) 2011-2013 Jared Hobbs\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\nimport os\nimport sys\nimport tempfile\nimport optparse\n\nclass Path(str):\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n os.unlink(self)\n\ndef mktemp(dir=None, suffix=''):\n (fd, filename) = tempfile.mkstemp(dir=dir, suffix=suffix)\n os.close(fd)\n return Path(filename)\n\ndef main(options, args):\n dmgFile, license = args\n with mktemp('.') as tmpFile:\n with open(tmpFile, 'w') as f:\n f.write(\"\"\"data 'TMPL' (128, \"LPic\") {\n $\"1344 6566 6175 6C74 204C 616E 6775 6167\"\n $\"6520 4944 4457 5244 0543 6F75 6E74 4F43\"\n $\"4E54 042A 2A2A 2A4C 5354 430B 7379 7320\"\n $\"6C61 6E67 2049 4444 5752 441E 6C6F 6361\"\n $\"6C20 7265 7320 4944 2028 6F66 6673 6574\"\n $\"2066 726F 6D20 3530 3030 4457 5244 1032\"\n $\"2D62 7974 6520 6C61 6E67 7561 6765 3F44\"\n $\"5752 4404 2A2A 2A2A 4C53 5445\"\n};\n\ndata 'LPic' (5000) {\n $\"0000 0002 0000 0000 0000 0000 0004 0000\"\n};\n\ndata 'STR#' (5000, \"English buttons\") {\n $\"0006 0D45 6E67 6C69 7368 2074 6573 7431\"\n $\"0541 6772 6565 0844 6973 6167 7265 6505\"\n $\"5072 696E 7407 5361 7665 2E2E 2E7A 4966\"\n $\"2079 6F75 2061 6772 6565 2077 6974 6820\"\n $\"7468 6520 7465 726D 7320 6F66 2074 6869\"\n $\"7320 6C69 6365 6E73 652C 2063 6C69 636B\"\n $\"2022 4167 7265 6522 2074 6F20 6163 6365\"\n $\"7373 2074 6865 2073 6F66 7477 6172 652E\"\n $\"2020 4966 2079 6F75 2064 6F20 6E6F 7420\"\n $\"6167 7265 652C 2070 7265 7373 2022 4469\"\n $\"7361 6772 6565 2E22\"\n};\n\ndata 'STR#' (5002, \"English\") {\n $\"0006 0745 6E67 6C69 7368 0541 6772 6565\"\n $\"0844 6973 6167 7265 6505 5072 696E 7407\"\n $\"5361 7665 2E2E 2E7B 4966 2079 6F75 2061\"\n $\"6772 6565 2077 6974 6820 7468 6520 7465\"\n $\"726D 7320 6F66 2074 6869 7320 6C69 6365\"\n $\"6E73 652C 2070 7265 7373 2022 4167 7265\"\n $\"6522 2074 6F20 696E 7374 616C 6C20 7468\"\n $\"6520 736F 6674 7761 7265 2E20 2049 6620\"\n $\"796F 7520 646F 206E 6F74 2061 6772 6565\"\n $\"2C20 7072 6573 7320 2244 6973 6167 7265\"\n $\"6522 2E\"\n};\\n\\n\"\"\")\n with open(license, 'r') as l:\n kind = 'RTF ' if license.lower().endswith('.rtf') else 'TEXT'\n f.write('data \\'%s\\' (5000, \"English\") {\\n' % kind)\n def escape(s):\n return s.strip().replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"')\n\n for line in l:\n if len(line) < 1000:\n f.write(' \"' + escape(line) + '\\\\n\"\\n')\n else:\n for liner in line.split('.'):\n f.write(' \"' + escape(liner) + '. \\\\n\"\\n')\n f.write('};\\n\\n')\n f.write(\"\"\"data 'styl' (5000, \"English\") {\n $\"0003 0000 0000 000C 0009 0014 0000 0000\"\n $\"0000 0000 0000 0000 0027 000C 0009 0014\"\n $\"0100 0000 0000 0000 0000 0000 002A 000C\"\n $\"0009 0014 0000 0000 0000 0000 0000\"\n};\\n\"\"\")\n os.system('hdiutil unflatten -quiet \"%s\"' % dmgFile)\n ret = os.system('%s -a %s -o \"%s\"' %\n (options.rez, tmpFile, dmgFile))\n os.system('hdiutil flatten -quiet \"%s\"' % dmgFile)\n if options.compression is not None:\n os.system('cp %s %s.temp.dmg' % (dmgFile, dmgFile))\n os.remove(dmgFile)\n if options.compression == \"bz2\":\n os.system('hdiutil convert %s.temp.dmg -format UDBZ -o %s' %\n (dmgFile, dmgFile))\n elif options.compression == \"gz\":\n os.system('hdiutil convert %s.temp.dmg -format ' % dmgFile +\n 'UDZO -imagekey zlib-devel=9 -o %s' % dmgFile)\n os.remove('%s.temp.dmg' % dmgFile)\n if ret == 0:\n print \"Successfully added license to '%s'\" % dmgFile\n else:\n print \"Failed to add license to '%s'\" % dmgFile\n\nif __name__ == '__main__':\n parser = optparse.OptionParser()\n parser.set_usage(\"\"\"%prog [OPTIONS]\n This program adds a software license agreement to a DMG file.\n It requires Xcode and either a plain ascii text \n or a with the RTF contents.\n\n See --help for more details.\"\"\")\n parser.add_option(\n '--rez',\n '-r',\n action='store',\n default='/Applications/Xcode.app/Contents/Developer/Tools/Rez',\n help='The path to the Rez tool. Defaults to %default'\n )\n parser.add_option(\n '--compression',\n '-c',\n action='store',\n choices=['bz2', 'gz'],\n default=None,\n help='Optionally compress dmg using specified compression type. '\n 'Choices are bz2 and gz.'\n )\n options, args = parser.parse_args()\n cond = len(args) != 2\n if not os.path.exists(options.rez):\n print 'Failed to find Rez at \"%s\"!\\n' % options.rez\n cond = True\n if cond:\n parser.print_usage()\n sys.exit(1)\n main(options, args)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements config.py from xolox/python-deb-pkg-tools (path: deb_pkg_tools/config.py)."}, {"role": "assistant", "content": "# deb_pkg_tools/config.py (from xolox/python-deb-pkg-tools, license: mit)\n\n# Debian packaging tools: Configuration defaults.\n#\n# Author: Peter Odding \n# Last Change: February 6, 2020\n# URL: https://github.com/xolox/python-deb-pkg-tools\n\n\"\"\"Configuration defaults for the `deb-pkg-tools` package.\"\"\"\n\n# Standard library modules.\nimport os\n\n# External dependencies.\nfrom humanfriendly import parse_path\n\n# Public identifiers that require documentation.\n__all__ = (\n \"package_cache_directory\",\n \"repo_config_file\",\n \"system_cache_directory\",\n \"system_config_directory\",\n \"user_cache_directory\",\n \"user_config_directory\",\n)\n\nsystem_config_directory = '/etc/deb-pkg-tools'\n\"\"\"The pathname of the global (system wide) configuration directory used by `deb-pkg-tools` (a string).\"\"\"\n\nsystem_cache_directory = '/var/cache/deb-pkg-tools'\n\"\"\"The pathname of the global (system wide) package cache directory (a string).\"\"\"\n\nuser_config_directory = parse_path('~/.deb-pkg-tools')\n\"\"\"\nThe pathname of the current user's configuration directory used by `deb-pkg-tools` (a string).\n\n:default: The expanded value of ``~/.deb-pkg-tools``.\n\"\"\"\n\nuser_cache_directory = parse_path('~/.cache/deb-pkg-tools')\n\"\"\"\nThe pathname of the current user's package cache directory (a string).\n\n:default: The expanded value of ``~/.cache/deb-pkg-tools``.\n\"\"\"\n\n# The location of the package cache. If we're running as root we have write\n# access to the system wide package cache so we'll pick that; the more users\n# sharing this cache the more effective it is.\n\npackage_cache_directory = system_cache_directory if os.getuid() == 0 else user_cache_directory\n\"\"\"\nThe pathname of the selected package cache directory (a string).\n\n:default: The value of :data:`system_cache_directory` when running as ``root``,\n the value of :data:`user_cache_directory` otherwise.\n\"\"\"\n\nrepo_config_file = 'repos.ini'\n\"\"\"\nThe base name of the configuration file with user-defined Debian package repositories (a string).\n\nThis configuration file is loaded from :data:`system_config_directory` and/or\n:data:`user_config_directory`.\n\n:default: The string ``repos.ini``.\n\"\"\""}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_run_results.py from angelman/phantomjs (path: src/qt/qtwebkit/Tools/Scripts/webkitpy/layout_tests/models/test_run_results.py)."}, {"role": "assistant", "content": "# src/qt/qtwebkit/Tools/Scripts/webkitpy/layout_tests/models/test_run_results.py (from angelman/phantomjs, license: bsd-3-clause)\n\n# Copyright (C) 2010 Google Inc. All rights reserved.\n# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport logging\n\nfrom webkitpy.layout_tests.models import test_expectations\nfrom webkitpy.layout_tests.models import test_failures\n\n_log = logging.getLogger(__name__)\n\nclass TestRunResults(object):\n def __init__(self, expectations, num_tests):\n self.total = num_tests\n self.remaining = self.total\n self.expectations = expectations\n self.expected = 0\n self.unexpected = 0\n self.unexpected_failures = 0\n self.unexpected_crashes = 0\n self.unexpected_timeouts = 0\n self.tests_by_expectation = {}\n self.tests_by_timeline = {}\n self.results_by_name = {} # Map of test name to the last result for the test.\n self.all_results = [] # All results from a run, including every iteration of every test.\n self.unexpected_results_by_name = {}\n self.failures_by_name = {}\n self.total_failures = 0\n self.expected_skips = 0\n for expectation in test_expectations.TestExpectations.EXPECTATIONS.values():\n self.tests_by_expectation[expectation] = set()\n for timeline in test_expectations.TestExpectations.TIMELINES.values():\n self.tests_by_timeline[timeline] = expectations.get_tests_with_timeline(timeline)\n self.slow_tests = set()\n self.interrupted = False\n\n def add(self, test_result, expected, test_is_slow):\n self.tests_by_expectation[test_result.type].add(test_result.test_name)\n self.results_by_name[test_result.test_name] = test_result\n if test_result.type != test_expectations.SKIP:\n self.all_results.append(test_result)\n self.remaining -= 1\n if len(test_result.failures):\n self.total_failures += 1\n self.failures_by_name[test_result.test_name] = test_result.failures\n if expected:\n self.expected += 1\n if test_result.type == test_expectations.SKIP:\n self.expected_skips += 1\n else:\n self.unexpected_results_by_name[test_result.test_name] = test_result\n self.unexpected += 1\n if len(test_result.failures):\n self.unexpected_failures += 1\n if test_result.type == test_expectations.CRASH:\n self.unexpected_crashes += 1\n elif test_result.type == test_expectations.TIMEOUT:\n self.unexpected_timeouts += 1\n if test_is_slow:\n self.slow_tests.add(test_result.test_name)\n\nclass RunDetails(object):\n def __init__(self, exit_code, summarized_results=None, initial_results=None, retry_results=None, enabled_pixel_tests_in_retry=False):\n self.exit_code = exit_code\n self.summarized_results = summarized_results\n self.initial_results = initial_results\n self.retry_results = retry_results\n self.enabled_pixel_tests_in_retry = enabled_pixel_tests_in_retry\n\ndef _interpret_test_failures(failures):\n test_dict = {}\n failure_types = [type(failure) for failure in failures]\n # FIXME: get rid of all this is_* values once there is a 1:1 map between\n # TestFailure type and test_expectations.EXPECTATION.\n if test_failures.FailureMissingAudio in failure_types:\n test_dict['is_missing_audio'] = True\n\n if test_failures.FailureMissingResult in failure_types:\n test_dict['is_missing_text'] = True\n\n if test_failures.FailureMissingImage in failure_types or test_failures.FailureMissingImageHash in failure_types:\n test_dict['is_missing_image'] = True\n\n if 'image_diff_percent' not in test_dict:\n for failure in failures:\n if isinstance(failure, test_failures.FailureImageHashMismatch) or isinstance(failure, test_failures.FailureReftestMismatch):\n test_dict['image_diff_percent'] = failure.diff_percent\n\n return test_dict\n\ndef summarize_results(port_obj, expectations, initial_results, retry_results, enabled_pixel_tests_in_retry):\n \"\"\"Returns a dictionary containing a summary of the test runs, with the following fields:\n 'version': a version indicator\n 'fixable': The number of fixable tests (NOW - PASS)\n 'skipped': The number of skipped tests (NOW & SKIPPED)\n 'num_regressions': The number of non-flaky failures\n 'num_flaky': The number of flaky failures\n 'num_missing': The number of tests with missing results\n 'num_passes': The number of unexpected passes\n 'tests': a dict of tests -> {'expected': '...', 'actual': '...'}\n \"\"\"\n results = {}\n results['version'] = 3\n\n tbe = initial_results.tests_by_expectation\n tbt = initial_results.tests_by_timeline\n results['fixable'] = len(tbt[test_expectations.NOW] - tbe[test_expectations.PASS])\n results['skipped'] = len(tbt[test_expectations.NOW] & tbe[test_expectations.SKIP])\n\n num_passes = 0\n num_flaky = 0\n num_missing = 0\n num_regressions = 0\n keywords = {}\n for expecation_string, expectation_enum in test_expectations.TestExpectations.EXPECTATIONS.iteritems():\n keywords[expectation_enum] = expecation_string.upper()\n\n for modifier_string, modifier_enum in test_expectations.TestExpectations.MODIFIERS.iteritems():\n keywords[modifier_enum] = modifier_string.upper()\n\n tests = {}\n\n for test_name, result in initial_results.results_by_name.iteritems():\n # Note that if a test crashed in the original run, we ignore\n # whether or not it crashed when we retried it (if we retried it),\n # and always consider the result not flaky.\n expected = expectations.get_expectations_string(test_name)\n result_type = result.type\n actual = [keywords[result_type]]\n\n if result_type == test_expectations.SKIP:\n continue\n\n test_dict = {}\n if result.has_stderr:\n test_dict['has_stderr'] = True\n\n if result.reftest_type:\n test_dict.update(reftest_type=list(result.reftest_type))\n\n if expectations.has_modifier(test_name, test_expectations.WONTFIX):\n test_dict['wontfix'] = True\n\n if result_type == test_expectations.PASS:\n num_passes += 1\n # FIXME: include passing tests that have stderr output.\n if expected == 'PASS':\n continue\n elif result_type == test_expectations.CRASH:\n if test_name in initial_results.unexpected_results_by_name:\n num_regressions += 1\n elif result_type == test_expectations.MISSING:\n if test_name in initial_results.unexpected_results_by_name:\n num_missing += 1\n elif test_name in initial_results.unexpected_results_by_name:\n if retry_results and test_name not in retry_results.unexpected_results_by_name:\n actual.extend(expectations.get_expectations_string(test_name).split(\" \"))\n num_flaky += 1\n elif retry_results:\n retry_result_type = retry_results.unexpected_results_by_name[test_name].type\n if result_type != retry_result_type:\n if enabled_pixel_tests_in_retry and result_type == test_expectations.TEXT and retry_result_type == test_expectations.IMAGE_PLUS_TEXT:\n num_regressions += 1\n else:\n num_flaky += 1\n actual.append(keywords[retry_result_type])\n else:\n num_regressions += 1\n else:\n num_regressions += 1\n\n test_dict['expected'] = expected\n test_dict['actual'] = \" \".join(actual)\n\n test_dict.update(_interpret_test_failures(result.failures))\n\n if retry_results:\n retry_result = retry_results.unexpected_results_by_name.get(test_name)\n if retry_result:\n test_dict.update(_interpret_test_failures(retry_result.failures))\n\n # Store test hierarchically by directory. e.g.\n # foo/bar/baz.html: test_dict\n # foo/bar/baz1.html: test_dict\n #\n # becomes\n # foo: {\n # bar: {\n # baz.html: test_dict,\n # baz1.html: test_dict\n # }\n # }\n parts = test_name.split('/')\n current_map = tests\n for i, part in enumerate(parts):\n if i == (len(parts) - 1):\n current_map[part] = test_dict\n break\n if part not in current_map:\n current_map[part] = {}\n current_map = current_map[part]\n\n results['tests'] = tests\n results['num_passes'] = num_passes\n results['num_flaky'] = num_flaky\n results['num_missing'] = num_missing\n results['num_regressions'] = num_regressions\n results['uses_expectations_file'] = port_obj.uses_test_expectations_file()\n results['interrupted'] = initial_results.interrupted # Does results.html have enough information to compute this itself? (by checking total number of results vs. total number of tests?)\n results['layout_tests_dir'] = port_obj.layout_tests_dir()\n results['has_wdiff'] = port_obj.wdiff_available()\n results['has_pretty_patch'] = port_obj.pretty_patch_available()\n results['pixel_tests_enabled'] = port_obj.get_option('pixel_tests')\n\n try:\n # We only use the svn revision for using trac links in the results.html file,\n # Don't do this by default since it takes >100ms.\n # FIXME: Do we really need to populate this both here and in the json_results_generator?\n if port_obj.get_option(\"builder_name\"):\n port_obj.host.initialize_scm()\n results['revision'] = port_obj.host.scm().head_svn_revision()\n except Exception, e:\n _log.warn(\"Failed to determine svn revision for checkout (cwd: %s, webkit_base: %s), leaving 'revision' key blank in full_results.json.\\n%s\" % (port_obj._filesystem.getcwd(), port_obj.path_from_webkit_base(), e))\n # Handle cases where we're running outside of version control.\n import traceback\n _log.debug('Failed to learn head svn revision:')\n _log.debug(traceback.format_exc())\n results['revision'] = \"\"\n\n return results"}]} {"messages": [{"role": "user", "content": "Write Python code that implements 0020_add_repository_type_column.py from mikel-egana-aranguren/SADI-Galaxy-Docker (path: galaxy-dist/lib/galaxy/webapps/tool_shed/model/migrate/versions/0020_add_repository_type_column.py)."}, {"role": "assistant", "content": "# galaxy-dist/lib/galaxy/webapps/tool_shed/model/migrate/versions/0020_add_repository_type_column.py (from mikel-egana-aranguren/SADI-Galaxy-Docker, license: gpl-3.0)\n\n\"\"\"Migration script to add the type column to the repository table.\"\"\"\n\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import *\nfrom migrate import *\nfrom migrate.changeset import *\n\n# Need our custom types, but don't import anything else from model\nfrom galaxy.model.custom_types import *\n\nimport sys, logging\nlog = logging.getLogger( __name__ )\nlog.setLevel(logging.DEBUG)\nhandler = logging.StreamHandler( sys.stdout )\nformat = \"%(name)s %(levelname)s %(asctime)s %(message)s\"\nformatter = logging.Formatter( format )\nhandler.setFormatter( formatter )\nlog.addHandler( handler )\n\nmetadata = MetaData()\n\ndef upgrade( migrate_engine ):\n print __doc__\n metadata.bind = migrate_engine\n metadata.reflect()\n Repository_table = Table( \"repository\", metadata, autoload=True )\n c = Column( \"type\", TrimmedString( 255 ), index=True )\n try:\n # Create\n c.create( Repository_table, index_name=\"ix_repository_type\" )\n assert c is Repository_table.c.type\n except Exception, e:\n print \"Adding type column to the repository table failed: %s\" % str( e )\n # Update the type column to have the default unrestricted value.\n cmd = \"UPDATE repository SET type = 'unrestricted'\"\n migrate_engine.execute( cmd )\n\ndef downgrade( migrate_engine ):\n metadata.bind = migrate_engine\n metadata.reflect()\n # Drop type column from repository table.\n Repository_table = Table( \"repository\", metadata, autoload=True )\n try:\n Repository_table.c.type.drop()\n except Exception, e:\n print \"Dropping column type from the repository table failed: %s\" % str( e )"}]} {"messages": [{"role": "user", "content": "Write Python code that implements FacilitiesSearchByZip.py from willprice/arduino-sphere-project (path: scripts/example_direction_finder/temboo/Library/EnviroFacts/Toxins/FacilitiesSearchByZip.py)."}, {"role": "assistant", "content": "# scripts/example_direction_finder/temboo/Library/EnviroFacts/Toxins/FacilitiesSearchByZip.py (from willprice/arduino-sphere-project, license: gpl-2.0)\n\n# -*- coding: utf-8 -*-\n\n###############################################################################\n#\n# FacilitiesSearchByZip\n# Retrieves a list of EPA-regulated facilities in the Toxics Release Inventory (TRI) database within a given area code.\n#\n# Python versions 2.6, 2.7, 3.x\n#\n# Copyright 2014, Temboo Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n# either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n#\n#\n###############################################################################\n\nfrom temboo.core.choreography import Choreography\nfrom temboo.core.choreography import InputSet\nfrom temboo.core.choreography import ResultSet\nfrom temboo.core.choreography import ChoreographyExecution\n\nimport json\n\nclass FacilitiesSearchByZip(Choreography):\n\n def __init__(self, temboo_session):\n \"\"\"\n Create a new instance of the FacilitiesSearchByZip Choreo. A TembooSession object, containing a valid\n set of Temboo credentials, must be supplied.\n \"\"\"\n super(FacilitiesSearchByZip, self).__init__(temboo_session, '/Library/EnviroFacts/Toxins/FacilitiesSearchByZip')\n\n def new_input_set(self):\n return FacilitiesSearchByZipInputSet()\n\n def _make_result_set(self, result, path):\n return FacilitiesSearchByZipResultSet(result, path)\n\n def _make_execution(self, session, exec_id, path):\n return FacilitiesSearchByZipChoreographyExecution(session, exec_id, path)\n\nclass FacilitiesSearchByZipInputSet(InputSet):\n \"\"\"\n An InputSet with methods appropriate for specifying the inputs to the FacilitiesSearchByZip\n Choreo. The InputSet object is used to specify input parameters when executing this Choreo.\n \"\"\"\n def set_ResponseFormat(self, value):\n \"\"\"\n Set the value of the ResponseFormat input for this Choreo. ((optional, string) Specify the desired response format. Valid formats are: xml (the default) and csv.)\n \"\"\"\n super(FacilitiesSearchByZipInputSet, self)._set_input('ResponseFormat', value)\n def set_RowEnd(self, value):\n \"\"\"\n Set the value of the RowEnd input for this Choreo. ((optional, integer) Number 1 or greater indicates the ending row number of the results displayed. Default is 4999 when RowStart is 0. Up to 5000 entries are returned in the output.)\n \"\"\"\n super(FacilitiesSearchByZipInputSet, self)._set_input('RowEnd', value)\n def set_RowStart(self, value):\n \"\"\"\n Set the value of the RowStart input for this Choreo. ((optional, integer) Indicates the starting row number of the results displayed. Default is 0.)\n \"\"\"\n super(FacilitiesSearchByZipInputSet, self)._set_input('RowStart', value)\n def set_Zip(self, value):\n \"\"\"\n Set the value of the Zip input for this Choreo. ((required, string) Zip code to be searched.)\n \"\"\"\n super(FacilitiesSearchByZipInputSet, self)._set_input('Zip', value)\n\nclass FacilitiesSearchByZipResultSet(ResultSet):\n \"\"\"\n A ResultSet with methods tailored to the values returned by the FacilitiesSearchByZip Choreo.\n The ResultSet object is used to retrieve the results of a Choreo execution.\n \"\"\"\n\n def getJSONFromString(self, str):\n return json.loads(str)\n\n def get_Response(self):\n \"\"\"\n Retrieve the value for the \"Response\" output from this Choreo execution. (The response from EnviroFacts.)\n \"\"\"\n return self._output.get('Response', None)\n\nclass FacilitiesSearchByZipChoreographyExecution(ChoreographyExecution):\n\n def _make_result_set(self, response, path):\n return FacilitiesSearchByZipResultSet(response, path)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements pofile.py from krismcfarlin/todo_angular_endpoints_sockets (path: bp_includes/external/babel/messages/pofile.py)."}, {"role": "assistant", "content": "# bp_includes/external/babel/messages/pofile.py (from krismcfarlin/todo_angular_endpoints_sockets, license: lgpl-3.0)\n\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2007 Edgewall Software\n# All rights reserved.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at http://babel.edgewall.org/wiki/License.\n#\n# This software consists of voluntary contributions made by many\n# individuals. For the exact contribution history, see the revision\n# history and logs, available at http://babel.edgewall.org/log/.\n\n\"\"\"Reading and writing of files in the ``gettext`` PO (portable object)\nformat.\n\n:see: `The Format of PO Files\n `_\n\"\"\"\n\nfrom datetime import date, datetime\nimport os\nimport re\n\nfrom babel import __version__ as VERSION\nfrom babel.messages.catalog import Catalog, Message\nfrom babel.util import set, wraptext, LOCALTZ\n\n__all__ = ['read_po', 'write_po']\n__docformat__ = 'restructuredtext en'\n\ndef unescape(string):\n r\"\"\"Reverse `escape` the given string.\n\n >>> print unescape('\"Say:\\\\n \\\\\"hello, world!\\\\\"\\\\n\"')\n Say:\n \"hello, world!\"\n \n\n :param string: the string to unescape\n :return: the unescaped string\n :rtype: `str` or `unicode`\n \"\"\"\n return string[1:-1].replace('\\\\\\\\', '\\\\') \\\n .replace('\\\\t', '\\t') \\\n .replace('\\\\r', '\\r') \\\n .replace('\\\\n', '\\n') \\\n .replace('\\\\\"', '\\\"')\n\ndef denormalize(string):\n r\"\"\"Reverse the normalization done by the `normalize` function.\n\n >>> print denormalize(r'''\"\"\n ... \"Say:\\n\"\n ... \" \\\"hello, world!\\\"\\n\"''')\n Say:\n \"hello, world!\"\n \n\n >>> print denormalize(r'''\"\"\n ... \"Say:\\n\"\n ... \" \\\"Lorem ipsum dolor sit \"\n ... \"amet, consectetur adipisicing\"\n ... \" elit, \\\"\\n\"''')\n Say:\n \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, \"\n \n\n :param string: the string to denormalize\n :return: the denormalized string\n :rtype: `unicode` or `str`\n \"\"\"\n if string.startswith('\"\"'):\n lines = []\n for line in string.splitlines()[1:]:\n lines.append(unescape(line))\n return ''.join(lines)\n else:\n return unescape(string)\n\ndef read_po(fileobj, locale=None, domain=None, ignore_obsolete=False):\n \"\"\"Read messages from a ``gettext`` PO (portable object) file from the given\n file-like object and return a `Catalog`.\n\n >>> from StringIO import StringIO\n >>> buf = StringIO('''\n ... #: main.py:1\n ... #, fuzzy, python-format\n ... msgid \"foo %(name)s\"\n ... msgstr \"\"\n ...\n ... # A user comment\n ... #. An auto comment\n ... #: main.py:3\n ... msgid \"bar\"\n ... msgid_plural \"baz\"\n ... msgstr[0] \"\"\n ... msgstr[1] \"\"\n ... ''')\n >>> catalog = read_po(buf)\n >>> catalog.revision_date = datetime(2007, 04, 01)\n\n >>> for message in catalog:\n ... if message.id:\n ... print (message.id, message.string)\n ... print ' ', (message.locations, message.flags)\n ... print ' ', (message.user_comments, message.auto_comments)\n (u'foo %(name)s', '')\n ([(u'main.py', 1)], set([u'fuzzy', u'python-format']))\n ([], [])\n ((u'bar', u'baz'), ('', ''))\n ([(u'main.py', 3)], set([]))\n ([u'A user comment'], [u'An auto comment'])\n\n :param fileobj: the file-like object to read the PO file from\n :param locale: the locale identifier or `Locale` object, or `None`\n if the catalog is not bound to a locale (which basically\n means it's a template)\n :param domain: the message domain\n :param ignore_obsolete: whether to ignore obsolete messages in the input\n :return: an iterator over ``(message, translation, location)`` tuples\n :rtype: ``iterator``\n \"\"\"\n catalog = Catalog(locale=locale, domain=domain)\n\n counter = [0]\n offset = [0]\n messages = []\n translations = []\n locations = []\n flags = []\n user_comments = []\n auto_comments = []\n obsolete = [False]\n in_msgid = [False]\n in_msgstr = [False]\n\n def _add_message():\n translations.sort()\n if len(messages) > 1:\n msgid = tuple([denormalize(m) for m in messages])\n else:\n msgid = denormalize(messages[0])\n if isinstance(msgid, (list, tuple)):\n string = []\n for idx in range(catalog.num_plurals):\n try:\n string.append(translations[idx])\n except IndexError:\n string.append((idx, ''))\n string = tuple([denormalize(t[1]) for t in string])\n else:\n string = denormalize(translations[0][1])\n message = Message(msgid, string, list(locations), set(flags),\n auto_comments, user_comments, lineno=offset[0] + 1)\n if obsolete[0]:\n if not ignore_obsolete:\n catalog.obsolete[msgid] = message\n else:\n catalog[msgid] = message\n del messages[:]; del translations[:]; del locations[:];\n del flags[:]; del auto_comments[:]; del user_comments[:]\n obsolete[0] = False\n counter[0] += 1\n\n def _process_message_line(lineno, line):\n if line.startswith('msgid_plural'):\n in_msgid[0] = True\n msg = line[12:].lstrip()\n messages.append(msg)\n elif line.startswith('msgid'):\n in_msgid[0] = True\n offset[0] = lineno\n txt = line[5:].lstrip()\n if messages:\n _add_message()\n messages.append(txt)\n elif line.startswith('msgstr'):\n in_msgid[0] = False\n in_msgstr[0] = True\n msg = line[6:].lstrip()\n if msg.startswith('['):\n idx, msg = msg[1:].split(']', 1)\n translations.append([int(idx), msg.lstrip()])\n else:\n translations.append([0, msg])\n elif line.startswith('\"'):\n if in_msgid[0]:\n messages[-1] += u'\\n' + line.rstrip()\n elif in_msgstr[0]:\n translations[-1][1] += u'\\n' + line.rstrip()\n\n for lineno, line in enumerate(fileobj.readlines()):\n line = line.strip()\n if not isinstance(line, unicode):\n line = line.decode(catalog.charset)\n if line.startswith('#'):\n in_msgid[0] = in_msgstr[0] = False\n if messages and translations:\n _add_message()\n if line[1:].startswith(':'):\n for location in line[2:].lstrip().split():\n pos = location.rfind(':')\n if pos >= 0:\n try:\n lineno = int(location[pos + 1:])\n except ValueError:\n continue\n locations.append((location[:pos], lineno))\n elif line[1:].startswith(','):\n for flag in line[2:].lstrip().split(','):\n flags.append(flag.strip())\n elif line[1:].startswith('~'):\n obsolete[0] = True\n _process_message_line(lineno, line[2:].lstrip())\n elif line[1:].startswith('.'):\n # These are called auto-comments\n comment = line[2:].strip()\n if comment: # Just check that we're not adding empty comments\n auto_comments.append(comment)\n else:\n # These are called user comments\n user_comments.append(line[1:].strip())\n else:\n _process_message_line(lineno, line)\n\n if messages:\n _add_message()\n\n # No actual messages found, but there was some info in comments, from which\n # we'll construct an empty header message\n elif not counter[0] and (flags or user_comments or auto_comments):\n messages.append(u'')\n translations.append([0, u''])\n _add_message()\n\n return catalog\n\nWORD_SEP = re.compile('('\n r'\\s+|' # any whitespace\n r'[^\\s\\w]*\\w+[a-zA-Z]-(?=\\w+[a-zA-Z])|' # hyphenated words\n r'(?<=[\\w\\!\\\"\\'\\&\\.\\,\\?])-{2,}(?=\\w)' # em-dash\n')')\n\ndef escape(string):\n r\"\"\"Escape the given string so that it can be included in double-quoted\n strings in ``PO`` files.\n\n >>> escape('''Say:\n ... \"hello, world!\"\n ... ''')\n '\"Say:\\\\n \\\\\"hello, world!\\\\\"\\\\n\"'\n\n :param string: the string to escape\n :return: the escaped string\n :rtype: `str` or `unicode`\n \"\"\"\n return '\"%s\"' % string.replace('\\\\', '\\\\\\\\') \\\n .replace('\\t', '\\\\t') \\\n .replace('\\r', '\\\\r') \\\n .replace('\\n', '\\\\n') \\\n .replace('\\\"', '\\\\\"')\n\ndef normalize(string, prefix='', width=76):\n r\"\"\"Convert a string into a format that is appropriate for .po files.\n\n >>> print normalize('''Say:\n ... \"hello, world!\"\n ... ''', width=None)\n \"\"\n \"Say:\\n\"\n \" \\\"hello, world!\\\"\\n\"\n\n >>> print normalize('''Say:\n ... \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, \"\n ... ''', width=32)\n \"\"\n \"Say:\\n\"\n \" \\\"Lorem ipsum dolor sit \"\n \"amet, consectetur adipisicing\"\n \" elit, \\\"\\n\"\n\n :param string: the string to normalize\n :param prefix: a string that should be prepended to every line\n :param width: the maximum line width; use `None`, 0, or a negative number\n to completely disable line wrapping\n :return: the normalized string\n :rtype: `unicode`\n \"\"\"\n if width and width > 0:\n prefixlen = len(prefix)\n lines = []\n for idx, line in enumerate(string.splitlines(True)):\n if len(escape(line)) + prefixlen > width:\n chunks = WORD_SEP.split(line)\n chunks.reverse()\n while chunks:\n buf = []\n size = 2\n while chunks:\n l = len(escape(chunks[-1])) - 2 + prefixlen\n if size + l < width:\n buf.append(chunks.pop())\n size += l\n else:\n if not buf:\n # handle long chunks by putting them on a\n # separate line\n buf.append(chunks.pop())\n break\n lines.append(u''.join(buf))\n else:\n lines.append(line)\n else:\n lines = string.splitlines(True)\n\n if len(lines) <= 1:\n return escape(string)\n\n # Remove empty trailing line\n if lines and not lines[-1]:\n del lines[-1]\n lines[-1] += '\\n'\n return u'\"\"\\n' + u'\\n'.join([(prefix + escape(l)) for l in lines])\n\ndef write_po(fileobj, catalog, width=76, no_location=False, omit_header=False,\n sort_output=False, sort_by_file=False, ignore_obsolete=False,\n include_previous=False):\n r\"\"\"Write a ``gettext`` PO (portable object) template file for a given\n message catalog to the provided file-like object.\n\n >>> catalog = Catalog()\n >>> catalog.add(u'foo %(name)s', locations=[('main.py', 1)],\n ... flags=('fuzzy',))\n >>> catalog.add((u'bar', u'baz'), locations=[('main.py', 3)])\n >>> from StringIO import StringIO\n >>> buf = StringIO()\n >>> write_po(buf, catalog, omit_header=True)\n >>> print buf.getvalue()\n #: main.py:1\n #, fuzzy, python-format\n msgid \"foo %(name)s\"\n msgstr \"\"\n \n #: main.py:3\n msgid \"bar\"\n msgid_plural \"baz\"\n msgstr[0] \"\"\n msgstr[1] \"\"\n \n \n\n :param fileobj: the file-like object to write to\n :param catalog: the `Catalog` instance\n :param width: the maximum line width for the generated output; use `None`,\n 0, or a negative number to completely disable line wrapping\n :param no_location: do not emit a location comment for every message\n :param omit_header: do not include the ``msgid \"\"`` entry at the top of the\n output\n :param sort_output: whether to sort the messages in the output by msgid\n :param sort_by_file: whether to sort the messages in the output by their\n locations\n :param ignore_obsolete: whether to ignore obsolete messages and not include\n them in the output; by default they are included as\n comments\n :param include_previous: include the old msgid as a comment when\n updating the catalog\n \"\"\"\n def _normalize(key, prefix=''):\n return normalize(key, prefix=prefix, width=width) \\\n .encode(catalog.charset, 'backslashreplace')\n\n def _write(text):\n if isinstance(text, unicode):\n text = text.encode(catalog.charset)\n fileobj.write(text)\n\n def _write_comment(comment, prefix=''):\n # xgettext always wraps comments even if --no-wrap is passed;\n # provide the same behaviour\n if width and width > 0:\n _width = width\n else:\n _width = 76\n for line in wraptext(comment, _width):\n _write('#%s %s\\n' % (prefix, line.strip()))\n\n def _write_message(message, prefix=''):\n if isinstance(message.id, (list, tuple)):\n _write('%smsgid %s\\n' % (prefix, _normalize(message.id[0], prefix)))\n _write('%smsgid_plural %s\\n' % (\n prefix, _normalize(message.id[1], prefix)\n ))\n\n for idx in range(catalog.num_plurals):\n try:\n string = message.string[idx]\n except IndexError:\n string = ''\n _write('%smsgstr[%d] %s\\n' % (\n prefix, idx, _normalize(string, prefix)\n ))\n else:\n _write('%smsgid %s\\n' % (prefix, _normalize(message.id, prefix)))\n _write('%smsgstr %s\\n' % (\n prefix, _normalize(message.string or '', prefix)\n ))\n\n messages = list(catalog)\n if sort_output:\n messages.sort()\n elif sort_by_file:\n messages.sort(lambda x,y: cmp(x.locations, y.locations))\n\n for message in messages:\n if not message.id: # This is the header \"message\"\n if omit_header:\n continue\n comment_header = catalog.header_comment\n if width and width > 0:\n lines = []\n for line in comment_header.splitlines():\n lines += wraptext(line, width=width,\n subsequent_indent='# ')\n comment_header = u'\\n'.join(lines) + u'\\n'\n _write(comment_header)\n\n for comment in message.user_comments:\n _write_comment(comment)\n for comment in message.auto_comments:\n _write_comment(comment, prefix='.')\n\n if not no_location:\n locs = u' '.join([u'%s:%d' % (filename.replace(os.sep, '/'), lineno)\n for filename, lineno in message.locations])\n _write_comment(locs, prefix=':')\n if message.flags:\n _write('#%s\\n' % ', '.join([''] + list(message.flags)))\n\n if message.previous_id and include_previous:\n _write_comment('msgid %s' % _normalize(message.previous_id[0]),\n prefix='|')\n if len(message.previous_id) > 1:\n _write_comment('msgid_plural %s' % _normalize(\n message.previous_id[1]\n ), prefix='|')\n\n _write_message(message)\n _write('\\n')\n\n if not ignore_obsolete:\n for message in catalog.obsolete.values():\n for comment in message.user_comments:\n _write_comment(comment)\n _write_message(message, prefix='#~ ')\n _write('\\n')"}]} {"messages": [{"role": "user", "content": "Write Python code that implements controls.py from jpippy/pyo (path: pyolib/controls.py)."}, {"role": "assistant", "content": "# pyolib/controls.py (from jpippy/pyo, license: gpl-3.0)\n\n\"\"\"\nObjects designed to create parameter's control at audio rate.\n\nThese objects can be used to create envelopes, line segments\nand conversion from python number to audio signal.\n\nThe audio streams of these objects can't be sent to the output\nsoundcard.\n\n\"\"\"\n\n\"\"\"\nCopyright 2009-2015 Olivier Belanger\n\nThis file is part of pyo, a python module to help digital signal\nprocessing script creation.\n\npyo is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\npyo is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with pyo. If not, see .\n\"\"\"\nimport sys\nfrom _core import *\nfrom _maps import *\nfrom _widgets import createGraphWindow\nfrom types import ListType, TupleType\n\n######################################################################\n### Controls\n######################################################################\nclass Fader(PyoObject):\n \"\"\"\n Fadein - fadeout envelope generator.\n\n Generate an amplitude envelope between 0 and 1 with control on fade\n times and total duration of the envelope.\n\n The play() method starts the envelope and is not called at the\n object creation time.\n\n :Parent: :py:class:`PyoObject`\n\n :Args:\n\n fadein : float, optional\n Rising time of the envelope in seconds. Defaults to 0.01.\n fadeout : float, optional\n Falling time of the envelope in seconds. Defaults to 0.1.\n dur : float, optional\n Total duration of the envelope. Defaults to 0, which means wait\n for the stop() method to start the fadeout.\n\n .. note::\n\n The out() method is bypassed. Fader's signal can not be sent to audio outs.\n\n The play() method starts the envelope.\n\n The stop() calls the envelope's release phase if `dur` = 0.\n\n >>> s = Server().boot()\n >>> s.start()\n >>> f = Fader(fadein=0.5, fadeout=0.5, dur=2, mul=.5)\n >>> a = BrownNoise(mul=f).mix(2).out()\n >>> def repeat():\n ... f.play()\n >>> pat = Pattern(function=repeat, time=2).play()\n\n \"\"\"\n def __init__(self, fadein=0.01, fadeout=0.1, dur=0, mul=1, add=0):\n pyoArgsAssert(self, \"nnnOO\", fadein, fadeout, dur, mul, add)\n PyoObject.__init__(self, mul, add)\n self._fadein = fadein\n self._fadeout = fadeout\n self._dur = dur\n fadein, fadeout, dur, mul, add, lmax = convertArgsToLists(fadein, fadeout, dur, mul, add)\n self._base_objs = [Fader_base(wrap(fadein,i), wrap(fadeout,i), wrap(dur,i), wrap(mul,i), wrap(add,i)) for i in range(lmax)]\n\n def out(self, chnl=0, inc=1, dur=0, delay=0):\n return self.play(dur, delay)\n\n def setFadein(self, x):\n \"\"\"\n Replace the `fadein` attribute.\n\n :Args:\n\n x : float\n new `fadein` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"n\", x)\n self._fadein = x\n x, lmax = convertArgsToLists(x)\n [obj.setFadein(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def setFadeout(self, x):\n \"\"\"\n Replace the `fadeout` attribute.\n\n :Args:\n\n x : float\n new `fadeout` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"n\", x)\n self._fadeout = x\n x, lmax = convertArgsToLists(x)\n [obj.setFadeout(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def setDur(self, x):\n \"\"\"\n Replace the `dur` attribute.\n\n :Args:\n\n x : float\n new `dur` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"n\", x)\n self._dur = x\n x, lmax = convertArgsToLists(x)\n [obj.setDur(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def ctrl(self, map_list=None, title=None, wxnoserver=False):\n self._map_list = [SLMap(0, 10., 'lin', 'fadein', self._fadein, dataOnly=True),\n SLMap(0, 10., 'lin', 'fadeout', self._fadeout, dataOnly=True),\n SLMap(0, 20., 'lin', 'dur', self._dur, dataOnly=True)]\n PyoObject.ctrl(self, map_list, title, wxnoserver)\n\n @property\n def fadein(self):\n \"\"\"float. Rising time of the envelope in seconds.\"\"\"\n return self._fadein\n @fadein.setter\n def fadein(self, x): self.setFadein(x)\n\n @property\n def fadeout(self):\n \"\"\"float. Falling time of the envelope in seconds.\"\"\"\n return self._fadeout\n @fadeout.setter\n def fadeout(self, x): self.setFadeout(x)\n\n @property\n def dur(self):\n \"\"\"float. Total duration of the envelope.\"\"\"\n return self._dur\n @dur.setter\n def dur(self, x): self.setDur(x)\n\nclass Adsr(PyoObject):\n \"\"\"\n Attack - Decay - Sustain - Release envelope generator.\n\n Calculates the classical ADSR envelope using linear segments.\n Duration can be set to 0 to give an infinite sustain. In this\n case, the stop() method calls the envelope release part.\n\n The play() method starts the envelope and is not called at the\n object creation time.\n\n :Parent: :py:class:`PyoObject`\n\n :Args:\n\n attack : float, optional\n Duration of the attack phase in seconds. Defaults to 0.01.\n decay : float, optional\n Duration of the decay in seconds. Defaults to 0.05.\n sustain : float, optional\n Amplitude of the sustain phase. Defaults to 0.707.\n release : float, optional\n Duration of the release in seconds. Defaults to 0.1.\n dur : float, optional\n Total duration of the envelope. Defaults to 0, which means wait\n for the stop() method to start the release phase.\n\n .. note::\n\n The out() method is bypassed. Adsr's signal can not be sent to audio outs.\n\n The play() method starts the envelope.\n\n The stop() calls the envelope's release phase if `dur` = 0.\n\n >>> s = Server().boot()\n >>> s.start()\n >>> f = Adsr(attack=.01, decay=.2, sustain=.5, release=.1, dur=2, mul=.5)\n >>> a = BrownNoise(mul=f).mix(2).out()\n >>> def repeat():\n ... f.play()\n >>> pat = Pattern(function=repeat, time=2).play()\n\n \"\"\"\n def __init__(self, attack=0.01, decay=0.05, sustain=0.707, release=0.1, dur=0, mul=1, add=0):\n pyoArgsAssert(self, \"nnnnnOO\", attack, decay, sustain, release, dur, mul, add)\n PyoObject.__init__(self, mul, add)\n self._attack = attack\n self._decay = decay\n self._sustain = sustain\n self._release = release\n self._dur = dur\n attack, decay, sustain, release, dur, mul, add, lmax = convertArgsToLists(attack, decay, sustain, release, dur, mul, add)\n self._base_objs = [Adsr_base(wrap(attack,i), wrap(decay,i), wrap(sustain,i), wrap(release,i), wrap(dur,i), wrap(mul,i), wrap(add,i)) for i in range(lmax)]\n\n def out(self, chnl=0, inc=1, dur=0, delay=0):\n return self.play(dur, delay)\n\n def setAttack(self, x):\n \"\"\"\n Replace the `attack` attribute.\n\n :Args:\n\n x : float\n new `attack` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"n\", x)\n self._attack = x\n x, lmax = convertArgsToLists(x)\n [obj.setAttack(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def setDecay(self, x):\n \"\"\"\n Replace the `decay` attribute.\n\n :Args:\n\n x : float\n new `decay` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"n\", x)\n self._decay = x\n x, lmax = convertArgsToLists(x)\n [obj.setDecay(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def setSustain(self, x):\n \"\"\"\n Replace the `sustain` attribute.\n\n :Args:\n\n x : float\n new `sustain` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"n\", x)\n self._sustain = x\n x, lmax = convertArgsToLists(x)\n [obj.setSustain(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def setRelease(self, x):\n \"\"\"\n Replace the `sustain` attribute.\n\n :Args:\n\n x : float\n new `sustain` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"n\", x)\n self._release = x\n x, lmax = convertArgsToLists(x)\n [obj.setRelease(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def setDur(self, x):\n \"\"\"\n Replace the `dur` attribute.\n\n :Args:\n\n x : float\n new `dur` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"n\", x)\n self._dur = x\n x, lmax = convertArgsToLists(x)\n [obj.setDur(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def ctrl(self, map_list=None, title=None, wxnoserver=False):\n self._map_list = [SLMap(0, 5, 'lin', 'attack', self._attack, dataOnly=True),\n SLMap(0, 5, 'lin', 'decay', self._decay, dataOnly=True),\n SLMap(0, 1, 'lin', 'sustain', self._sustain, dataOnly=True),\n SLMap(0, 10, 'lin', 'release', self._release, dataOnly=True),\n SLMap(0, 20., 'lin', 'dur', self._dur, dataOnly=True)]\n PyoObject.ctrl(self, map_list, title, wxnoserver)\n\n @property\n def attack(self):\n \"\"\"float. Duration of the attack phase in seconds.\"\"\"\n return self._attack\n @attack.setter\n def attack(self, x): self.setAttack(x)\n\n @property\n def decay(self):\n \"\"\"float. Duration of the decay phase in seconds.\"\"\"\n return self._decay\n @decay.setter\n def decay(self, x): self.setDecay(x)\n\n @property\n def sustain(self):\n \"\"\"float. Amplitude of the sustain phase.\"\"\"\n return self._sustain\n @sustain.setter\n def sustain(self, x): self.setSustain(x)\n\n @property\n def release(self):\n \"\"\"float. Duration of the release phase in seconds.\"\"\"\n return self._release\n @release.setter\n def release(self, x): self.setRelease(x)\n\n @property\n def dur(self):\n \"\"\"float. Total duration of the envelope.\"\"\"\n return self._dur\n @dur.setter\n def dur(self, x): self.setDur(x)\n\nclass Linseg(PyoObject):\n \"\"\"\n Trace a series of line segments between specified break-points.\n\n The play() method starts the envelope and is not called at the\n object creation time.\n\n :Parent: :py:class:`PyoObject`\n\n :Args:\n\n list : list of tuples\n Points used to construct the line segments. Each tuple is a\n new point in the form (time, value).\n\n Times are given in seconds and must be in increasing order.\n loop : boolean, optional\n Looping mode. Defaults to False.\n initToFirstVal : boolean, optional\n If True, audio buffer will be filled at initialization with the\n first value of the line. Defaults to False.\n\n .. note::\n\n The out() method is bypassed. Linseg's signal can not be sent to audio outs.\n\n >>> s = Server().boot()\n >>> s.start()\n >>> l = Linseg([(0,500),(.03,1000),(.1,700),(1,500),(2,500)], loop=True)\n >>> a = Sine(freq=l, mul=.3).mix(2).out()\n >>> # then call:\n >>> l.play()\n\n \"\"\"\n def __init__(self, list, loop=False, initToFirstVal=False, mul=1, add=0):\n pyoArgsAssert(self, \"lbbOO\", list, loop, initToFirstVal, mul, add)\n PyoObject.__init__(self, mul, add)\n self._list = list\n self._loop = loop\n initToFirstVal, loop, mul, add, lmax = convertArgsToLists(initToFirstVal, loop, mul, add)\n if type(list[0]) != ListType:\n self._base_objs = [Linseg_base(list, wrap(loop,i), wrap(initToFirstVal,i), wrap(mul,i), wrap(add,i)) for i in range(lmax)]\n else:\n listlen = len(list)\n lmax = max(listlen, lmax)\n self._base_objs = [Linseg_base(wrap(list,i), wrap(loop,i), wrap(initToFirstVal,i), wrap(mul,i), wrap(add,i)) for i in range(lmax)]\n\n def out(self, chnl=0, inc=1, dur=0, delay=0):\n return self.play(dur, delay)\n\n def setList(self, x):\n \"\"\"\n Replace the `list` attribute.\n\n :Args:\n\n x : list of tuples\n new `list` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"l\", x)\n self._list = x\n if type(x[0]) != ListType:\n [obj.setList(x) for i, obj in enumerate(self._base_objs)]\n else:\n [obj.setList(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def replace(self, x):\n \"\"\"\n Alias for `setList` method.\n\n :Args:\n\n x : list of tuples\n new `list` attribute.\n\n \"\"\"\n self.setList(x)\n\n def getPoints(self):\n return self._list\n\n def setLoop(self, x):\n \"\"\"\n Replace the `loop` attribute.\n\n :Args:\n\n x : boolean\n new `loop` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"b\", x)\n self._loop = x\n x, lmax = convertArgsToLists(x)\n [obj.setLoop(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def graph(self, xlen=None, yrange=None, title=None, wxnoserver=False):\n \"\"\"\n Opens a grapher window to control the shape of the envelope.\n\n When editing the grapher with the mouse, the new set of points\n will be send to the object on mouse up.\n\n Ctrl+C with focus on the grapher will copy the list of points to the\n clipboard, giving an easy way to insert the new shape in a script.\n\n :Args:\n\n xlen : float, optional\n Set the maximum value of the X axis of the graph. If None, the\n maximum value is retrieve from the current list of points.\n yrange : tuple, optional\n Set the min and max values of the Y axis of the graph. If\n None, min and max are retrieve from the current list of points.\n title : string, optional\n Title of the window. If none is provided, the name of the\n class is used.\n wxnoserver : boolean, optional\n With wxPython graphical toolkit, if True, tells the\n interpreter that there will be no server window.\n\n If `wxnoserver` is set to True, the interpreter will not wait for the\n server GUI before showing the controller window.\n\n \"\"\"\n if xlen == None:\n xlen = float(self._list[-1][0])\n else:\n xlen = float(xlen)\n if yrange == None:\n ymin = float(min([x[1] for x in self._list]))\n ymax = float(max([x[1] for x in self._list]))\n if ymin == ymax:\n yrange = (0, ymax)\n else:\n yrange = (ymin, ymax)\n createGraphWindow(self, 0, xlen, yrange, title, wxnoserver)\n\n @property\n def list(self):\n \"\"\"float. List of points (time, value).\"\"\"\n return self._list\n @list.setter\n def list(self, x): self.setList(x)\n\n @property\n def loop(self):\n \"\"\"boolean. Looping mode.\"\"\"\n return self._loop\n @loop.setter\n def loop(self, x): self.setLoop(x)\n\nclass Expseg(PyoObject):\n \"\"\"\n Trace a series of exponential segments between specified break-points.\n\n The play() method starts the envelope and is not called at the\n object creation time.\n\n :Parent: :py:class:`PyoObject`\n\n :Args:\n\n list : list of tuples\n Points used to construct the line segments. Each tuple is a\n new point in the form (time, value).\n\n Times are given in seconds and must be in increasing order.\n loop : boolean, optional\n Looping mode. Defaults to False.\n exp : float, optional\n Exponent factor. Used to control the slope of the curves.\n Defaults to 10.\n inverse : boolean, optional\n If True, downward slope will be inversed. Useful to create\n biexponential curves. Defaults to True.\n initToFirstVal : boolean, optional\n If True, audio buffer will be filled at initialization with the\n first value of the line. Defaults to False.\n\n .. note::\n\n The out() method is bypassed. Expseg's signal can not be sent to audio outs.\n\n >>> s = Server().boot()\n >>> s.start()\n >>> l = Expseg([(0,500),(.03,1000),(.1,700),(1,500),(2,500)], loop=True)\n >>> a = Sine(freq=l, mul=.3).mix(2).out()\n >>> # then call:\n >>> l.play()\n\n \"\"\"\n def __init__(self, list, loop=False, exp=10, inverse=True, initToFirstVal=False, mul=1, add=0):\n pyoArgsAssert(self, \"lbnbbOO\", list, loop, exp, inverse, initToFirstVal, mul, add)\n PyoObject.__init__(self, mul, add)\n self._list = list\n self._loop = loop\n self._exp = exp\n self._inverse = inverse\n loop, exp, inverse, initToFirstVal, mul, add, lmax = convertArgsToLists(loop, exp, inverse, initToFirstVal, mul, add)\n if type(list[0]) != ListType:\n self._base_objs = [Expseg_base(list, wrap(loop,i), wrap(exp,i), wrap(inverse,i), wrap(initToFirstVal,i), wrap(mul,i), wrap(add,i)) for i in range(lmax)]\n else:\n listlen = len(list)\n lmax = max(listlen, lmax)\n self._base_objs = [Expseg_base(wrap(list,i), wrap(loop,i), wrap(exp,i), wrap(inverse,i), wrap(initToFirstVal,i), wrap(mul,i), wrap(add,i)) for i in range(lmax)]\n\n def out(self, chnl=0, inc=1, dur=0, delay=0):\n return self.play(dur, delay)\n\n def setList(self, x):\n \"\"\"\n Replace the `list` attribute.\n\n :Args:\n\n x : list of tuples\n new `list` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"l\", x)\n self._list = x\n if type(x[0]) != ListType:\n [obj.setList(x) for i, obj in enumerate(self._base_objs)]\n else:\n [obj.setList(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def setLoop(self, x):\n \"\"\"\n Replace the `loop` attribute.\n\n :Args:\n\n x : boolean\n new `loop` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"b\", x)\n self._loop = x\n x, lmax = convertArgsToLists(x)\n [obj.setLoop(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def setExp(self, x):\n \"\"\"\n Replace the `exp` attribute.\n\n :Args:\n\n x : float\n new `exp` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"n\", x)\n self._exp = x\n x, lmax = convertArgsToLists(x)\n [obj.setExp(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def setInverse(self, x):\n \"\"\"\n Replace the `inverse` attribute.\n\n :Args:\n\n x : boolean\n new `inverse` attribute.\n\n \"\"\"\n pyoArgsAssert(self, \"b\", x)\n self._inverse = x\n x, lmax = convertArgsToLists(x)\n [obj.setInverse(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def replace(self, x):\n \"\"\"\n Alias for `setList` method.\n\n :Args:\n\n x : list of tuples\n new `list` attribute.\n\n \"\"\"\n self.setList(x)\n\n def getPoints(self):\n return self._list\n\n def graph(self, xlen=None, yrange=None, title=None, wxnoserver=False):\n \"\"\"\n Opens a grapher window to control the shape of the envelope.\n\n When editing the grapher with the mouse, the new set of points\n will be send to the object on mouse up.\n\n Ctrl+C with focus on the grapher will copy the list of points to the\n clipboard, giving an easy way to insert the new shape in a script.\n\n :Args:\n\n xlen : float, optional\n Set the maximum value of the X axis of the graph. If None, the\n maximum value is retrieve from the current list of points.\n Defaults to None.\n yrange : tuple, optional\n Set the min and max values of the Y axis of the graph. If\n None, min and max are retrieve from the current list of points.\n Defaults to None.\n title : string, optional\n Title of the window. If none is provided, the name of the\n class is used.\n wxnoserver : boolean, optional\n With wxPython graphical toolkit, if True, tells the\n interpreter that there will be no server window.\n\n If `wxnoserver` is set to True, the interpreter will not wait for the\n server GUI before showing the controller window.\n\n \"\"\"\n if xlen == None:\n xlen = float(self._list[-1][0])\n else:\n xlen = float(xlen)\n if yrange == None:\n ymin = float(min([x[1] for x in self._list]))\n ymax = float(max([x[1] for x in self._list]))\n if ymin == ymax:\n yrange = (0, ymax)\n else:\n yrange = (ymin, ymax)\n createGraphWindow(self, 2, xlen, yrange, title, wxnoserver)\n\n @property\n def list(self):\n \"\"\"float. List of points (time, value).\"\"\"\n return self._list\n @list.setter\n def list(self, x): self.setList(x)\n\n @property\n def loop(self):\n \"\"\"boolean. Looping mode.\"\"\"\n return self._loop\n @loop.setter\n def loop(self, x): self.setLoop(x)\n\n @property\n def exp(self):\n \"\"\"float. Exponent factor.\"\"\"\n return self._exp\n @exp.setter\n def exp(self, x): self.setExp(x)\n\n @property\n def inverse(self):\n \"\"\"boolean. Inverse downward slope.\"\"\"\n return self._inverse\n @inverse.setter\n def inverse(self, x): self.setInverse(x)\n\nclass SigTo(PyoObject):\n \"\"\"\n Convert numeric value to PyoObject signal with portamento.\n\n When `value` is changed, a ramp is applied from the current\n value to the new value. Can be used with PyoObject to apply\n a linear portamento on an audio signal.\n\n :Parent: :py:class:`PyoObject`\n\n :Args:\n\n value : float or PyoObject\n Numerical value to convert.\n time : float, optional\n Ramp time, in seconds, to reach the new value. Defaults to 0.025.\n init : float, optional\n Initial value of the internal memory. Defaults to 0.\n\n .. note::\n\n The out() method is bypassed. SigTo's signal can not be sent to audio outs.\n\n >>> import random\n >>> s = Server().boot()\n >>> s.start()\n >>> fr = SigTo(value=200, time=0.5, init=200)\n >>> a = SineLoop(freq=fr, feedback=0.08, mul=.3).out()\n >>> b = SineLoop(freq=fr*1.005, feedback=0.08, mul=.3).out(1)\n >>> def pick_new_freq():\n ... fr.value = random.randrange(200,501,50)\n >>> pat = Pattern(function=pick_new_freq, time=1).play()\n\n \"\"\"\n def __init__(self, value, time=0.025, init=0.0, mul=1, add=0):\n pyoArgsAssert(self, \"OnnOO\", value, time, init, mul, add)\n PyoObject.__init__(self, mul, add)\n self._value = value\n self._time = time\n value, time, init, mul ,add, lmax = convertArgsToLists(value, time, init, mul, add)\n self._base_objs = [SigTo_base(wrap(value,i), wrap(time,i), wrap(init,i), wrap(mul,i), wrap(add,i)) for i in range(lmax)]\n\n def setValue(self, x):\n \"\"\"\n Changes the value of the signal stream.\n\n :Args:\n\n x : float or PyoObject\n Numerical value to convert.\n\n \"\"\"\n pyoArgsAssert(self, \"O\", x)\n self._value = x\n x, lmax = convertArgsToLists(x)\n [obj.setValue(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def setTime(self, x):\n \"\"\"\n Changes the ramp time of the object.\n\n :Args:\n\n x : float\n New ramp time.\n\n \"\"\"\n pyoArgsAssert(self, \"n\", x)\n self._time = x\n x, lmax = convertArgsToLists(x)\n [obj.setTime(wrap(x,i)) for i, obj in enumerate(self._base_objs)]\n\n def ctrl(self, map_list=None, title=None, wxnoserver=False):\n self._map_list = [SLMap(0, 10, 'lin', 'time', self._time, dataOnly=True)]\n PyoObject.ctrl(self, map_list, title, wxnoserver)\n\n @property\n def value(self):\n \"\"\"float or PyoObject. Numerical value to convert.\"\"\"\n return self._value\n @value.setter\n def value(self, x): self.setValue(x)\n\n @property\n def time(self):\n \"\"\"float. Ramp time.\"\"\"\n return self._time\n @time.setter\n def time(self, x): self.setTime(x)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements multistream_multiprofile_driver.py from GoogleCloudPlatform/PerfKitBenchmarker (path: perfkitbenchmarker/data/edw/multistream_multiprofile_driver.py)."}, {"role": "assistant", "content": "# perfkitbenchmarker/data/edw/multistream_multiprofile_driver.py (from GoogleCloudPlatform/PerfKitBenchmarker, license: apache-2.0)\n\n\"\"\"Driver for running multiple profiles concurrently against a cluster.\n\nThe list of profiles are passed via flag each of which are defined in the\nprofile_details module.\n\"\"\"\n\n__author__ = 'p3rf@google.com'\n\nimport json\nimport logging\nfrom multiprocessing import Process\nfrom multiprocessing import Queue\nimport time\nfrom absl import app\nfrom absl import flags\nimport unistream_profile_driver\n\nflags.DEFINE_list('profile_list', None, 'List of profiles. Each will be run on '\n 'its own process to simulate '\n 'concurrency.')\n\nflags.mark_flags_as_required(['profile_list'])\n\nFLAGS = flags.FLAGS\n\ndef process_profile(profile, response_q):\n \"\"\"Method to execute a profile (list of sql scripts) on a cluster.\n\n Args:\n profile: The profile to run.\n response_q: Communication channel between processes.\n \"\"\"\n profile_output = unistream_profile_driver.execute_profile(profile)\n response_q.put([profile, profile_output])\n\ndef manage_streams():\n \"\"\"Method to launch concurrent execution of multiple profiles.\n\n Returns:\n A dictionary containing\n 1. wall_time: Total time taken for all the profiles to complete execution.\n 2. profile details:\n 2.1. profile_execution_time: Time taken for all scripts in the profile to\n complete execution.\n 2.2. Individual script metrics: script name and its execution time (-1 if\n the script fails)\n \"\"\"\n profile_handling_process_list = []\n profile_performance = Queue()\n\n start_time = time.time()\n\n for profile in FLAGS.profile_list:\n profile_handling_process = Process(target=process_profile,\n args=(profile, profile_performance,))\n profile_handling_process.start()\n profile_handling_process_list.append(profile_handling_process)\n\n for profile_handling_process in profile_handling_process_list:\n profile_handling_process.join()\n\n # All processes have joined, implying all profiles have been completed\n execution_time = round((time.time() - start_time), 2)\n\n num_profiles = len(FLAGS.profile_list)\n\n overall_performance = {}\n\n while num_profiles:\n temp_performance_response = profile_performance.get()\n profile = temp_performance_response[0]\n overall_performance[profile] = json.loads(temp_performance_response[1])\n num_profiles -= 1\n\n overall_performance['wall_time'] = execution_time\n return json.dumps(overall_performance)\n\ndef main(argv):\n del argv\n print(manage_streams())\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n app.run(main)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements ins-del-datetime.py from nick-thompson/servo (path: tests/wpt/web-platform-tests/conformance-checkers/tools/ins-del-datetime.py)."}, {"role": "assistant", "content": "# tests/wpt/web-platform-tests/conformance-checkers/tools/ins-del-datetime.py (from nick-thompson/servo, license: mpl-2.0)\n\n# -*- coding: utf-8 -*-\nimport os\nccdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\ntemplate = \"\"\"\n\n\"\"\"\nerrors = {\n \"date-year-0000\": \"0000-12-09\",\n \"date-month-00\": \"2002-00-15\",\n \"date-month-13\": \"2002-13-15\",\n \"date-0005-02-29\": \"0005-02-29\",\n \"date-1969-02-29\": \"1969-02-29\",\n \"date-1900-02-29\": \"1900-02-29\",\n \"date-2100-02-29\": \"2100-02-29\",\n \"date-2200-02-29\": \"2200-02-29\",\n \"date-2014-02-29\": \"2014-02-29\",\n \"date-day-04-31\": \"2002-04-31\",\n \"date-day-06-31\": \"2002-06-31\",\n \"date-day-09-31\": \"2002-09-31\",\n \"date-day-11-31\": \"2002-11-31\",\n \"date-day-01-32\": \"2002-01-32\",\n \"date-day-03-32\": \"2002-03-32\",\n \"date-day-05-32\": \"2002-05-32\",\n \"date-day-07-32\": \"2002-07-32\",\n \"date-day-08-32\": \"2002-08-32\",\n \"date-day-10-32\": \"2002-10-32\",\n \"date-day-12-32\": \"2002-12-32\",\n \"date-iso8601-YYYYMMDD-no-hyphen\": \"20020929\",\n \"date-leading-whitespace\": \" 2002-09-29\",\n \"date-trailing-whitespace\": \"2002-09-29 \",\n \"date-month-one-digit\": \"2002-9-29\",\n \"date-month-three-digits\": \"2002-011-29\",\n \"date-year-three-digits\": \"782-09-29\",\n \"date-day-one-digit\": \"2002-09-9\",\n \"date-day-three-digits\": \"2002-11-009\",\n \"date-day-missing-separator\": \"2014-0220\",\n \"date-month-missing-separator\": \"201402-20\",\n \"date-non-ascii-digit\": \"2002-09-29\",\n \"date-trailing-U+0000\": \"2002-09-29�\",\n \"date-trailing-pile-of-poo\": \"2002-09-29💩\",\n \"date-wrong-day-separator\": \"2014-02:20\",\n \"date-wrong-month-separator\": \"2014:02-20\",\n \"date-year-negative\": \"-2002-09-29\",\n \"date-leading-bom\": \"2002-09-29\",\n \"global-date-and-time-60-minutes\": \"2011-11-12T00:60:00+08:00\",\n \"global-date-and-time-60-seconds\": \"2011-11-12T00:00:60+08:00\",\n \"global-date-and-time-2400\": \"2011-11-12T24:00:00+08:00\",\n \"global-date-and-time-space-before-timezone\": \"2011-11-12T06:54:39 08:00\",\n \"global-date-and-time-hour-one-digit\": \"2011-11-12T6:54:39-08:00\",\n \"global-date-and-time-hour-three-digits\": \"2011-11-12T016:54:39-08:00\",\n \"global-date-and-time-minutes-one-digit\": \"2011-11-12T16:4:39-08:00\",\n \"global-date-and-time-minutes-three-digits\": \"2011-11-12T16:354:39-08:00\",\n \"global-date-and-time-seconds-one-digit\": \"2011-11-12T16:54:9-08:00\",\n \"global-date-and-time-seconds-three-digits\": \"2011-11-12T16:54:039-08:00\",\n \"global-date-and-time-timezone-with-seconds\": \"2011-11-12T06:54:39-08:00:00\",\n \"global-date-and-time-timezone-60-minutes\": \"2011-11-12T06:54:39-08:60\",\n \"global-date-and-time-timezone-one-digit-hour\": \"2011-11-12T06:54:39-5:00\",\n \"global-date-and-time-timezone-one-digit-minute\": \"2011-11-12T06:54:39-05:0\",\n \"global-date-and-time-timezone-three-digit-hour\": \"2011-11-12T06:54:39-005:00\",\n \"global-date-and-time-timezone-three-digit-minute\": \"2011-11-12T06:54:39-05:000\",\n \"global-date-and-time-nbsp\": \"2011-11-12 14:54Z\",\n \"global-date-and-time-missing-minutes-separator\": \"2011-11-12T1454Z\",\n \"global-date-and-time-missing-seconds-separator\": \"2011-11-12T14:5439Z\",\n \"global-date-and-time-wrong-minutes-separator\": \"2011-11-12T14-54Z\",\n \"global-date-and-time-wrong-seconds-separator\": \"2011-11-12T14:54-39Z\",\n \"global-date-and-time-lowercase-z\": \"2011-11-12T14:54z\",\n \"global-date-and-time-with-both-T-and-space\": \"2011-11-12T 14:54Z\",\n \"global-date-and-time-zero-digit-fraction\": \"2011-11-12T06:54:39.-08:00\",\n \"global-date-and-time-four-digit-fraction\": \"2011-11-12T06:54:39.9291-08:00\",\n \"global-date-and-time-bad-fraction-separator\": \"2011-11-12T14:54:39,929+0000\",\n \"global-date-and-time-timezone-non-T-character\": \"2011-11-12+14:54Z\",\n \"global-date-and-time-timezone-lowercase-t\": \"2011-11-12t14:54Z\",\n \"global-date-and-time-timezone-multiple-spaces\": \"2011-11-12 14:54Z\",\n \"global-date-and-time-timezone-offset-space-start\": \"2011-11-12T06:54:39.929 08:00\",\n \"global-date-and-time-timezone-offset-colon-start\": \"2011-11-12T06:54:39.929:08:00\",\n \"global-date-and-time-timezone-plus-2400\": \"2011-11-12T06:54:39-24:00\",\n \"global-date-and-time-timezone-minus-2400\": \"2011-11-12T06:54:39-24:00\",\n \"global-date-and-time-timezone-iso8601-two-digit\": \"2011-11-12T06:54:39-08\",\n \"global-date-and-time-iso8601-hhmmss-no-colon\": \"2011-11-12T145439Z\",\n \"global-date-and-time-iso8601-hhmm-no-colon\": \"2011-11-12T1454Z\",\n \"global-date-and-time-iso8601-hh\": \"2011-11-12T14Z\",\n \"year\": \"2006\",\n \"yearless-date\": \"07-15\",\n \"month\": \"2011-11\",\n \"week\": \"2011-W46\",\n \"time\": \"14:54:39\",\n \"local-date-and-time\": \"2011-11-12T14:54\",\n \"duration-P-form\": \"PT4H18M3S\",\n \"duration-time-component\": \"4h 18m 3s\",\n}\n\nwarnings = {\n \"global-date-and-time-timezone-plus-1500\": \"2011-11-12T00:00:00+1500\",\n \"global-date-and-time-timezone-minus-1300\": \"2011-11-12T00:00:00-1300\",\n \"global-date-and-time-timezone-minutes-15\": \"2011-11-12T00:00:00+08:15\",\n \"date-0214-09-29\": \"0214-09-29\",\n \"date-20014-09-29\": \"20014-09-29\",\n \"date-0004-02-29\": \"0004-02-29\",\n \"date-year-five-digits\": \"12014-09-29\",\n}\n\nnon_errors = {\n \"date\": \"2002-09-29\",\n \"date-2000-02-29\": \"2000-02-29\",\n \"date-2400-02-29\": \"2400-02-29\",\n \"date-1968-02-29\": \"1968-02-29\",\n \"date-1900-02-28\": \"1900-02-28\",\n \"date-2100-02-28\": \"2100-02-28\",\n \"date-2100-02-28\": \"2100-02-28\",\n \"date-2200-02-28\": \"2200-02-28\",\n \"date-2014-02-28\": \"2014-02-28\",\n \"date-day-01-31\": \"2002-01-31\",\n \"date-day-03-31\": \"2002-03-31\",\n \"date-day-05-31\": \"2002-05-31\",\n \"date-day-07-31\": \"2002-07-31\",\n \"date-day-08-31\": \"2002-08-31\",\n \"date-day-10-31\": \"2002-10-31\",\n \"date-day-12-31\": \"2002-12-31\",\n \"date-day-04-30\": \"2002-04-30\",\n \"date-day-06-30\": \"2002-06-30\",\n \"date-day-09-30\": \"2002-09-30\",\n \"date-day-11-30\": \"2002-11-30\",\n \"global-date-and-time-no-seconds\": \"2011-11-12T14:54Z\",\n \"global-date-and-time-with-seconds\": \"2011-11-12T14:54:39+0000\",\n \"global-date-and-time-with-one-digit-fraction\": \"2011-11-12T06:54:39.9-08:00\",\n \"global-date-and-time-with-two-digit-fraction\": \"2011-11-12T06:54:39.92+07:00\",\n \"global-date-and-time-with-three-digit-fraction\": \"2011-11-12T06:54:39.929-06:00\",\n \"global-date-and-time-space\": \"2011-11-12 14:54Z\",\n \"global-date-and-time-timezone\": \"2011-11-12T06:54:39+0900\",\n \"global-date-and-time-timezone-30\": \"2011-11-12T06:54:39-0830\",\n \"global-date-and-time-timezone-45\": \"2011-11-12T06:54:39-0845\",\n \"global-date-and-time-timezone-with-colon\": \"2011-11-12T06:54:39-08:00\",\n \"global-date-and-time-timezone-without-colon\": \"2011-11-12T06:54:39-0800\",\n}\n\nfor key in errors.keys():\n error = errors[key]\n template_ins = template\n template_del = template\n template_ins += '%s\\n' % key\n template_del += '%s\\n' % key\n template_ins += '' % errors[key]\n template_del += '' % errors[key]\n ins_file = open(os.path.join(ccdir, \"html/elements/ins/%s-novalid.html\" % key), 'wb')\n ins_file.write(template_ins)\n ins_file.close()\n del_file = open(os.path.join(ccdir, \"html/elements/del/%s-novalid.html\" % key), 'wb')\n del_file.write(template_del)\n del_file.close()\n\nfor key in warnings.keys():\n non_error = warnings[key]\n template_ins = template\n template_del = template\n template_ins += '%s\\n' % key\n template_del += '%s\\n' % key\n template_ins += '' % warnings[key]\n template_del += '' % warnings[key]\n ins_file = open(os.path.join(ccdir, \"html/elements/ins/%s-haswarn.html\" % key), 'wb')\n ins_file.write(template_ins)\n ins_file.close()\n del_file = open(os.path.join(ccdir, \"html/elements/del/%s-haswarn.html\" % key), 'wb')\n del_file.write(template_del)\n del_file.close()\n\nins_file = open(os.path.join(ccdir, \"html/elements/ins/datetime-isvalid.html\"), 'wb')\ndel_file = open(os.path.join(ccdir, \"html/elements/del/datetime-isvalid.html\"), 'wb')\nins_file.write(template + 'valid datetime\\n')\ndel_file.write(template + 'valid datetime\\n')\nfor key in non_errors.keys():\n non_error = non_errors[key]\n ins_file.write(' \\n' % (non_errors[key], key))\n del_file.write(' \\n' % (non_errors[key], key))\nins_file.close()\ndel_file.close()\n# vim: ts=4:sw=4"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_item_sort_key.py from MonicaHsu/truvaluation (path: venv/lib/python2.7/site-packages/simplejson/tests/test_item_sort_key.py)."}, {"role": "assistant", "content": "# venv/lib/python2.7/site-packages/simplejson/tests/test_item_sort_key.py (from MonicaHsu/truvaluation, license: mit)\n\nfrom unittest import TestCase\n\nimport simplejson as json\nfrom operator import itemgetter\n\nclass TestItemSortKey(TestCase):\n def test_simple_first(self):\n a = {'a': 1, 'c': 5, 'jack': 'jill', 'pick': 'axe', 'array': [1, 5, 6, 9], 'tuple': (83, 12, 3), 'crate': 'dog', 'zeak': 'oh'}\n self.assertEqual(\n '{\"a\": 1, \"c\": 5, \"crate\": \"dog\", \"jack\": \"jill\", \"pick\": \"axe\", \"zeak\": \"oh\", \"array\": [1, 5, 6, 9], \"tuple\": [83, 12, 3]}',\n json.dumps(a, item_sort_key=json.simple_first))\n\n def test_case(self):\n a = {'a': 1, 'c': 5, 'Jack': 'jill', 'pick': 'axe', 'Array': [1, 5, 6, 9], 'tuple': (83, 12, 3), 'crate': 'dog', 'zeak': 'oh'}\n self.assertEqual(\n '{\"Array\": [1, 5, 6, 9], \"Jack\": \"jill\", \"a\": 1, \"c\": 5, \"crate\": \"dog\", \"pick\": \"axe\", \"tuple\": [83, 12, 3], \"zeak\": \"oh\"}',\n json.dumps(a, item_sort_key=itemgetter(0)))\n self.assertEqual(\n '{\"a\": 1, \"Array\": [1, 5, 6, 9], \"c\": 5, \"crate\": \"dog\", \"Jack\": \"jill\", \"pick\": \"axe\", \"tuple\": [83, 12, 3], \"zeak\": \"oh\"}',\n json.dumps(a, item_sort_key=lambda kv: kv[0].lower()))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements pvec.py from robovm/robovm-studio (path: plugins/hg4idea/testData/bin/mercurial/pvec.py)."}, {"role": "assistant", "content": "# plugins/hg4idea/testData/bin/mercurial/pvec.py (from robovm/robovm-studio, license: apache-2.0)\n\n# pvec.py - probabilistic vector clocks for Mercurial\n#\n# Copyright 2012 Matt Mackall \n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2 or any later version.\n\n'''\nA \"pvec\" is a changeset property based on the theory of vector clocks\nthat can be compared to discover relatedness without consulting a\ngraph. This can be useful for tasks like determining how a\ndisconnected patch relates to a repository.\n\nCurrently a pvec consist of 448 bits, of which 24 are 'depth' and the\nremainder are a bit vector. It is represented as a 70-character base85\nstring.\n\nConstruction:\n\n- a root changeset has a depth of 0 and a bit vector based on its hash\n- a normal commit has a changeset where depth is increased by one and\n one bit vector bit is flipped based on its hash\n- a merge changeset pvec is constructed by copying changes from one pvec into\n the other to balance its depth\n\nProperties:\n\n- for linear changes, difference in depth is always <= hamming distance\n- otherwise, changes are probably divergent\n- when hamming distance is < 200, we can reliably detect when pvecs are near\n\nIssues:\n\n- hamming distance ceases to work over distances of ~ 200\n- detecting divergence is less accurate when the common ancestor is very close\n to either revision or total distance is high\n- this could probably be improved by modeling the relation between\n delta and hdist\n\nUses:\n\n- a patch pvec can be used to locate the nearest available common ancestor for\n resolving conflicts\n- ordering of patches can be established without a DAG\n- two head pvecs can be compared to determine whether push/pull/merge is needed\n and approximately how many changesets are involved\n- can be used to find a heuristic divergence measure between changesets on\n different branches\n'''\n\nimport base85, util\nfrom node import nullrev\n\n_size = 448 # 70 chars b85-encoded\n_bytes = _size / 8\n_depthbits = 24\n_depthbytes = _depthbits / 8\n_vecbytes = _bytes - _depthbytes\n_vecbits = _vecbytes * 8\n_radius = (_vecbits - 30) / 2 # high probability vectors are related\n\ndef _bin(bs):\n '''convert a bytestring to a long'''\n v = 0\n for b in bs:\n v = v * 256 + ord(b)\n return v\n\ndef _str(v, l):\n bs = \"\"\n for p in xrange(l):\n bs = chr(v & 255) + bs\n v >>= 8\n return bs\n\ndef _split(b):\n '''depth and bitvec'''\n return _bin(b[:_depthbytes]), _bin(b[_depthbytes:])\n\ndef _join(depth, bitvec):\n return _str(depth, _depthbytes) + _str(bitvec, _vecbytes)\n\ndef _hweight(x):\n c = 0\n while x:\n if x & 1:\n c += 1\n x >>= 1\n return c\n_htab = [_hweight(x) for x in xrange(256)]\n\ndef _hamming(a, b):\n '''find the hamming distance between two longs'''\n d = a ^ b\n c = 0\n while d:\n c += _htab[d & 0xff]\n d >>= 8\n return c\n\ndef _mergevec(x, y, c):\n # Ideally, this function would be x ^ y ^ ancestor, but finding\n # ancestors is a nuisance. So instead we find the minimal number\n # of changes to balance the depth and hamming distance\n\n d1, v1 = x\n d2, v2 = y\n if d1 < d2:\n d1, d2, v1, v2 = d2, d1, v2, v1\n\n hdist = _hamming(v1, v2)\n ddist = d1 - d2\n v = v1\n m = v1 ^ v2 # mask of different bits\n i = 1\n\n if hdist > ddist:\n # if delta = 10 and hdist = 100, then we need to go up 55 steps\n # to the ancestor and down 45\n changes = (hdist - ddist + 1) / 2\n else:\n # must make at least one change\n changes = 1\n depth = d1 + changes\n\n # copy changes from v2\n if m:\n while changes:\n if m & i:\n v ^= i\n changes -= 1\n i <<= 1\n else:\n v = _flipbit(v, c)\n\n return depth, v\n\ndef _flipbit(v, node):\n # converting bit strings to longs is slow\n bit = (hash(node) & 0xffffffff) % _vecbits\n return v ^ (1< delta:\n return False\n return True\n\n def __gt__(self, b):\n return b < self\n\n def __or__(self, b):\n delta = abs(b._depth - self._depth)\n if _hamming(self._vec, b._vec) <= delta:\n return False\n return True\n\n def __sub__(self, b):\n if self | b:\n raise ValueError(\"concurrent pvecs\")\n return self._depth - b._depth\n\n def distance(self, b):\n d = abs(b._depth - self._depth)\n h = _hamming(self._vec, b._vec)\n return max(d, h)\n\n def near(self, b):\n dist = abs(b.depth - self._depth)\n if dist > _radius or _hamming(self._vec, b._vec) > _radius:\n return False"}]} {"messages": [{"role": "user", "content": "Write Python code that implements helpers.py from globocom/oauth2u (path: tests/helpers.py)."}, {"role": "assistant", "content": "# tests/helpers.py (from globocom/oauth2u, license: mit)\n\nimport sys\nimport urllib\nimport cgi\nimport base64\nimport json\nfrom functools import partial\n\nimport requests\n\n__all__ = ('TEST_SERVER_HOST',\n 'build_root_url',\n 'build_basic_authorization_header',\n 'build_access_token_url',\n 'parse_json_response',\n 'parse_query_string',\n 'get_code_from_url',\n 'request_authorization_code')\n\nTEST_SERVER_HOST = 'http://localhost:8888'\n\ndef build_url(host, path, query=None):\n query = query or {}\n return u'{0}/{1}?{2}'.format(host.rstrip('/'),\n path.lstrip('/'),\n urllib.urlencode(query))\n\nbuild_root_url = partial(build_url, TEST_SERVER_HOST)\nbuild_authorize_url = partial(build_url, TEST_SERVER_HOST, '/authorize')\nbuild_access_token_url = partial(build_url, TEST_SERVER_HOST, '/access-token')\n\ndef parse_json_response(response):\n assert 'application/json; charset=UTF-8' == response.headers['content-type']\n return json.loads(response.content)\n\ndef parse_query_string(url):\n url, query_string = url.split('?')\n query = dict(cgi.parse_qsl(query_string))\n return url, query\n\ndef get_code_from_url(url):\n ''' Given an url returns the 'code' GET parameter '''\n query = dict(cgi.parse_qsl(url.split('?')[1]))\n return query['code']\n\ndef request_authorization_code(client_id='123',\n redirect_uri='http://callback'):\n ''' Performs a GET on the authorization request url, waits for the \n redirect and return the code provided \n '''\n url = build_authorize_url({'client_id': client_id,\n 'response_type': 'code',\n 'redirect_uri': redirect_uri})\n resp = requests.get(url, allow_redirects=False)\n assert 302 == resp.status_code\n code = get_code_from_url(resp.headers['Location'])\n return code\n\ndef build_basic_authorization_header(client_id, code):\n ''' Build the value for a Basic ``Authorization`` HTTP header '''\n digest = base64.b64encode('{0}:{1}'.format(client_id, code))\n return 'Basic {0}'.format(digest)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements nc.py from play113/swer (path: heekscnc-read-only/nc/nc.py)."}, {"role": "assistant", "content": "# heekscnc-read-only/nc/nc.py (from play113/swer, license: mit)\n\n################################################################################\n# nc.py\n#\n# Base class for NC code creation\n# And global functions for calling current creator\n#\n# Hirutso Enni, 2009-01-13\n# altered by Dan Falck 2010-08-04\n# added tap() arguments Michael Haberler 2010-10-07\n################################################################################\n\nncOFF = 0\n\nncLEFT = -1\nncRIGHT = +1\n\nncCW = -1\nncCCW = +1\n\nncMIST = 1\nncFLOOD = 2\n\n################################################################################\nclass Creator:\n\n def __init__(self):\n pass\n\n ############################################################################\n ## Internals\n\n def file_open(self, name):\n self.file = open(name, 'w')\n self.filename = name\n\n def file_close(self):\n self.file.close()\n\n def write(self, s):\n self.file.write(s)\n\n ############################################################################\n ## Programs\n\n def program_begin(self, id, name=''):\n \"\"\"Begin a program\"\"\"\n pass\n \n def add_stock(self, type_name, params):\n pass\n\n def program_stop(self, optional=False):\n \"\"\"Stop the machine\"\"\"\n pass\n\n def program_end(self):\n \"\"\"End the program\"\"\"\n pass\n\n def flush_nc(self):\n \"\"\"Flush all pending codes\"\"\"\n pass\n\n ############################################################################\n ## Subprograms\n \n def sub_begin(self, id, name=''):\n \"\"\"Begin a subprogram\"\"\"\n pass\n\n def sub_call(self, id):\n \"\"\"Call a subprogram\"\"\"\n pass\n\n def sub_end(self):\n \"\"\"Return from a subprogram\"\"\"\n pass\n\n ############################################################################\n ## Settings\n \n def imperial(self):\n \"\"\"Set imperial units\"\"\"\n pass\n\n def metric(self):\n \"\"\"Set metric units\"\"\"\n pass\n\n def absolute(self):\n \"\"\"Set absolute coordinates\"\"\"\n pass\n\n def incremental(self):\n \"\"\"Set incremental coordinates\"\"\"\n pass\n\n def polar(self, on=True):\n \"\"\"Set polar coordinates\"\"\"\n pass\n\n def set_plane(self, plane):\n \"\"\"Set plane\"\"\"\n pass\n\n def set_temporary_origin(self, x=None, y=None, z=None, a=None, b=None, c=None):\n \"\"\"Set temporary origin G92\"\"\"\n pass\n\n def remove_temporary_origin(self):\n \"\"\"Remote temporary origin G92.1\"\"\"\n pass\n \n ############################################################################\n ## Tools\n \n def tool_change(self, id):\n \"\"\"Change the tool\"\"\"\n pass\n\n def tool_defn(self, id, name='', params=None):\n \"\"\"Define a tool\"\"\"\n pass\n\n def offset_radius(self, id, radius=None):\n \"\"\"Set tool radius offsetting\"\"\"\n pass\n\n def offset_length(self, id, length=None):\n \"\"\"Set tool length offsetting\"\"\"\n pass\n \n def current_tool(self):\n return None\n\n ############################################################################\n ## Datums\n \n def datum_shift(self, x=None, y=None, z=None, a=None, b=None, c=None):\n \"\"\"Shift the datum\"\"\"\n pass\n\n def datum_set(self, x=None, y=None, z=None, a=None, b=None, c=None):\n \"\"\"Set the datum\"\"\"\n pass\n\n def workplane(self, id):\n \"\"\"Set the workplane\"\"\"\n pass\n\n def clearanceplane(self,z=None):\n \"\"\"set clearance plane\"\"\"\n pass\n\n ############################################################################\n ## APT360 like Transformation Definitions\n ## These definitions were created while looking at Irvin Kraal's book on APT\n ## - Numerical Control Progamming in APT - page 211\n\n def matrix(self,a1=None,b1=None,c1=None,a2=None,b2=None,c2=None,a3=None,b3=None,c3=None):\n \"\"\"Create a matrix for transformations\"\"\"\n pass\n def translate(self,x=None,y=None,z=None):\n \"\"\"Translate in x,y,z direction\"\"\"\n pass\n def rotate(self,xyrot=None,yzrot=None,zxrot=None,angle=None):\n \"\"\"Rotate about a coordinate axis\"\"\"\n pass\n def scale(self,k=None):\n \"\"\"Scale by factor k\"\"\"\n pass\n def matrix_product(self,matrix1=None,matrix2=None):\n \"\"\"Create matrix that is the product of two other matrices\"\"\"\n pass\n def mirror_plane(self,plane1=None,plane2=None,plane3=None):\n \"\"\"Mirror image about one or more coordinate planes\"\"\"\n pass\n def mirror_line(self,line=None):\n \"\"\"Mirror about a line\"\"\"\n pass\n\n ############################################################################\n ## Rates + Modes\n \n def feedrate(self, f):\n \"\"\"Set the feedrate\"\"\"\n pass\n\n def feedrate_hv(self, fh, fv):\n \"\"\"Set the horizontal and vertical feedrates\"\"\"\n pass\n\n def spindle(self, s, clockwise=True):\n \"\"\"Set the spindle speed\"\"\"\n pass\n\n def coolant(self, mode=0):\n \"\"\"Set the coolant mode\"\"\"\n pass\n\n def gearrange(self, gear=0):\n \"\"\"Set the gear range\"\"\"\n pass\n\n ############################################################################\n ## Moves\n \n def rapid(self, x=None, y=None, z=None, a=None, b=None, c=None):\n \"\"\"Rapid move\"\"\"\n pass\n\n def feed(self, x=None, y=None, z=None, a = None, b = None, c = None):\n \"\"\"Feed move\"\"\"\n pass\n\n def arc_cw(self, x=None, y=None, z=None, i=None, j=None, k=None, r=None):\n \"\"\"Clockwise arc move\"\"\"\n pass\n\n def arc_ccw(self, x=None, y=None, z=None, i=None, j=None, k=None, r=None):\n \"\"\"Counterclockwise arc move\"\"\"\n pass\n\n def dwell(self, t):\n \"\"\"Dwell\"\"\"\n pass\n\n def rapid_home(self, x=None, y=None, z=None, a=None, b=None, c=None):\n \"\"\"Rapid relative to home position\"\"\"\n pass\n\n def rapid_unhome(self):\n \"\"\"Return from rapid home\"\"\"\n pass\n\n def set_machine_coordinates(self):\n \"\"\"Set machine coordinates\"\"\"\n pass\n\n ############################################################################\n ## Cutter radius compensation\n \n def use_CRC(self):\n \"\"\"CRC\"\"\"\n return False\n \n ############################################################################\n ## Cycles\n\n def pattern(self):\n \"\"\"Simple pattern eg. circle, rect\"\"\"\n pass\n\n def pocket(self):\n \"\"\"Pocket routine\"\"\"\n pass\n\n def profile(self):\n \"\"\"Profile routine\"\"\"\n pass\n\n def drill(self, x=None, y=None, dwell=None, depthparams = None, retract_mode=None, spindle_mode=None, internal_coolant_on=None, rapid_to_clearance=None):\n \"\"\"Drilling routines\"\"\"\n pass\n\n # original prototype was:\n # def tap(self, x=None, y=None, z=None, zretract=None, depth=None, standoff=None, dwell_bottom=None, pitch=None, stoppos=None, spin_in=None, spin_out=None):\n #\n # current call is like so:\n # tap(x=10, y=10, z=0, tap_mode=0, depth=12.7, standoff=6.35, direction=0, pitch=1.25)\n # just add tap_mode & direction parameters\n\n def tap(self, x=None, y=None, z=None, zretract=None, depth=None, standoff=None, dwell_bottom=None, pitch=None, stoppos=None, spin_in=None, spin_out=None, tap_mode=None, direction=None):\n \"\"\"Tapping routines\"\"\"\n pass\n\n def bore(self, x=None, y=None, z=None, zretract=None, depth=None, standoff=None, dwell_bottom=None, feed_in=None, feed_out=None, stoppos=None, shift_back=None, shift_right=None, backbore=False, stop=False):\n \"\"\"Boring routines\"\"\"\n pass\n\n def end_canned_cycle(self):\n pass\n\n ############################################################################\n ## Misc\n\n def comment(self, text):\n \"\"\"Insert a comment\"\"\"\n pass\n\n def insert(self, text):\n \"\"\"APT style INSERT statement\"\"\"\n pass\n\n def block_delete(self, on=False):\n \"\"\"block to ignore if block delete switch is on\"\"\"\n pass\n\n def variable(self, id):\n \"\"\"Insert a variable\"\"\"\n pass\n\n def variable_set(self, id, value):\n \"\"\"Set a variable\"\"\"\n pass\n\n def probe_linear_centre_outside(self, x1=None, y1=None, depth=None, x2=None, y2=None ):\n pass\n\n def probe_single_point(self, point_along_edge_x=None, point_along_edge_y=None, depth=None, retracted_point_x=None, retracted_point_y=None, destination_point_x=None, destination_point_y=None, intersection_variable_x=None, intersection_variable_y=None, probe_offset_x_component=None, probe_offset_y_component=None ):\n pass\n\n def probe_downward_point(self, x=None, y=None, depth=None, intersection_variable_z=None):\n pass\n\n def report_probe_results(self, x1=None, y1=None, z1=None, x2=None, y2=None, z2=None, x3=None, y3=None, z3=None, x4=None, y4=None, z4=None, x5=None, y5=None, z5=None, x6=None, y6=None, z6=None, xml_file_name=None ):\n pass\n\n def open_log_file(self, xml_file_name=None ):\n pass\n\n def log_coordinate(self, x=None, y=None, z=None):\n pass\n\n def log_message(self, message=None):\n pass\n\n def close_log_file(self):\n pass\n\n def rapid_to_midpoint(self, x1=None, y1=None, z1=None, x2=None, y2=None, z2=None):\n pass\n\n def rapid_to_intersection(self, x1, y1, x2, y2, x3, y3, x4, y4, intersection_x, intersection_y, ua_numerator, ua_denominator, ua, ub_numerator, ub):\n pass\n\n def rapid_to_rotated_coordinate(self, x1, y1, x2, y2, ref_x, ref_y, x_current, y_current, x_final, y_final):\n pass\n\n def set_path_control_mode(self, mode, motion_blending_tolerance, naive_cam_tolerance ):\n pass\n\n ############################################################################\n ## NC code creator for additive machines like RepRap\n\n def wipe(self):\n \"\"\"wipe routine\"\"\"\n pass\n\n def extruder_on(self):\n \"\"\"Turn on the extruder\"\"\"\n pass\n\n def extruder_off(self):\n \"\"\"turn off the extruder\"\"\"\n pass\n\n def set_extruder_flowrate(self, flowrate):\n \"\"\"Set the flowrate for the extruder\"\"\"\n pass\n\n def extruder_temp(self, temp):\n \"\"\"Set the extruder temp in celsius\"\"\"\n pass\n\n def fan_on(self):\n \"\"\"turn on the cooling fan\"\"\"\n pass\n\n def fan_off(self):\n \"\"\"turn off the cooling fan\"\"\"\n pass\n\n def build_bed_temp(self, temp):\n \"\"\"Set the bed temp in celsius\"\"\"\n pass\n\n def chamber_temp(self, temp):\n \"\"\"Set the chamber temp in celsius\"\"\"\n pass\n\n def begin_ncblock(self):\n # if the moves have come from backplotting nc code, then the nc code text can be given with these three functions\n pass\n\n def end_ncblock(self):\n pass\n\n def add_text(self, s, col, cdata):\n pass\n\n################################################################################\n\ncreator = Creator()\n\n############################################################################\n## Internals\n\ndef write(s):\n creator.write(s)\n \ndef output(filename):\n creator.file_open(filename)\n\n############################################################################\n## Programs\n\ndef program_begin(id, name=''):\n creator.program_begin(id, name)\n\ndef add_stock(type_name, params):\n creator.add_stock(type_name, params)\n\ndef program_stop(optional=False):\n creator.program_stop(optional)\n\ndef program_end():\n creator.program_end()\n\ndef flush_nc():\n creator.flush_nc()\n\n############################################################################\n## Subprograms\n\ndef sub_begin(id, name=''):\n creator.sub_begin(id, name)\n\ndef sub_call(id):\n creator.sub_call(id)\n\ndef sub_end():\n creator.sub_end()\n\n############################################################################\n## Settings\n\ndef imperial():\n creator.imperial()\n\ndef metric():\n creator.metric()\n\ndef absolute():\n creator.absolute()\n\ndef incremental():\n creator.incremental()\n\ndef polar(on=True):\n creator.polar(on)\n\ndef set_plane(plane):\n creator.set_plane(plane)\n\ndef set_temporary_origin(x=None, y=None, z=None, a=None, b=None, c=None):\n creator.set_temporary_origin(x,y,z,a,b,c)\n\ndef remove_temporary_origin():\n creator.remove_temporary_origin()\n \n############################################################################\n## Tools\n\ndef tool_change(id):\n creator.tool_change(id)\n\ndef tool_defn(id, name='', params=None):\n creator.tool_defn(id, name, params)\n\ndef offset_radius(id, radius=None):\n creator.offset_radius(id, radius)\n\ndef offset_length(id, length=None):\n creator.offset_length(id, length)\n\ndef current_tool(self):\n return creator.current_tool()\n\n############################################################################\n## Datums\n\ndef datum_shift(x=None, y=None, z=None, a=None, b=None, c=None):\n creator.datum_shift(x, y, z, a, b, c)\n\ndef datum_set(x=None, y=None, z=None, a=None, b=None, c=None):\n creator.datum_set(x, y, z, a, b, c)\n\ndef workplane(id):\n creator.workplane(id)\n\ndef clearanceplane(z=None):\n creator.clearanceplane(z)\n\n############################################################################\n## APT360 like Transformation Definitions\n## These definitions were created while looking at Irvin Kraal's book on APT\n## - Numerical Control Progamming in APT - page 211\n\ndef matrix(a1=None,b1=None,c1=None,a2=None,b2=None,c2=None,a3=None,b3=None,c3=None):\n creator.matrix(a1,b1,c1,a2,b2,c2,a3,b3,c3)\n \ndef translate(x=None,y=None,z=None):\n creator.translate(x,y,z)\n \ndef rotate(xyrot=None,yzrot=None,zxrot=None,angle=None):\n creator.rotate(xyrot,yzrot,zxrot,angle)\n \ndef scale(k=None):\n creator.scale(k)\n \ndef matrix_product(matrix1=None,matrix2=None):\n creator.matrix_product(matrix1,matrix2)\n \ndef mirror_plane(plane1=None,plane2=None,plane3=None):\n creator.mirror_plane(plane1,plane2,plane3)\n \ndef mirror_line(line=None):\n creator.mirror_line(line)\n \n\n############################################################################\n## Rates + Modes\n\ndef feedrate(f):\n creator.feedrate(f)\n\ndef feedrate_hv(fh, fv):\n creator.feedrate_hv(fh, fv)\n\ndef spindle(s, clockwise=True):\n creator.spindle(s, clockwise)\n\ndef coolant(mode=0):\n creator.coolant(mode)\n\ndef gearrange(gear=0):\n creator.gearrange(gear)\n\n############################################################################\n## Moves\n\ndef rapid(x=None, y=None, z=None, a=None, b=None, c=None):\n creator.rapid(x, y, z, a, b, c)\n\ndef feed(x=None, y=None, z=None, a = None, b = None, c = None):\n creator.feed(x, y, z)\n\ndef arc_cw(x=None, y=None, z=None, i=None, j=None, k=None, r=None):\n creator.arc_cw(x, y, z, i, j, k, r)\n\ndef arc_ccw(x=None, y=None, z=None, i=None, j=None, k=None, r=None):\n creator.arc_ccw(x, y, z, i, j, k, r)\n\ndef dwell(t):\n creator.dwell(t)\n\ndef rapid_home(x=None, y=None, z=None, a=None, b=None, c=None):\n creator.rapid_home(x, y, z, a, b, c)\n\ndef rapid_unhome():\n creator.rapid_unhome()\n \ndef set_machine_coordinates():\n creator.set_machine_coordinates()\n\n############################################################################\n## Cutter radius compensation\n\ndef use_CRC():\n return creator.use_CRC()\n\ndef CRC_nominal_path():\n return creator.CRC_nominal_path()\n\ndef start_CRC(left = True, radius = 0.0):\n creator.start_CRC(left, radius)\n\ndef end_CRC():\n creator.end_CRC()\n\n############################################################################\n## Cycles\n\ndef pattern():\n creator.pattern()\n\ndef pocket():\n creator.pocket()\n\ndef profile():\n creator.profile()\n\ndef drill(x=None, y=None, dwell=None, depthparams = None, retract_mode=None, spindle_mode=None, internal_coolant_on=None, rapid_to_clearance=None):\n creator.drill(x, y, dwell, depthparams, retract_mode, spindle_mode, internal_coolant_on, rapid_to_clearance)\n\ndef tap(x=None, y=None, z=None, zretract=None, depth=None, standoff=None, dwell_bottom=None, pitch=None, stoppos=None, spin_in=None, spin_out=None, tap_mode=None, direction=None):\n creator.tap(x, y, z, zretract, depth, standoff, dwell_bottom, pitch, stoppos, spin_in, spin_out, tap_mode, direction)\n\ndef bore(x=None, y=None, z=None, zretract=None, depth=None, standoff=None, dwell_bottom=None, feed_in=None, feed_out=None, stoppos=None, shift_back=None, shift_right=None, backbore=False, stop=False):\n creator.bore(x, y, z, zretract, depth, standoff, dwell_Bottom, feed_in, feed_out, stoppos, shift_back, shift_right, backbore, stop)\n\ndef end_canned_cycle():\n creator.end_canned_cycle()\n\ndef peck(count, first, last=None, step=0.0):\n pecks = []\n peck = first\n if (last == None) : last = first\n for i in range(0,count):\n pecks.append(peck)\n if (peck - step > last) : peck -= step\n return pecks\n\n############################################################################\n## Misc\n\ndef comment(text):\n creator.comment(text)\n\ndef insert(text):\n creator.insert(text)\n\ndef block_delete(on=False):\n creator.block_delete(on) \n\ndef variable(id):\n creator.variable(id)\n\ndef variable_set(id, value):\n creator.variable_set(id, value)\n\ndef probe_single_point(point_along_edge_x=None, point_along_edge_y=None, depth=None, retracted_point_x=None, retracted_point_y=None, destination_point_x=None, destination_point_y=None, intersection_variable_x=None, intersection_variable_y=None, probe_offset_x_component=None, probe_offset_y_component=None ):\n creator.probe_single_point(point_along_edge_x, point_along_edge_y, depth, retracted_point_x, retracted_point_y, destination_point_x, destination_point_y, intersection_variable_x, intersection_variable_y, probe_offset_x_component, probe_offset_y_component )\n\ndef probe_downward_point(x=None, y=None, depth=None, intersection_variable_z=None):\n creator.probe_downward_point(x, y, depth, intersection_variable_z)\n\ndef report_probe_results(x1=None, y1=None, z1=None, x2=None, y2=None, z2=None, x3=None, y3=None, z3=None, x4=None, y4=None, z4=None, x5=None, y5=None, z5=None, x6=None, y6=None, z6=None, xml_file_name=None ):\n creator.report_probe_results(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4, x5, y5, z5, x6, y6, z6, xml_file_name)\n\ndef open_log_file(xml_file_name=None ):\n creator.open_log_file(xml_file_name)\n\ndef log_coordinate(x=None, y=None, z=None):\n creator.log_coordinate(x, y, z)\n\ndef log_message(message=None):\n creator.log_message(message)\n\ndef close_log_file():\n creator.close_log_file()\n\ndef rapid_to_midpoint(x1=None, y1=None, z1=None, x2=None, y2=None, z2=None):\n creator.rapid_to_midpoint(x1, y1, z1, x2, y2, z2)\n\ndef rapid_to_intersection(x1, y1, x2, y2, x3, y3, x4, y4, intersection_x, intersection_y, ua_numerator, ua_denominator, ua, ub_numerator, ub):\n creator.rapid_to_intersection(x1, y1, x2, y2, x3, y3, x4, y4, intersection_x, intersection_y, ua_numerator, ua_denominator, ua, ub_numerator, ub)\n\ndef rapid_to_rotated_coordinate(x1, y1, x2, y2, ref_x, ref_y, x_current, y_current, x_final, y_final):\n creator.rapid_to_rotated_coordinate(x1, y1, x2, y2, ref_x, ref_y, x_current, y_current, x_final, y_final)\n\ndef set_path_control_mode(mode, motion_blending_tolerance, naive_cam_tolerance ):\n creator.set_path_control_mode(mode, motion_blending_tolerance, naive_cam_tolerance )\n\n############################################################################\n## NC code creator for additive machines like RepRap\n\ndef wipe():\n creator.wipe()\n\ndef extruder_on():\n creator.extruder_on()\n\ndef extruder_off():\n creator.extruder_off()\n\ndef set_extruder_flowrate(flowrate):\n creator.set_extruder_flowrate(flowrate)\n \ndef extruder_temp(temp=None):\n creator.extruder_temp(temp)\n\ndef fan_on():\n creator.fan_on()\n\ndef fan_off():\n creator.fan_off()\n\ndef build_bed_temp(temp=None):\n creator.build_bed_temp(temp)\n\ndef chamber_temp(temp=None):\n creator.chamber_temp(temp)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements production.py from andersinno/foosball (path: config/settings/production.py)."}, {"role": "assistant", "content": "# config/settings/production.py (from andersinno/foosball, license: mit)\n\n# -*- coding: utf-8 -*-\n\"\"\"\nProduction Configurations\n\"\"\"\nfrom __future__ import absolute_import, unicode_literals\n\nfrom django.utils import six\n\nfrom .common import * # noqa\n\n# Enable social integration plugins\nSOCIAL_ACCOUNTS = (\n 'allauth.socialaccount.providers.google',\n 'allauth.socialaccount.providers.facebook',\n\n)\nINSTALLED_APPS += SOCIAL_ACCOUNTS\n\n# SECRET CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key\n# Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ\nSECRET_KEY = env(\"DJANGO_SECRET_KEY\")\n\n# This ensures that Django will be able to detect a secure connection\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\nSECURITY_MIDDLEWARE = (\n 'django.middleware.security.SecurityMiddleware',\n)\n\n# Make sure SecurityMiddleware is listed first\nMIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + MIDDLEWARE_CLASSES\n\nSESSION_COOKIE_SECURE = True\nSESSION_COOKIE_HTTPONLY = True\nSECURE_SSL_REDIRECT = True\n\nACCOUNT_DEFAULT_HTTP_PROTOCOL = \"https\"\n\n# SITE CONFIGURATION\n# ------------------------------------------------------------------------------\n# Hosts/domain names that are valid for this site\n# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts\nALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['foosball.anders.fi'])\n# END SITE CONFIGURATION\n\n# EMAIL\n# ------------------------------------------------------------------------------\nDEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',\n default='foosball ')\nEMAIL_SUBJECT_PREFIX = env(\"DJANGO_EMAIL_SUBJECT_PREFIX\", default='[foosball] ')\nSERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)\n\n# TEMPLATE CONFIGURATION\n# ------------------------------------------------------------------------------\n# See:\n# https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader\nTEMPLATES[1]['OPTIONS']['loaders'] = [\n ('django.template.loaders.cached.Loader', [\n 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]),\n]\n\n# DATABASE CONFIGURATION\n# ------------------------------------------------------------------------------\n# Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ\nDATABASES['default'] = env.db(\"DATABASE_URL\")\n\n# CACHING\n# ------------------------------------------------------------------------------\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"{0}/{1}\".format(env('REDIS_URL', default=\"redis://127.0.0.1:6379\"), 0),\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n \"IGNORE_EXCEPTIONS\": True, # mimics memcache behavior.\n # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior\n }\n }\n}\n\n# LOGGING CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s '\n '%(process)d %(thread)d %(message)s'\n },\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n },\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'verbose',\n },\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True\n },\n 'django.security.DisallowedHost': {\n 'level': 'ERROR',\n 'handlers': ['console', 'mail_admins'],\n 'propagate': True\n }\n }\n}\n\n# Custom Admin URL, use {% url 'admin:index' %}\nADMIN_URL = env('DJANGO_ADMIN_URL')"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_task_hook.py from wangli1426/heron (path: heron/examples/src/python/misc/test_task_hook.py)."}, {"role": "assistant", "content": "# heron/examples/src/python/misc/test_task_hook.py (from wangli1426/heron, license: apache-2.0)\n\n# Copyright 2016 Twitter. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n'''module for example task hook'''\nfrom collections import Counter\n\nfrom heron.common.src.python.utils.log import Log\nfrom heron.common.src.python.utils.topology import ITaskHook\n\n# pylint: disable=unused-argument\nclass TestTaskHook(ITaskHook):\n \"\"\"TestTaskHook logs event information every 10000 times\"\"\"\n CONST = 10000\n\n def prepare(self, conf, context):\n Log.info(\"In prepare of TestTaskHook\")\n self.counter = Counter()\n\n # pylint: disable=no-self-use\n def clean_up(self):\n Log.info(\"In clean_up of TestTaskHook\")\n\n def emit(self, emit_info):\n self.counter['emit'] += 1\n if self.counter['emit'] % self.CONST == 0:\n Log.info(\"TestTaskHook: emitted %s tuples\" % str(self.counter['emit']))\n\n def spout_ack(self, spout_ack_info):\n self.counter['sp_ack'] += 1\n if self.counter['sp_ack'] % self.CONST == 0:\n Log.info(\"TestTaskHook: spout acked %s tuples\" % str(self.counter['sp_ack']))\n\n def spout_fail(self, spout_fail_info):\n self.counter['sp_fail'] += 1\n if self.counter['sp_fail'] % self.CONST == 0:\n Log.info(\"TestTaskHook: spout failed %s tuples\" % str(self.counter['sp_fail']))\n\n def bolt_execute(self, bolt_execute_info):\n self.counter['bl_exec'] += 1\n if self.counter['bl_exec'] % self.CONST == 0:\n Log.info(\"TestTaskHook: bolt executed %s tuples\" % str(self.counter['bl_exec']))\n\n def bolt_ack(self, bolt_ack_info):\n self.counter['bl_ack'] += 1\n if self.counter['bl_ack'] % self.CONST == 0:\n Log.info(\"TestTaskHook: bolt acked %s tuples\" % str(self.counter['bl_ack']))\n\n def bolt_fail(self, bolt_fail_info):\n self.counter['bl_fail'] += 1\n if self.counter['bl_fail'] % self.CONST == 0:\n Log.info(\"TestTaskHook: bolt failed %s tuples\" % str(self.counter['bl_fail']))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements luci.py from teodoc/home-assistant (path: homeassistant/components/device_tracker/luci.py)."}, {"role": "assistant", "content": "# homeassistant/components/device_tracker/luci.py (from teodoc/home-assistant, license: mit)\n\n\"\"\"\nhomeassistant.components.device_tracker.luci\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nDevice tracker platform that supports scanning a OpenWRT router for device\npresence.\n\nIt's required that the luci RPC package is installed on the OpenWRT router:\n# opkg install luci-mod-rpc\n\nConfiguration:\n\nTo use the Luci tracker you will need to add something like the following\nto your config/configuration.yaml\n\ndevice_tracker:\n platform: luci\n host: YOUR_ROUTER_IP\n username: YOUR_ADMIN_USERNAME\n password: YOUR_ADMIN_PASSWORD\n\nVariables:\n\nhost\n*Required\nThe IP address of your router, e.g. 192.168.1.1.\n\nusername\n*Required\nThe username of an user with administrative privileges, usually 'admin'.\n\npassword\n*Required\nThe password for your given admin account.\n\"\"\"\nimport logging\nimport json\nfrom datetime import timedelta\nimport re\nimport threading\nimport requests\n\nfrom homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD\nfrom homeassistant.helpers import validate_config\nfrom homeassistant.util import Throttle\nfrom homeassistant.components.device_tracker import DOMAIN\n\n# Return cached results if last scan was less then this time ago\nMIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)\n\n_LOGGER = logging.getLogger(__name__)\n\ndef get_scanner(hass, config):\n \"\"\" Validates config and returns a Luci scanner. \"\"\"\n if not validate_config(config,\n {DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]},\n _LOGGER):\n return None\n\n scanner = LuciDeviceScanner(config[DOMAIN])\n\n return scanner if scanner.success_init else None\n\n# pylint: disable=too-many-instance-attributes\nclass LuciDeviceScanner(object):\n \"\"\" This class queries a wireless router running OpenWrt firmware\n for connected devices. Adapted from Tomato scanner.\n\n # opkg install luci-mod-rpc\n for this to work on the router.\n\n The API is described here:\n http://luci.subsignal.org/trac/wiki/Documentation/JsonRpcHowTo\n\n (Currently, we do only wifi iwscan, and no DHCP lease access.)\n \"\"\"\n\n def __init__(self, config):\n host = config[CONF_HOST]\n username, password = config[CONF_USERNAME], config[CONF_PASSWORD]\n\n self.parse_api_pattern = re.compile(r\"(?P\\w*) = (?P.*);\")\n\n self.lock = threading.Lock()\n\n self.last_results = {}\n\n self.token = _get_token(host, username, password)\n self.host = host\n\n self.mac2name = None\n self.success_init = self.token is not None\n\n def scan_devices(self):\n \"\"\" Scans for new devices and return a\n list containing found device ids. \"\"\"\n\n self._update_info()\n\n return self.last_results\n\n def get_device_name(self, device):\n \"\"\" Returns the name of the given device or None if we don't know. \"\"\"\n\n with self.lock:\n if self.mac2name is None:\n url = 'http://{}/cgi-bin/luci/rpc/uci'.format(self.host)\n result = _req_json_rpc(url, 'get_all', 'dhcp',\n params={'auth': self.token})\n if result:\n hosts = [x for x in result.values()\n if x['.type'] == 'host' and\n 'mac' in x and 'name' in x]\n mac2name_list = [\n (x['mac'].upper(), x['name']) for x in hosts]\n self.mac2name = dict(mac2name_list)\n else:\n # Error, handled in the _req_json_rpc\n return\n return self.mac2name.get(device.upper(), None)\n\n @Throttle(MIN_TIME_BETWEEN_SCANS)\n def _update_info(self):\n \"\"\" Ensures the information from the Luci router is up to date.\n Returns boolean if scanning successful. \"\"\"\n if not self.success_init:\n return False\n\n with self.lock:\n _LOGGER.info(\"Checking ARP\")\n\n url = 'http://{}/cgi-bin/luci/rpc/sys'.format(self.host)\n result = _req_json_rpc(url, 'net.arptable',\n params={'auth': self.token})\n if result:\n self.last_results = []\n for device_entry in result:\n # Check if the Flags for each device contain\n # NUD_REACHABLE and if so, add it to last_results\n if int(device_entry['Flags'], 16) & 0x2:\n self.last_results.append(device_entry['HW address'])\n\n return True\n\n return False\n\ndef _req_json_rpc(url, method, *args, **kwargs):\n \"\"\" Perform one JSON RPC operation. \"\"\"\n data = json.dumps({'method': method, 'params': args})\n try:\n res = requests.post(url, data=data, timeout=5, **kwargs)\n except requests.exceptions.Timeout:\n _LOGGER.exception(\"Connection to the router timed out\")\n return\n if res.status_code == 200:\n try:\n result = res.json()\n except ValueError:\n # If json decoder could not parse the response\n _LOGGER.exception(\"Failed to parse response from luci\")\n return\n try:\n return result['result']\n except KeyError:\n _LOGGER.exception(\"No result in response from luci\")\n return\n elif res.status_code == 401:\n # Authentication error\n _LOGGER.exception(\n \"Failed to authenticate, \"\n \"please check your username and password\")\n return\n else:\n _LOGGER.error(\"Invalid response from luci: %s\", res)\n\ndef _get_token(host, username, password):\n \"\"\" Get authentication token for the given host+username+password \"\"\"\n url = 'http://{}/cgi-bin/luci/rpc/auth'.format(host)\n return _req_json_rpc(url, 'login', username, password)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements meta_oe_sources.py from mrchapp/meta-openembedded (path: meta-oe/lib/oeqa/selftest/cases/meta_oe_sources.py)."}, {"role": "assistant", "content": "# meta-oe/lib/oeqa/selftest/cases/meta_oe_sources.py (from mrchapp/meta-openembedded, license: mit)\n\nimport os\nimport re\nimport glob as g\nimport shutil\nimport tempfile\nfrom oeqa.selftest.case import OESelftestTestCase\nfrom oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars\n\nclass MetaOESourceMirroring(OESelftestTestCase):\n # Can we download everything from the OpenEmbedded Sources Mirror over http only\n def test_oe_source_mirror(self):\n self.write_config(\"\"\"\nBB_ALLOWED_NETWORKS = \" sources.openembedded.org\"\nMIRRORS = \"\"\nDL_DIR = \"${TMPDIR}/test_oe_downloads\"\nPREMIRRORS = \"\\\\\n bzr://.*/.* http://sources.openembedded.org/ \\\\n \\\\\n cvs://.*/.* http://sources.openembedded.org/ \\\\n \\\\\n git://.*/.* http://sources.openembedded.org/ \\\\n \\\\\n gitsm://.*/.* http://sources.openembedded.org/ \\\\n \\\\\n hg://.*/.* http://sources.openembedded.org/ \\\\n \\\\\n osc://.*/.* http://sources.openembedded.org/ \\\\n \\\\\n p4://.*/.* http://sources.openembedded.org/ \\\\n \\\\\n svn://.*/.* http://sources.openembedded.org/ \\\\n \\\\\n ftp://.*/.* http://sources.openembedded.org/ \\\\n \\\\\n http://.*/.* http://sources.openembedded.org/ \\\\n \\\\\n https://.*/.* http://sources.openembedded.org/ \\\\n\"\n \"\"\")\n\n bitbake(\"world --runall fetch\")"}]} {"messages": [{"role": "user", "content": "Write Python code that implements 0001_initial.py from Suite5/DataColibri (path: articles/migrations/0001_initial.py)."}, {"role": "assistant", "content": "# articles/migrations/0001_initial.py (from Suite5/DataColibri, license: mit)\n\n# encoding: utf-8\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n \n # Adding model 'Tag'\n db.create_table('articles_tag', (\n ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('name', self.gf('django.db.models.fields.CharField')(unique=True, max_length=64)),\n ))\n db.send_create_signal('articles', ['Tag'])\n\n # Adding model 'ArticleStatus'\n db.create_table('articles_articlestatus', (\n ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('name', self.gf('django.db.models.fields.CharField')(max_length=50)),\n ('ordering', self.gf('django.db.models.fields.IntegerField')(default=0)),\n ('is_live', self.gf('django.db.models.fields.BooleanField')(default=False)),\n ))\n db.send_create_signal('articles', ['ArticleStatus'])\n\n # Adding model 'Article'\n db.create_table('articles_article', (\n ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('title', self.gf('django.db.models.fields.CharField')(max_length=100)),\n ('slug', self.gf('django.db.models.fields.SlugField')(max_length=50, db_index=True)),\n ('status', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['articles.ArticleStatus'])),\n ('author', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),\n ('keywords', self.gf('django.db.models.fields.TextField')(blank=True)),\n ('description', self.gf('django.db.models.fields.TextField')(blank=True)),\n ('markup', self.gf('django.db.models.fields.CharField')(default='h', max_length=1)),\n ('content', self.gf('django.db.models.fields.TextField')()),\n ('rendered_content', self.gf('django.db.models.fields.TextField')()),\n ('publish_date', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),\n ('expiration_date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),\n ('is_active', self.gf('django.db.models.fields.BooleanField')(default=True)),\n ('login_required', self.gf('django.db.models.fields.BooleanField')(default=False)),\n ('use_addthis_button', self.gf('django.db.models.fields.BooleanField')(default=True)),\n ('addthis_use_author', self.gf('django.db.models.fields.BooleanField')(default=True)),\n ('addthis_username', self.gf('django.db.models.fields.CharField')(default=None, max_length=50, blank=True)),\n ))\n db.send_create_signal('articles', ['Article'])\n\n # Adding M2M table for field sites on 'Article'\n db.create_table('articles_article_sites', (\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),\n ('article', models.ForeignKey(orm['articles.article'], null=False)),\n ('site', models.ForeignKey(orm['sites.site'], null=False))\n ))\n db.create_unique('articles_article_sites', ['article_id', 'site_id'])\n\n # Adding M2M table for field tags on 'Article'\n db.create_table('articles_article_tags', (\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),\n ('article', models.ForeignKey(orm['articles.article'], null=False)),\n ('tag', models.ForeignKey(orm['articles.tag'], null=False))\n ))\n db.create_unique('articles_article_tags', ['article_id', 'tag_id'])\n\n # Adding M2M table for field followup_for on 'Article'\n db.create_table('articles_article_followup_for', (\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),\n ('from_article', models.ForeignKey(orm['articles.article'], null=False)),\n ('to_article', models.ForeignKey(orm['articles.article'], null=False))\n ))\n db.create_unique('articles_article_followup_for', ['from_article_id', 'to_article_id'])\n\n # Adding M2M table for field related_articles on 'Article'\n db.create_table('articles_article_related_articles', (\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),\n ('from_article', models.ForeignKey(orm['articles.article'], null=False)),\n ('to_article', models.ForeignKey(orm['articles.article'], null=False))\n ))\n db.create_unique('articles_article_related_articles', ['from_article_id', 'to_article_id'])\n\n # Adding model 'Attachment'\n db.create_table('articles_attachment', (\n ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('article', self.gf('django.db.models.fields.related.ForeignKey')(related_name='attachments', to=orm['articles.Article'])),\n ('attachment', self.gf('django.db.models.fields.files.FileField')(max_length=100)),\n ('caption', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),\n ))\n db.send_create_signal('articles', ['Attachment'])\n\n def backwards(self, orm):\n \n # Deleting model 'Tag'\n db.delete_table('articles_tag')\n\n # Deleting model 'ArticleStatus'\n db.delete_table('articles_articlestatus')\n\n # Deleting model 'Article'\n db.delete_table('articles_article')\n\n # Removing M2M table for field sites on 'Article'\n db.delete_table('articles_article_sites')\n\n # Removing M2M table for field tags on 'Article'\n db.delete_table('articles_article_tags')\n\n # Removing M2M table for field followup_for on 'Article'\n db.delete_table('articles_article_followup_for')\n\n # Removing M2M table for field related_articles on 'Article'\n db.delete_table('articles_article_related_articles')\n\n # Deleting model 'Attachment'\n db.delete_table('articles_attachment')\n\n models = {\n 'articles.article': {\n 'Meta': {'ordering': \"('-publish_date', 'title')\", 'object_name': 'Article'},\n 'addthis_use_author': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),\n 'addthis_username': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '50', 'blank': 'True'}),\n 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['auth.User']\"}),\n 'content': ('django.db.models.fields.TextField', [], {}),\n 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n 'expiration_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),\n 'followup_for': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': \"'followups'\", 'blank': 'True', 'to': \"orm['articles.Article']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),\n 'keywords': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n 'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'markup': ('django.db.models.fields.CharField', [], {'default': \"'h'\", 'max_length': '1'}),\n 'publish_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),\n 'related_articles': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': \"'related_articles_rel_+'\", 'blank': 'True', 'to': \"orm['articles.Article']\"}),\n 'rendered_content': ('django.db.models.fields.TextField', [], {}),\n 'sites': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['sites.Site']\", 'symmetrical': 'False', 'blank': 'True'}),\n 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),\n 'status': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['articles.ArticleStatus']\"}),\n 'tags': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['articles.Tag']\", 'symmetrical': 'False', 'blank': 'True'}),\n 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'use_addthis_button': ('django.db.models.fields.BooleanField', [], {'default': 'True'})\n },\n 'articles.articlestatus': {\n 'Meta': {'ordering': \"('ordering', 'name')\", 'object_name': 'ArticleStatus'},\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'is_live': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),\n 'ordering': ('django.db.models.fields.IntegerField', [], {'default': '0'})\n },\n 'articles.attachment': {\n 'Meta': {'ordering': \"('-article', 'id')\", 'object_name': 'Attachment'},\n 'article': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'attachments'\", 'to': \"orm['articles.Article']\"}),\n 'attachment': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),\n 'caption': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})\n },\n 'articles.tag': {\n 'Meta': {'ordering': \"('name',)\", 'object_name': 'Tag'},\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'})\n },\n 'auth.group': {\n 'Meta': {'object_name': 'Group'},\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),\n 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['auth.Permission']\", 'symmetrical': 'False', 'blank': 'True'})\n },\n 'auth.permission': {\n 'Meta': {'ordering': \"('content_type__app_label', 'content_type__model', 'codename')\", 'unique_together': \"(('content_type', 'codename'),)\", 'object_name': 'Permission'},\n 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['contenttypes.ContentType']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})\n },\n 'auth.user': {\n 'Meta': {'object_name': 'User'},\n 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),\n 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),\n 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),\n 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['auth.Group']\", 'symmetrical': 'False', 'blank': 'True'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),\n 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),\n 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),\n 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),\n 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['auth.Permission']\", 'symmetrical': 'False', 'blank': 'True'}),\n 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})\n },\n 'contenttypes.contenttype': {\n 'Meta': {'ordering': \"('name',)\", 'unique_together': \"(('app_label', 'model'),)\", 'object_name': 'ContentType', 'db_table': \"'django_content_type'\"},\n 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})\n },\n 'sites.site': {\n 'Meta': {'ordering': \"('domain',)\", 'object_name': 'Site', 'db_table': \"'django_site'\"},\n 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})\n }\n }\n\n complete_apps = ['articles']"}]} {"messages": [{"role": "user", "content": "Write Python code that implements convert_mhd2jpg_png_LUNA16.py from ALISCIFP/tensorflow-resnet-segmentation (path: convert_mhd2jpg_png_LUNA16.py)."}, {"role": "assistant", "content": "# convert_mhd2jpg_png_LUNA16.py (from ALISCIFP/tensorflow-resnet-segmentation, license: mit)\n\n#!/usr/bin/env python\n\n# This script belongs to https://github.com/\n\n# this script convert LUNA 16 mhd file to RGB-jpg file.\n\n__author__ = \"Zengming Shen,Email:szm0219@gmail.com\"\n\nimport os,glob\nimport argparse\n\nimport numpy as np\nimport SimpleITK as sitk\nfrom PIL import Image\nimport cv2\nimport scipy.misc\n\nDATA_DIRECTORY = '/home/zack/Data/LUNA16/'\nOUT_DIRECTORY = \"/home/zack/Data/LUNA16/\"\n\ndef mhd2ndarray(data_file):\n itkimg = sitk.ReadImage(data_file)\n img=sitk.GetArrayFromImage(itkimg)\n img = np.transpose(img,(1,2,0))\n\n return img\n\ndef ndarry2jpg_png(data_file,out_dir,subsetIndex,flist):\n\n data_path,fn = os.path.split(data_file)\n # img_gt_file= data_path+\"output/yes_lesion_no_rescale/seg/\"+fn\n img_gt_file = data_file.replace(\"subset\"+str(subsetIndex),\"output/yes_lesion_no_rescale/subset\"+str(subsetIndex)+\"/seg\")\n\n img = mhd2ndarray(data_file)\n img_gt = mhd2ndarray(img_gt_file)\n\n img_pad=np.lib.pad(img, ((0, 0),(0,0),(1,1)), 'constant', constant_values=(-3024, -3024))\n # img_pos = img_pad-img_pad.min()\n # img_pad = img_pos*(255.0/img_pos.max())\n\n for i in xrange(0,img.shape[2]):\n img3c = img_pad[:,:,i:i+3]\n try:\n scipy.misc.imsave(os.path.join(out_dir+\"JPEGImages/subset\"+str(subsetIndex),fn+\"_\"+str(i)+\".jpg\"), img3c)\n except ValueError:\n print fn\n pass\n # im = Image.fromarray(img3c)\n # im.save(os.path.join(out_dir+\"JPEGImages/subset\"+str(subsetIndex),fn+\"_\"+str(i)+\"_\"+\".jpg\"))\n cv2.imwrite(os.path.join(out_dir+\"PNGImages/subset\"+str(subsetIndex),fn+\"_\"+str(i)+\".png\"),img_gt[:,:,i])\n flist.write(\"/JPEGImages/subset\"+str(subsetIndex)+\"/\"+fn+\"_\"+str(i)+\".jpg \"+\"/PNGImages/subset\"+str(subsetIndex)+\"/\"+fn+\"_\"+str(i)+\".png\\n\")\n\ndef convert(data_dir,out_dir):\n\n ftrain = open(data_dir + \"dataset/train.txt\", 'a')\n\n fval = open(data_dir + \"dataset/val.txt\", 'w')\n\n for i in xrange(3,10):\n print \"converting subset \"+str(i)\n\n os.chdir(data_dir + \"subset\" + str(i))\n if not os.path.exists(data_dir + \"JPEGImages/subset\" + str(i)):\n os.mkdir(data_dir + \"JPEGImages/subset\" + str(i))\n if not os.path.exists(data_dir + \"PNGImages/subset\" + str(i)):\n os.mkdir(data_dir + \"PNGImages/subset\" + str(i))\n for file in glob.glob(\"*.mhd\"):\n if i<8:\n ndarry2jpg_png(os.path.join(data_dir + \"subset\" + str(i),file), out_dir, i,ftrain)\n else:\n ndarry2jpg_png(os.path.join(data_dir + \"subset\" + str(i),file), out_dir, i,fval)\n\n ftrain.close()\n fval.close()\n\n print \"done.\"\n\ndef main():\n\n parser = argparse.ArgumentParser()\n\n parser = argparse.ArgumentParser(description=\"mdh to jpg-png file converter\")\n\n parser.add_argument(\"--data-dir\", type=str, default=DATA_DIRECTORY,\n help=\"Path to the directory containing the ILD dataset.\")\n parser.add_argument(\"--out-dir\", type=str, default=OUT_DIRECTORY,\n help=\"Path to the directory containing the ILD dataset in jpg and png format.\")\n\n args = parser.parse_args()\n convert(args.data_dir,args.out_dir)\n\nif __name__ == '__main__':\n main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements models.py from jualvarez/charlex (path: 03-Bonus/charlexapi/charlas/models.py)."}, {"role": "assistant", "content": "# 03-Bonus/charlexapi/charlas/models.py (from jualvarez/charlex, license: gpl-3.0)\n\nfrom django.db import models\nfrom django.conf import settings\n\nclass Orador(models.Model):\n\n class Meta:\n verbose_name = \"orador\"\n verbose_name_plural = \"oradores\"\n\n nombre = models.CharField(verbose_name='nombre', max_length=100)\n bio = models.TextField(verbose_name='curriculum vitae')\n foto = models.ImageField(verbose_name='foto', upload_to='fotosorador')\n\n def __str__(self):\n return self.nombre\n\nclass Lugar(models.Model):\n\n class Meta:\n verbose_name = \"lugar\"\n verbose_name_plural = \"lugares\"\n\n nombre = models.CharField(verbose_name='nombre del lugar', max_length=100)\n\n def __str__(self):\n return self.nombre\n\nclass Charla(models.Model):\n\n class Meta:\n verbose_name = \"charla\"\n verbose_name_plural = \"charlas\"\n\n titulo = models.CharField(verbose_name='título', max_length=100)\n orador = models.ForeignKey(Orador, verbose_name='orador')\n lugar = models.ForeignKey(Lugar, verbose_name='lugar')\n hora = models.DateTimeField(verbose_name='hora')\n duracion = models.DurationField(verbose_name='duración')\n descripcion = models.TextField(verbose_name='descripción de la charla', null=True)\n\n asistentes = models.ManyToManyField(\n settings.AUTH_USER_MODEL,\n through='UsuarioCharla',\n through_fields=('charla', 'usuario'),\n related_name='charlas'\n )\n\n fotos = models.ManyToManyField(\n settings.AUTH_USER_MODEL,\n through='FotoCharla',\n through_fields=('charla', 'usuario'),\n related_name='fotos_charlas'\n )\n\n def __str__(self):\n return \"%s (%s)\" % (self.titulo, self.orador.nombre)\n\nclass UsuarioCharla(models.Model):\n usuario = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n charla = models.ForeignKey(Charla, on_delete=models.CASCADE)\n rating = models.IntegerField(verbose_name='rating', null=True)\n\n class Meta:\n unique_together = ('usuario', 'charla')\n\n def __str__(self):\n return \"%s va a '%s'\" % (self.usuario.username, self.charla.titulo)\n\nclass FotoCharla(models.Model):\n foto = models.ImageField(upload_to='fotoscharla')\n usuario = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL)\n charla = models.ForeignKey(Charla, on_delete=models.CASCADE)\n\n def __str__(self):\n return \"Sacada por %s en '%s'\" % (self.usuario.username, self.charla.titulo)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements benchmark_sn_blocker.py from anhaidgroup/py_entitymatching (path: benchmarks/benchmark_sn_blocker.py)."}, {"role": "assistant", "content": "# benchmarks/benchmark_sn_blocker.py (from anhaidgroup/py_entitymatching, license: bsd-3-clause)\n\n# Write the benchmarking functions here. \n# See \"Writing benchmarks\" in the asv docs for more information.\n\nimport os\nimport sys\n\nimport py_entitymatching as mg\n\np = mg.get_install_path()\ndatasets_path = os.sep.join([p, 'datasets', 'example_datasets'])\nsnb = mg.SortedNeighborhoodBlocker()\n\nclass TimeBlockTablesAnime:\n def setup(self):\n path_for_A = os.sep.join([datasets_path, 'anime', 'A.csv'])\n path_for_B = os.sep.join([datasets_path, 'anime', 'B.csv'])\n self.l_block_attr = 'Year'\n self.r_block_attr = 'Year'\n self.l_output_attrs = ['Title', 'Year', 'Episodes']\n self.r_output_attrs = ['Title', 'Year', 'Episodes']\n try:\n self.A = mg.read_csv_metadata(path_for_A)\n mg.set_key(self.A, 'ID')\n self.B = mg.read_csv_metadata(path_for_B)\n mg.set_key(self.B, 'ID')\n except AssertionError:\n print(\"Dataset \\'anime\\' not found. Please visit the project\"\n \" website to download the dataset.\")\n raise SystemExit\n\n def time_block_tables(self):\n snb.block_tables(self.A, self.B, self.l_block_attr,\n self.r_block_attr, self.l_output_attrs,\n self.r_output_attrs)\n\n def teardown(self):\n del self.A\n del self.B\n del self.l_block_attr\n del self.r_block_attr\n del self.l_output_attrs\n del self.r_output_attrs\n\nclass TimeBlockTablesBikes:\n def setup(self):\n p = mg.get_install_path()\n path_for_A = os.sep.join([datasets_path, 'bikes', 'A.csv'])\n path_for_B = os.sep.join([datasets_path, 'bikes', 'B.csv'])\n try:\n self.A = mg.read_csv_metadata(path_for_A)\n mg.set_key(self.A, 'id')\n self.B = mg.read_csv_metadata(path_for_B)\n mg.set_key(self.B, 'id')\n except AssertionError:\n print(\"Dataset \\'bikes\\' not found. Please visit the project\"\n \" website to download the dataset.\") \n raise SystemExit\n\n self.l_block_attr = 'city_posted'\n self.r_block_attr = 'city_posted'\n self.l_output_attrs = ['bike_name', 'city_posted', 'km_driven', 'price',\n 'color', 'model_year']\n self.r_output_attrs = ['bike_name', 'city_posted', 'km_driven', 'price',\n 'color', 'model_year']\n\n def time_block_tables(self):\n snb.block_tables(self.A, self.B, self.l_block_attr,\n self.r_block_attr, self.l_output_attrs,\n self.r_output_attrs)\n\n def teardown(self):\n del self.A\n del self.B\n del self.l_block_attr\n del self.r_block_attr\n del self.l_output_attrs\n del self.r_output_attrs\n\nclass TimeBlockTablesBooks:\n def setup(self):\n path_for_A = os.sep.join([datasets_path, 'books', 'A.csv'])\n path_for_B = os.sep.join([datasets_path, 'books', 'B.csv'])\n self.l_block_attr = 'Author'\n self.r_block_attr = 'Author'\n self.l_output_attrs = ['Title', 'Author', 'ISBN13', 'Publisher',\n 'Publication_Date']\n self.r_output_attrs = ['Title', 'Author', 'ISBN13', 'Publisher',\n 'Publication_Date']\n try:\n self.A = mg.read_csv_metadata(path_for_A)\n mg.set_key(self.A, 'ID')\n self.B = mg.read_csv_metadata(path_for_B)\n mg.set_key(self.B, 'ID')\n except AssertionError:\n print(\"Dataset \\'books\\' not found. Please visit the project\"\n \" website to download the dataset.\") \n raise SystemExit\n\n def time_block_tables(self):\n snb.block_tables(self.A, self.B, self.l_block_attr,\n self.r_block_attr, self.l_output_attrs,\n self.r_output_attrs)\n\n def teardown(self):\n del self.A\n del self.B\n del self.l_block_attr\n del self.r_block_attr\n del self.l_output_attrs\n del self.r_output_attrs\n\nclass TimeBlockTablesCitations:\n def setup(self):\n path_for_A = os.sep.join([datasets_path, 'citations', 'A.csv'])\n path_for_B = os.sep.join([datasets_path, 'citations', 'B.csv'])\n self.l_block_attr = 'year'\n self.r_block_attr = 'year'\n self.l_output_attrs = ['title', 'author', 'year', 'ENTRYTYPE']\n self.r_output_attrs = ['title', 'author', 'year', 'ENTRYTYPE']\n try:\n self.A = mg.read_csv_metadata(path_for_A)\n mg.set_key(self.A, 'ID')\n self.B = mg.read_csv_metadata(path_for_B)\n mg.set_key(self.B, 'ID')\n except AssertionError:\n print(\"Dataset \\'citations\\' not found. Please visit the project\"\n \" website to download the dataset.\") \n raise SystemExit\n \n def time_block_tables(self):\n snb.block_tables(self.A, self.B, self.l_block_attr,\n self.r_block_attr, self.l_output_attrs,\n self.r_output_attrs)\n\n def teardown(self):\n del self.A\n del self.B\n del self.l_block_attr\n del self.r_block_attr\n del self.l_output_attrs\n del self.r_output_attrs\n\nclass TimeBlockTablesElectronics:\n def setup(self):\n path_for_A = os.sep.join([datasets_path, 'electronics', 'A.csv'])\n path_for_B = os.sep.join([datasets_path, 'electronics', 'B.csv'])\n self.l_block_attr = 'Brand'\n self.r_block_attr = 'Brand'\n self.l_output_attrs = ['Brand', 'Amazon_Price']\n self.r_output_attrs = ['Brand', 'Price']\n try:\n self.A = mg.read_csv_metadata(path_for_A)\n mg.set_key(self.A, 'ID')\n self.B = mg.read_csv_metadata(path_for_B)\n mg.set_key(self.B, 'ID')\n except AssertionError:\n print(\"Dataset \\'electronics\\' not found. Please visit the project\"\n \" website to download the dataset.\")\n raise SystemExit\n \n\n def time_block_tables(self):\n snb.block_tables(self.A, self.B, self.l_block_attr,\n self.r_block_attr, self.l_output_attrs,\n self.r_output_attrs)\n\n def teardown(self):\n del self.A\n del self.B\n del self.l_block_attr\n del self.r_block_attr\n del self.l_output_attrs\n del self.r_output_attrs\n\nclass TimeBlockTablesRestaurants:\n def setup(self):\n path_for_A = os.sep.join([datasets_path, 'restaurants', 'A.csv'])\n path_for_B = os.sep.join([datasets_path, 'restaurants', 'B.csv'])\n self.l_block_attr = 'PHONENUMBER'\n self.r_block_attr = 'PHONENUMBER'\n self.l_output_attrs = ['NAME', 'PHONENUMBER', 'ADDRESS']\n self.r_output_attrs = ['NAME', 'PHONENUMBER', 'ADDRESS']\n try:\n self.A = mg.read_csv_metadata(path_for_A)\n mg.set_key(self.A, 'ID')\n self.B = mg.read_csv_metadata(path_for_B)\n mg.set_key(self.B, 'ID')\n except AssertionError:\n print(\"Dataset \\'restaurants\\' not found. Please visit the project\"\n \" website to download the dataset.\")\n raise SystemExit\n\n def time_block_tables(self):\n snb.block_tables(self.A, self.B, self.l_block_attr,\n self.r_block_attr, self.l_output_attrs,\n self.r_output_attrs)\n\n def teardown(self):\n del self.A\n del self.B\n del self.l_block_attr\n del self.r_block_attr\n del self.l_output_attrs\n del self.r_output_attrs\n\nclass TimeBlockCandsetAnime:\n def setup(self):\n path_for_A = os.sep.join([datasets_path, 'anime', 'A.csv'])\n path_for_B = os.sep.join([datasets_path, 'anime', 'B.csv'])\n try:\n A = mg.read_csv_metadata(path_for_A)\n mg.set_key(A, 'ID')\n B = mg.read_csv_metadata(path_for_B)\n mg.set_key(B, 'ID')\n self.C = snb.block_tables(A, B, 'Year', 'Year',\n ['Title', 'Year', 'Episodes'],\n ['Title', 'Year', 'Episodes'])\n except AssertionError:\n print(\"Dataset \\'anime\\' not found. Please visit the project\"\n \" website to download the dataset.\")\n raise SystemExit\n\n self.l_block_attr = 'Episodes'\n self.r_block_attr = 'Episodes'\n\n def time_block_candset(self):\n snb.block_candset(self.C, self.l_block_attr, self.r_block_attr)\n\n def teardown(self):\n del self.C\n del self.l_block_attr\n del self.r_block_attr\n\nclass TimeBlockCandsetBikes:\n timeout = 300.0\n\n def setup(self):\n path_for_A = os.sep.join([datasets_path, 'bikes', 'A.csv'])\n path_for_B = os.sep.join([datasets_path, 'bikes', 'B.csv'])\n try:\n A = mg.read_csv_metadata(path_for_A)\n mg.set_key(A, 'id')\n B = mg.read_csv_metadata(path_for_B)\n mg.set_key(B, 'id')\n l_output_attrs = ['bike_name', 'city_posted', 'km_driven', 'price',\n 'color', 'model_year']\n r_output_attrs = ['bike_name', 'city_posted', 'km_driven', 'price',\n 'color', 'model_year']\n self.C = snb.block_tables(A, B, 'city_posted', 'city_posted',\n l_output_attrs, r_output_attrs)\n except AssertionError:\n print(\"Dataset \\'bikes\\' not found. Please visit the project\"\n \" website to download the dataset.\") \n raise SystemExit\n \n self.l_block_attr = 'model_year'\n self.r_block_attr = 'model_year'\n\n def time_block_candset(self):\n snb.block_candset(self.C, self.l_block_attr, self.r_block_attr)\n\n def teardown(self):\n del self.C\n del self.l_block_attr\n del self.r_block_attr\n\nclass TimeBlockCandsetBooks:\n def setup(self):\n path_for_A = os.sep.join([datasets_path, 'books', 'A.csv'])\n path_for_B = os.sep.join([datasets_path, 'books', 'B.csv'])\n try:\n A = mg.read_csv_metadata(path_for_A)\n mg.set_key(A, 'ID')\n B = mg.read_csv_metadata(path_for_B)\n mg.set_key(B, 'ID')\n self.C = snb.block_tables(A, B, 'Author', 'Author',\n ['Title', 'Author', 'ISBN13', 'Publisher'],\n ['Title', 'Author', 'ISBN13', 'Publisher'])\n except AssertionError:\n print(\"Dataset \\'books\\' not found. Please visit the project\"\n \" website to download the dataset.\") \n raise SystemExit\n\n self.l_block_attr = 'ISBN13'\n self.r_block_attr = 'ISBN13'\n\n def time_block_candset(self):\n snb.block_candset(self.C, self.l_block_attr, self.r_block_attr)\n\n def teardown(self):\n del self.C\n del self.l_block_attr\n del self.r_block_attr"}]} {"messages": [{"role": "user", "content": "Write Python code that implements processor_test.py from sencha/chromium-spacewalk (path: third_party/closure_compiler/processor_test.py)."}, {"role": "assistant", "content": "# third_party/closure_compiler/processor_test.py (from sencha/chromium-spacewalk, license: bsd-3-clause)\n\n#!/usr/bin/env python\n# Copyright 2014 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Test resources processing, i.e. and tag handling.\"\"\"\n\nimport unittest\nfrom processor import FileCache, Processor, LineNumber\n\nclass ProcessorTest(unittest.TestCase):\n \"\"\"Test tag processing logic.\"\"\"\n\n def __init__(self, *args, **kwargs):\n unittest.TestCase.__init__(self, *args, **kwargs)\n self.maxDiff = None\n\n def setUp(self):\n FileCache._cache[\"/debug.js\"] = \"\"\"\n// Copyright 2002 Older Chromium Author dudes.\nfunction debug(msg) { if (window.DEBUG) alert(msg); }\n\"\"\".strip()\n\n FileCache._cache[\"/global.js\"] = \"\"\"\n// Copyright 2014 Old Chromium Author dudes.\n\nvar global = 'type checking!';\n\"\"\".strip()\n\n FileCache._cache[\"/checked.js\"] = \"\"\"\n// Copyright 2028 Future Chromium Author dudes.\n/**\n * @fileoverview Coolest app ever.\n * @author Douglas Crockford (douglas@crockford.com)\n */\n\ndebug(global);\n// Here continues checked.js, a swell file.\n\"\"\".strip()\n\n self._processor = Processor(\"/checked.js\")\n\n def testInline(self):\n self.assertMultiLineEqual(\"\"\"\n// Copyright 2028 Future Chromium Author dudes.\n/**\n * @fileoverview Coolest app ever.\n * @author Douglas Crockford (douglas@crockford.com)\n */\n// Copyright 2014 Old Chromium Author dudes.\n// Copyright 2002 Older Chromium Author dudes.\nfunction debug(msg) { if (window.DEBUG) alert(msg); }\nvar global = 'type checking!';\ndebug(global);\n// Here continues checked.js, a swell file.\n\"\"\".strip(), self._processor.contents)\n\n def assertLineNumber(self, abs_line, expected_line):\n actual_line = self._processor.get_file_from_line(abs_line)\n self.assertEqual(expected_line.file, actual_line.file)\n self.assertEqual(expected_line.line_number, actual_line.line_number)\n\n def testGetFileFromLine(self):\n \"\"\"Verify that inlined files retain their original line info.\"\"\"\n self.assertLineNumber(1, LineNumber(\"/checked.js\", 1))\n self.assertLineNumber(5, LineNumber(\"/checked.js\", 5))\n self.assertLineNumber(6, LineNumber(\"/global.js\", 1))\n self.assertLineNumber(7, LineNumber(\"/debug.js\", 1))\n self.assertLineNumber(8, LineNumber(\"/debug.js\", 2))\n self.assertLineNumber(9, LineNumber(\"/global.js\", 3))\n self.assertLineNumber(10, LineNumber(\"/checked.js\", 7))\n self.assertLineNumber(11, LineNumber(\"/checked.js\", 8))\n\n def testIncludedFiles(self):\n \"\"\"Verify that files are tracked correctly as they're inlined.\"\"\"\n self.assertEquals(set([\"/global.js\", \"/debug.js\"]),\n self._processor.included_files)\n\nclass IfStrippingTest(unittest.TestCase):\n \"\"\"Test that the contents of XML blocks are stripped.\"\"\"\n\n def __init__(self, *args, **kwargs):\n unittest.TestCase.__init__(self, *args, **kwargs)\n self.maxDiff = None\n\n def setUp(self):\n FileCache._cache[\"/century.js\"] = \"\"\"\n function getCurrentCentury() {\n\n alert(\"Oh wow!\");\n return \"XX\";\n\n return \"XXI\";\n }\n\"\"\".strip()\n\n self.processor_ = Processor(\"/century.js\")\n\n def testIfStripping(self):\n self.assertMultiLineEqual(\"\"\"\n function getCurrentCentury() {\n\n alert(\"Oh wow!\");\n return \"XX\";\n\n return \"XXI\";\n }\n\"\"\".strip(), self.processor_.contents)\n\nif __name__ == '__main__':\n unittest.main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements interfaces.py from mcfletch/AutobahnPython (path: autobahn/autobahn/websocket/interfaces.py)."}, {"role": "assistant", "content": "# autobahn/autobahn/websocket/interfaces.py (from mcfletch/AutobahnPython, license: apache-2.0)\n\n###############################################################################\n##\n## Copyright (C) 2013-2014 Tavendo GmbH\n##\n## Licensed under the Apache License, Version 2.0 (the \"License\");\n## you may not use this file except in compliance with the License.\n## You may obtain a copy of the License at\n##\n## http://www.apache.org/licenses/LICENSE-2.0\n##\n## Unless required by applicable law or agreed to in writing, software\n## distributed under the License is distributed on an \"AS IS\" BASIS,\n## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n## See the License for the specific language governing permissions and\n## limitations under the License.\n##\n###############################################################################\n\n__all__ = ['IWebSocketChannel',\n 'IWebSocketChannelFrameApi',\n 'IWebSocketChannelStreamingApi']\n\nimport abc\nimport six\n\n@six.add_metaclass(abc.ABCMeta)\nclass IWebSocketChannel(object):\n \"\"\"\n A WebSocket channel is a bidirectional, full-duplex, ordered, reliable message channel\n over a WebSocket connection as specified in RFC6455.\n\n This interface defines a message-based API to WebSocket plus auxiliary hooks\n and methods.\n \"\"\"\n\n @abc.abstractmethod\n def onConnect(self, requestOrResponse):\n \"\"\"\n Callback fired during WebSocket opening handshake when a client connects (with\n request from client) or when server connection established (with response from\n server).\n\n :param requestOrResponse: Connection request or response.\n :type requestOrResponse: Instance of :class:`autobahn.websocket.protocol.ConnectionRequest`\n or :class:`autobahn.websocket.protocol.ConnectionResponse`.\n \"\"\"\n\n @abc.abstractmethod\n def onOpen(self):\n \"\"\"\n Callback fired when the initial WebSocket opening handshake was completed.\n You now can send and receive WebSocket messages.\n \"\"\"\n\n @abc.abstractmethod\n def sendMessage(self, payload, isBinary = False, fragmentSize = None, sync = False, doNotCompress = False):\n \"\"\"\n Send a WebSocket message.\n\n You can send text or binary messages, and optionally specifiy a payload fragment size.\n When the latter is given, the payload will be split up into WebSocket frames each with\n payload length `<= fragmentSize`.\n\n :param payload: The message payload.\n :type payload: bytes\n :param isBinary: `True` iff payload is binary, else the payload must be UTF-8 encoded text.\n :type isBinary: bool\n :param fragmentSize: Fragment message into WebSocket fragments of this size.\n :type fragmentSize: int\n :param sync: Iff `True`, try to force data onto the wire immediately. Note: do NOT use\n this normally unless you know what you are doing. Performance likely will\n suffer significantly. This feature is mainly here for use by Autobahn|Testsuite.\n :type sync: bool\n :param doNotCompress: Iff `True`, never compress this message. This only applies to\n Hybi-Mode and only when WebSocket compression has been negotiated on\n the WebSocket connection. Use when you know the payload \n uncompressible (e.g. encrypted or already compressed).\n :type doNotCompress: bool\n \"\"\"\n\n @abc.abstractmethod\n def onMessage(self, payload, isBinary):\n \"\"\"\n Callback fired when a complete WebSocket message was received.\n\n :param payload: Message payload (UTF-8 encoded text or binary). Can also be empty when\n the WebSocket message contained no payload.\n :type payload: bytes\n :param isBinary: `True` iff payload is binary, else the payload is UTF-8 encoded text.\n :type isBinary: bool\n \"\"\"\n\n @abc.abstractmethod\n def sendClose(self, code = None, reason = None):\n \"\"\"\n Starts a WebSocket closing handshake tearing down the WebSocket connection.\n\n :param code: An optional close status code (`1000` for normal close or `3000-4999` for\n application specific close).\n :type code: int\n :param reason: An optional close reason (a string that when present, a status\n code MUST also be present).\n :type reason: str\n \"\"\"\n\n @abc.abstractmethod\n def onClose(self, wasClean, code, reason):\n \"\"\"\n Callback fired when the WebSocket connection has been closed (WebSocket closing\n handshake has been finished or the connection was closed uncleanly).\n\n :param wasClean: True, iff the WebSocket connection was closed cleanly.\n :type wasClean: bool\n :param code: None or close status code (as sent by the WebSocket peer).\n :type code: int\n :param reason: None or close reason (as sent by the WebSocket peer).\n :type reason: str\n \"\"\"\n\n @abc.abstractmethod\n def sendPreparedMessage(self, preparedMsg):\n \"\"\"\n Send a message that was previously prepared with :func:`autobahn.websocket.protocol.WebSocketFactory.prepareMessage`.\n\n :param prepareMessage: A previsouly prepared message.\n :type prepareMessage: Instance of :class:`autobahn.websocket.protocol.PreparedMessage`.\n \"\"\"\n\n @abc.abstractmethod\n def sendPing(self, payload = None):\n \"\"\"\n Send a WebSocket ping to the peer.\n\n A peer is expected to pong back the payload a soon as \"practical\". When more than\n one ping is outstanding at a peer, the peer may elect to respond only to the last ping.\n\n :param payload: An (optional) arbitrary payload of length `<126` octets.\n :type payload: bytes\n \"\"\"\n\n @abc.abstractmethod\n def onPing(self, payload):\n \"\"\"\n Callback fired when a WebSocket ping was received. A default implementation responds\n by sending a WebSocket pong.\n\n :param payload: Payload of ping (when there was any). Can be arbitrary, up to `125` octets.\n :type payload: bytes\n \"\"\"\n\n @abc.abstractmethod\n def sendPong(self, payload = None):\n \"\"\"\n Send a WebSocket pong to the peer.\n\n A WebSocket pong may be sent unsolicited. This serves as a unidirectional heartbeat.\n A response to an unsolicited pong is \"not expected\".\n\n :param payload: An (optional) arbitrary payload of length < 126 octets.\n :type payload: bytes\n \"\"\"\n\n @abc.abstractmethod\n def onPong(self, payload):\n \"\"\"\n Callback fired when a WebSocket pong was received. A default implementation does nothing.\n\n :param payload: Payload of pong (when there was any). Can be arbitrary, up to 125 octets.\n :type payload: bytes\n \"\"\"\n\nclass IWebSocketChannelFrameApi(IWebSocketChannel):\n \"\"\"\n Frame-based API to a WebSocket channel.\n \"\"\"\n\n @abc.abstractmethod\n def onMessageBegin(self, isBinary):\n \"\"\"\n Callback fired when receiving of a new WebSocket message has begun.\n\n :param isBinary: `True` iff payload is binary, else the payload is UTF-8 encoded text.\n :type isBinary: bool\n \"\"\"\n\n @abc.abstractmethod\n def onMessageFrame(self, payload):\n \"\"\"\n Callback fired when a complete WebSocket message frame for a previously begun\n WebSocket message has been received.\n\n :param payload: Message frame payload (a list of chunks received).\n :type payload: list of bytes\n \"\"\"\n\n @abc.abstractmethod\n def onMessageEnd(self):\n \"\"\"\n Callback fired when a WebSocket message has been completely received (the last\n WebSocket frame for that message has been received).\n \"\"\"\n\n @abc.abstractmethod\n def beginMessage(self, isBinary = False, doNotCompress = False):\n \"\"\"\n Begin sending a new WebSocket message.\n\n :param isBinary: `True` iff payload is binary, else the payload must be UTF-8 encoded text.\n :type isBinary: bool\n :param doNotCompress: Iff `True`, never compress this message. This only applies to\n Hybi-Mode and only when WebSocket compression has been negotiated on\n the WebSocket connection. Use when you know the payload \n uncompressible (e.g. encrypted or already compressed).\n :type doNotCompress: bool\n \"\"\"\n\n @abc.abstractmethod\n def sendMessageFrame(self, payload, sync = False):\n \"\"\"\n When a message has been previously begun, send a complete message frame in one go.\n\n :param payload: The message frame payload. When sending a text message, the payload must\n be UTF-8 encoded already.\n :type payload: bytes\n :param sync: Iff `True`, try to force data onto the wire immediately. Note: do NOT use\n this normally unless you know what you are doing. Performance likely will\n suffer significantly. This feature is mainly here for use by Autobahn|Testsuite.\n :type sync: bool\n \"\"\"\n\n @abc.abstractmethod\n def endMessage(self):\n \"\"\"\n End a message previously begun message. No more frames may be sent (for that message).\n You have to begin a new message before sending again.\n \"\"\"\n\nclass IWebSocketChannelStreamingApi(IWebSocketChannelFrameApi):\n \"\"\"\n Streaming API to a WebSocket channel.\n \"\"\"\n\n @abc.abstractmethod\n def onMessageFrameBegin(self, length):\n \"\"\"\n Callback fired when receiving a new message frame has begun.\n A default implementation will prepare to buffer message frame data.\n\n :param length: Payload length of message frame which is subsequently received.\n :type length: int\n \"\"\"\n\n @abc.abstractmethod\n def onMessageFrameData(self, payload):\n \"\"\"\n Callback fired when receiving data within a previously begun message frame.\n A default implementation will buffer data for frame.\n\n :param payload: Partial payload for message frame.\n :type payload: bytes\n \"\"\"\n\n @abc.abstractmethod\n def onMessageFrameEnd(self):\n \"\"\"\n Callback fired when a previously begun message frame has been completely received.\n A default implementation will flatten the buffered frame data and\n fire `onMessageFrame`.\n \"\"\"\n\n @abc.abstractmethod\n def beginMessageFrame(self, length):\n \"\"\"\n Begin sending a new message frame.\n\n :param length: Length of the frame which is to be started. Must be `>= 0` and `<= 2^63`.\n :type length: int\n \"\"\"\n\n @abc.abstractmethod\n def sendMessageFrameData(self, payload, sync = False):\n \"\"\"\n Send out data when within a message frame (message was begun, frame was begun).\n Note that the frame is automatically ended when enough data has been sent.\n In other words, there is no `endMessageFrame`, since you have begun the frame\n specifying the frame length, which implicitly defined the frame end. This is different\n from messages, which you begin *and* end explicitly , since a message can contain\n an unlimited number of frames.\n\n :param payload: Frame payload to send.\n :type payload: bytes\n :param sync: Iff `True`, try to force data onto the wire immediately. Note: do NOT use\n this normally unless you know what you are doing. Performance likely will\n suffer significantly. This feature is mainly here for use by Autobahn|Testsuite.\n :type sync: bool\n\n :returns: int -- When the currently sent message frame is still incomplete,\n returns octets remaining to be sent. When the frame is complete,\n returns `0`, when `< 0`, the amount of unconsumed data in payload\n argument.\n \"\"\""}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_importer.py from chromium/chromium (path: third_party/blink/tools/blinkpy/w3c/test_importer.py)."}, {"role": "assistant", "content": "# third_party/blink/tools/blinkpy/w3c/test_importer.py (from chromium/chromium, license: bsd-3-clause)\n\n# Copyright 2014 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\"\"\"Fetches a copy of the latest state of a W3C test repository and commits.\n\nIf this script is given the argument --auto-update, it will also:\n 1. Upload a CL.\n 2. Trigger try jobs and wait for them to complete.\n 3. Make any changes that are required for new failing tests.\n 4. Attempt to land the CL.\n\"\"\"\n\nimport argparse\nimport datetime\nimport json\nimport logging\nimport re\n\nfrom blinkpy.common.net.git_cl import GitCL\nfrom blinkpy.common.net.network_transaction import NetworkTimeout\nfrom blinkpy.common.path_finder import PathFinder\nfrom blinkpy.common.system.executive import ScriptError\nfrom blinkpy.common.system.log_utils import configure_logging\nfrom blinkpy.w3c.android_wpt_expectations_updater import AndroidWPTExpectationsUpdater\nfrom blinkpy.w3c.chromium_exportable_commits import exportable_commits_over_last_n_commits\nfrom blinkpy.w3c.common import read_credentials, is_testharness_baseline, is_file_exportable, WPT_GH_URL\nfrom blinkpy.w3c.directory_owners_extractor import DirectoryOwnersExtractor\nfrom blinkpy.w3c.import_notifier import ImportNotifier\nfrom blinkpy.w3c.local_wpt import LocalWPT\nfrom blinkpy.w3c.test_copier import TestCopier\nfrom blinkpy.w3c.wpt_expectations_updater import WPTExpectationsUpdater\nfrom blinkpy.w3c.wpt_github import WPTGitHub\nfrom blinkpy.w3c.wpt_manifest import WPTManifest, BASE_MANIFEST_NAME\nfrom blinkpy.web_tests.port.base import Port\nfrom blinkpy.web_tests.models.test_expectations import TestExpectations\n\n# Settings for how often to check try job results and how long to wait.\nPOLL_DELAY_SECONDS = 2 * 60\nTIMEOUT_SECONDS = 210 * 60\n\n# Sheriff calendar URL, used for getting the ecosystem infra sheriff to cc.\nROTATIONS_URL = 'https://chrome-ops-rotation-proxy.appspot.com/current/grotation:chrome-ecosystem-infra'\nSHERIFF_EMAIL_FALLBACK = 'smcgruer@google.com'\nRUBBER_STAMPER_BOT = 'rubber-stamper@appspot.gserviceaccount.com'\n\n_log = logging.getLogger(__file__)\n\nclass TestImporter(object):\n def __init__(self, host, wpt_github=None, wpt_manifests=None):\n self.host = host\n self.wpt_github = wpt_github\n\n self.executive = host.executive\n self.fs = host.filesystem\n self.finder = PathFinder(self.fs)\n self.chromium_git = self.host.git(self.finder.chromium_base())\n self.dest_path = self.finder.path_from_web_tests('external', 'wpt')\n\n # A common.net.git_cl.GitCL instance.\n self.git_cl = None\n # Another Git instance with local WPT as CWD, which can only be\n # instantiated after the working directory is created.\n self.wpt_git = None\n # The WPT revision we are importing and the one imported last time.\n self.wpt_revision = None\n self.last_wpt_revision = None\n # A set of rebaselined tests and a dictionary of new test expectations\n # mapping failing tests to platforms to\n # wpt_expectations_updater.SimpleTestResult.\n self.rebaselined_tests = set()\n self.new_test_expectations = {}\n # New override expectations for Android targets. A dictionary mapping\n # products to dictionary that maps test names to test expectation lines\n self.new_override_expectations = {}\n self.verbose = False\n\n args = ['--clean-up-affected-tests-only',\n '--clean-up-test-expectations']\n self._expectations_updater = WPTExpectationsUpdater(\n self.host, args, wpt_manifests)\n\n args = [\n '--android-product',\n 'android_weblayer'\n ]\n self._android_expectations_updater = AndroidWPTExpectationsUpdater(\n self.host, args, wpt_manifests)\n\n def main(self, argv=None):\n # TODO(robertma): Test this method! Split it to make it easier to test\n # if necessary.\n\n options = self.parse_args(argv)\n\n self.verbose = options.verbose\n log_level = logging.DEBUG if self.verbose else logging.INFO\n configure_logging(logging_level=log_level, include_time=True)\n\n # Having the full output when executive.run_command fails is useful when\n # investigating a failed import, as all we have are logs.\n self.executive.error_output_limit = None\n\n if options.auto_update and options.auto_upload:\n _log.error(\n '--auto-upload and --auto-update cannot be used together.')\n return 1\n\n if not self.checkout_is_okay():\n return 1\n\n credentials = read_credentials(self.host, options.credentials_json)\n gh_user = credentials.get('GH_USER')\n gh_token = credentials.get('GH_TOKEN')\n if not gh_user or not gh_token:\n _log.warning('You have not set your GitHub credentials. This '\n 'script may fail with a network error when making '\n 'an API request to GitHub.')\n _log.warning('See https://chromium.googlesource.com/chromium/src'\n '/+/main/docs/testing/web_platform_tests.md'\n '#GitHub-credentials for instructions on how to set '\n 'your credentials up.')\n self.wpt_github = self.wpt_github or WPTGitHub(self.host, gh_user,\n gh_token)\n self.git_cl = GitCL(\n self.host, auth_refresh_token_json=options.auth_refresh_token_json)\n\n _log.debug('Noting the current Chromium revision.')\n chromium_revision = self.chromium_git.latest_git_commit()\n\n # Instantiate Git after local_wpt.fetch() to make sure the path exists.\n local_wpt = LocalWPT(self.host, gh_token=gh_token)\n local_wpt.fetch()\n self.wpt_git = self.host.git(local_wpt.path)\n\n if options.revision is not None:\n _log.info('Checking out %s', options.revision)\n self.wpt_git.run(['checkout', options.revision])\n\n _log.debug('Noting the revision we are importing.')\n self.wpt_revision = self.wpt_git.latest_git_commit()\n self.last_wpt_revision = self._get_last_imported_wpt_revision()\n import_commit = 'wpt@%s' % self.wpt_revision\n\n _log.info('Importing %s to Chromium %s', import_commit,\n chromium_revision)\n\n if options.ignore_exportable_commits:\n commit_message = self._commit_message(chromium_revision,\n import_commit)\n else:\n commits = self.apply_exportable_commits_locally(local_wpt)\n if commits is None:\n _log.error('Could not apply some exportable commits cleanly.')\n _log.error('Aborting import to prevent clobbering commits.')\n return 1\n commit_message = self._commit_message(\n chromium_revision,\n import_commit,\n locally_applied_commits=commits)\n\n self._clear_out_dest_path()\n\n _log.info('Copying the tests from the temp repo to the destination.')\n test_copier = TestCopier(self.host, local_wpt.path)\n test_copier.do_import()\n\n # TODO(robertma): Implement `add --all` in Git (it is different from `commit --all`).\n self.chromium_git.run(['add', '--all', self.dest_path])\n\n # Remove expectations for tests that were deleted and rename tests in\n # expectations for renamed tests. This requires the old WPT manifest, so\n # must happen before we regenerate it.\n self._expectations_updater.cleanup_test_expectations_files()\n\n self._generate_manifest()\n\n # TODO(crbug.com/800570 robertma): Re-enable it once we fix the bug.\n # self._delete_orphaned_baselines()\n\n if not self.chromium_git.has_working_directory_changes():\n _log.info('Done: no changes to import.')\n return 0\n\n if self._only_wpt_manifest_changed():\n _log.info('Only manifest was updated; skipping the import.')\n return 0\n\n with self._expectations_updater.prepare_smoke_tests(self.chromium_git):\n self._commit_changes(commit_message)\n _log.info('Changes imported and committed.')\n\n if not options.auto_upload and not options.auto_update:\n return 0\n\n self._upload_cl()\n _log.info('Issue: %s', self.git_cl.run(['issue']).strip())\n\n if not self.update_expectations_for_cl():\n return 1\n\n if not options.auto_update:\n return 0\n\n if not self.run_commit_queue_for_cl():\n return 1\n\n if not self.send_notifications(local_wpt, options.auto_file_bugs,\n options.monorail_auth_json):\n return 1\n\n return 0\n\n def update_expectations_for_cl(self):\n \"\"\"Performs the expectation-updating part of an auto-import job.\n\n This includes triggering try jobs and waiting; then, if applicable,\n writing new baselines and TestExpectation lines, committing, and\n uploading a new patchset.\n\n This assumes that there is CL associated with the current branch.\n\n Returns True if everything is OK to continue, or False on failure.\n \"\"\"\n _log.info('Triggering try jobs for updating expectations.')\n self.git_cl.trigger_try_jobs(self.blink_try_bots())\n cl_status = self.git_cl.wait_for_try_jobs(\n poll_delay_seconds=POLL_DELAY_SECONDS,\n timeout_seconds=TIMEOUT_SECONDS)\n\n if not cl_status:\n _log.error('No initial try job results, aborting.')\n self.git_cl.run(['set-close'])\n return False\n\n if cl_status.status == 'closed':\n _log.error('The CL was closed, aborting.')\n return False\n\n _log.info('All jobs finished.')\n try_results = cl_status.try_job_results\n\n if try_results and self.git_cl.some_failed(try_results):\n self.fetch_new_expectations_and_baselines()\n self.fetch_wpt_override_expectations()\n if self.chromium_git.has_working_directory_changes():\n self._generate_manifest()\n message = 'Update test expectations and baselines.'\n self._commit_changes(message)\n self._upload_patchset(message)\n return True\n\n def run_commit_queue_for_cl(self):\n \"\"\"Triggers CQ and either commits or aborts; returns True on success.\"\"\"\n _log.info('Triggering CQ try jobs.')\n self.git_cl.run(['try'])\n cl_status = self.git_cl.wait_for_try_jobs(\n poll_delay_seconds=POLL_DELAY_SECONDS,\n timeout_seconds=TIMEOUT_SECONDS,\n cq_only=True)\n\n if not cl_status:\n self.git_cl.run(['set-close'])\n _log.error('Timed out waiting for CQ; aborting.')\n return False\n\n if cl_status.status == 'closed':\n _log.error('The CL was closed; aborting.')\n return False\n\n _log.info('All jobs finished.')\n cq_try_results = cl_status.try_job_results\n\n if not cq_try_results:\n _log.error('No CQ try results found in try results')\n self.git_cl.run(['set-close'])\n return False\n\n if not self.git_cl.all_success(cq_try_results):\n _log.error('CQ appears to have failed; aborting.')\n self.git_cl.run(['set-close'])\n return False\n\n _log.info(\n 'CQ appears to have passed; sending to the rubber-stamper bot for '\n 'CR+1 and commit.')\n _log.info(\n 'If the rubber-stamper bot rejects the CL, you either need to '\n 'modify the benign file patterns, or manually CR+1 and land the '\n 'import yourself if it touches code files. See https://chromium.'\n 'googlesource.com/infra/infra/+/refs/heads/main/go/src/infra/'\n 'appengine/rubber-stamper/README.md')\n\n # `--send-mail` is required to take the CL out of WIP mode.\n self.git_cl.run([\n 'upload', '-f', '--send-mail', '--enable-auto-submit',\n '--reviewers', RUBBER_STAMPER_BOT\n ])\n\n if self.git_cl.wait_for_closed_status():\n _log.info('Update completed.')\n return True\n\n _log.error('Cannot submit CL; aborting.')\n try:\n self.git_cl.run(['set-close'])\n except ScriptError as e:\n if e.output and 'Conflict: change is merged' in e.output:\n _log.error('CL is already merged; treating as success.')\n return True\n else:\n raise e\n return False\n\n def blink_try_bots(self):\n \"\"\"Returns the collection of builders used for updating expectations.\"\"\"\n return self.host.builders.filter_builders(is_try=True)\n\n def parse_args(self, argv):\n parser = argparse.ArgumentParser()\n parser.description = __doc__\n parser.add_argument(\n '-v',\n '--verbose',\n action='store_true',\n help='log extra details that may be helpful when debugging')\n parser.add_argument(\n '--ignore-exportable-commits',\n action='store_true',\n help='do not check for exportable commits that would be clobbered')\n parser.add_argument('-r', '--revision', help='target wpt revision')\n parser.add_argument(\n '--auto-upload',\n action='store_true',\n help='upload a CL, update expectations, but do NOT trigger CQ')\n parser.add_argument(\n '--auto-update',\n action='store_true',\n help='upload a CL, update expectations, and trigger CQ')\n parser.add_argument(\n '--auto-file-bugs',\n action='store_true',\n help='file new failures automatically to crbug.com')\n parser.add_argument(\n '--auth-refresh-token-json',\n help='authentication refresh token JSON file used for try jobs, '\n 'generally not necessary on developer machines')\n parser.add_argument(\n '--credentials-json',\n help='A JSON file with GitHub credentials, '\n 'generally not necessary on developer machines')\n parser.add_argument(\n '--monorail-auth-json',\n help='A JSON file containing the private key of a service account '\n 'to access Monorail (crbug.com), only needed when '\n '--auto-file-bugs is used')\n\n return parser.parse_args(argv)\n\n def checkout_is_okay(self):\n if self.chromium_git.has_working_directory_changes():\n _log.warning('Checkout is dirty; aborting.')\n return False\n # TODO(robertma): Add a method in Git to query a range of commits.\n local_commits = self.chromium_git.run(\n ['log', '--oneline', 'origin/main..HEAD'])\n if local_commits:\n _log.warning('Checkout has local commits before import.')\n return True\n\n def apply_exportable_commits_locally(self, local_wpt):\n \"\"\"Applies exportable Chromium changes to the local WPT repo.\n\n The purpose of this is to avoid clobbering changes that were made in\n Chromium but not yet merged upstream. By applying these changes to the\n local copy of web-platform-tests before copying files over, we make\n it so that the resulting change in Chromium doesn't undo the\n previous Chromium change.\n\n Args:\n A LocalWPT instance for our local copy of WPT.\n\n Returns:\n A list of commits applied (could be empty), or None if any\n of the patches could not be applied cleanly.\n \"\"\"\n commits = self.exportable_but_not_exported_commits(local_wpt)\n for commit in commits:\n _log.info('Applying exportable commit locally:')\n _log.info(commit.url())\n _log.info('Subject: %s', commit.subject().strip())\n # Log a note about the corresponding PR.\n # This might not be necessary, and could potentially be removed.\n pull_request = self.wpt_github.pr_for_chromium_commit(commit)\n if pull_request:\n _log.info('PR: %spull/%d', WPT_GH_URL, pull_request.number)\n else:\n _log.warning('No pull request found.')\n error = local_wpt.apply_patch(commit.format_patch())\n if error:\n _log.error('Commit cannot be applied cleanly:')\n _log.error(error)\n return None\n self.wpt_git.commit_locally_with_message(\n 'Applying patch %s' % commit.sha)\n return commits\n\n def exportable_but_not_exported_commits(self, local_wpt):\n \"\"\"Returns a list of commits that would be clobbered by importer.\n\n The list contains all exportable but not exported commits, not filtered\n by whether they can apply cleanly.\n \"\"\"\n # The errors returned by exportable_commits_over_last_n_commits are\n # irrelevant and ignored here, because it tests patches *individually*\n # while the importer tries to reapply these patches *cumulatively*.\n commits, _ = exportable_commits_over_last_n_commits(\n self.host,\n local_wpt,\n self.wpt_github,\n require_clean=False,\n verify_merged_pr=True)\n return commits\n\n def _generate_manifest(self):\n \"\"\"Generates MANIFEST.json for imported tests.\n\n Runs the (newly-updated) manifest command if it's found, and then\n stages the generated MANIFEST.json in the git index, ready to commit.\n \"\"\"\n _log.info('Generating MANIFEST.json')\n WPTManifest.generate_manifest(self.host.port_factory.get(),\n self.dest_path)\n manifest_path = self.fs.join(self.dest_path, 'MANIFEST.json')\n assert self.fs.exists(manifest_path)\n manifest_base_path = self.fs.normpath(\n self.fs.join(self.dest_path, '..', BASE_MANIFEST_NAME))\n self.copyfile(manifest_path, manifest_base_path)\n self.chromium_git.add_list([manifest_base_path])\n\n def _clear_out_dest_path(self):\n \"\"\"Removes all files that are synced with upstream from Chromium WPT.\n\n Instead of relying on TestCopier to overwrite these files, cleaning up\n first ensures if upstream deletes some files, we also delete them.\n \"\"\"\n _log.info('Cleaning out tests from %s.', self.dest_path)\n should_remove = lambda fs, dirname, basename: (\n is_file_exportable(fs.relpath(fs.join(dirname, basename), self.finder.chromium_base())))\n files_to_delete = self.fs.files_under(\n self.dest_path, file_filter=should_remove)\n for subpath in files_to_delete:\n self.remove(self.finder.path_from_web_tests('external', subpath))\n\n def _commit_changes(self, commit_message):\n _log.info('Committing changes.')\n self.chromium_git.commit_locally_with_message(commit_message)\n\n def _only_wpt_manifest_changed(self):\n changed_files = self.chromium_git.changed_files()\n wpt_base_manifest = self.fs.relpath(\n self.fs.join(self.dest_path, '..', BASE_MANIFEST_NAME),\n self.finder.chromium_base())\n return changed_files == [wpt_base_manifest]\n\n def _commit_message(self,\n chromium_commit_sha,\n import_commit_sha,\n locally_applied_commits=None):\n message = 'Import {}\\n\\nUsing wpt-import in Chromium {}.\\n'.format(\n import_commit_sha, chromium_commit_sha)\n if locally_applied_commits:\n message += 'With Chromium commits locally applied on WPT:\\n'\n message += '\\n'.join(\n str(commit) for commit in locally_applied_commits)\n message += '\\nNo-Export: true'\n return message\n\n def _delete_orphaned_baselines(self):\n _log.info('Deleting any orphaned baselines.')\n\n is_baseline_filter = lambda fs, dirname, basename: is_testharness_baseline(basename)\n\n baselines = self.fs.files_under(\n self.dest_path, file_filter=is_baseline_filter)\n\n # Note about possible refactoring:\n # - the manifest path could be factored out to a common location, and\n # - the logic for reading the manifest could be factored out from here\n # and the Port class.\n manifest_path = self.finder.path_from_web_tests(\n 'external', 'wpt', 'MANIFEST.json')\n manifest = WPTManifest(self.fs.read_text_file(manifest_path))\n wpt_urls = manifest.all_urls()\n\n # Currently baselines for tests with query strings are merged,\n # so that the tests foo.html?r=1 and foo.html?r=2 both have the same\n # baseline, foo-expected.txt.\n # TODO(qyearsley): Remove this when this behavior is fixed.\n wpt_urls = [url.split('?')[0] for url in wpt_urls]\n\n wpt_dir = self.finder.path_from_web_tests('external', 'wpt')\n for full_path in baselines:\n rel_path = self.fs.relpath(full_path, wpt_dir)\n if not self._has_corresponding_test(rel_path, wpt_urls):\n self.fs.remove(full_path)\n\n def _has_corresponding_test(self, rel_path, wpt_urls):\n # TODO(qyearsley): Ensure that this works with platform baselines and\n # virtual baselines, and add unit tests.\n base = '/' + rel_path.replace('-expected.txt', '')\n return any(\n (base + ext) in wpt_urls for ext in Port.supported_file_extensions)\n\n def copyfile(self, source, destination):\n _log.debug('cp %s %s', source, destination)\n self.fs.copyfile(source, destination)\n\n def remove(self, dest):\n _log.debug('rm %s', dest)\n self.fs.remove(dest)\n\n def _upload_patchset(self, message):\n self.git_cl.run(['upload', '--bypass-hooks', '-f', '-t', message])\n\n def _upload_cl(self):\n _log.info('Uploading change list.')\n directory_owners = self.get_directory_owners()\n description = self._cl_description(directory_owners)\n sheriff_email = self.sheriff_email()\n\n temp_file, temp_path = self.fs.open_text_tempfile()\n temp_file.write(description)\n temp_file.close()\n\n self.git_cl.run([\n 'upload',\n '--bypass-hooks',\n '-f',\n '--message-file',\n temp_path,\n '--cc',\n sheriff_email,\n ])\n\n self.fs.remove(temp_path)\n\n def get_directory_owners(self):\n \"\"\"Returns a mapping of email addresses to owners of changed tests.\"\"\"\n _log.info('Gathering directory owners emails to CC.')\n changed_files = self.chromium_git.changed_files()\n extractor = DirectoryOwnersExtractor(self.host)\n return extractor.list_owners(changed_files)\n\n def _cl_description(self, directory_owners):\n \"\"\"Returns a CL description string.\n\n Args:\n directory_owners: A dict of tuples of owner names to lists of directories.\n \"\"\"\n # TODO(robertma): Add a method in Git for getting the commit body.\n description = self.chromium_git.run(['log', '-1', '--format=%B'])\n description += (\n 'Note to sheriffs: This CL imports external tests and adds\\n'\n 'expectations for those tests; if this CL is large and causes\\n'\n 'a few new failures, please fix the failures by adding new\\n'\n 'lines to TestExpectations rather than reverting. See:\\n'\n 'https://chromium.googlesource.com'\n '/chromium/src/+/main/docs/testing/web_platform_tests.md\\n\\n')\n\n if directory_owners:\n description += self._format_directory_owners(\n directory_owners) + '\\n\\n'\n\n # Prevent FindIt from auto-reverting import CLs.\n description += 'NOAUTOREVERT=true\\n'\n\n # Move any No-Export tag to the end of the description.\n description = description.replace('No-Export: true', '')\n description = description.replace('\\n\\n\\n\\n', '\\n\\n')\n description += 'No-Export: true\\n'\n\n # Add the wptrunner MVP tryjobs as blocking trybots, to catch any test\n # changes or infrastructure changes from upstream.\n #\n # If this starts blocking the importer unnecessarily, revert\n # https://chromium-review.googlesource.com/c/chromium/src/+/2451504\n description += (\n 'Cq-Include-Trybots: luci.chromium.try:linux-wpt-identity-fyi-rel,'\n 'linux-wpt-input-fyi-rel')\n\n return description\n\n @staticmethod\n def _format_directory_owners(directory_owners):\n message_lines = ['Directory owners for changes in this CL:']\n for owner_tuple, directories in sorted(directory_owners.items()):\n message_lines.append(', '.join(owner_tuple) + ':')\n message_lines.extend(' ' + d for d in directories)\n return '\\n'.join(message_lines)\n\n def sheriff_email(self):\n \"\"\"Returns the sheriff email address to cc.\n\n This tries to fetch the current ecosystem infra sheriff, but falls back\n in case of error.\n \"\"\"\n email = ''\n try:\n email = self._fetch_ecosystem_infra_sheriff_email()\n except (IOError, KeyError, ValueError) as error:\n _log.error('Exception while fetching current sheriff: %s', error)\n return email or SHERIFF_EMAIL_FALLBACK\n\n def _fetch_ecosystem_infra_sheriff_email(self):\n try:\n content = self.host.web.get_binary(ROTATIONS_URL)\n except NetworkTimeout:\n _log.error('Cannot fetch %s', ROTATIONS_URL)\n return ''\n data = json.loads(content)\n if not data.get('emails'):\n _log.error(\n 'No email found for current sheriff. Retrieved content: %s',\n content)\n return ''\n return data['emails'][0]\n\n def fetch_new_expectations_and_baselines(self):\n \"\"\"Modifies expectation lines and baselines based on try job results.\n\n Assuming that there are some try job results available, this\n adds new expectation lines to TestExpectations and downloads new\n baselines based on the try job results.\n\n This is the same as invoking the `wpt-update-expectations` script.\n \"\"\"\n _log.info('Adding test expectations lines to TestExpectations.')\n self.rebaselined_tests, self.new_test_expectations = (\n self._expectations_updater.update_expectations())\n\n def fetch_wpt_override_expectations(self):\n \"\"\"Modifies WPT Override expectations based on try job results.\n\n Assuming that there are some try job results available, this\n adds new expectation lines to WPT Override Expectation files,\n e.g. WebLayerWPTOverrideExpectations\n\n This is the same as invoking the `wpt-update-expectations` script.\n \"\"\"\n _log.info('Adding test expectations lines to Override Expectations.')\n _, self.new_override_expectations = (\n self._android_expectations_updater.update_expectations())\n\n def _get_last_imported_wpt_revision(self):\n \"\"\"Finds the last imported WPT revision.\"\"\"\n # TODO(robertma): Only match commit subjects.\n output = self.chromium_git.most_recent_log_matching(\n '^Import wpt@', self.finder.chromium_base())\n # No line-start anchor (^) below because of the formatting of output.\n result = re.search(r'Import wpt@(\\w+)', output)\n if result:\n return result.group(1)\n else:\n _log.error('Cannot find last WPT import.')\n return None\n\n def send_notifications(self, local_wpt, auto_file_bugs,\n monorail_auth_json):\n issue = self.git_cl.run(['status', '--field=id']).strip()\n patchset = self.git_cl.run(['status', '--field=patch']).strip()\n # Construct the notifier here so that any errors won't affect the import.\n notifier = ImportNotifier(self.host, self.chromium_git, local_wpt)\n notifier.main(\n self.last_wpt_revision,\n self.wpt_revision,\n self.rebaselined_tests,\n self.new_test_expectations,\n self.new_override_expectations,\n issue,\n patchset,\n dry_run=not auto_file_bugs,\n service_account_key_json=monorail_auth_json)\n return True"}]} {"messages": [{"role": "user", "content": "Write Python code that implements models.py from 10clouds/edx-platform (path: cms/djangoapps/course_creators/models.py)."}, {"role": "assistant", "content": "# cms/djangoapps/course_creators/models.py (from 10clouds/edx-platform, license: agpl-3.0)\n\n\"\"\"\nTable for storing information about whether or not Studio users have course creation privileges.\n\"\"\"\nfrom django.db import models\nfrom django.db.models.signals import post_init, post_save\nfrom django.dispatch import receiver, Signal\nfrom django.contrib.auth.models import User\n\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext as _\n\n# A signal that will be sent when users should be added or removed from the creator group\nupdate_creator_state = Signal(providing_args=[\"caller\", \"user\", \"state\"])\n\n# A signal that will be sent when admin should be notified of a pending user request\nsend_admin_notification = Signal(providing_args=[\"user\"])\n\n# A signal that will be sent when user should be notified of change in course creator privileges\nsend_user_notification = Signal(providing_args=[\"user\", \"state\"])\n\nclass CourseCreator(models.Model):\n \"\"\"\n Creates the database table model.\n \"\"\"\n UNREQUESTED = 'unrequested'\n PENDING = 'pending'\n GRANTED = 'granted'\n DENIED = 'denied'\n\n # Second value is the \"human-readable\" version.\n STATES = (\n (UNREQUESTED, _(u'unrequested')),\n (PENDING, _(u'pending')),\n (GRANTED, _(u'granted')),\n (DENIED, _(u'denied')),\n )\n\n user = models.OneToOneField(User, help_text=_(\"Studio user\"))\n state_changed = models.DateTimeField('state last updated', auto_now_add=True,\n help_text=_(\"The date when state was last updated\"))\n state = models.CharField(max_length=24, blank=False, choices=STATES, default=UNREQUESTED,\n help_text=_(\"Current course creator state\"))\n note = models.CharField(max_length=512, blank=True, help_text=_(\"Optional notes about this user (for example, \"\n \"why course creation access was denied)\"))\n\n def __unicode__(self):\n return u\"{0} | {1} [{2}]\".format(self.user, self.state, self.state_changed)\n\n@receiver(post_init, sender=CourseCreator)\ndef post_init_callback(sender, **kwargs):\n \"\"\"\n Extend to store previous state.\n \"\"\"\n instance = kwargs['instance']\n instance.orig_state = instance.state\n\n@receiver(post_save, sender=CourseCreator)\ndef post_save_callback(sender, **kwargs):\n \"\"\"\n Extend to update state_changed time and fire event to update course creator group, if appropriate.\n \"\"\"\n instance = kwargs['instance']\n # We only wish to modify the state_changed time if the state has been modified. We don't wish to\n # modify it for changes to the notes field.\n if instance.state != instance.orig_state:\n granted_state_change = instance.state == CourseCreator.GRANTED or instance.orig_state == CourseCreator.GRANTED\n # If either old or new state is 'granted', we must manipulate the course creator\n # group maintained by authz. That requires staff permissions (stored admin).\n if granted_state_change:\n assert hasattr(instance, 'admin'), 'Must have stored staff user to change course creator group'\n update_creator_state.send(\n sender=sender,\n caller=instance.admin,\n user=instance.user,\n state=instance.state\n )\n\n # If user has been denied access, granted access, or previously granted access has been\n # revoked, send a notification message to the user.\n if instance.state == CourseCreator.DENIED or granted_state_change:\n send_user_notification.send(\n sender=sender,\n user=instance.user,\n state=instance.state\n )\n\n # If the user has gone into the 'pending' state, send a notification to interested admin.\n if instance.state == CourseCreator.PENDING:\n send_admin_notification.send(\n sender=sender,\n user=instance.user\n )\n\n instance.state_changed = timezone.now()\n instance.orig_state = instance.state\n instance.save()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements schema.py from shaistaansari/django (path: django/db/backends/base/schema.py)."}, {"role": "assistant", "content": "# django/db/backends/base/schema.py (from shaistaansari/django, license: bsd-3-clause)\n\nimport hashlib\nimport logging\n\nfrom django.db.backends.utils import truncate_name\nfrom django.db.transaction import atomic\nfrom django.utils import six\nfrom django.utils.encoding import force_bytes\n\nlogger = logging.getLogger('django.db.backends.schema')\n\ndef _related_non_m2m_objects(old_field, new_field):\n # Filters out m2m objects from reverse relations.\n # Returns (old_relation, new_relation) tuples.\n return zip(\n (obj for obj in old_field.model._meta.related_objects if not obj.field.many_to_many),\n (obj for obj in new_field.model._meta.related_objects if not obj.field.many_to_many)\n )\n\nclass BaseDatabaseSchemaEditor(object):\n \"\"\"\n This class (and its subclasses) are responsible for emitting schema-changing\n statements to the databases - model creation/removal/alteration, field\n renaming, index fiddling, and so on.\n\n It is intended to eventually completely replace DatabaseCreation.\n\n This class should be used by creating an instance for each set of schema\n changes (e.g. a migration file), and by first calling start(),\n then the relevant actions, and then commit(). This is necessary to allow\n things like circular foreign key references - FKs will only be created once\n commit() is called.\n \"\"\"\n\n # Overrideable SQL templates\n sql_create_table = \"CREATE TABLE %(table)s (%(definition)s)\"\n sql_rename_table = \"ALTER TABLE %(old_table)s RENAME TO %(new_table)s\"\n sql_retablespace_table = \"ALTER TABLE %(table)s SET TABLESPACE %(new_tablespace)s\"\n sql_delete_table = \"DROP TABLE %(table)s CASCADE\"\n\n sql_create_column = \"ALTER TABLE %(table)s ADD COLUMN %(column)s %(definition)s\"\n sql_alter_column = \"ALTER TABLE %(table)s %(changes)s\"\n sql_alter_column_type = \"ALTER COLUMN %(column)s TYPE %(type)s\"\n sql_alter_column_null = \"ALTER COLUMN %(column)s DROP NOT NULL\"\n sql_alter_column_not_null = \"ALTER COLUMN %(column)s SET NOT NULL\"\n sql_alter_column_default = \"ALTER COLUMN %(column)s SET DEFAULT %(default)s\"\n sql_alter_column_no_default = \"ALTER COLUMN %(column)s DROP DEFAULT\"\n sql_delete_column = \"ALTER TABLE %(table)s DROP COLUMN %(column)s CASCADE\"\n sql_rename_column = \"ALTER TABLE %(table)s RENAME COLUMN %(old_column)s TO %(new_column)s\"\n sql_update_with_default = \"UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL\"\n\n sql_create_check = \"ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s)\"\n sql_delete_check = \"ALTER TABLE %(table)s DROP CONSTRAINT %(name)s\"\n\n sql_create_unique = \"ALTER TABLE %(table)s ADD CONSTRAINT %(name)s UNIQUE (%(columns)s)\"\n sql_delete_unique = \"ALTER TABLE %(table)s DROP CONSTRAINT %(name)s\"\n\n sql_create_fk = (\n \"ALTER TABLE %(table)s ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) \"\n \"REFERENCES %(to_table)s (%(to_column)s) DEFERRABLE INITIALLY DEFERRED\"\n )\n sql_create_inline_fk = None\n sql_delete_fk = \"ALTER TABLE %(table)s DROP CONSTRAINT %(name)s\"\n\n sql_create_index = \"CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s\"\n sql_delete_index = \"DROP INDEX %(name)s\"\n\n sql_create_pk = \"ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)\"\n sql_delete_pk = \"ALTER TABLE %(table)s DROP CONSTRAINT %(name)s\"\n\n def __init__(self, connection, collect_sql=False):\n self.connection = connection\n self.collect_sql = collect_sql\n if self.collect_sql:\n self.collected_sql = []\n\n # State-managing methods\n\n def __enter__(self):\n self.deferred_sql = []\n if self.connection.features.can_rollback_ddl:\n self.atomic = atomic(self.connection.alias)\n self.atomic.__enter__()\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n if exc_type is None:\n for sql in self.deferred_sql:\n self.execute(sql)\n if self.connection.features.can_rollback_ddl:\n self.atomic.__exit__(exc_type, exc_value, traceback)\n\n # Core utility functions\n\n def execute(self, sql, params=[]):\n \"\"\"\n Executes the given SQL statement, with optional parameters.\n \"\"\"\n # Log the command we're running, then run it\n logger.debug(\"%s; (params %r)\" % (sql, params))\n if self.collect_sql:\n ending = \"\" if sql.endswith(\";\") else \";\"\n if params is not None:\n self.collected_sql.append((sql % tuple(map(self.quote_value, params))) + ending)\n else:\n self.collected_sql.append(sql + ending)\n else:\n with self.connection.cursor() as cursor:\n cursor.execute(sql, params)\n\n def quote_name(self, name):\n return self.connection.ops.quote_name(name)\n\n @classmethod\n def _digest(cls, *args):\n \"\"\"\n Generates a 32-bit digest of a set of arguments that can be used to\n shorten identifying names.\n \"\"\"\n h = hashlib.md5()\n for arg in args:\n h.update(force_bytes(arg))\n return h.hexdigest()[:8]\n\n # Field <-> database mapping functions\n\n def column_sql(self, model, field, include_default=False):\n \"\"\"\n Takes a field and returns its column definition.\n The field must already have had set_attributes_from_name called.\n \"\"\"\n # Get the column's type and use that as the basis of the SQL\n db_params = field.db_parameters(connection=self.connection)\n sql = db_params['type']\n params = []\n # Check for fields that aren't actually columns (e.g. M2M)\n if sql is None:\n return None, None\n # Work out nullability\n null = field.null\n # If we were told to include a default value, do so\n include_default = include_default and not self.skip_default(field)\n if include_default:\n default_value = self.effective_default(field)\n if default_value is not None:\n if self.connection.features.requires_literal_defaults:\n # Some databases can't take defaults as a parameter (oracle)\n # If this is the case, the individual schema backend should\n # implement prepare_default\n sql += \" DEFAULT %s\" % self.prepare_default(default_value)\n else:\n sql += \" DEFAULT %s\"\n params += [default_value]\n # Oracle treats the empty string ('') as null, so coerce the null\n # option whenever '' is a possible value.\n if (field.empty_strings_allowed and not field.primary_key and\n self.connection.features.interprets_empty_strings_as_nulls):\n null = True\n if null and not self.connection.features.implied_column_null:\n sql += \" NULL\"\n elif not null:\n sql += \" NOT NULL\"\n # Primary key/unique outputs\n if field.primary_key:\n sql += \" PRIMARY KEY\"\n elif field.unique:\n sql += \" UNIQUE\"\n # Optionally add the tablespace if it's an implicitly indexed column\n tablespace = field.db_tablespace or model._meta.db_tablespace\n if tablespace and self.connection.features.supports_tablespaces and field.unique:\n sql += \" %s\" % self.connection.ops.tablespace_sql(tablespace, inline=True)\n # Return the sql\n return sql, params\n\n def skip_default(self, field):\n \"\"\"\n Some backends don't accept default values for certain columns types\n (i.e. MySQL longtext and longblob).\n \"\"\"\n return False\n\n def prepare_default(self, value):\n \"\"\"\n Only used for backends which have requires_literal_defaults feature\n \"\"\"\n raise NotImplementedError(\n 'subclasses of BaseDatabaseSchemaEditor for backends which have '\n 'requires_literal_defaults must provide a prepare_default() method'\n )\n\n def effective_default(self, field):\n \"\"\"\n Returns a field's effective database default value\n \"\"\"\n if field.has_default():\n default = field.get_default()\n elif not field.null and field.blank and field.empty_strings_allowed:\n if field.get_internal_type() == \"BinaryField\":\n default = six.binary_type()\n else:\n default = six.text_type()\n else:\n default = None\n # If it's a callable, call it\n if six.callable(default):\n default = default()\n # Run it through the field's get_db_prep_save method so we can send it\n # to the database.\n default = field.get_db_prep_save(default, self.connection)\n return default\n\n def quote_value(self, value):\n \"\"\"\n Returns a quoted version of the value so it's safe to use in an SQL\n string. This is not safe against injection from user code; it is\n intended only for use in making SQL scripts or preparing default values\n for particularly tricky backends (defaults are not user-defined, though,\n so this is safe).\n \"\"\"\n raise NotImplementedError()\n\n # Actions\n\n def create_model(self, model):\n \"\"\"\n Takes a model and creates a table for it in the database.\n Will also create any accompanying indexes or unique constraints.\n \"\"\"\n # Create column SQL, add FK deferreds if needed\n column_sqls = []\n params = []\n for field in model._meta.local_fields:\n # SQL\n definition, extra_params = self.column_sql(model, field)\n if definition is None:\n continue\n # Check constraints can go on the column SQL here\n db_params = field.db_parameters(connection=self.connection)\n if db_params['check']:\n definition += \" CHECK (%s)\" % db_params['check']\n # Autoincrement SQL (for backends with inline variant)\n col_type_suffix = field.db_type_suffix(connection=self.connection)\n if col_type_suffix:\n definition += \" %s\" % col_type_suffix\n params.extend(extra_params)\n # FK\n if field.remote_field and field.db_constraint:\n to_table = field.remote_field.model._meta.db_table\n to_column = field.remote_field.model._meta.get_field(field.remote_field.field_name).column\n if self.connection.features.supports_foreign_keys:\n self.deferred_sql.append(self._create_fk_sql(model, field, \"_fk_%(to_table)s_%(to_column)s\"))\n elif self.sql_create_inline_fk:\n definition += \" \" + self.sql_create_inline_fk % {\n \"to_table\": self.quote_name(to_table),\n \"to_column\": self.quote_name(to_column),\n }\n # Add the SQL to our big list\n column_sqls.append(\"%s %s\" % (\n self.quote_name(field.column),\n definition,\n ))\n # Autoincrement SQL (for backends with post table definition variant)\n if field.get_internal_type() == \"AutoField\":\n autoinc_sql = self.connection.ops.autoinc_sql(model._meta.db_table, field.column)\n if autoinc_sql:\n self.deferred_sql.extend(autoinc_sql)\n\n # Add any unique_togethers (always deferred, as some fields might be\n # created afterwards, like geometry fields with some backends)\n for fields in model._meta.unique_together:\n columns = [model._meta.get_field(field).column for field in fields]\n self.deferred_sql.append(self._create_unique_sql(model, columns))\n # Make the table\n sql = self.sql_create_table % {\n \"table\": self.quote_name(model._meta.db_table),\n \"definition\": \", \".join(column_sqls)\n }\n if model._meta.db_tablespace:\n tablespace_sql = self.connection.ops.tablespace_sql(model._meta.db_tablespace)\n if tablespace_sql:\n sql += ' ' + tablespace_sql\n # Prevent using [] as params, in the case a literal '%' is used in the definition\n self.execute(sql, params or None)\n\n # Add any field index and index_together's (deferred as SQLite3 _remake_table needs it)\n self.deferred_sql.extend(self._model_indexes_sql(model))\n\n # Make M2M tables\n for field in model._meta.local_many_to_many:\n if field.remote_field.through._meta.auto_created:\n self.create_model(field.remote_field.through)\n\n def delete_model(self, model):\n \"\"\"\n Deletes a model from the database.\n \"\"\"\n # Handle auto-created intermediary models\n for field in model._meta.local_many_to_many:\n if field.remote_field.through._meta.auto_created:\n self.delete_model(field.remote_field.through)\n\n # Delete the table\n self.execute(self.sql_delete_table % {\n \"table\": self.quote_name(model._meta.db_table),\n })\n\n def alter_unique_together(self, model, old_unique_together, new_unique_together):\n \"\"\"\n Deals with a model changing its unique_together.\n Note: The input unique_togethers must be doubly-nested, not the single-\n nested [\"foo\", \"bar\"] format.\n \"\"\"\n olds = set(tuple(fields) for fields in old_unique_together)\n news = set(tuple(fields) for fields in new_unique_together)\n # Deleted uniques\n for fields in olds.difference(news):\n self._delete_composed_index(model, fields, {'unique': True}, self.sql_delete_unique)\n # Created uniques\n for fields in news.difference(olds):\n columns = [model._meta.get_field(field).column for field in fields]\n self.execute(self._create_unique_sql(model, columns))\n\n def alter_index_together(self, model, old_index_together, new_index_together):\n \"\"\"\n Deals with a model changing its index_together.\n Note: The input index_togethers must be doubly-nested, not the single-\n nested [\"foo\", \"bar\"] format.\n \"\"\"\n olds = set(tuple(fields) for fields in old_index_together)\n news = set(tuple(fields) for fields in new_index_together)\n # Deleted indexes\n for fields in olds.difference(news):\n self._delete_composed_index(model, fields, {'index': True}, self.sql_delete_index)\n # Created indexes\n for field_names in news.difference(olds):\n fields = [model._meta.get_field(field) for field in field_names]\n self.execute(self._create_index_sql(model, fields, suffix=\"_idx\"))\n\n def _delete_composed_index(self, model, fields, constraint_kwargs, sql):\n columns = [model._meta.get_field(field).column for field in fields]\n constraint_names = self._constraint_names(model, columns, **constraint_kwargs)\n if len(constraint_names) != 1:\n raise ValueError(\"Found wrong number (%s) of constraints for %s(%s)\" % (\n len(constraint_names),\n model._meta.db_table,\n \", \".join(columns),\n ))\n self.execute(self._delete_constraint_sql(sql, model, constraint_names[0]))\n\n def alter_db_table(self, model, old_db_table, new_db_table):\n \"\"\"\n Renames the table a model points to.\n \"\"\"\n if old_db_table == new_db_table:\n return\n self.execute(self.sql_rename_table % {\n \"old_table\": self.quote_name(old_db_table),\n \"new_table\": self.quote_name(new_db_table),\n })\n\n def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace):\n \"\"\"\n Moves a model's table between tablespaces\n \"\"\"\n self.execute(self.sql_retablespace_table % {\n \"table\": self.quote_name(model._meta.db_table),\n \"old_tablespace\": self.quote_name(old_db_tablespace),\n \"new_tablespace\": self.quote_name(new_db_tablespace),\n })\n\n def add_field(self, model, field):\n \"\"\"\n Creates a field on a model.\n Usually involves adding a column, but may involve adding a\n table instead (for M2M fields)\n \"\"\"\n # Special-case implicit M2M tables\n if field.many_to_many and field.remote_field.through._meta.auto_created:\n return self.create_model(field.remote_field.through)\n # Get the column's definition\n definition, params = self.column_sql(model, field, include_default=True)\n # It might not actually have a column behind it\n if definition is None:\n return\n # Check constraints can go on the column SQL here\n db_params = field.db_parameters(connection=self.connection)\n if db_params['check']:\n definition += \" CHECK (%s)\" % db_params['check']\n # Build the SQL and run it\n sql = self.sql_create_column % {\n \"table\": self.quote_name(model._meta.db_table),\n \"column\": self.quote_name(field.column),\n \"definition\": definition,\n }\n self.execute(sql, params)\n # Drop the default if we need to\n # (Django usually does not use in-database defaults)\n if not self.skip_default(field) and field.default is not None:\n sql = self.sql_alter_column % {\n \"table\": self.quote_name(model._meta.db_table),\n \"changes\": self.sql_alter_column_no_default % {\n \"column\": self.quote_name(field.column),\n }\n }\n self.execute(sql)\n # Add an index, if required\n if field.db_index and not field.unique:\n self.deferred_sql.append(self._create_index_sql(model, [field]))\n # Add any FK constraints later\n if field.remote_field and self.connection.features.supports_foreign_keys and field.db_constraint:\n self.deferred_sql.append(self._create_fk_sql(model, field, \"_fk_%(to_table)s_%(to_column)s\"))\n # Reset connection if required\n if self.connection.features.connection_persists_old_columns:\n self.connection.close()\n\n def remove_field(self, model, field):\n \"\"\"\n Removes a field from a model. Usually involves deleting a column,\n but for M2Ms may involve deleting a table.\n \"\"\"\n # Special-case implicit M2M tables\n if field.many_to_many and field.remote_field.through._meta.auto_created:\n return self.delete_model(field.remote_field.through)\n # It might not actually have a column behind it\n if field.db_parameters(connection=self.connection)['type'] is None:\n return\n # Drop any FK constraints, MySQL requires explicit deletion\n if field.remote_field:\n fk_names = self._constraint_names(model, [field.column], foreign_key=True)\n for fk_name in fk_names:\n self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name))\n # Delete the column\n sql = self.sql_delete_column % {\n \"table\": self.quote_name(model._meta.db_table),\n \"column\": self.quote_name(field.column),\n }\n self.execute(sql)\n # Reset connection if required\n if self.connection.features.connection_persists_old_columns:\n self.connection.close()\n\n def alter_field(self, model, old_field, new_field, strict=False):\n \"\"\"\n Allows a field's type, uniqueness, nullability, default, column,\n constraints etc. to be modified.\n Requires a copy of the old field as well so we can only perform\n changes that are required.\n If strict is true, raises errors if the old column does not match old_field precisely.\n \"\"\"\n # Ensure this field is even column-based\n old_db_params = old_field.db_parameters(connection=self.connection)\n old_type = old_db_params['type']\n new_db_params = new_field.db_parameters(connection=self.connection)\n new_type = new_db_params['type']\n if ((old_type is None and old_field.remote_field is None) or\n (new_type is None and new_field.remote_field is None)):\n raise ValueError(\n \"Cannot alter field %s into %s - they do not properly define \"\n \"db_type (are you using a badly-written custom field?)\" %\n (old_field, new_field),\n )\n elif old_type is None and new_type is None and (\n old_field.remote_field.through and new_field.remote_field.through and\n old_field.remote_field.through._meta.auto_created and\n new_field.remote_field.through._meta.auto_created):\n return self._alter_many_to_many(model, old_field, new_field, strict)\n elif old_type is None and new_type is None and (\n old_field.remote_field.through and new_field.remote_field.through and\n not old_field.remote_field.through._meta.auto_created and\n not new_field.remote_field.through._meta.auto_created):\n # Both sides have through models; this is a no-op.\n return\n elif old_type is None or new_type is None:\n raise ValueError(\n \"Cannot alter field %s into %s - they are not compatible types \"\n \"(you cannot alter to or from M2M fields, or add or remove \"\n \"through= on M2M fields)\" % (old_field, new_field)\n )\n\n self._alter_field(model, old_field, new_field, old_type, new_type,\n old_db_params, new_db_params, strict)\n\n def _alter_field(self, model, old_field, new_field, old_type, new_type,\n old_db_params, new_db_params, strict=False):\n \"\"\"Actually perform a \"physical\" (non-ManyToMany) field update.\"\"\"\n\n # Drop any FK constraints, we'll remake them later\n fks_dropped = set()\n if old_field.remote_field and old_field.db_constraint:\n fk_names = self._constraint_names(model, [old_field.column], foreign_key=True)\n if strict and len(fk_names) != 1:\n raise ValueError(\"Found wrong number (%s) of foreign key constraints for %s.%s\" % (\n len(fk_names),\n model._meta.db_table,\n old_field.column,\n ))\n for fk_name in fk_names:\n fks_dropped.add((old_field.column,))\n self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name))\n # Has unique been removed?\n if old_field.unique and (not new_field.unique or (not old_field.primary_key and new_field.primary_key)):\n # Find the unique constraint for this field\n constraint_names = self._constraint_names(model, [old_field.column], unique=True)\n if strict and len(constraint_names) != 1:\n raise ValueError(\"Found wrong number (%s) of unique constraints for %s.%s\" % (\n len(constraint_names),\n model._meta.db_table,\n old_field.column,\n ))\n for constraint_name in constraint_names:\n self.execute(self._delete_constraint_sql(self.sql_delete_unique, model, constraint_name))\n # Drop incoming FK constraints if we're a primary key and things are going\n # to change.\n if old_field.primary_key and new_field.primary_key and old_type != new_type:\n # '_meta.related_field' also contains M2M reverse fields, these\n # will be filtered out\n for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field):\n rel_fk_names = self._constraint_names(\n new_rel.related_model, [new_rel.field.column], foreign_key=True\n )\n for fk_name in rel_fk_names:\n self.execute(self._delete_constraint_sql(self.sql_delete_fk, new_rel.related_model, fk_name))\n # Removed an index? (no strict check, as multiple indexes are possible)\n if (old_field.db_index and not new_field.db_index and\n not old_field.unique and not\n (not new_field.unique and old_field.unique)):\n # Find the index for this field\n index_names = self._constraint_names(model, [old_field.column], index=True)\n for index_name in index_names:\n self.execute(self._delete_constraint_sql(self.sql_delete_index, model, index_name))\n # Change check constraints?\n if old_db_params['check'] != new_db_params['check'] and old_db_params['check']:\n constraint_names = self._constraint_names(model, [old_field.column], check=True)\n if strict and len(constraint_names) != 1:\n raise ValueError(\"Found wrong number (%s) of check constraints for %s.%s\" % (\n len(constraint_names),\n model._meta.db_table,\n old_field.column,\n ))\n for constraint_name in constraint_names:\n self.execute(self._delete_constraint_sql(self.sql_delete_check, model, constraint_name))\n # Have they renamed the column?\n if old_field.column != new_field.column:\n self.execute(self._rename_field_sql(model._meta.db_table, old_field, new_field, new_type))\n # Next, start accumulating actions to do\n actions = []\n null_actions = []\n post_actions = []\n # Type change?\n if old_type != new_type:\n fragment, other_actions = self._alter_column_type_sql(\n model._meta.db_table, old_field, new_field, new_type\n )\n actions.append(fragment)\n post_actions.extend(other_actions)\n # When changing a column NULL constraint to NOT NULL with a given\n # default value, we need to perform 4 steps:\n # 1. Add a default for new incoming writes\n # 2. Update existing NULL rows with new default\n # 3. Replace NULL constraint with NOT NULL\n # 4. Drop the default again.\n # Default change?\n old_default = self.effective_default(old_field)\n new_default = self.effective_default(new_field)\n needs_database_default = (\n old_default != new_default and\n new_default is not None and\n not self.skip_default(new_field)\n )\n if needs_database_default:\n if self.connection.features.requires_literal_defaults:\n # Some databases can't take defaults as a parameter (oracle)\n # If this is the case, the individual schema backend should\n # implement prepare_default\n actions.append((\n self.sql_alter_column_default % {\n \"column\": self.quote_name(new_field.column),\n \"default\": self.prepare_default(new_default),\n },\n [],\n ))\n else:\n actions.append((\n self.sql_alter_column_default % {\n \"column\": self.quote_name(new_field.column),\n \"default\": \"%s\",\n },\n [new_default],\n ))\n # Nullability change?\n if old_field.null != new_field.null:\n if (self.connection.features.interprets_empty_strings_as_nulls and\n new_field.get_internal_type() in (\"CharField\", \"TextField\")):\n # The field is nullable in the database anyway, leave it alone\n pass\n elif new_field.null:\n null_actions.append((\n self.sql_alter_column_null % {\n \"column\": self.quote_name(new_field.column),\n \"type\": new_type,\n },\n [],\n ))\n else:\n null_actions.append((\n self.sql_alter_column_not_null % {\n \"column\": self.quote_name(new_field.column),\n \"type\": new_type,\n },\n [],\n ))\n # Only if we have a default and there is a change from NULL to NOT NULL\n four_way_default_alteration = (\n new_field.has_default() and\n (old_field.null and not new_field.null)\n )\n if actions or null_actions:\n if not four_way_default_alteration:\n # If we don't have to do a 4-way default alteration we can\n # directly run a (NOT) NULL alteration\n actions = actions + null_actions\n # Combine actions together if we can (e.g. postgres)\n if self.connection.features.supports_combined_alters and actions:\n sql, params = tuple(zip(*actions))\n actions = [(\", \".join(sql), sum(params, []))]\n # Apply those actions\n for sql, params in actions:\n self.execute(\n self.sql_alter_column % {\n \"table\": self.quote_name(model._meta.db_table),\n \"changes\": sql,\n },\n params,\n )\n if four_way_default_alteration:\n # Update existing rows with default value\n self.execute(\n self.sql_update_with_default % {\n \"table\": self.quote_name(model._meta.db_table),\n \"column\": self.quote_name(new_field.column),\n \"default\": \"%s\",\n },\n [new_default],\n )\n # Since we didn't run a NOT NULL change before we need to do it\n # now\n for sql, params in null_actions:\n self.execute(\n self.sql_alter_column % {\n \"table\": self.quote_name(model._meta.db_table),\n \"changes\": sql,\n },\n params,\n )\n if post_actions:\n for sql, params in post_actions:\n self.execute(sql, params)\n # Added a unique?\n if (not old_field.unique and new_field.unique) or (\n old_field.primary_key and not new_field.primary_key and new_field.unique\n ):\n self.execute(self._create_unique_sql(model, [new_field.column]))\n # Added an index?\n if (not old_field.db_index and new_field.db_index and\n not new_field.unique and not\n (not old_field.unique and new_field.unique)):\n self.execute(self._create_index_sql(model, [new_field], suffix=\"_uniq\"))\n # Type alteration on primary key? Then we need to alter the column\n # referring to us.\n rels_to_update = []\n if old_field.primary_key and new_field.primary_key and old_type != new_type:\n rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))\n # Changed to become primary key?\n # Note that we don't detect unsetting of a PK, as we assume another field\n # will always come along and replace it.\n if not old_field.primary_key and new_field.primary_key:\n # First, drop the old PK\n constraint_names = self._constraint_names(model, primary_key=True)\n if strict and len(constraint_names) != 1:\n raise ValueError(\"Found wrong number (%s) of PK constraints for %s\" % (\n len(constraint_names),\n model._meta.db_table,\n ))\n for constraint_name in constraint_names:\n self.execute(self._delete_constraint_sql(self.sql_delete_pk, model, constraint_name))\n # Make the new one\n self.execute(\n self.sql_create_pk % {\n \"table\": self.quote_name(model._meta.db_table),\n \"name\": self.quote_name(self._create_index_name(model, [new_field.column], suffix=\"_pk\")),\n \"columns\": self.quote_name(new_field.column),\n }\n )\n # Update all referencing columns\n rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))\n # Handle our type alters on the other end of rels from the PK stuff above\n for old_rel, new_rel in rels_to_update:\n rel_db_params = new_rel.field.db_parameters(connection=self.connection)\n rel_type = rel_db_params['type']\n fragment, other_actions = self._alter_column_type_sql(\n new_rel.related_model._meta.db_table, old_rel.field, new_rel.field, rel_type\n )\n self.execute(\n self.sql_alter_column % {\n \"table\": self.quote_name(new_rel.related_model._meta.db_table),\n \"changes\": fragment[0],\n },\n fragment[1],\n )\n for sql, params in other_actions:\n self.execute(sql, params)\n # Does it have a foreign key?\n if (new_field.remote_field and\n (fks_dropped or not old_field.remote_field or not old_field.db_constraint) and\n new_field.db_constraint):\n self.execute(self._create_fk_sql(model, new_field, \"_fk_%(to_table)s_%(to_column)s\"))\n # Rebuild FKs that pointed to us if we previously had to drop them\n if old_field.primary_key and new_field.primary_key and old_type != new_type:\n for rel in new_field.model._meta.related_objects:\n if not rel.many_to_many:\n self.execute(self._create_fk_sql(rel.related_model, rel.field, \"_fk\"))\n # Does it have check constraints we need to add?\n if old_db_params['check'] != new_db_params['check'] and new_db_params['check']:\n self.execute(\n self.sql_create_check % {\n \"table\": self.quote_name(model._meta.db_table),\n \"name\": self.quote_name(self._create_index_name(model, [new_field.column], suffix=\"_check\")),\n \"column\": self.quote_name(new_field.column),\n \"check\": new_db_params['check'],\n }\n )\n # Drop the default if we need to\n # (Django usually does not use in-database defaults)\n if needs_database_default:\n sql = self.sql_alter_column % {\n \"table\": self.quote_name(model._meta.db_table),\n \"changes\": self.sql_alter_column_no_default % {\n \"column\": self.quote_name(new_field.column),\n }\n }\n self.execute(sql)\n # Reset connection if required\n if self.connection.features.connection_persists_old_columns:\n self.connection.close()\n\n def _alter_column_type_sql(self, table, old_field, new_field, new_type):\n \"\"\"\n Hook to specialize column type alteration for different backends,\n for cases when a creation type is different to an alteration type\n (e.g. SERIAL in PostgreSQL, PostGIS fields).\n\n Should return two things; an SQL fragment of (sql, params) to insert\n into an ALTER TABLE statement, and a list of extra (sql, params) tuples\n to run once the field is altered.\n \"\"\"\n return (\n (\n self.sql_alter_column_type % {\n \"column\": self.quote_name(new_field.column),\n \"type\": new_type,\n },\n [],\n ),\n [],\n )\n\n def _alter_many_to_many(self, model, old_field, new_field, strict):\n \"\"\"\n Alters M2Ms to repoint their to= endpoints.\n \"\"\"\n # Rename the through table\n if old_field.remote_field.through._meta.db_table != new_field.remote_field.through._meta.db_table:\n self.alter_db_table(old_field.remote_field.through, old_field.remote_field.through._meta.db_table,\n new_field.remote_field.through._meta.db_table)\n # Repoint the FK to the other side\n self.alter_field(\n new_field.remote_field.through,\n # We need the field that points to the target model, so we can tell alter_field to change it -\n # this is m2m_reverse_field_name() (as opposed to m2m_field_name, which points to our model)\n old_field.remote_field.through._meta.get_field(old_field.m2m_reverse_field_name()),\n new_field.remote_field.through._meta.get_field(new_field.m2m_reverse_field_name()),\n )\n self.alter_field(\n new_field.remote_field.through,\n # for self-referential models we need to alter field from the other end too\n old_field.remote_field.through._meta.get_field(old_field.m2m_field_name()),\n new_field.remote_field.through._meta.get_field(new_field.m2m_field_name()),\n )\n\n def _create_index_name(self, model, column_names, suffix=\"\"):\n \"\"\"\n Generates a unique name for an index/unique constraint.\n \"\"\"\n # If there is just one column in the index, use a default algorithm from Django\n if len(column_names) == 1 and not suffix:\n return truncate_name(\n '%s_%s' % (model._meta.db_table, self._digest(column_names[0])),\n self.connection.ops.max_name_length()\n )\n # Else generate the name for the index using a different algorithm\n table_name = model._meta.db_table.replace('\"', '').replace('.', '_')\n index_unique_name = '_%s' % self._digest(table_name, *column_names)\n max_length = self.connection.ops.max_name_length() or 200\n # If the index name is too long, truncate it\n index_name = ('%s_%s%s%s' % (\n table_name, column_names[0], index_unique_name, suffix,\n )).replace('\"', '').replace('.', '_')\n if len(index_name) > max_length:\n part = ('_%s%s%s' % (column_names[0], index_unique_name, suffix))\n index_name = '%s%s' % (table_name[:(max_length - len(part))], part)\n # It shouldn't start with an underscore (Oracle hates this)\n if index_name[0] == \"_\":\n index_name = index_name[1:]\n # If it's STILL too long, just hash it down\n if len(index_name) > max_length:\n index_name = hashlib.md5(force_bytes(index_name)).hexdigest()[:max_length]\n # It can't start with a number on Oracle, so prepend D if we need to\n if index_name[0].isdigit():\n index_name = \"D%s\" % index_name[:-1]\n return index_name\n\n def _create_index_sql(self, model, fields, suffix=\"\", sql=None):\n \"\"\"\n Return the SQL statement to create the index for one or several fields.\n `sql` can be specified if the syntax differs from the standard (GIS\n indexes, ...).\n \"\"\"\n if len(fields) == 1 and fields[0].db_tablespace:\n tablespace_sql = self.connection.ops.tablespace_sql(fields[0].db_tablespace)\n elif model._meta.db_tablespace:\n tablespace_sql = self.connection.ops.tablespace_sql(model._meta.db_tablespace)\n else:\n tablespace_sql = \"\"\n if tablespace_sql:\n tablespace_sql = \" \" + tablespace_sql\n\n columns = [field.column for field in fields]\n sql_create_index = sql or self.sql_create_index\n return sql_create_index % {\n \"table\": self.quote_name(model._meta.db_table),\n \"name\": self.quote_name(self._create_index_name(model, columns, suffix=suffix)),\n \"columns\": \", \".join(self.quote_name(column) for column in columns),\n \"extra\": tablespace_sql,\n }\n\n def _model_indexes_sql(self, model):\n \"\"\"\n Return all index SQL statements (field indexes, index_together) for the\n specified model, as a list.\n \"\"\"\n if not model._meta.managed or model._meta.proxy or model._meta.swapped:\n return []\n output = []\n for field in model._meta.local_fields:\n if field.db_index and not field.unique:\n output.append(self._create_index_sql(model, [field], suffix=\"\"))\n\n for field_names in model._meta.index_together:\n fields = [model._meta.get_field(field) for field in field_names]\n output.append(self._create_index_sql(model, fields, suffix=\"_idx\"))\n return output\n\n def _rename_field_sql(self, table, old_field, new_field, new_type):\n return self.sql_rename_column % {\n \"table\": self.quote_name(table),\n \"old_column\": self.quote_name(old_field.column),\n \"new_column\": self.quote_name(new_field.column),\n \"type\": new_type,\n }\n\n def _create_fk_sql(self, model, field, suffix):\n from_table = model._meta.db_table\n from_column = field.column\n to_table = field.target_field.model._meta.db_table\n to_column = field.target_field.column\n suffix = suffix % {\n \"to_table\": to_table,\n \"to_column\": to_column,\n }\n\n return self.sql_create_fk % {\n \"table\": self.quote_name(from_table),\n \"name\": self.quote_name(self._create_index_name(model, [from_column], suffix=suffix)),\n \"column\": self.quote_name(from_column),\n \"to_table\": self.quote_name(to_table),\n \"to_column\": self.quote_name(to_column),\n }\n\n def _create_unique_sql(self, model, columns):\n return self.sql_create_unique % {\n \"table\": self.quote_name(model._meta.db_table),\n \"name\": self.quote_name(self._create_index_name(model, columns, suffix=\"_uniq\")),\n \"columns\": \", \".join(self.quote_name(column) for column in columns),\n }\n\n def _delete_constraint_sql(self, template, model, name):\n return template % {\n \"table\": self.quote_name(model._meta.db_table),\n \"name\": self.quote_name(name),\n }\n\n def _constraint_names(self, model, column_names=None, unique=None,\n primary_key=None, index=None, foreign_key=None,\n check=None):\n \"\"\"\n Returns all constraint names matching the columns and conditions\n \"\"\"\n column_names = list(column_names) if column_names else None\n with self.connection.cursor() as cursor:\n constraints = self.connection.introspection.get_constraints(cursor, model._meta.db_table)\n result = []\n for name, infodict in constraints.items():\n if column_names is None or column_names == infodict['columns']:\n if unique is not None and infodict['unique'] != unique:\n continue\n if primary_key is not None and infodict['primary_key'] != primary_key:\n continue\n if index is not None and infodict['index'] != index:\n continue\n if check is not None and infodict['check'] != check:\n continue\n if foreign_key is not None and not infodict['foreign_key']:\n continue\n result.append(name)\n return result"}]} {"messages": [{"role": "user", "content": "Write Python code that implements __main__.py from Hasimir/pyjs (path: examples/widgets/__main__.py)."}, {"role": "assistant", "content": "# examples/widgets/__main__.py (from Hasimir/pyjs, license: apache-2.0)\n\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nTARGETS = [\n 'Widgets.py',\n]\n\nPACKAGE = {\n 'title': 'Widgets',\n 'desc': 'Widgets example',\n}\n\ndef setup(targets):\n '''Setup example for translation, MUST call util.setup(targets).'''\n util.setup(targets)\n\ndef translate():\n '''Translate example, MUST call util.translate().'''\n util.translate()\n\ndef install(package):\n '''Install and cleanup example module. MUST call util.install(package)'''\n util.install(package)\n\n##---------------------------------------##\n# --------- (-: DO NOT EDIT :-) --------- #\n##---------------------------------------##\n\nimport sys\nimport os\n\nexamples = head = os.path.abspath(os.path.dirname(__file__))\nwhile os.path.split(examples)[1].lower() != 'examples':\n examples = os.path.split(examples)[0]\n if not examples:\n raise ValueError(\"Cannot determine examples directory\")\nsys.path.insert(0, os.path.join(examples))\nfrom _examples import util\nsys.path.pop(0)\n\nutil.init(head)\n\nsetup(TARGETS)\ntranslate()\ninstall(PACKAGE)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements prepare.py from vaporry/dapp-bin (path: serpent_gamble/prepare.py)."}, {"role": "assistant", "content": "# serpent_gamble/prepare.py (from vaporry/dapp-bin, license: mit)\n\n# This is an ultra-minimal \"dapp framework\" that simplifies the deployment\n# process by generating a config.js file that specifies the ABI for all of\n# the contracts that you need and also includes the ability to update\n# addresses. By default, it simply scans through every .se and .sol file in\n# the current directory and adds and ABI object for each one into a JS\n# object stored under window.accounts, with the key of each ABI object being\n# the filename noc including the .se/.sol ending. For example, wallet.sol\n# will create window.accounts.wallet = { abi: ... }\n#\n# You can also use the x=y syntax to set an address. For example, if you\n# call python prepare.py admin=0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae,\n# then in the JS object you will get window.accounts.admin =\n# '0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae'; this persists if you call\n# python prepare.py after without setting the argument again as the script\n# always tries to read the value set from the previous time the config.js\n# file was created.\n#\n# Example use:\n#\n# Step 1: serpent compile currency.se\n# Step 2: in eth/geth/pyeth, send a transaction to create a contract whose\n# code is the output of the previous line\n# Step 3: get the contract address of the contract you created. Suppose that\n# this address is 0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae\n# Step 4: run\n# python prepare.py currency=0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae\n# Step 5: make sure to include config.js as a javascript file in your\n# application.\n\nimport sys\nimport json\nimport serpent\nimport os\nsolidity = None\naccounts = {}\n# Fill in contract ABI declarations\nfor f in os.listdir(os.getcwd()):\n if f[-3:] == \".se\":\n accounts[f[:-3]] = {\"abi\": serpent.mk_full_signature(f)}\n elif f[-4:] == \".sol\":\n if not solidity:\n from ethereum import _solidity\n solidity = _solidity.get_solidity()\n accounts[f[:-4]] = {\"abi\": solidity.mk_full_signature(open(f).read())}\n# Fill in previously known addresses\nif 'config.js' in os.listdir(os.getcwd()):\n data = open('config.js').read()\n code = json.loads(data[data.find('{'):])\n # For contracts (ie. objects that contain an 'abi' parameter), if\n # we detect a .se or .sol file removed then we do not add the\n # associated address from the registry. For regular accounts, we\n # transfer all of them over\n for k, v in code.items():\n if 'address' in v and (k in accounts or 'abi' not in v):\n if k not in accounts:\n accounts[k] = {}\n accounts[k][\"address\"] = v['address']\n# Fill in addresses from sys.argv\nfor arg in sys.argv:\n if '=' in arg:\n k, v = arg.split('=')\n if len(v) == 40:\n v = '0x' + v\n if k not in accounts:\n accounts[k] = {}\n accounts[k][\"address\"] = v\n \nopen('config.js', 'w').write(\"window.accounts = \" + json.dumps(accounts, indent=4))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements acpid.py from csutherl/sos (path: sos/plugins/acpid.py)."}, {"role": "assistant", "content": "# sos/plugins/acpid.py (from csutherl/sos, license: gpl-2.0)\n\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\nfrom sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin\n\nclass Acpid(Plugin):\n \"\"\"ACPI daemon information\"\"\"\n plugin_name = \"acpid\"\n profiles = ('hardware',)\n\nclass RedHatAcpid(Acpid, RedHatPlugin):\n def setup(self):\n self.add_copy_spec([\n \"/var/log/acpid*\",\n \"/etc/acpi/events/power.conf\"])\n\nclass DebianAcpid(Acpid, DebianPlugin, UbuntuPlugin):\n def setup(self):\n self.add_copy_spec([\n \"/etc/acpi/events/powerbtn*\"])\n\n# vim: set et ts=4 sw=4 :"}]} {"messages": [{"role": "user", "content": "Write Python code that implements GetMonitoredTwitterHandle.py from willprice/arduino-sphere-project (path: scripts/example_direction_finder/temboo/Library/Zendesk/MonitoredTwitterHandles/GetMonitoredTwitterHandle.py)."}, {"role": "assistant", "content": "# scripts/example_direction_finder/temboo/Library/Zendesk/MonitoredTwitterHandles/GetMonitoredTwitterHandle.py (from willprice/arduino-sphere-project, license: gpl-2.0)\n\n# -*- coding: utf-8 -*-\n\n###############################################################################\n#\n# GetMonitoredTwitterHandle\n# Retrieves detailed information on a specified monitored Twitter account. \n#\n# Python versions 2.6, 2.7, 3.x\n#\n# Copyright 2014, Temboo Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n# either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n#\n#\n###############################################################################\n\nfrom temboo.core.choreography import Choreography\nfrom temboo.core.choreography import InputSet\nfrom temboo.core.choreography import ResultSet\nfrom temboo.core.choreography import ChoreographyExecution\n\nimport json\n\nclass GetMonitoredTwitterHandle(Choreography):\n\n def __init__(self, temboo_session):\n \"\"\"\n Create a new instance of the GetMonitoredTwitterHandle Choreo. A TembooSession object, containing a valid\n set of Temboo credentials, must be supplied.\n \"\"\"\n super(GetMonitoredTwitterHandle, self).__init__(temboo_session, '/Library/Zendesk/MonitoredTwitterHandles/GetMonitoredTwitterHandle')\n\n def new_input_set(self):\n return GetMonitoredTwitterHandleInputSet()\n\n def _make_result_set(self, result, path):\n return GetMonitoredTwitterHandleResultSet(result, path)\n\n def _make_execution(self, session, exec_id, path):\n return GetMonitoredTwitterHandleChoreographyExecution(session, exec_id, path)\n\nclass GetMonitoredTwitterHandleInputSet(InputSet):\n \"\"\"\n An InputSet with methods appropriate for specifying the inputs to the GetMonitoredTwitterHandle\n Choreo. The InputSet object is used to specify input parameters when executing this Choreo.\n \"\"\"\n def set_Email(self, value):\n \"\"\"\n Set the value of the Email input for this Choreo. ((required, string) The email address you use to login to your Zendesk account.)\n \"\"\"\n super(GetMonitoredTwitterHandleInputSet, self)._set_input('Email', value)\n def set_ID(self, value):\n \"\"\"\n Set the value of the ID input for this Choreo. ((required, string) ID of the monitored Twitter handle.)\n \"\"\"\n super(GetMonitoredTwitterHandleInputSet, self)._set_input('ID', value)\n def set_Password(self, value):\n \"\"\"\n Set the value of the Password input for this Choreo. ((required, password) Your Zendesk password.)\n \"\"\"\n super(GetMonitoredTwitterHandleInputSet, self)._set_input('Password', value)\n def set_Server(self, value):\n \"\"\"\n Set the value of the Server input for this Choreo. ((required, string) Your Zendesk domain and subdomain (e.g., temboocare.zendesk.com).)\n \"\"\"\n super(GetMonitoredTwitterHandleInputSet, self)._set_input('Server', value)\n\nclass GetMonitoredTwitterHandleResultSet(ResultSet):\n \"\"\"\n A ResultSet with methods tailored to the values returned by the GetMonitoredTwitterHandle Choreo.\n The ResultSet object is used to retrieve the results of a Choreo execution.\n \"\"\"\n\n def getJSONFromString(self, str):\n return json.loads(str)\n\n def get_Response(self):\n \"\"\"\n Retrieve the value for the \"Response\" output from this Choreo execution. ((json) The response from Zendesk.)\n \"\"\"\n return self._output.get('Response', None)\n\nclass GetMonitoredTwitterHandleChoreographyExecution(ChoreographyExecution):\n\n def _make_result_set(self, response, path):\n return GetMonitoredTwitterHandleResultSet(response, path)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements main.py from young-geng/leet_code (path: problems/200_number-of-islands/main.py)."}, {"role": "assistant", "content": "# problems/200_number-of-islands/main.py (from young-geng/leet_code, license: mit)\n\n# https://leetcode.com/problems/number-of-islands/\nclass Solution(object):\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n if len(grid) == 0: return 0\n cols,rows = len(grid), len(grid[0])\n def dfs(i, j):\n \"\"\"\n helper function to start filling every cell reachable from (i,j)\n with '0's. A variation of Flood Fill algorithm for connected\n components.\n \"\"\"\n if i >= 0 and j >= 0 and i < cols and j < rows:\n # if not visited, mark it '0' and run dfs\n if grid[i][j] == '1':\n grid[i][j] = '0'\n # vertical move\n dfs(i-1, j)\n dfs(i+1, j)\n # horizontal move\n dfs(i, j-1)\n dfs(i, j+1)\n\n cc_count = 0\n for i in xrange(cols):\n for j in xrange(rows):\n if grid[i][j] == '1':\n dfs(i, j)\n cc_count += 1\n return cc_count\n\n# BFS Solution for practice\n# Runtime: O(cN) => O(N)\nimport Queue\nclass BFSSolution(object):\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n if len(grid) == 0: return 0\n\n cols, rows = len(grid), len(grid[0])\n cc_count = 0\n for i in xrange(cols):\n for j in xrange(rows):\n if grid[i][j] == '1':\n self.bfs(grid, i, j)\n cc_count += 1\n return cc_count\n\n def bfs(self, grid, i, j):\n cols, rows = len(grid), len(grid[0])\n q = Queue.Queue()\n q.put([i,j])\n while not q.empty():\n x, y = q.get()\n # if the point is not visited, a.k.a '1'\n if grid[x][y] == '1':\n grid[x][y] = '0'\n self.pushToQueue(q, cols, rows, x-1, y)\n self.pushToQueue(q, cols, rows, x+1, y)\n self.pushToQueue(q, cols, rows, x, y-1)\n self.pushToQueue(q, cols, rows, x, y+1)\n\n def pushToQueue(self, q, cols, rows, i, j):\n if i >= 0 and i < cols and j >= 0 and j < rows:\n q.put([i,j])"}]} {"messages": [{"role": "user", "content": "Write Python code that implements pysqlitebkup.py from sureshsundriyal/pysqlitebkup (path: pysqlitebkup.py)."}, {"role": "assistant", "content": "# pysqlitebkup.py (from sureshsundriyal/pysqlitebkup, license: cc0-1.0)\n\n#! /usr/bin/env python\n\nimport ctypes\nfrom ctypes.util import find_library\n\n__author__ = 'Suresh Sundriyal'\n__license__ = 'CC0 - No rights reserved.'\n__version__ = '0.0.1'\n__credits__ = [ 'Joongi Kim: https://gist.github.com/achimnol/3021995',\n 'sqlite3.org: http://www.sqlite.org/backup.html' ]\n\nSQLITE_OK = 0\nSQLITE_ERROR = 1\nSQLITE_BUSY = 5\nSQLITE_LOCKED = 6\nSQLITE_DONE = 101\n\nSQLITE_OPEN_READONLY = 1\nSQLITE_OPEN_READWRITE = 2\nSQLITE_OPEN_CREATE = 4\n\nsqlite = ctypes.CDLL(find_library('sqlite3'))\nsqlite.sqlite3_backup_init.restype = ctypes.c_void_p\n\nclass BackupInitError(Exception):\n pass\n\nclass BackupFailedError(Exception):\n pass\n\nclass FileOpenError(Exception):\n pass\n\nclass UninitializedError(Exception):\n pass\n\ndef _openFile(fileAttributes):\n fileName, ptr, mode = fileAttributes\n fileName_p = ctypes.c_char_p(fileName.encode('utf-8'))\n rc = sqlite.sqlite3_open_v2(fileName_p, ctypes.byref(ptr),\n mode, None)\n if (rc != SQLITE_OK or ptr.value is None):\n raise FileOpenError(\"Unable to open file(%s), rc(%s)\" % (\n fileName, rc))\n\nclass dbbackup(object):\n def __init__(self, src, dst):\n self.src = src\n self.dst = dst\n self.p_src_db = ctypes.c_void_p(None)\n self.p_dst_db = ctypes.c_void_p(None)\n self.p_backup = ctypes.c_void_p(None)\n self.finished = False\n self.remaining = None\n self.pagecount = None\n\n def __enter__(self):\n self.backupInit()\n return self\n\n def __exit__(self, type, value, traceback):\n self.backupFinish()\n\n def backupInit(self):\n # We do this for the side-effect of opening both the files and not\n # having boilerplate code and the fact that map is generally faster\n # than a for loop.\n list(map(_openFile,\n [(self.src, self.p_src_db, SQLITE_OPEN_READONLY),\n (self.dst, self.p_dst_db,\n SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE)]))\n\n dbType = 'main'.encode('utf-8')\n self.p_backup = ctypes.c_void_p(sqlite.sqlite3_backup_init(\n self.p_dst_db, dbType,\n self.p_src_db, dbType))\n if self.p_backup.value is None:\n raise BackupInitError(\"Failed to backup_init\")\n\n def backupFinish(self):\n\n if self.p_backup.value is not None:\n sqlite.sqlite3_backup_finish(self.p_backup)\n\n rc = sqlite.sqlite3_errcode(self.p_dst_db)\n\n if self.p_dst_db.value is not None:\n sqlite.sqlite3_close(self.p_dst_db)\n if self.p_src_db.value is not None:\n sqlite.sqlite3_close(self.p_src_db)\n\n if rc != SQLITE_OK:\n raise BackupFailedError(\"Failed to backup db: rc(%s)\" % rc)\n\n def step(self, size=5):\n if self.p_backup.value is None:\n raise UninitializedError(\n \"step called without calling backupInit first\")\n\n rc = sqlite.sqlite3_backup_step(self.p_backup, size)\n self.remaining = sqlite.sqlite3_backup_remaining(self.p_backup)\n self.pagecount = sqlite.sqlite3_backup_pagecount(self.p_backup)\n\n if rc == SQLITE_DONE:\n self.finished = True\n\n if rc in (SQLITE_OK, SQLITE_BUSY, SQLITE_LOCKED):\n # sleep for 250 ms before continuing.\n sqlite.sqlite3_sleep(250)\n\n def backup(self, stepSize=5):\n import os\n\n __unlink = True\n if os.path.exists(self.dst):\n __unlink = False\n try:\n while not self.finished:\n self.step(stepSize)\n except:\n if __unlink:\n try:\n os.unlink(self.dst)\n except OSError as e:\n pass\n raise\n\nif __name__ == '__main__':\n import sys\n import logging\n try:\n with dbbackup(sys.argv[1], sys.argv[2]) as p:\n p.backup(20)\n except:\n logging.exception(\"Failed to backup sqlite db\")"}]} {"messages": [{"role": "user", "content": "Write Python code that implements helpers.py from tangfeng1/flask (path: flask/helpers.py)."}, {"role": "assistant", "content": "# flask/helpers.py (from tangfeng1/flask, license: bsd-3-clause)\n\n# -*- coding: utf-8 -*-\n\"\"\"\n flask.helpers\n ~~~~~~~~~~~~~\n\n Implements various helpers.\n\n :copyright: (c) 2015 by Armin Ronacher.\n :license: BSD, see LICENSE for more details.\n\"\"\"\n\nimport os\nimport sys\nimport pkgutil\nimport posixpath\nimport mimetypes\nfrom time import time\nfrom zlib import adler32\nfrom threading import RLock\nfrom werkzeug.routing import BuildError\nfrom functools import update_wrapper\n\ntry:\n from werkzeug.urls import url_quote\nexcept ImportError:\n from urlparse import quote as url_quote\n\nfrom werkzeug.datastructures import Headers\nfrom werkzeug.exceptions import NotFound\n\n# this was moved in 0.7\ntry:\n from werkzeug.wsgi import wrap_file\nexcept ImportError:\n from werkzeug.utils import wrap_file\n\nfrom jinja2 import FileSystemLoader\n\nfrom .signals import message_flashed\nfrom .globals import session, _request_ctx_stack, _app_ctx_stack, \\\n current_app, request\nfrom ._compat import string_types, text_type\n\n# sentinel\n_missing = object()\n\n# what separators does this operating system provide that are not a slash?\n# this is used by the send_from_directory function to ensure that nobody is\n# able to access files from outside the filesystem.\n_os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]\n if sep not in (None, '/'))\n\ndef _endpoint_from_view_func(view_func):\n \"\"\"Internal helper that returns the default endpoint for a given\n function. This always is the function name.\n \"\"\"\n assert view_func is not None, 'expected view func if endpoint ' \\\n 'is not provided.'\n return view_func.__name__\n\ndef stream_with_context(generator_or_function):\n \"\"\"Request contexts disappear when the response is started on the server.\n This is done for efficiency reasons and to make it less likely to encounter\n memory leaks with badly written WSGI middlewares. The downside is that if\n you are using streamed responses, the generator cannot access request bound\n information any more.\n\n This function however can help you keep the context around for longer::\n\n from flask import stream_with_context, request, Response\n\n @app.route('/stream')\n def streamed_response():\n @stream_with_context\n def generate():\n yield 'Hello '\n yield request.args['name']\n yield '!'\n return Response(generate())\n\n Alternatively it can also be used around a specific generator::\n\n from flask import stream_with_context, request, Response\n\n @app.route('/stream')\n def streamed_response():\n def generate():\n yield 'Hello '\n yield request.args['name']\n yield '!'\n return Response(stream_with_context(generate()))\n\n .. versionadded:: 0.9\n \"\"\"\n try:\n gen = iter(generator_or_function)\n except TypeError:\n def decorator(*args, **kwargs):\n gen = generator_or_function()\n return stream_with_context(gen)\n return update_wrapper(decorator, generator_or_function)\n\n def generator():\n ctx = _request_ctx_stack.top\n if ctx is None:\n raise RuntimeError('Attempted to stream with context but '\n 'there was no context in the first place to keep around.')\n with ctx:\n # Dummy sentinel. Has to be inside the context block or we're\n # not actually keeping the context around.\n yield None\n\n # The try/finally is here so that if someone passes a WSGI level\n # iterator in we're still running the cleanup logic. Generators\n # don't need that because they are closed on their destruction\n # automatically.\n try:\n for item in gen:\n yield item\n finally:\n if hasattr(gen, 'close'):\n gen.close()\n\n # The trick is to start the generator. Then the code execution runs until\n # the first dummy None is yielded at which point the context was already\n # pushed. This item is discarded. Then when the iteration continues the\n # real generator is executed.\n wrapped_g = generator()\n next(wrapped_g)\n return wrapped_g\n\ndef make_response(*args):\n \"\"\"Sometimes it is necessary to set additional headers in a view. Because\n views do not have to return response objects but can return a value that\n is converted into a response object by Flask itself, it becomes tricky to\n add headers to it. This function can be called instead of using a return\n and you will get a response object which you can use to attach headers.\n\n If view looked like this and you want to add a new header::\n\n def index():\n return render_template('index.html', foo=42)\n\n You can now do something like this::\n\n def index():\n response = make_response(render_template('index.html', foo=42))\n response.headers['X-Parachutes'] = 'parachutes are cool'\n return response\n\n This function accepts the very same arguments you can return from a\n view function. This for example creates a response with a 404 error\n code::\n\n response = make_response(render_template('not_found.html'), 404)\n\n The other use case of this function is to force the return value of a\n view function into a response which is helpful with view\n decorators::\n\n response = make_response(view_function())\n response.headers['X-Parachutes'] = 'parachutes are cool'\n\n Internally this function does the following things:\n\n - if no arguments are passed, it creates a new response argument\n - if one argument is passed, :meth:`flask.Flask.make_response`\n is invoked with it.\n - if more than one argument is passed, the arguments are passed\n to the :meth:`flask.Flask.make_response` function as tuple.\n\n .. versionadded:: 0.6\n \"\"\"\n if not args:\n return current_app.response_class()\n if len(args) == 1:\n args = args[0]\n return current_app.make_response(args)\n\ndef url_for(endpoint, **values):\n \"\"\"Generates a URL to the given endpoint with the method provided.\n\n Variable arguments that are unknown to the target endpoint are appended\n to the generated URL as query arguments. If the value of a query argument\n is ``None``, the whole pair is skipped. In case blueprints are active\n you can shortcut references to the same blueprint by prefixing the\n local endpoint with a dot (``.``).\n\n This will reference the index function local to the current blueprint::\n\n url_for('.index')\n\n For more information, head over to the :ref:`Quickstart `.\n\n To integrate applications, :class:`Flask` has a hook to intercept URL build\n errors through :attr:`Flask.url_build_error_handlers`. The `url_for`\n function results in a :exc:`~werkzeug.routing.BuildError` when the current\n app does not have a URL for the given endpoint and values. When it does, the\n :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if\n it is not ``None``, which can return a string to use as the result of\n `url_for` (instead of `url_for`'s default to raise the\n :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.\n An example::\n\n def external_url_handler(error, endpoint, values):\n \"Looks up an external URL when `url_for` cannot build a URL.\"\n # This is an example of hooking the build_error_handler.\n # Here, lookup_url is some utility function you've built\n # which looks up the endpoint in some external URL registry.\n url = lookup_url(endpoint, **values)\n if url is None:\n # External lookup did not have a URL.\n # Re-raise the BuildError, in context of original traceback.\n exc_type, exc_value, tb = sys.exc_info()\n if exc_value is error:\n raise exc_type, exc_value, tb\n else:\n raise error\n # url_for will use this result, instead of raising BuildError.\n return url\n\n app.url_build_error_handlers.append(external_url_handler)\n\n Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and\n `endpoint` and `values` are the arguments passed into `url_for`. Note\n that this is for building URLs outside the current application, and not for\n handling 404 NotFound errors.\n\n .. versionadded:: 0.10\n The `_scheme` parameter was added.\n\n .. versionadded:: 0.9\n The `_anchor` and `_method` parameters were added.\n\n .. versionadded:: 0.9\n Calls :meth:`Flask.handle_build_error` on\n :exc:`~werkzeug.routing.BuildError`.\n\n :param endpoint: the endpoint of the URL (name of the function)\n :param values: the variable arguments of the URL rule\n :param _external: if set to ``True``, an absolute URL is generated. Server\n address can be changed via ``SERVER_NAME`` configuration variable which\n defaults to `localhost`.\n :param _scheme: a string specifying the desired URL scheme. The `_external`\n parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default\n behavior uses the same scheme as the current request, or\n ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration ` if no\n request context is available. As of Werkzeug 0.10, this also can be set\n to an empty string to build protocol-relative URLs.\n :param _anchor: if provided this is added as anchor to the URL.\n :param _method: if provided this explicitly specifies an HTTP method.\n \"\"\"\n appctx = _app_ctx_stack.top\n reqctx = _request_ctx_stack.top\n if appctx is None:\n raise RuntimeError('Attempted to generate a URL without the '\n 'application context being pushed. This has to be '\n 'executed when application context is available.')\n\n # If request specific information is available we have some extra\n # features that support \"relative\" URLs.\n if reqctx is not None:\n url_adapter = reqctx.url_adapter\n blueprint_name = request.blueprint\n if not reqctx.request._is_old_module:\n if endpoint[:1] == '.':\n if blueprint_name is not None:\n endpoint = blueprint_name + endpoint\n else:\n endpoint = endpoint[1:]\n else:\n # TODO: get rid of this deprecated functionality in 1.0\n if '.' not in endpoint:\n if blueprint_name is not None:\n endpoint = blueprint_name + '.' + endpoint\n elif endpoint.startswith('.'):\n endpoint = endpoint[1:]\n external = values.pop('_external', False)\n\n # Otherwise go with the url adapter from the appctx and make\n # the URLs external by default.\n else:\n url_adapter = appctx.url_adapter\n if url_adapter is None:\n raise RuntimeError('Application was not able to create a URL '\n 'adapter for request independent URL generation. '\n 'You might be able to fix this by setting '\n 'the SERVER_NAME config variable.')\n external = values.pop('_external', True)\n\n anchor = values.pop('_anchor', None)\n method = values.pop('_method', None)\n scheme = values.pop('_scheme', None)\n appctx.app.inject_url_defaults(endpoint, values)\n\n if scheme is not None:\n if not external:\n raise ValueError('When specifying _scheme, _external must be True')\n url_adapter.url_scheme = scheme\n\n try:\n rv = url_adapter.build(endpoint, values, method=method,\n force_external=external)\n except BuildError as error:\n # We need to inject the values again so that the app callback can\n # deal with that sort of stuff.\n values['_external'] = external\n values['_anchor'] = anchor\n values['_method'] = method\n return appctx.app.handle_url_build_error(error, endpoint, values)\n\n if anchor is not None:\n rv += '#' + url_quote(anchor)\n return rv\n\ndef get_template_attribute(template_name, attribute):\n \"\"\"Loads a macro (or variable) a template exports. This can be used to\n invoke a macro from within Python code. If you for example have a\n template named :file:`_cider.html` with the following contents:\n\n .. sourcecode:: html+jinja\n\n {% macro hello(name) %}Hello {{ name }}!{% endmacro %}\n\n You can access this from Python code like this::\n\n hello = get_template_attribute('_cider.html', 'hello')\n return hello('World')\n\n .. versionadded:: 0.2\n\n :param template_name: the name of the template\n :param attribute: the name of the variable of macro to access\n \"\"\"\n return getattr(current_app.jinja_env.get_template(template_name).module,\n attribute)\n\ndef flash(message, category='message'):\n \"\"\"Flashes a message to the next request. In order to remove the\n flashed message from the session and to display it to the user,\n the template has to call :func:`get_flashed_messages`.\n\n .. versionchanged:: 0.3\n `category` parameter added.\n\n :param message: the message to be flashed.\n :param category: the category for the message. The following values\n are recommended: ``'message'`` for any kind of message,\n ``'error'`` for errors, ``'info'`` for information\n messages and ``'warning'`` for warnings. However any\n kind of string can be used as category.\n \"\"\"\n # Original implementation:\n #\n # session.setdefault('_flashes', []).append((category, message))\n #\n # This assumed that changes made to mutable structures in the session are\n # are always in sync with the session object, which is not true for session\n # implementations that use external storage for keeping their keys/values.\n flashes = session.get('_flashes', [])\n flashes.append((category, message))\n session['_flashes'] = flashes\n message_flashed.send(current_app._get_current_object(),\n message=message, category=category)\n\ndef get_flashed_messages(with_categories=False, category_filter=[]):\n \"\"\"Pulls all flashed messages from the session and returns them.\n Further calls in the same request to the function will return\n the same messages. By default just the messages are returned,\n but when `with_categories` is set to ``True``, the return value will\n be a list of tuples in the form ``(category, message)`` instead.\n\n Filter the flashed messages to one or more categories by providing those\n categories in `category_filter`. This allows rendering categories in\n separate html blocks. The `with_categories` and `category_filter`\n arguments are distinct:\n\n * `with_categories` controls whether categories are returned with message\n text (``True`` gives a tuple, where ``False`` gives just the message text).\n * `category_filter` filters the messages down to only those matching the\n provided categories.\n\n See :ref:`message-flashing-pattern` for examples.\n\n .. versionchanged:: 0.3\n `with_categories` parameter added.\n\n .. versionchanged:: 0.9\n `category_filter` parameter added.\n\n :param with_categories: set to ``True`` to also receive categories.\n :param category_filter: whitelist of categories to limit return values\n \"\"\"\n flashes = _request_ctx_stack.top.flashes\n if flashes is None:\n _request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \\\n if '_flashes' in session else []\n if category_filter:\n flashes = list(filter(lambda f: f[0] in category_filter, flashes))\n if not with_categories:\n return [x[1] for x in flashes]\n return flashes\n\ndef send_file(filename_or_fp, mimetype=None, as_attachment=False,\n attachment_filename=None, add_etags=True,\n cache_timeout=None, conditional=False):\n \"\"\"Sends the contents of a file to the client. This will use the\n most efficient method available and configured. By default it will\n try to use the WSGI server's file_wrapper support. Alternatively\n you can set the application's :attr:`~Flask.use_x_sendfile` attribute\n to ``True`` to directly emit an ``X-Sendfile`` header. This however\n requires support of the underlying webserver for ``X-Sendfile``.\n\n By default it will try to guess the mimetype for you, but you can\n also explicitly provide one. For extra security you probably want\n to send certain files as attachment (HTML for instance). The mimetype\n guessing requires a `filename` or an `attachment_filename` to be\n provided.\n\n Please never pass filenames to this function from user sources;\n you should use :func:`send_from_directory` instead.\n\n .. versionadded:: 0.2\n\n .. versionadded:: 0.5\n The `add_etags`, `cache_timeout` and `conditional` parameters were\n added. The default behavior is now to attach etags.\n\n .. versionchanged:: 0.7\n mimetype guessing and etag support for file objects was\n deprecated because it was unreliable. Pass a filename if you are\n able to, otherwise attach an etag yourself. This functionality\n will be removed in Flask 1.0\n\n .. versionchanged:: 0.9\n cache_timeout pulls its default from application config, when None.\n\n :param filename_or_fp: the filename of the file to send in `latin-1`.\n This is relative to the :attr:`~Flask.root_path`\n if a relative path is specified.\n Alternatively a file object might be provided in\n which case ``X-Sendfile`` might not work and fall\n back to the traditional method. Make sure that the\n file pointer is positioned at the start of data to\n send before calling :func:`send_file`.\n :param mimetype: the mimetype of the file if provided, otherwise\n auto detection happens.\n :param as_attachment: set to ``True`` if you want to send this file with\n a ``Content-Disposition: attachment`` header.\n :param attachment_filename: the filename for the attachment if it\n differs from the file's filename.\n :param add_etags: set to ``False`` to disable attaching of etags.\n :param conditional: set to ``True`` to enable conditional responses.\n\n :param cache_timeout: the timeout in seconds for the headers. When ``None``\n (default), this value is set by\n :meth:`~Flask.get_send_file_max_age` of\n :data:`~flask.current_app`.\n \"\"\"\n mtime = None\n if isinstance(filename_or_fp, string_types):\n filename = filename_or_fp\n file = None\n else:\n from warnings import warn\n file = filename_or_fp\n filename = getattr(file, 'name', None)\n\n # XXX: this behavior is now deprecated because it was unreliable.\n # removed in Flask 1.0\n if not attachment_filename and not mimetype \\\n and isinstance(filename, string_types):\n warn(DeprecationWarning('The filename support for file objects '\n 'passed to send_file is now deprecated. Pass an '\n 'attach_filename if you want mimetypes to be guessed.'),\n stacklevel=2)\n if add_etags:\n warn(DeprecationWarning('In future flask releases etags will no '\n 'longer be generated for file objects passed to the send_file '\n 'function because this behavior was unreliable. Pass '\n 'filenames instead if possible, otherwise attach an etag '\n 'yourself based on another value'), stacklevel=2)\n\n if filename is not None:\n if not os.path.isabs(filename):\n filename = os.path.join(current_app.root_path, filename)\n if mimetype is None and (filename or attachment_filename):\n mimetype = mimetypes.guess_type(filename or attachment_filename)[0]\n if mimetype is None:\n mimetype = 'application/octet-stream'\n\n headers = Headers()\n if as_attachment:\n if attachment_filename is None:\n if filename is None:\n raise TypeError('filename unavailable, required for '\n 'sending as attachment')\n attachment_filename = os.path.basename(filename)\n headers.add('Content-Disposition', 'attachment',\n filename=attachment_filename)\n\n if current_app.use_x_sendfile and filename:\n if file is not None:\n file.close()\n headers['X-Sendfile'] = filename\n headers['Content-Length'] = os.path.getsize(filename)\n data = None\n else:\n if file is None:\n file = open(filename, 'rb')\n mtime = os.path.getmtime(filename)\n headers['Content-Length'] = os.path.getsize(filename)\n data = wrap_file(request.environ, file)\n\n rv = current_app.response_class(data, mimetype=mimetype, headers=headers,\n direct_passthrough=True)\n\n # if we know the file modification date, we can store it as\n # the time of the last modification.\n if mtime is not None:\n rv.last_modified = int(mtime)\n\n rv.cache_control.public = True\n if cache_timeout is None:\n cache_timeout = current_app.get_send_file_max_age(filename)\n if cache_timeout is not None:\n rv.cache_control.max_age = cache_timeout\n rv.expires = int(time() + cache_timeout)\n\n if add_etags and filename is not None:\n try:\n rv.set_etag('flask-%s-%s-%s' % (\n os.path.getmtime(filename),\n os.path.getsize(filename),\n adler32(\n filename.encode('utf-8') if isinstance(filename, text_type)\n else filename\n ) & 0xffffffff\n ))\n except OSError:\n warn('Access %s failed, maybe it does not exist, so ignore etags in '\n 'headers' % filename, stacklevel=2)\n\n if conditional:\n rv = rv.make_conditional(request)\n # make sure we don't send x-sendfile for servers that\n # ignore the 304 status code for x-sendfile.\n if rv.status_code == 304:\n rv.headers.pop('x-sendfile', None)\n return rv\n\ndef safe_join(directory, filename):\n \"\"\"Safely join `directory` and `filename`.\n\n Example usage::\n\n @app.route('/wiki/')\n def wiki_page(filename):\n filename = safe_join(app.config['WIKI_FOLDER'], filename)\n with open(filename, 'rb') as fd:\n content = fd.read() # Read and process the file content...\n\n :param directory: the base directory.\n :param filename: the untrusted filename relative to that directory.\n :raises: :class:`~werkzeug.exceptions.NotFound` if the resulting path\n would fall out of `directory`.\n \"\"\"\n filename = posixpath.normpath(filename)\n for sep in _os_alt_seps:\n if sep in filename:\n raise NotFound()\n if os.path.isabs(filename) or \\\n filename == '..' or \\\n filename.startswith('../'):\n raise NotFound()\n return os.path.join(directory, filename)\n\ndef send_from_directory(directory, filename, **options):\n \"\"\"Send a file from a given directory with :func:`send_file`. This\n is a secure way to quickly expose static files from an upload folder\n or something similar.\n\n Example usage::\n\n @app.route('/uploads/')\n def download_file(filename):\n return send_from_directory(app.config['UPLOAD_FOLDER'],\n filename, as_attachment=True)\n\n .. admonition:: Sending files and Performance\n\n It is strongly recommended to activate either ``X-Sendfile`` support in\n your webserver or (if no authentication happens) to tell the webserver\n to serve files for the given path on its own without calling into the\n web application for improved performance.\n\n .. versionadded:: 0.5\n\n :param directory: the directory where all the files are stored.\n :param filename: the filename relative to that directory to\n download.\n :param options: optional keyword arguments that are directly\n forwarded to :func:`send_file`.\n \"\"\"\n filename = safe_join(directory, filename)\n if not os.path.isabs(filename):\n filename = os.path.join(current_app.root_path, filename)\n if not os.path.isfile(filename):\n raise NotFound()\n options.setdefault('conditional', True)\n return send_file(filename, **options)\n\ndef get_root_path(import_name):\n \"\"\"Returns the path to a package or cwd if that cannot be found. This\n returns the path of a package or the folder that contains a module.\n\n Not to be confused with the package path returned by :func:`find_package`.\n \"\"\"\n # Module already imported and has a file attribute. Use that first.\n mod = sys.modules.get(import_name)\n if mod is not None and hasattr(mod, '__file__'):\n return os.path.dirname(os.path.abspath(mod.__file__))\n\n # Next attempt: check the loader.\n loader = pkgutil.get_loader(import_name)\n\n # Loader does not exist or we're referring to an unloaded main module\n # or a main module without path (interactive sessions), go with the\n # current working directory.\n if loader is None or import_name == '__main__':\n return os.getcwd()\n\n # For .egg, zipimporter does not have get_filename until Python 2.7.\n # Some other loaders might exhibit the same behavior.\n if hasattr(loader, 'get_filename'):\n filepath = loader.get_filename(import_name)\n else:\n # Fall back to imports.\n __import__(import_name)\n mod = sys.modules[import_name]\n filepath = getattr(mod, '__file__', None)\n\n # If we don't have a filepath it might be because we are a\n # namespace package. In this case we pick the root path from the\n # first module that is contained in our package.\n if filepath is None:\n raise RuntimeError('No root path can be found for the provided '\n 'module \"%s\". This can happen because the '\n 'module came from an import hook that does '\n 'not provide file name information or because '\n 'it\\'s a namespace package. In this case '\n 'the root path needs to be explicitly '\n 'provided.' % import_name)\n\n # filepath is import_name.py for a module, or __init__.py for a package.\n return os.path.dirname(os.path.abspath(filepath))\n\ndef _matching_loader_thinks_module_is_package(loader, mod_name):\n \"\"\"Given the loader that loaded a module and the module this function\n attempts to figure out if the given module is actually a package.\n \"\"\"\n # If the loader can tell us if something is a package, we can\n # directly ask the loader.\n if hasattr(loader, 'is_package'):\n return loader.is_package(mod_name)\n # importlib's namespace loaders do not have this functionality but\n # all the modules it loads are packages, so we can take advantage of\n # this information.\n elif (loader.__class__.__module__ == '_frozen_importlib' and\n loader.__class__.__name__ == 'NamespaceLoader'):\n return True\n # Otherwise we need to fail with an error that explains what went\n # wrong.\n raise AttributeError(\n ('%s.is_package() method is missing but is required by Flask of '\n 'PEP 302 import hooks. If you do not use import hooks and '\n 'you encounter this error please file a bug against Flask.') %\n loader.__class__.__name__)\n\ndef find_package(import_name):\n \"\"\"Finds a package and returns the prefix (or None if the package is\n not installed) as well as the folder that contains the package or\n module as a tuple. The package path returned is the module that would\n have to be added to the pythonpath in order to make it possible to\n import the module. The prefix is the path below which a UNIX like\n folder structure exists (lib, share etc.).\n \"\"\"\n root_mod_name = import_name.split('.')[0]\n loader = pkgutil.get_loader(root_mod_name)\n if loader is None or import_name == '__main__':\n # import name is not found, or interactive/main module\n package_path = os.getcwd()\n else:\n # For .egg, zipimporter does not have get_filename until Python 2.7.\n if hasattr(loader, 'get_filename'):\n filename = loader.get_filename(root_mod_name)\n elif hasattr(loader, 'archive'):\n # zipimporter's loader.archive points to the .egg or .zip\n # archive filename is dropped in call to dirname below.\n filename = loader.archive\n else:\n # At least one loader is missing both get_filename and archive:\n # Google App Engine's HardenedModulesHook\n #\n # Fall back to imports.\n __import__(import_name)\n filename = sys.modules[import_name].__file__\n package_path = os.path.abspath(os.path.dirname(filename))\n\n # In case the root module is a package we need to chop of the\n # rightmost part. This needs to go through a helper function\n # because of python 3.3 namespace packages.\n if _matching_loader_thinks_module_is_package(\n loader, root_mod_name):\n package_path = os.path.dirname(package_path)\n\n site_parent, site_folder = os.path.split(package_path)\n py_prefix = os.path.abspath(sys.prefix)\n if package_path.startswith(py_prefix):\n return py_prefix, package_path\n elif site_folder.lower() == 'site-packages':\n parent, folder = os.path.split(site_parent)\n # Windows like installations\n if folder.lower() == 'lib':\n base_dir = parent\n # UNIX like installations\n elif os.path.basename(parent).lower() == 'lib':\n base_dir = os.path.dirname(parent)\n else:\n base_dir = site_parent\n return base_dir, package_path\n return None, package_path\n\nclass locked_cached_property(object):\n \"\"\"A decorator that converts a function into a lazy property. The\n function wrapped is called the first time to retrieve the result\n and then that calculated result is used the next time you access\n the value. Works like the one in Werkzeug but has a lock for\n thread safety.\n \"\"\"\n\n def __init__(self, func, name=None, doc=None):\n self.__name__ = name or func.__name__\n self.__module__ = func.__module__\n self.__doc__ = doc or func.__doc__\n self.func = func\n self.lock = RLock()\n\n def __get__(self, obj, type=None):\n if obj is None:\n return self\n with self.lock:\n value = obj.__dict__.get(self.__name__, _missing)\n if value is _missing:\n value = self.func(obj)\n obj.__dict__[self.__name__] = value\n return value\n\nclass _PackageBoundObject(object):\n\n def __init__(self, import_name, template_folder=None, root_path=None):\n #: The name of the package or module. Do not change this once\n #: it was set by the constructor.\n self.import_name = import_name\n\n #: location of the templates. ``None`` if templates should not be\n #: exposed.\n self.template_folder = template_folder\n\n if root_path is None:\n root_path = get_root_path(self.import_name)\n\n #: Where is the app root located?\n self.root_path = root_path\n\n self._static_folder = None\n self._static_url_path = None\n\n def _get_static_folder(self):\n if self._static_folder is not None:\n return os.path.join(self.root_path, self._static_folder)\n def _set_static_folder(self, value):\n self._static_folder = value\n static_folder = property(_get_static_folder, _set_static_folder, doc='''\n The absolute path to the configured static folder.\n ''')\n del _get_static_folder, _set_static_folder\n\n def _get_static_url_path(self):\n if self._static_url_path is not None:\n return self._static_url_path\n if self.static_folder is not None:\n return '/' + os.path.basename(self.static_folder)\n def _set_static_url_path(self, value):\n self._static_url_path = value\n static_url_path = property(_get_static_url_path, _set_static_url_path)\n del _get_static_url_path, _set_static_url_path\n\n @property\n def has_static_folder(self):\n \"\"\"This is ``True`` if the package bound object's container has a\n folder for static files.\n\n .. versionadded:: 0.5\n \"\"\"\n return self.static_folder is not None\n\n @locked_cached_property\n def jinja_loader(self):\n \"\"\"The Jinja loader for this package bound object.\n\n .. versionadded:: 0.5\n \"\"\"\n if self.template_folder is not None:\n return FileSystemLoader(os.path.join(self.root_path,\n self.template_folder))\n\n def get_send_file_max_age(self, filename):\n \"\"\"Provides default cache_timeout for the :func:`send_file` functions.\n\n By default, this function returns ``SEND_FILE_MAX_AGE_DEFAULT`` from\n the configuration of :data:`~flask.current_app`.\n\n Static file functions such as :func:`send_from_directory` use this\n function, and :func:`send_file` calls this function on\n :data:`~flask.current_app` when the given cache_timeout is ``None``. If a\n cache_timeout is given in :func:`send_file`, that timeout is used;\n otherwise, this method is called.\n\n This allows subclasses to change the behavior when sending files based\n on the filename. For example, to set the cache timeout for .js files\n to 60 seconds::\n\n class MyFlask(flask.Flask):\n def get_send_file_max_age(self, name):\n if name.lower().endswith('.js'):\n return 60\n return flask.Flask.get_send_file_max_age(self, name)\n\n .. versionadded:: 0.9\n \"\"\"\n return current_app.config['SEND_FILE_MAX_AGE_DEFAULT']\n\n def send_static_file(self, filename):\n \"\"\"Function used internally to send static files from the static\n folder to the browser.\n\n .. versionadded:: 0.5\n \"\"\"\n if not self.has_static_folder:\n raise RuntimeError('No static folder for this object')\n # Ensure get_send_file_max_age is called in all cases.\n # Here, we ensure get_send_file_max_age is called for Blueprints.\n cache_timeout = self.get_send_file_max_age(filename)\n return send_from_directory(self.static_folder, filename,\n cache_timeout=cache_timeout)\n\n def open_resource(self, resource, mode='rb'):\n \"\"\"Opens a resource from the application's resource folder. To see\n how this works, consider the following folder structure::\n\n /myapplication.py\n /schema.sql\n /static\n /style.css\n /templates\n /layout.html\n /index.html\n\n If you want to open the :file:`schema.sql` file you would do the\n following::\n\n with app.open_resource('schema.sql') as f:\n contents = f.read()\n do_something_with(contents)\n\n :param resource: the name of the resource. To access resources within\n subfolders use forward slashes as separator.\n :param mode: resource file opening mode, default is 'rb'.\n \"\"\"\n if mode not in ('r', 'rb'):\n raise ValueError('Resources can only be opened for reading')\n return open(os.path.join(self.root_path, resource), mode)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements operations.py from aisipos/django (path: django/db/backends/base/operations.py)."}, {"role": "assistant", "content": "# django/db/backends/base/operations.py (from aisipos/django, license: bsd-3-clause)\n\nimport datetime\nimport decimal\nimport warnings\nfrom importlib import import_module\n\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db.backends import utils\nfrom django.utils import six, timezone\nfrom django.utils.dateparse import parse_duration\nfrom django.utils.deprecation import RemovedInDjango20Warning\nfrom django.utils.encoding import force_text\n\nclass BaseDatabaseOperations(object):\n \"\"\"\n This class encapsulates all backend-specific differences, such as the way\n a backend performs ordering or calculates the ID of a recently-inserted\n row.\n \"\"\"\n compiler_module = \"django.db.models.sql.compiler\"\n\n # Integer field safe ranges by `internal_type` as documented\n # in docs/ref/models/fields.txt.\n integer_field_ranges = {\n 'SmallIntegerField': (-32768, 32767),\n 'IntegerField': (-2147483648, 2147483647),\n 'BigIntegerField': (-9223372036854775808, 9223372036854775807),\n 'PositiveSmallIntegerField': (0, 32767),\n 'PositiveIntegerField': (0, 2147483647),\n }\n\n def __init__(self, connection):\n self.connection = connection\n self._cache = None\n\n def autoinc_sql(self, table, column):\n \"\"\"\n Returns any SQL needed to support auto-incrementing primary keys, or\n None if no SQL is necessary.\n\n This SQL is executed when a table is created.\n \"\"\"\n return None\n\n def bulk_batch_size(self, fields, objs):\n \"\"\"\n Returns the maximum allowed batch size for the backend. The fields\n are the fields going to be inserted in the batch, the objs contains\n all the objects to be inserted.\n \"\"\"\n return len(objs)\n\n def cache_key_culling_sql(self):\n \"\"\"\n Returns an SQL query that retrieves the first cache key greater than the\n n smallest.\n\n This is used by the 'db' cache backend to determine where to start\n culling.\n \"\"\"\n return \"SELECT cache_key FROM %s ORDER BY cache_key LIMIT 1 OFFSET %%s\"\n\n def unification_cast_sql(self, output_field):\n \"\"\"\n Given a field instance, returns the SQL necessary to cast the result of\n a union to that type. Note that the resulting string should contain a\n '%s' placeholder for the expression being cast.\n \"\"\"\n return '%s'\n\n def date_extract_sql(self, lookup_type, field_name):\n \"\"\"\n Given a lookup_type of 'year', 'month' or 'day', returns the SQL that\n extracts a value from the given date field field_name.\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations may require a date_extract_sql() method')\n\n def date_interval_sql(self, timedelta):\n \"\"\"\n Implements the date interval functionality for expressions\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations may require a date_interval_sql() method')\n\n def date_trunc_sql(self, lookup_type, field_name):\n \"\"\"\n Given a lookup_type of 'year', 'month' or 'day', returns the SQL that\n truncates the given date field field_name to a date object with only\n the given specificity.\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetrunc_sql() method')\n\n def datetime_cast_date_sql(self, field_name, tzname):\n \"\"\"\n Returns the SQL necessary to cast a datetime value to date value.\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_cast_date() method')\n\n def datetime_extract_sql(self, lookup_type, field_name, tzname):\n \"\"\"\n Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute' or\n 'second', returns the SQL that extracts a value from the given\n datetime field field_name, and a tuple of parameters.\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method')\n\n def datetime_trunc_sql(self, lookup_type, field_name, tzname):\n \"\"\"\n Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute' or\n 'second', returns the SQL that truncates the given datetime field\n field_name to a datetime object with only the given specificity, and\n a tuple of parameters.\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_trunk_sql() method')\n\n def time_extract_sql(self, lookup_type, field_name):\n \"\"\"\n Given a lookup_type of 'hour', 'minute' or 'second', returns the SQL\n that extracts a value from the given time field field_name.\n \"\"\"\n return self.date_extract_sql(lookup_type, field_name)\n\n def deferrable_sql(self):\n \"\"\"\n Returns the SQL necessary to make a constraint \"initially deferred\"\n during a CREATE TABLE statement.\n \"\"\"\n return ''\n\n def distinct_sql(self, fields):\n \"\"\"\n Returns an SQL DISTINCT clause which removes duplicate rows from the\n result set. If any fields are given, only the given fields are being\n checked for duplicates.\n \"\"\"\n if fields:\n raise NotImplementedError('DISTINCT ON fields is not supported by this database backend')\n else:\n return 'DISTINCT'\n\n def drop_foreignkey_sql(self):\n \"\"\"\n Returns the SQL command that drops a foreign key.\n \"\"\"\n return \"DROP CONSTRAINT\"\n\n def drop_sequence_sql(self, table):\n \"\"\"\n Returns any SQL necessary to drop the sequence for the given table.\n Returns None if no SQL is necessary.\n \"\"\"\n return None\n\n def fetch_returned_insert_id(self, cursor):\n \"\"\"\n Given a cursor object that has just performed an INSERT...RETURNING\n statement into a table that has an auto-incrementing ID, returns the\n newly created ID.\n \"\"\"\n return cursor.fetchone()[0]\n\n def field_cast_sql(self, db_type, internal_type):\n \"\"\"\n Given a column type (e.g. 'BLOB', 'VARCHAR'), and an internal type\n (e.g. 'GenericIPAddressField'), returns the SQL necessary to cast it\n before using it in a WHERE statement. Note that the resulting string\n should contain a '%s' placeholder for the column being searched against.\n \"\"\"\n return '%s'\n\n def force_no_ordering(self):\n \"\"\"\n Returns a list used in the \"ORDER BY\" clause to force no ordering at\n all. Returning an empty list means that nothing will be included in the\n ordering.\n \"\"\"\n return []\n\n def for_update_sql(self, nowait=False):\n \"\"\"\n Returns the FOR UPDATE SQL clause to lock rows for an update operation.\n \"\"\"\n if nowait:\n return 'FOR UPDATE NOWAIT'\n else:\n return 'FOR UPDATE'\n\n def fulltext_search_sql(self, field_name):\n \"\"\"\n Returns the SQL WHERE clause to use in order to perform a full-text\n search of the given field_name. Note that the resulting string should\n contain a '%s' placeholder for the value being searched against.\n \"\"\"\n # RemovedInDjango20Warning\n raise NotImplementedError('Full-text search is not implemented for this database backend')\n\n def last_executed_query(self, cursor, sql, params):\n \"\"\"\n Returns a string of the query last executed by the given cursor, with\n placeholders replaced with actual values.\n\n `sql` is the raw query containing placeholders, and `params` is the\n sequence of parameters. These are used by default, but this method\n exists for database backends to provide a better implementation\n according to their own quoting schemes.\n \"\"\"\n # Convert params to contain Unicode values.\n def to_unicode(s):\n return force_text(s, strings_only=True, errors='replace')\n if isinstance(params, (list, tuple)):\n u_params = tuple(to_unicode(val) for val in params)\n elif params is None:\n u_params = ()\n else:\n u_params = {to_unicode(k): to_unicode(v) for k, v in params.items()}\n\n return six.text_type(\"QUERY = %r - PARAMS = %r\") % (sql, u_params)\n\n def last_insert_id(self, cursor, table_name, pk_name):\n \"\"\"\n Given a cursor object that has just performed an INSERT statement into\n a table that has an auto-incrementing ID, returns the newly created ID.\n\n This method also receives the table name and the name of the primary-key\n column.\n \"\"\"\n return cursor.lastrowid\n\n def lookup_cast(self, lookup_type, internal_type=None):\n \"\"\"\n Returns the string to use in a query when performing lookups\n (\"contains\", \"like\", etc.). The resulting string should contain a '%s'\n placeholder for the column being searched against.\n \"\"\"\n return \"%s\"\n\n def max_in_list_size(self):\n \"\"\"\n Returns the maximum number of items that can be passed in a single 'IN'\n list condition, or None if the backend does not impose a limit.\n \"\"\"\n return None\n\n def max_name_length(self):\n \"\"\"\n Returns the maximum length of table and column names, or None if there\n is no limit.\n \"\"\"\n return None\n\n def no_limit_value(self):\n \"\"\"\n Returns the value to use for the LIMIT when we are wanting \"LIMIT\n infinity\". Returns None if the limit clause can be omitted in this case.\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations may require a no_limit_value() method')\n\n def pk_default_value(self):\n \"\"\"\n Returns the value to use during an INSERT statement to specify that\n the field should use its default value.\n \"\"\"\n return 'DEFAULT'\n\n def prepare_sql_script(self, sql):\n \"\"\"\n Takes an SQL script that may contain multiple lines and returns a list\n of statements to feed to successive cursor.execute() calls.\n\n Since few databases are able to process raw SQL scripts in a single\n cursor.execute() call and PEP 249 doesn't talk about this use case,\n the default implementation is conservative.\n \"\"\"\n try:\n import sqlparse\n except ImportError:\n raise ImproperlyConfigured(\n \"sqlparse is required if you don't split your SQL \"\n \"statements manually.\"\n )\n else:\n return [sqlparse.format(statement, strip_comments=True)\n for statement in sqlparse.split(sql) if statement]\n\n def process_clob(self, value):\n \"\"\"\n Returns the value of a CLOB column, for backends that return a locator\n object that requires additional processing.\n \"\"\"\n return value\n\n def return_insert_id(self):\n \"\"\"\n For backends that support returning the last insert ID as part\n of an insert query, this method returns the SQL and params to\n append to the INSERT query. The returned fragment should\n contain a format string to hold the appropriate column.\n \"\"\"\n pass\n\n def compiler(self, compiler_name):\n \"\"\"\n Returns the SQLCompiler class corresponding to the given name,\n in the namespace corresponding to the `compiler_module` attribute\n on this backend.\n \"\"\"\n if self._cache is None:\n self._cache = import_module(self.compiler_module)\n return getattr(self._cache, compiler_name)\n\n def quote_name(self, name):\n \"\"\"\n Returns a quoted version of the given table, index or column name. Does\n not quote the given name if it's already been quoted.\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations may require a quote_name() method')\n\n def random_function_sql(self):\n \"\"\"\n Returns an SQL expression that returns a random value.\n \"\"\"\n return 'RANDOM()'\n\n def regex_lookup(self, lookup_type):\n \"\"\"\n Returns the string to use in a query when performing regular expression\n lookups (using \"regex\" or \"iregex\"). The resulting string should\n contain a '%s' placeholder for the column being searched against.\n\n If the feature is not supported (or part of it is not supported), a\n NotImplementedError exception can be raised.\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations may require a regex_lookup() method')\n\n def savepoint_create_sql(self, sid):\n \"\"\"\n Returns the SQL for starting a new savepoint. Only required if the\n \"uses_savepoints\" feature is True. The \"sid\" parameter is a string\n for the savepoint id.\n \"\"\"\n return \"SAVEPOINT %s\" % self.quote_name(sid)\n\n def savepoint_commit_sql(self, sid):\n \"\"\"\n Returns the SQL for committing the given savepoint.\n \"\"\"\n return \"RELEASE SAVEPOINT %s\" % self.quote_name(sid)\n\n def savepoint_rollback_sql(self, sid):\n \"\"\"\n Returns the SQL for rolling back the given savepoint.\n \"\"\"\n return \"ROLLBACK TO SAVEPOINT %s\" % self.quote_name(sid)\n\n def set_time_zone_sql(self):\n \"\"\"\n Returns the SQL that will set the connection's time zone.\n\n Returns '' if the backend doesn't support time zones.\n \"\"\"\n return ''\n\n def sql_flush(self, style, tables, sequences, allow_cascade=False):\n \"\"\"\n Returns a list of SQL statements required to remove all data from\n the given database tables (without actually removing the tables\n themselves).\n\n The returned value also includes SQL statements required to reset DB\n sequences passed in :param sequences:.\n\n The `style` argument is a Style object as returned by either\n color_style() or no_style() in django.core.management.color.\n\n The `allow_cascade` argument determines whether truncation may cascade\n to tables with foreign keys pointing the tables being truncated.\n PostgreSQL requires a cascade even if these tables are empty.\n \"\"\"\n raise NotImplementedError('subclasses of BaseDatabaseOperations must provide an sql_flush() method')\n\n def sequence_reset_by_name_sql(self, style, sequences):\n \"\"\"\n Returns a list of the SQL statements required to reset sequences\n passed in :param sequences:.\n\n The `style` argument is a Style object as returned by either\n color_style() or no_style() in django.core.management.color.\n \"\"\"\n return []\n\n def sequence_reset_sql(self, style, model_list):\n \"\"\"\n Returns a list of the SQL statements required to reset sequences for\n the given models.\n\n The `style` argument is a Style object as returned by either\n color_style() or no_style() in django.core.management.color.\n \"\"\"\n return [] # No sequence reset required by default.\n\n def start_transaction_sql(self):\n \"\"\"\n Returns the SQL statement required to start a transaction.\n \"\"\"\n return \"BEGIN;\"\n\n def end_transaction_sql(self, success=True):\n \"\"\"\n Returns the SQL statement required to end a transaction.\n \"\"\"\n if not success:\n return \"ROLLBACK;\"\n return \"COMMIT;\"\n\n def tablespace_sql(self, tablespace, inline=False):\n \"\"\"\n Returns the SQL that will be used in a query to define the tablespace.\n\n Returns '' if the backend doesn't support tablespaces.\n\n If inline is True, the SQL is appended to a row; otherwise it's appended\n to the entire CREATE TABLE or CREATE INDEX statement.\n \"\"\"\n return ''\n\n def prep_for_like_query(self, x):\n \"\"\"Prepares a value for use in a LIKE query.\"\"\"\n return force_text(x).replace(\"\\\\\", \"\\\\\\\\\").replace(\"%\", \"\\%\").replace(\"_\", \"\\_\")\n\n # Same as prep_for_like_query(), but called for \"iexact\" matches, which\n # need not necessarily be implemented using \"LIKE\" in the backend.\n prep_for_iexact_query = prep_for_like_query\n\n def validate_autopk_value(self, value):\n \"\"\"\n Certain backends do not accept some values for \"serial\" fields\n (for example zero in MySQL). This method will raise a ValueError\n if the value is invalid, otherwise returns validated value.\n \"\"\"\n return value\n\n def adapt_unknown_value(self, value):\n \"\"\"\n Transforms a value to something compatible with the backend driver.\n\n This method only depends on the type of the value. It's designed for\n cases where the target type isn't known, such as .raw() SQL queries.\n As a consequence it may not work perfectly in all circumstances.\n \"\"\"\n if isinstance(value, datetime.datetime): # must be before date\n return self.adapt_datetimefield_value(value)\n elif isinstance(value, datetime.date):\n return self.adapt_datefield_value(value)\n elif isinstance(value, datetime.time):\n return self.adapt_timefield_value(value)\n elif isinstance(value, decimal.Decimal):\n return self.adapt_decimalfield_value(value)\n else:\n return value\n\n def adapt_datefield_value(self, value):\n \"\"\"\n Transforms a date value to an object compatible with what is expected\n by the backend driver for date columns.\n \"\"\"\n if value is None:\n return None\n return six.text_type(value)\n\n def adapt_datetimefield_value(self, value):\n \"\"\"\n Transforms a datetime value to an object compatible with what is expected\n by the backend driver for datetime columns.\n \"\"\"\n if value is None:\n return None\n return six.text_type(value)\n\n def adapt_timefield_value(self, value):\n \"\"\"\n Transforms a time value to an object compatible with what is expected\n by the backend driver for time columns.\n \"\"\"\n if value is None:\n return None\n if timezone.is_aware(value):\n raise ValueError(\"Django does not support timezone-aware times.\")\n return six.text_type(value)\n\n def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None):\n \"\"\"\n Transforms a decimal.Decimal value to an object compatible with what is\n expected by the backend driver for decimal (numeric) columns.\n \"\"\"\n return utils.format_number(value, max_digits, decimal_places)\n\n def adapt_ipaddressfield_value(self, value):\n \"\"\"\n Transforms a string representation of an IP address into the expected\n type for the backend driver.\n \"\"\"\n return value or None\n\n def year_lookup_bounds_for_date_field(self, value):\n \"\"\"\n Returns a two-elements list with the lower and upper bound to be used\n with a BETWEEN operator to query a DateField value using a year\n lookup.\n\n `value` is an int, containing the looked-up year.\n \"\"\"\n first = datetime.date(value, 1, 1)\n second = datetime.date(value, 12, 31)\n first = self.adapt_datefield_value(first)\n second = self.adapt_datefield_value(second)\n return [first, second]\n\n def year_lookup_bounds_for_datetime_field(self, value):\n \"\"\"\n Returns a two-elements list with the lower and upper bound to be used\n with a BETWEEN operator to query a DateTimeField value using a year\n lookup.\n\n `value` is an int, containing the looked-up year.\n \"\"\"\n first = datetime.datetime(value, 1, 1)\n second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999)\n if settings.USE_TZ:\n tz = timezone.get_current_timezone()\n first = timezone.make_aware(first, tz)\n second = timezone.make_aware(second, tz)\n first = self.adapt_datetimefield_value(first)\n second = self.adapt_datetimefield_value(second)\n return [first, second]\n\n def get_db_converters(self, expression):\n \"\"\"\n Get a list of functions needed to convert field data.\n\n Some field types on some backends do not provide data in the correct\n format, this is the hook for converter functions.\n \"\"\"\n return []\n\n def convert_durationfield_value(self, value, expression, connection, context):\n if value is not None:\n value = str(decimal.Decimal(value) / decimal.Decimal(1000000))\n value = parse_duration(value)\n return value\n\n def check_aggregate_support(self, aggregate_func):\n warnings.warn(\n \"check_aggregate_support has been deprecated. Use \"\n \"check_expression_support instead.\",\n RemovedInDjango20Warning, stacklevel=2)\n return self.check_expression_support(aggregate_func)\n\n def check_expression_support(self, expression):\n \"\"\"\n Check that the backend supports the provided expression.\n\n This is used on specific backends to rule out known expressions\n that have problematic or nonexistent implementations. If the\n expression has a known problem, the backend should raise\n NotImplementedError.\n \"\"\"\n pass\n\n def combine_expression(self, connector, sub_expressions):\n \"\"\"Combine a list of subexpressions into a single expression, using\n the provided connecting operator. This is required because operators\n can vary between backends (e.g., Oracle with %% and &) and between\n subexpression types (e.g., date expressions)\n \"\"\"\n conn = ' %s ' % connector\n return conn.join(sub_expressions)\n\n def combine_duration_expression(self, connector, sub_expressions):\n return self.combine_expression(connector, sub_expressions)\n\n def binary_placeholder_sql(self, value):\n \"\"\"\n Some backends require special syntax to insert binary content (MySQL\n for example uses '_binary %s').\n \"\"\"\n return '%s'\n\n def modify_insert_params(self, placeholder, params):\n \"\"\"Allow modification of insert parameters. Needed for Oracle Spatial\n backend due to #10888.\n \"\"\"\n return params\n\n def integer_field_range(self, internal_type):\n \"\"\"\n Given an integer field internal type (e.g. 'PositiveIntegerField'),\n returns a tuple of the (min_value, max_value) form representing the\n range of the column type bound to the field.\n \"\"\"\n return self.integer_field_ranges[internal_type]\n\n def subtract_temporals(self, internal_type, lhs, rhs):\n if self.connection.features.supports_temporal_subtraction:\n lhs_sql, lhs_params = lhs\n rhs_sql, rhs_params = rhs\n return \"(%s - %s)\" % (lhs_sql, rhs_sql), lhs_params + rhs_params\n raise NotImplementedError(\"This backend does not support %s subtraction.\" % internal_type)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements deploy.py from mhnatiuk/phd_sociology_of_religion (path: scrapper/build/scrapy/build/lib.linux-x86_64-2.7/scrapy/commands/deploy.py)."}, {"role": "assistant", "content": "# scrapper/build/scrapy/build/lib.linux-x86_64-2.7/scrapy/commands/deploy.py (from mhnatiuk/phd_sociology_of_religion, license: gpl-2.0)\n\nfrom __future__ import print_function\nimport sys\nimport os\nimport glob\nimport tempfile\nimport shutil\nimport time\nimport urllib2\nimport netrc\nimport json\nfrom urlparse import urlparse, urljoin\nfrom subprocess import Popen, PIPE, check_call\n\nfrom w3lib.form import encode_multipart\n\nfrom scrapy.command import ScrapyCommand\nfrom scrapy.exceptions import UsageError\nfrom scrapy.utils.http import basic_auth_header\nfrom scrapy.utils.python import retry_on_eintr\nfrom scrapy.utils.conf import get_config, closest_scrapy_cfg\n\n_SETUP_PY_TEMPLATE = \\\n\"\"\"# Automatically created by: scrapy deploy\n\nfrom setuptools import setup, find_packages\n\nsetup(\n name = 'project',\n version = '1.0',\n packages = find_packages(),\n entry_points = {'scrapy': ['settings = %(settings)s']},\n)\n\"\"\"\n\nclass Command(ScrapyCommand):\n\n requires_project = True\n\n def syntax(self):\n return \"[options] [ [target] | -l | -L ]\"\n\n def short_desc(self):\n return \"Deploy project in Scrapyd target\"\n\n def long_desc(self):\n return \"Deploy the current project into the given Scrapyd server \" \\\n \"(known as target)\"\n\n def add_options(self, parser):\n ScrapyCommand.add_options(self, parser)\n parser.add_option(\"-p\", \"--project\",\n help=\"the project name in the target\")\n parser.add_option(\"-v\", \"--version\",\n help=\"the version to deploy. Defaults to current timestamp\")\n parser.add_option(\"-l\", \"--list-targets\", action=\"store_true\", \\\n help=\"list available targets\")\n parser.add_option(\"-d\", \"--debug\", action=\"store_true\",\n help=\"debug mode (do not remove build dir)\")\n parser.add_option(\"-L\", \"--list-projects\", metavar=\"TARGET\", \\\n help=\"list available projects on TARGET\")\n parser.add_option(\"--egg\", metavar=\"FILE\",\n help=\"use the given egg, instead of building it\")\n parser.add_option(\"--build-egg\", metavar=\"FILE\",\n help=\"only build the egg, don't deploy it\")\n\n def run(self, args, opts):\n try:\n import setuptools\n except ImportError:\n raise UsageError(\"setuptools not installed\")\n\n urllib2.install_opener(urllib2.build_opener(HTTPRedirectHandler))\n\n if opts.list_targets:\n for name, target in _get_targets().items():\n print(\"%-20s %s\" % (name, target['url']))\n return\n\n if opts.list_projects:\n target = _get_target(opts.list_projects)\n req = urllib2.Request(_url(target, 'listprojects.json'))\n _add_auth_header(req, target)\n f = urllib2.urlopen(req)\n projects = json.loads(f.read())['projects']\n print(os.linesep.join(projects))\n return\n\n tmpdir = None\n\n if opts.build_egg: # build egg only\n egg, tmpdir = _build_egg()\n _log(\"Writing egg to %s\" % opts.build_egg)\n shutil.copyfile(egg, opts.build_egg)\n else: # buld egg and deploy\n target_name = _get_target_name(args)\n target = _get_target(target_name)\n project = _get_project(target, opts)\n version = _get_version(target, opts)\n if opts.egg:\n _log(\"Using egg: %s\" % opts.egg)\n egg = opts.egg\n else:\n _log(\"Packing version %s\" % version)\n egg, tmpdir = _build_egg()\n if not _upload_egg(target, egg, project, version):\n self.exitcode = 1\n\n if tmpdir:\n if opts.debug:\n _log(\"Output dir not removed: %s\" % tmpdir)\n else:\n shutil.rmtree(tmpdir)\n\ndef _log(message):\n sys.stderr.write(message + os.linesep)\n\ndef _get_target_name(args):\n if len(args) > 1:\n raise UsageError(\"Too many arguments: %s\" % ' '.join(args))\n elif args:\n return args[0]\n elif len(args) < 1:\n return 'default'\n\ndef _get_project(target, opts):\n project = opts.project or target.get('project')\n if not project:\n raise UsageError(\"Missing project\")\n return project\n\ndef _get_option(section, option, default=None):\n cfg = get_config()\n return cfg.get(section, option) if cfg.has_option(section, option) \\\n else default\n\ndef _get_targets():\n cfg = get_config()\n baset = dict(cfg.items('deploy')) if cfg.has_section('deploy') else {}\n targets = {}\n if 'url' in baset:\n targets['default'] = baset\n for x in cfg.sections():\n if x.startswith('deploy:'):\n t = baset.copy()\n t.update(cfg.items(x))\n targets[x[7:]] = t\n return targets\n\ndef _get_target(name):\n try:\n return _get_targets()[name]\n except KeyError:\n raise UsageError(\"Unknown target: %s\" % name)\n\ndef _url(target, action):\n return urljoin(target['url'], action)\n\ndef _get_version(target, opts):\n version = opts.version or target.get('version')\n if version == 'HG':\n p = Popen(['hg', 'tip', '--template', '{rev}'], stdout=PIPE)\n d = 'r%s' % p.communicate()[0]\n p = Popen(['hg', 'branch'], stdout=PIPE)\n b = p.communicate()[0].strip('\\n')\n return '%s-%s' % (d, b)\n elif version == 'GIT':\n p = Popen(['git', 'describe', '--always'], stdout=PIPE)\n d = p.communicate()[0].strip('\\n')\n p = Popen(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], stdout=PIPE)\n b = p.communicate()[0].strip('\\n')\n return '%s-%s' % (d, b)\n elif version:\n return version\n else:\n return str(int(time.time()))\n\ndef _upload_egg(target, eggpath, project, version):\n with open(eggpath, 'rb') as f:\n eggdata = f.read()\n data = {\n 'project': project,\n 'version': version,\n 'egg': ('project.egg', eggdata),\n }\n body, boundary = encode_multipart(data)\n url = _url(target, 'addversion.json')\n headers = {\n 'Content-Type': 'multipart/form-data; boundary=%s' % boundary,\n 'Content-Length': str(len(body)),\n }\n req = urllib2.Request(url, body, headers)\n _add_auth_header(req, target)\n _log('Deploying to project \"%s\" in %s' % (project, url))\n return _http_post(req)\n\ndef _add_auth_header(request, target):\n if 'username' in target:\n u, p = target.get('username'), target.get('password', '')\n request.add_header('Authorization', basic_auth_header(u, p))\n else: # try netrc\n try:\n host = urlparse(target['url']).hostname\n a = netrc.netrc().authenticators(host)\n request.add_header('Authorization', basic_auth_header(a[0], a[2]))\n except (netrc.NetrcParseError, IOError, TypeError):\n pass\n\ndef _http_post(request):\n try:\n f = urllib2.urlopen(request)\n _log(\"Server response (%s):\" % f.code)\n print(f.read())\n return True\n except urllib2.HTTPError as e:\n _log(\"Deploy failed (%s):\" % e.code)\n print(e.read())\n except urllib2.URLError as e:\n _log(\"Deploy failed: %s\" % e)\n\ndef _build_egg():\n closest = closest_scrapy_cfg()\n os.chdir(os.path.dirname(closest))\n if not os.path.exists('setup.py'):\n settings = get_config().get('settings', 'default')\n _create_default_setup_py(settings=settings)\n d = tempfile.mkdtemp(prefix=\"scrapydeploy-\")\n o = open(os.path.join(d, \"stdout\"), \"wb\")\n e = open(os.path.join(d, \"stderr\"), \"wb\")\n retry_on_eintr(check_call, [sys.executable, 'setup.py', 'clean', '-a', 'bdist_egg', '-d', d], stdout=o, stderr=e)\n o.close()\n e.close()\n egg = glob.glob(os.path.join(d, '*.egg'))[0]\n return egg, d\n\ndef _create_default_setup_py(**kwargs):\n with open('setup.py', 'w') as f:\n f.write(_SETUP_PY_TEMPLATE % kwargs)\n\nclass HTTPRedirectHandler(urllib2.HTTPRedirectHandler):\n\n def redirect_request(self, req, fp, code, msg, headers, newurl):\n newurl = newurl.replace(' ', '%20')\n if code in (301, 307):\n return urllib2.Request(newurl,\n data=req.get_data(),\n headers=req.headers,\n origin_req_host=req.get_origin_req_host(),\n unverifiable=True)\n elif code in (302, 303):\n newheaders = dict((k, v) for k, v in req.headers.items()\n if k.lower() not in (\"content-length\", \"content-type\"))\n return urllib2.Request(newurl,\n headers=newheaders,\n origin_req_host=req.get_origin_req_host(),\n unverifiable=True)\n else:\n raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements normalmodes.py from ibethune/lammps (path: tools/i-pi/ipi/inputs/normalmodes.py)."}, {"role": "assistant", "content": "# tools/i-pi/ipi/inputs/normalmodes.py (from ibethune/lammps, license: gpl-2.0)\n\n\"\"\"Deals with creating the normal mode representation arrays.\n\nCopyright (C) 2013, Joshua More and Michele Ceriotti\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\nClasses:\n InputNormalModes: Deals with creating the normal mode objects.\n\"\"\"\n\nimport numpy as np\nfrom copy import copy\nfrom ipi.engine.normalmodes import *\nfrom ipi.utils.inputvalue import *\nfrom ipi.utils.units import *\n\n__all__ = ['InputNormalModes']\n\nclass InputNormalModes(InputArray):\n \"\"\" Storage class for NormalModes engine.\n\n Describes how normal-modes transformation and integration should be\n performed.\n\n Attributes:\n mode: Specifies the method by which the dynamical masses are created.\n transform: Specifies whether the normal mode calculation will be\n done using a FFT transform or a matrix multiplication.\n \"\"\"\n\n attribs = copy(InputArray.attribs)\n attribs[\"mode\"] = (InputAttribute, {\"dtype\" : str,\n \"default\" : \"rpmd\",\n \"help\" : \"Specifies the technique to be used to calculate the dynamical masses. 'rpmd' simply assigns the bead masses the physical mass. 'manual' sets all the normal mode frequencies except the centroid normal mode manually. 'pa-cmd' takes an argument giving the frequency to set all the non-centroid normal modes to. 'wmax-cmd' is similar to 'pa-cmd', except instead of taking one argument it takes two ([wmax,wtarget]). The lowest-lying normal mode will be set to wtarget for a free particle, and all the normal modes will coincide at frequency wmax. \",\n \"options\" : ['pa-cmd', 'wmax-cmd', 'manual', 'rpmd']})\n attribs[\"transform\"] = (InputValue,{\"dtype\" : str,\n \"default\" : \"fft\",\n \"help\" : \"Specifies whether to calculate the normal mode transform using a fast Fourier transform or a matrix multiplication. For small numbers of beads the matrix multiplication may be faster.\",\n \"options\" : ['fft', 'matrix']})\n\n default_help = \"Deals with the normal mode transformations, including the adjustment of bead masses to give the desired ring polymer normal mode frequencies if appropriate. Takes as arguments frequencies, of which different numbers must be specified and which are used to scale the normal mode frequencies in different ways depending on which 'mode' is specified.\"\n default_label = \"NORMALMODES\"\n\n def __init__(self, help=None, dimension=None, default=None, dtype=None):\n \"\"\" Initializes InputNormalModes.\n\n Just calls the parent initialization function with appropriate arguments.\n \"\"\"\n\n super(InputNormalModes,self).__init__(help=help, default=default, dtype=float, dimension=\"frequency\")\n\n def store(self, nm):\n \"\"\"Takes a normal modes instance and stores a minimal representation\n of it.\n\n Args:\n nm: A normal modes object.\n \"\"\"\n\n super(InputNormalModes,self).store(nm.nm_freqs)\n self.mode.store(nm.mode)\n self.transform.store(nm.transform_method)\n\n def fetch(self):\n \"\"\"Creates a normal modes object.\n\n Returns:\n A normal modes object.\n \"\"\"\n\n super(InputNormalModes,self).check()\n return NormalModes(self.mode.fetch(), self.transform.fetch(), super(InputNormalModes,self).fetch() )"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_subreddit.py from voussoir/praw (path: tests/unit/models/reddit/test_subreddit.py)."}, {"role": "assistant", "content": "# tests/unit/models/reddit/test_subreddit.py (from voussoir/praw, license: gpl-3.0)\n\nimport pickle\n\nimport pytest\nfrom praw.models import Subreddit, WikiPage\n\nfrom ... import UnitTest\n\nclass TestSubreddit(UnitTest):\n def test_equality(self):\n subreddit1 = Subreddit(self.reddit,\n _data={'display_name': 'dummy1', 'n': 1})\n subreddit2 = Subreddit(self.reddit,\n _data={'display_name': 'Dummy1', 'n': 2})\n subreddit3 = Subreddit(self.reddit,\n _data={'display_name': 'dummy3', 'n': 2})\n assert subreddit1 == subreddit1\n assert subreddit2 == subreddit2\n assert subreddit3 == subreddit3\n assert subreddit1 == subreddit2\n assert subreddit2 != subreddit3\n assert subreddit1 != subreddit3\n assert 'dummy1' == subreddit1\n assert subreddit2 == 'dummy1'\n\n def test_construct_failure(self):\n message = 'Either `display_name` or `_data` must be provided.'\n with pytest.raises(TypeError) as excinfo:\n Subreddit(self.reddit)\n assert str(excinfo.value) == message\n\n with pytest.raises(TypeError) as excinfo:\n Subreddit(self.reddit, 'dummy', {'id': 'dummy'})\n assert str(excinfo.value) == message\n\n def test_fullname(self):\n subreddit = Subreddit(self.reddit, _data={'display_name': 'name',\n 'id': 'dummy'})\n assert subreddit.fullname == 't5_dummy'\n\n def test_hash(self):\n subreddit1 = Subreddit(self.reddit,\n _data={'display_name': 'dummy1', 'n': 1})\n subreddit2 = Subreddit(self.reddit,\n _data={'display_name': 'Dummy1', 'n': 2})\n subreddit3 = Subreddit(self.reddit,\n _data={'display_name': 'dummy3', 'n': 2})\n assert hash(subreddit1) == hash(subreddit1)\n assert hash(subreddit2) == hash(subreddit2)\n assert hash(subreddit3) == hash(subreddit3)\n assert hash(subreddit1) == hash(subreddit2)\n assert hash(subreddit2) != hash(subreddit3)\n assert hash(subreddit1) != hash(subreddit3)\n\n def test_pickle(self):\n subreddit = Subreddit(self.reddit, _data={'display_name': 'name',\n 'id': 'dummy'})\n for level in range(pickle.HIGHEST_PROTOCOL + 1):\n other = pickle.loads(pickle.dumps(subreddit, protocol=level))\n assert subreddit == other\n\n def test_repr(self):\n subreddit = Subreddit(self.reddit, display_name='name')\n assert repr(subreddit) == 'Subreddit(display_name=\\'name\\')'\n\n def test_search__params_not_modified(self):\n params = {'dummy': 'value'}\n subreddit = Subreddit(self.reddit, display_name='name')\n generator = subreddit.search(None, params=params)\n assert generator.params['dummy'] == 'value'\n assert params == {'dummy': 'value'}\n\n def test_str(self):\n subreddit = Subreddit(self.reddit, _data={'display_name': 'name',\n 'id': 'dummy'})\n assert str(subreddit) == 'name'\n\n def test_submit_failure(self):\n message = 'Either `selftext` or `url` must be provided.'\n subreddit = Subreddit(self.reddit, display_name='name')\n\n with pytest.raises(TypeError) as excinfo:\n subreddit.submit('Cool title')\n assert str(excinfo.value) == message\n\n with pytest.raises(TypeError) as excinfo:\n subreddit.submit('Cool title', selftext='a', url='b')\n assert str(excinfo.value) == message\n\nclass TestSubredditWiki(UnitTest):\n def test__getitem(self):\n subreddit = Subreddit(self.reddit, display_name='name')\n wikipage = subreddit.wiki['Foo']\n assert isinstance(wikipage, WikiPage)\n assert 'foo' == wikipage.name"}]} {"messages": [{"role": "user", "content": "Write Python code that implements StringConverter.py from scriptnull/coala (path: coalib/misc/StringConverter.py)."}, {"role": "assistant", "content": "# coalib/misc/StringConverter.py (from scriptnull/coala, license: agpl-3.0)\n\nfrom collections import Iterable, OrderedDict\nimport re\nfrom coalib.misc import Constants\nfrom coalib.parsing.StringProcessing import (unescaped_split,\n unescaped_strip,\n unescape)\n\nclass StringConverter:\n \"\"\"\n Converts strings to other things as needed. If you need some kind of string\n conversion that is not implemented here, consider adding it so everyone\n gets something out of it.\n \"\"\"\n\n def __init__(self,\n value,\n strip_whitespaces=True,\n list_delimiters=None,\n dict_delimiter=\":\",\n remove_empty_iter_elements=True):\n if list_delimiters is None:\n list_delimiters = [\",\", \";\"]\n\n if not isinstance(list_delimiters, Iterable):\n raise TypeError(\"list_delimiters has to be an Iterable.\")\n if not isinstance(strip_whitespaces, bool):\n raise TypeError(\"strip_whitespaces has to be a bool parameter\")\n\n self.__strip_whitespaces = strip_whitespaces\n self.__list_delimiters = list_delimiters\n self.__dict_delimiter = dict_delimiter\n self.__remove_empty_iter_elements = remove_empty_iter_elements\n\n self.__escaped_list = None\n self.__unescaped_list = None\n self.__dict = None\n self.value = value\n\n def __str__(self):\n return unescape(self.value)\n\n def __bool__(self):\n if str(self).lower() in Constants.TRUE_STRINGS:\n return True\n if str(self).lower() in Constants.FALSE_STRINGS:\n return False\n raise ValueError\n\n def __len__(self):\n return len(str(self))\n\n def __int__(self):\n return int(str(self))\n\n def __float__(self):\n return float(str(self))\n\n def __iter__(self, remove_backslashes=True):\n \"\"\"\n Converts the value to a list using the delimiters given at construction\n time.\n\n Note that escaped values will be unescaped and escaped list delimiters\n will be allowed in values. If you need the escapes you should not\n use this routine.\n\n :param remove_backslashes: Whether or not to remove the backslashes\n after conversion.\n :return: An iterator over all values.\n \"\"\"\n if remove_backslashes:\n return iter(self.__unescaped_list)\n else:\n return iter(self.__escaped_list)\n\n def __getitem__(self, item):\n return self.__dict.__getitem__(item)\n\n def keys(self):\n return self.__dict.keys()\n\n def __get_raw_list(self):\n pattern = (\"(?:\" +\n \"|\".join(re.escape(v) for v in self.__list_delimiters) +\n \")\")\n\n return list(unescaped_split(pattern,\n self.value,\n use_regex=True))\n\n def __prepare_list(self):\n self.__escaped_list = self.__get_raw_list()\n\n if self.__strip_whitespaces:\n self.__escaped_list = [unescaped_strip(elem)\n for elem in self.__escaped_list]\n\n self.__unescaped_list = [unescape(elem)\n for elem in self.__escaped_list]\n\n if self.__remove_empty_iter_elements:\n # Need to do after stripping, cant use builtin functionality of\n # split.\n while \"\" in self.__unescaped_list:\n self.__unescaped_list.remove(\"\")\n while \"\" in self.__escaped_list:\n self.__escaped_list.remove(\"\")\n\n def __prepare_dict(self):\n # We must keep order here, user can drop it later.\n self.__dict = OrderedDict()\n for elem in self.__get_raw_list():\n key_val = unescaped_split(self.__dict_delimiter, elem, max_split=1)\n\n if self.__strip_whitespaces:\n key_val = [unescaped_strip(item) for item in key_val]\n\n key_val = [unescape(item) for item in key_val]\n\n if not any(item != \"\" for item in key_val):\n continue\n\n if len(key_val) < 2:\n self.__dict[key_val[0]] = \"\"\n else:\n self.__dict[key_val[0]] = key_val[1]\n\n @property\n def value(self):\n return self.__value\n\n @value.setter\n def value(self, newval):\n self.__value = str(newval)\n if self.__strip_whitespaces:\n self.__value = unescaped_strip(self.__value)\n\n self.__prepare_list()\n self.__prepare_dict()\n\n def __eq__(self, other):\n return isinstance(other, StringConverter) and self.value == other.value\n\n def __ne__(self, other):\n return not self.__eq__(other)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test-installed-numpy.py from chatcannon/numpy (path: tools/test-installed-numpy.py)."}, {"role": "assistant", "content": "# tools/test-installed-numpy.py (from chatcannon/numpy, license: bsd-3-clause)\n\n#!/usr/bin/env python\nfrom __future__ import division, absolute_import, print_function\n\n# A simple script to test the installed version of numpy by calling\n# 'numpy.test()'. Key features:\n# -- convenient command-line syntax\n# -- sets exit status appropriately, useful for automated test environments\n\n# It would be better to set this up as a module in the numpy namespace, so\n# that it could be run as:\n# python -m numpy.run_tests \n# But, python2.4's -m switch only works with top-level modules, not modules\n# that are inside packages. So, once we drop 2.4 support, maybe...\n\nimport sys, os\n# In case we are run from the source directory, we don't want to import numpy\n# from there, we want to import the installed version:\nsys.path.pop(0)\n\nfrom optparse import OptionParser\nparser = OptionParser(\"usage: %prog [options] -- [nosetests options]\")\nparser.add_option(\"-v\", \"--verbose\",\n action=\"count\", dest=\"verbose\", default=1,\n help=\"increase verbosity\")\nparser.add_option(\"--doctests\",\n action=\"store_true\", dest=\"doctests\", default=False,\n help=\"Run doctests in module\")\nparser.add_option(\"--coverage\",\n action=\"store_true\", dest=\"coverage\", default=False,\n help=\"report coverage of NumPy code (requires 'coverage' module\")\nparser.add_option(\"-m\", \"--mode\",\n action=\"store\", dest=\"mode\", default=\"fast\",\n help=\"'fast', 'full', or something that could be \"\n \"passed to nosetests -A [default: %default]\")\n(options, args) = parser.parse_args()\n\nimport numpy\n\n# Check that NPY_RELAXED_STRIDES_CHECKING is active when set.\n# The same flags check is also used in the tests to switch behavior.\nif (os.environ.get('NPY_RELAXED_STRIDES_CHECKING', \"1\") != \"0\"):\n if not numpy.ones((10, 1), order='C').flags.f_contiguous:\n print('NPY_RELAXED_STRIDES_CHECKING set, but not active.')\n sys.exit(1)\nelif numpy.ones((10, 1), order='C').flags.f_contiguous:\n print('NPY_RELAXED_STRIDES_CHECKING not set, but active.')\n sys.exit(1)\n\nresult = numpy.test(options.mode,\n verbose=options.verbose,\n extra_argv=args,\n doctests=options.doctests,\n coverage=options.coverage)\n\nif result.wasSuccessful():\n sys.exit(0)\nelse:\n sys.exit(1)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements procurement.py from kirca/odoo (path: addons/stock/procurement.py)."}, {"role": "assistant", "content": "# addons/stock/procurement.py (from kirca/odoo, license: agpl-3.0)\n\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import fields, osv\nfrom openerp.tools.translate import _\n\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT\nfrom openerp import SUPERUSER_ID\nfrom dateutil.relativedelta import relativedelta\nfrom datetime import datetime\nimport openerp\n\nclass procurement_group(osv.osv):\n _inherit = 'procurement.group'\n _columns = {\n 'partner_id': fields.many2one('res.partner', 'Partner')\n }\n\nclass procurement_rule(osv.osv):\n _inherit = 'procurement.rule'\n\n def _get_action(self, cr, uid, context=None):\n result = super(procurement_rule, self)._get_action(cr, uid, context=context)\n return result + [('move', _('Move From Another Location'))]\n\n def _get_rules(self, cr, uid, ids, context=None):\n res = []\n for route in self.browse(cr, uid, ids):\n res += [x.id for x in route.pull_ids]\n return res\n\n _columns = {\n 'location_id': fields.many2one('stock.location', 'Procurement Location'),\n 'location_src_id': fields.many2one('stock.location', 'Source Location',\n help=\"Source location is action=move\"),\n 'route_id': fields.many2one('stock.location.route', 'Route',\n help=\"If route_id is False, the rule is global\"),\n 'procure_method': fields.selection([('make_to_stock', 'Take From Stock'), ('make_to_order', 'Create Procurement')], 'Move Supply Method', required=True, \n help=\"\"\"Determines the procurement method of the stock move that will be generated: whether it will need to 'take from the available stock' in its source location or needs to ignore its stock and create a procurement over there.\"\"\"),\n 'route_sequence': fields.related('route_id', 'sequence', string='Route Sequence',\n store={\n 'stock.location.route': (_get_rules, ['sequence'], 10),\n 'procurement.rule': (lambda self, cr, uid, ids, c={}: ids, ['route_id'], 10),\n }),\n 'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type',\n help=\"Picking Type determines the way the picking should be shown in the view, reports, ...\"),\n 'delay': fields.integer('Number of Days'),\n 'partner_address_id': fields.many2one('res.partner', 'Partner Address'),\n 'propagate': fields.boolean('Propagate cancel and split', help='If checked, when the previous move of the move (which was generated by a next procurement) is cancelled or split, the move generated by this move will too'),\n 'warehouse_id': fields.many2one('stock.warehouse', 'Served Warehouse', help='The warehouse this rule is for'),\n 'propagate_warehouse_id': fields.many2one('stock.warehouse', 'Warehouse to Propagate', help=\"The warehouse to propagate on the created move/procurement, which can be different of the warehouse this rule is for (e.g for resupplying rules from another warehouse)\"),\n }\n\n _defaults = {\n 'procure_method': 'make_to_stock',\n 'propagate': True,\n 'delay': 0,\n }\n\nclass procurement_order(osv.osv):\n _inherit = \"procurement.order\"\n _columns = {\n 'location_id': fields.many2one('stock.location', 'Procurement Location'), # not required because task may create procurements that aren't linked to a location with project_mrp\n 'partner_dest_id': fields.many2one('res.partner', 'Customer Address', help=\"In case of dropshipping, we need to know the destination address more precisely\"),\n 'move_ids': fields.one2many('stock.move', 'procurement_id', 'Moves', help=\"Moves created by the procurement\"),\n 'move_dest_id': fields.many2one('stock.move', 'Destination Move', help=\"Move which caused (created) the procurement\"),\n 'route_ids': fields.many2many('stock.location.route', 'stock_location_route_procurement', 'procurement_id', 'route_id', 'Preferred Routes', help=\"Preferred route to be followed by the procurement order. Usually copied from the generating document (SO) but could be set up manually.\"),\n 'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', help=\"Warehouse to consider for the route selection\"),\n 'orderpoint_id': fields.many2one('stock.warehouse.orderpoint', 'Minimum Stock Rule'),\n }\n\n def propagate_cancel(self, cr, uid, procurement, context=None):\n if procurement.rule_id.action == 'move' and procurement.move_ids:\n self.pool.get('stock.move').action_cancel(cr, uid, [m.id for m in procurement.move_ids], context=context)\n\n def cancel(self, cr, uid, ids, context=None):\n if context is None:\n context = {}\n to_cancel_ids = self.get_cancel_ids(cr, uid, ids, context=context)\n ctx = context.copy()\n #set the context for the propagation of the procurement cancelation\n ctx['cancel_procurement'] = True\n for procurement in self.browse(cr, uid, to_cancel_ids, context=ctx):\n self.propagate_cancel(cr, uid, procurement, context=ctx)\n return super(procurement_order, self).cancel(cr, uid, to_cancel_ids, context=ctx)\n\n def _find_parent_locations(self, cr, uid, procurement, context=None):\n location = procurement.location_id\n res = [location.id]\n while location.location_id:\n location = location.location_id\n res.append(location.id)\n return res\n\n def change_warehouse_id(self, cr, uid, ids, warehouse_id, context=None):\n if warehouse_id:\n warehouse = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context)\n return {'value': {'location_id': warehouse.lot_stock_id.id}}\n return {}\n\n def _search_suitable_rule(self, cr, uid, procurement, domain, context=None):\n '''we try to first find a rule among the ones defined on the procurement order group and if none is found, we try on the routes defined for the product, and finally we fallback on the default behavior'''\n pull_obj = self.pool.get('procurement.rule')\n warehouse_route_ids = []\n if procurement.warehouse_id:\n domain += ['|', ('warehouse_id', '=', procurement.warehouse_id.id), ('warehouse_id', '=', False)]\n warehouse_route_ids = [x.id for x in procurement.warehouse_id.route_ids]\n product_route_ids = [x.id for x in procurement.product_id.route_ids + procurement.product_id.categ_id.total_route_ids]\n procurement_route_ids = [x.id for x in procurement.route_ids]\n res = pull_obj.search(cr, uid, domain + [('route_id', 'in', procurement_route_ids)], order='route_sequence, sequence', context=context)\n if not res:\n res = pull_obj.search(cr, uid, domain + [('route_id', 'in', product_route_ids)], order='route_sequence, sequence', context=context)\n if not res:\n res = warehouse_route_ids and pull_obj.search(cr, uid, domain + [('route_id', 'in', warehouse_route_ids)], order='route_sequence, sequence', context=context) or []\n if not res:\n res = pull_obj.search(cr, uid, domain + [('route_id', '=', False)], order='sequence', context=context)\n return res\n\n def _find_suitable_rule(self, cr, uid, procurement, context=None):\n rule_id = super(procurement_order, self)._find_suitable_rule(cr, uid, procurement, context=context)\n if not rule_id:\n #a rule defined on 'Stock' is suitable for a procurement in 'Stock\\Bin A'\n all_parent_location_ids = self._find_parent_locations(cr, uid, procurement, context=context)\n rule_id = self._search_suitable_rule(cr, uid, procurement, [('location_id', 'in', all_parent_location_ids)], context=context)\n rule_id = rule_id and rule_id[0] or False\n return rule_id\n\n def _run_move_create(self, cr, uid, procurement, context=None):\n ''' Returns a dictionary of values that will be used to create a stock move from a procurement.\n This function assumes that the given procurement has a rule (action == 'move') set on it.\n\n :param procurement: browse record\n :rtype: dictionary\n '''\n newdate = (datetime.strptime(procurement.date_planned, '%Y-%m-%d %H:%M:%S') - relativedelta(days=procurement.rule_id.delay or 0)).strftime('%Y-%m-%d %H:%M:%S')\n group_id = False\n if procurement.rule_id.group_propagation_option == 'propagate':\n group_id = procurement.group_id and procurement.group_id.id or False\n elif procurement.rule_id.group_propagation_option == 'fixed':\n group_id = procurement.rule_id.group_id and procurement.rule_id.group_id.id or False\n #it is possible that we've already got some move done, so check for the done qty and create\n #a new move with the correct qty\n already_done_qty = 0\n already_done_qty_uos = 0\n for move in procurement.move_ids:\n already_done_qty += move.product_uom_qty if move.state == 'done' else 0\n already_done_qty_uos += move.product_uos_qty if move.state == 'done' else 0\n qty_left = max(procurement.product_qty - already_done_qty, 0)\n qty_uos_left = max(procurement.product_uos_qty - already_done_qty_uos, 0)\n vals = {\n 'name': procurement.name,\n 'company_id': procurement.rule_id.company_id.id or procurement.rule_id.location_src_id.company_id.id or procurement.rule_id.location_id.company_id.id or procurement.company_id.id,\n 'product_id': procurement.product_id.id,\n 'product_uom': procurement.product_uom.id,\n 'product_uom_qty': qty_left,\n 'product_uos_qty': (procurement.product_uos and qty_uos_left) or qty_left,\n 'product_uos': (procurement.product_uos and procurement.product_uos.id) or procurement.product_uom.id,\n 'partner_id': procurement.rule_id.partner_address_id.id or (procurement.group_id and procurement.group_id.partner_id.id) or False,\n 'location_id': procurement.rule_id.location_src_id.id,\n 'location_dest_id': procurement.rule_id.location_id.id,\n 'move_dest_id': procurement.move_dest_id and procurement.move_dest_id.id or False,\n 'procurement_id': procurement.id,\n 'rule_id': procurement.rule_id.id,\n 'procure_method': procurement.rule_id.procure_method,\n 'origin': procurement.origin,\n 'picking_type_id': procurement.rule_id.picking_type_id.id,\n 'group_id': group_id,\n 'route_ids': [(4, x.id) for x in procurement.route_ids],\n 'warehouse_id': procurement.rule_id.propagate_warehouse_id.id or procurement.rule_id.warehouse_id.id,\n 'date': newdate,\n 'date_expected': newdate,\n 'propagate': procurement.rule_id.propagate,\n }\n return vals\n\n def _run(self, cr, uid, procurement, context=None):\n if procurement.rule_id and procurement.rule_id.action == 'move':\n if not procurement.rule_id.location_src_id:\n self.message_post(cr, uid, [procurement.id], body=_('No source location defined!'), context=context)\n return False\n move_obj = self.pool.get('stock.move')\n move_dict = self._run_move_create(cr, uid, procurement, context=context)\n #create the move as SUPERUSER because the current user may not have the rights to do it (mto product launched by a sale for example)\n move_obj.create(cr, SUPERUSER_ID, move_dict, context=context)\n return True\n return super(procurement_order, self)._run(cr, uid, procurement, context=context)\n\n def run(self, cr, uid, ids, context=None):\n res = super(procurement_order, self).run(cr, uid, ids, context=context)\n #after all the procurements are run, check if some created a draft stock move that needs to be confirmed\n #(we do that in batch because it fasts the picking assignation and the picking state computation)\n move_to_confirm_ids = []\n for procurement in self.browse(cr, uid, ids, context=context):\n if procurement.state == \"running\" and procurement.rule_id and procurement.rule_id.action == \"move\":\n move_to_confirm_ids += [m.id for m in procurement.move_ids if m.state == 'draft']\n if move_to_confirm_ids:\n self.pool.get('stock.move').action_confirm(cr, uid, move_to_confirm_ids, context=context)\n return res\n\n def _check(self, cr, uid, procurement, context=None):\n ''' Implement the procurement checking for rules of type 'move'. The procurement will be satisfied only if all related\n moves are done/cancel and if the requested quantity is moved.\n '''\n if procurement.rule_id and procurement.rule_id.action == 'move':\n uom_obj = self.pool.get('product.uom')\n done_test_list = []\n done_cancel_test_list = []\n qty_done = 0\n for move in procurement.move_ids:\n done_test_list.append(move.state == 'done')\n done_cancel_test_list.append(move.state in ('done', 'cancel'))\n qty_done += move.product_qty if move.state == 'done' else 0\n qty_done = uom_obj._compute_qty(cr, uid, procurement.product_id.uom_id.id, qty_done, procurement.product_uom.id)\n at_least_one_done = any(done_test_list)\n all_done_or_cancel = all(done_cancel_test_list)\n if not all_done_or_cancel:\n return False\n elif all_done_or_cancel and procurement.product_qty == qty_done:\n return True\n elif at_least_one_done:\n #some move cancelled and some validated\n self.message_post(cr, uid, [procurement.id], body=_('Some stock moves have been cancelled for this procurement. Run the procurement again to trigger a move for the remaining quantity or change the procurement quantity to finish it directly'), context=context)\n else:\n #all move are cancelled\n self.message_post(cr, uid, [procurement.id], body=_('All stock moves have been cancelled for this procurement.'), context=context)\n self.write(cr, uid, [procurement.id], {'state': 'exception'}, context=context) \n return False\n\n return super(procurement_order, self)._check(cr, uid, procurement, context)\n\n def do_view_pickings(self, cr, uid, ids, context=None):\n '''\n This function returns an action that display the pickings of the procurements belonging\n to the same procurement group of given ids.\n '''\n mod_obj = self.pool.get('ir.model.data')\n act_obj = self.pool.get('ir.actions.act_window')\n result = mod_obj.get_object_reference(cr, uid, 'stock', 'do_view_pickings')\n id = result and result[1] or False\n result = act_obj.read(cr, uid, [id], context=context)[0]\n group_ids = set([proc.group_id.id for proc in self.browse(cr, uid, ids, context=context) if proc.group_id])\n result['domain'] = \"[('group_id','in',[\" + ','.join(map(str, list(group_ids))) + \"])]\"\n return result\n\n def run_scheduler(self, cr, uid, use_new_cursor=False, context=None):\n '''\n Call the scheduler in order to check the running procurements (super method), to check the minimum stock rules\n and the availability of moves. This function is intended to be run for all the companies at the same time, so\n we run functions as SUPERUSER to avoid intercompanies and access rights issues.\n\n @param self: The object pointer\n @param cr: The current row, from the database cursor,\n @param uid: The current user ID for security checks\n @param ids: List of selected IDs\n @param use_new_cursor: False or the dbname\n @param context: A standard dictionary for contextual values\n @return: Dictionary of values\n '''\n super(procurement_order, self).run_scheduler(cr, uid, use_new_cursor=use_new_cursor, context=context)\n if context is None:\n context = {}\n try:\n if use_new_cursor:\n cr = openerp.registry(use_new_cursor).cursor()\n\n move_obj = self.pool.get('stock.move')\n\n #Minimum stock rules\n company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id\n self._procure_orderpoint_confirm(cr, SUPERUSER_ID, use_new_cursor=False, company_id=company.id, context=context)\n\n #Search all confirmed stock_moves and try to assign them\n confirmed_ids = move_obj.search(cr, uid, [('state', '=', 'confirmed')], limit=None, order='picking_priority desc, date_expected asc', context=context)\n for x in xrange(0, len(confirmed_ids), 100):\n move_obj.action_assign(cr, uid, confirmed_ids[x:x + 100], context=context)\n if use_new_cursor:\n cr.commit()\n\n if use_new_cursor:\n cr.commit()\n finally:\n if use_new_cursor:\n try:\n cr.close()\n except Exception:\n pass\n return {}\n\n def _get_orderpoint_date_planned(self, cr, uid, orderpoint, start_date, context=None):\n date_planned = start_date\n return date_planned.strftime(DEFAULT_SERVER_DATE_FORMAT)\n\n def _prepare_orderpoint_procurement(self, cr, uid, orderpoint, product_qty, context=None):\n return {\n 'name': orderpoint.name,\n 'date_planned': self._get_orderpoint_date_planned(cr, uid, orderpoint, datetime.today(), context=context),\n 'product_id': orderpoint.product_id.id,\n 'product_qty': product_qty,\n 'company_id': orderpoint.company_id.id,\n 'product_uom': orderpoint.product_uom.id,\n 'location_id': orderpoint.location_id.id,\n 'origin': orderpoint.name,\n 'warehouse_id': orderpoint.warehouse_id.id,\n 'orderpoint_id': orderpoint.id,\n 'group_id': orderpoint.group_id.id,\n }\n\n def _product_virtual_get(self, cr, uid, order_point):\n product_obj = self.pool.get('product.product')\n return product_obj._product_available(cr, uid,\n [order_point.product_id.id],\n context={'location': order_point.location_id.id})[order_point.product_id.id]['virtual_available']\n\n def _procure_orderpoint_confirm(self, cr, uid, use_new_cursor=False, company_id=False, context=None):\n '''\n Create procurement based on Orderpoint\n use_new_cursor: False or the dbname\n\n @return: Dictionary of values\n \"\"\"\n '''\n if context is None:\n context = {}\n if use_new_cursor:\n cr = openerp.registry(use_new_cursor).db.cursor()\n orderpoint_obj = self.pool.get('stock.warehouse.orderpoint')\n\n procurement_obj = self.pool.get('procurement.order')\n offset = 0\n ids = [1]\n while ids:\n ids = orderpoint_obj.search(cr, uid, [('company_id', '=', company_id)], offset=offset, limit=100)\n for op in orderpoint_obj.browse(cr, uid, ids, context=context):\n prods = self._product_virtual_get(cr, uid, op)\n if prods is None:\n continue\n if prods < op.product_min_qty:\n qty = max(op.product_min_qty, op.product_max_qty) - prods\n\n reste = qty % op.qty_multiple\n if reste > 0:\n qty += op.qty_multiple - reste\n\n if qty <= 0:\n continue\n\n qty -= orderpoint_obj.subtract_procurements(cr, uid, op, context=context)\n\n if qty > 0:\n proc_id = procurement_obj.create(cr, uid,\n self._prepare_orderpoint_procurement(cr, uid, op, qty, context=context),\n context=context)\n self.check(cr, uid, [proc_id])\n self.run(cr, uid, [proc_id])\n offset += len(ids)\n if use_new_cursor:\n cr.commit()\n if use_new_cursor:\n cr.commit()\n cr.close()\n return {}"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_approximate.py from raghavrv/scikit-learn (path: sklearn/neighbors/tests/test_approximate.py)."}, {"role": "assistant", "content": "# sklearn/neighbors/tests/test_approximate.py (from raghavrv/scikit-learn, license: bsd-3-clause)\n\n\"\"\"\nTesting for the approximate neighbor search using\nLocality Sensitive Hashing Forest module\n(sklearn.neighbors.LSHForest).\n\"\"\"\n\n# Author: Maheshakya Wijewardena, Joel Nothman\n\nimport numpy as np\nimport scipy.sparse as sp\n\nfrom sklearn.utils.testing import assert_array_equal\nfrom sklearn.utils.testing import assert_almost_equal\nfrom sklearn.utils.testing import assert_array_almost_equal\nfrom sklearn.utils.testing import assert_equal\nfrom sklearn.utils.testing import assert_raises\nfrom sklearn.utils.testing import assert_array_less\nfrom sklearn.utils.testing import assert_greater\nfrom sklearn.utils.testing import assert_true\nfrom sklearn.utils.testing import assert_not_equal\nfrom sklearn.utils.testing import assert_warns_message\nfrom sklearn.utils.testing import ignore_warnings\n\nfrom sklearn.metrics.pairwise import pairwise_distances\nfrom sklearn.neighbors import LSHForest\nfrom sklearn.neighbors import NearestNeighbors\n\ndef test_lsh_forest_deprecation():\n assert_warns_message(DeprecationWarning,\n \"LSHForest has poor performance and has been \"\n \"deprecated in 0.19. It will be removed \"\n \"in version 0.21.\", LSHForest)\n\ndef test_neighbors_accuracy_with_n_candidates():\n # Checks whether accuracy increases as `n_candidates` increases.\n n_candidates_values = np.array([.1, 50, 500])\n n_samples = 100\n n_features = 10\n n_iter = 10\n n_points = 5\n rng = np.random.RandomState(42)\n accuracies = np.zeros(n_candidates_values.shape[0], dtype=float)\n X = rng.rand(n_samples, n_features)\n\n for i, n_candidates in enumerate(n_candidates_values):\n lshf = ignore_warnings(LSHForest, category=DeprecationWarning)(\n n_candidates=n_candidates)\n ignore_warnings(lshf.fit)(X)\n for j in range(n_iter):\n query = X[rng.randint(0, n_samples)].reshape(1, -1)\n\n neighbors = lshf.kneighbors(query, n_neighbors=n_points,\n return_distance=False)\n distances = pairwise_distances(query, X, metric='cosine')\n ranks = np.argsort(distances)[0, :n_points]\n\n intersection = np.intersect1d(ranks, neighbors).shape[0]\n ratio = intersection / float(n_points)\n accuracies[i] = accuracies[i] + ratio\n\n accuracies[i] = accuracies[i] / float(n_iter)\n # Sorted accuracies should be equal to original accuracies\n print('accuracies:', accuracies)\n assert_true(np.all(np.diff(accuracies) >= 0),\n msg=\"Accuracies are not non-decreasing.\")\n # Highest accuracy should be strictly greater than the lowest\n assert_true(np.ptp(accuracies) > 0,\n msg=\"Highest accuracy is not strictly greater than lowest.\")\n\ndef test_neighbors_accuracy_with_n_estimators():\n # Checks whether accuracy increases as `n_estimators` increases.\n n_estimators = np.array([1, 10, 100])\n n_samples = 100\n n_features = 10\n n_iter = 10\n n_points = 5\n rng = np.random.RandomState(42)\n accuracies = np.zeros(n_estimators.shape[0], dtype=float)\n X = rng.rand(n_samples, n_features)\n\n for i, t in enumerate(n_estimators):\n lshf = ignore_warnings(LSHForest, category=DeprecationWarning)(\n n_candidates=500, n_estimators=t)\n ignore_warnings(lshf.fit)(X)\n for j in range(n_iter):\n query = X[rng.randint(0, n_samples)].reshape(1, -1)\n neighbors = lshf.kneighbors(query, n_neighbors=n_points,\n return_distance=False)\n distances = pairwise_distances(query, X, metric='cosine')\n ranks = np.argsort(distances)[0, :n_points]\n\n intersection = np.intersect1d(ranks, neighbors).shape[0]\n ratio = intersection / float(n_points)\n accuracies[i] = accuracies[i] + ratio\n\n accuracies[i] = accuracies[i] / float(n_iter)\n # Sorted accuracies should be equal to original accuracies\n assert_true(np.all(np.diff(accuracies) >= 0),\n msg=\"Accuracies are not non-decreasing.\")\n # Highest accuracy should be strictly greater than the lowest\n assert_true(np.ptp(accuracies) > 0,\n msg=\"Highest accuracy is not strictly greater than lowest.\")\n\n@ignore_warnings\ndef test_kneighbors():\n # Checks whether desired number of neighbors are returned.\n # It is guaranteed to return the requested number of neighbors\n # if `min_hash_match` is set to 0. Returned distances should be\n # in ascending order.\n n_samples = 12\n n_features = 2\n n_iter = 10\n rng = np.random.RandomState(42)\n X = rng.rand(n_samples, n_features)\n\n lshf = ignore_warnings(LSHForest, category=DeprecationWarning)(\n min_hash_match=0)\n # Test unfitted estimator\n assert_raises(ValueError, lshf.kneighbors, X[0])\n\n ignore_warnings(lshf.fit)(X)\n\n for i in range(n_iter):\n n_neighbors = rng.randint(0, n_samples)\n query = X[rng.randint(0, n_samples)].reshape(1, -1)\n neighbors = lshf.kneighbors(query, n_neighbors=n_neighbors,\n return_distance=False)\n # Desired number of neighbors should be returned.\n assert_equal(neighbors.shape[1], n_neighbors)\n\n # Multiple points\n n_queries = 5\n queries = X[rng.randint(0, n_samples, n_queries)]\n distances, neighbors = lshf.kneighbors(queries,\n n_neighbors=1,\n return_distance=True)\n assert_equal(neighbors.shape[0], n_queries)\n assert_equal(distances.shape[0], n_queries)\n # Test only neighbors\n neighbors = lshf.kneighbors(queries, n_neighbors=1,\n return_distance=False)\n assert_equal(neighbors.shape[0], n_queries)\n # Test random point(not in the data set)\n query = rng.randn(n_features).reshape(1, -1)\n lshf.kneighbors(query, n_neighbors=1,\n return_distance=False)\n # Test n_neighbors at initialization\n neighbors = lshf.kneighbors(query, return_distance=False)\n assert_equal(neighbors.shape[1], 5)\n # Test `neighbors` has an integer dtype\n assert_true(neighbors.dtype.kind == 'i',\n msg=\"neighbors are not in integer dtype.\")\n\ndef test_radius_neighbors():\n # Checks whether Returned distances are less than `radius`\n # At least one point should be returned when the `radius` is set\n # to mean distance from the considering point to other points in\n # the database.\n # Moreover, this test compares the radius neighbors of LSHForest\n # with the `sklearn.neighbors.NearestNeighbors`.\n n_samples = 12\n n_features = 2\n n_iter = 10\n rng = np.random.RandomState(42)\n X = rng.rand(n_samples, n_features)\n\n lshf = ignore_warnings(LSHForest, category=DeprecationWarning)()\n # Test unfitted estimator\n assert_raises(ValueError, lshf.radius_neighbors, X[0])\n\n ignore_warnings(lshf.fit)(X)\n\n for i in range(n_iter):\n # Select a random point in the dataset as the query\n query = X[rng.randint(0, n_samples)].reshape(1, -1)\n\n # At least one neighbor should be returned when the radius is the\n # mean distance from the query to the points of the dataset.\n mean_dist = np.mean(pairwise_distances(query, X, metric='cosine'))\n neighbors = lshf.radius_neighbors(query, radius=mean_dist,\n return_distance=False)\n\n assert_equal(neighbors.shape, (1,))\n assert_equal(neighbors.dtype, object)\n assert_greater(neighbors[0].shape[0], 0)\n # All distances to points in the results of the radius query should\n # be less than mean_dist\n distances, neighbors = lshf.radius_neighbors(query,\n radius=mean_dist,\n return_distance=True)\n assert_array_less(distances[0], mean_dist)\n\n # Multiple points\n n_queries = 5\n queries = X[rng.randint(0, n_samples, n_queries)]\n distances, neighbors = lshf.radius_neighbors(queries,\n return_distance=True)\n\n # dists and inds should not be 1D arrays or arrays of variable lengths\n # hence the use of the object dtype.\n assert_equal(distances.shape, (n_queries,))\n assert_equal(distances.dtype, object)\n assert_equal(neighbors.shape, (n_queries,))\n assert_equal(neighbors.dtype, object)\n\n # Compare with exact neighbor search\n query = X[rng.randint(0, n_samples)].reshape(1, -1)\n mean_dist = np.mean(pairwise_distances(query, X, metric='cosine'))\n nbrs = NearestNeighbors(algorithm='brute', metric='cosine').fit(X)\n\n distances_exact, _ = nbrs.radius_neighbors(query, radius=mean_dist)\n distances_approx, _ = lshf.radius_neighbors(query, radius=mean_dist)\n\n # Radius-based queries do not sort the result points and the order\n # depends on the method, the random_state and the dataset order. Therefore\n # we need to sort the results ourselves before performing any comparison.\n sorted_dists_exact = np.sort(distances_exact[0])\n sorted_dists_approx = np.sort(distances_approx[0])\n\n # Distances to exact neighbors are less than or equal to approximate\n # counterparts as the approximate radius query might have missed some\n # closer neighbors.\n assert_true(np.all(np.less_equal(sorted_dists_exact,\n sorted_dists_approx)))\n\n@ignore_warnings\ndef test_radius_neighbors_boundary_handling():\n X = [[0.999, 0.001], [0.5, 0.5], [0, 1.], [-1., 0.001]]\n n_points = len(X)\n\n # Build an exact nearest neighbors model as reference model to ensure\n # consistency between exact and approximate methods\n nnbrs = NearestNeighbors(algorithm='brute', metric='cosine').fit(X)\n\n # Build a LSHForest model with hyperparameter values that always guarantee\n # exact results on this toy dataset.\n lsfh = ignore_warnings(LSHForest, category=DeprecationWarning)(\n min_hash_match=0, n_candidates=n_points, random_state=42).fit(X)\n\n # define a query aligned with the first axis\n query = [[1., 0.]]\n\n # Compute the exact cosine distances of the query to the four points of\n # the dataset\n dists = pairwise_distances(query, X, metric='cosine').ravel()\n\n # The first point is almost aligned with the query (very small angle),\n # the cosine distance should therefore be almost null:\n assert_almost_equal(dists[0], 0, decimal=5)\n\n # The second point form an angle of 45 degrees to the query vector\n assert_almost_equal(dists[1], 1 - np.cos(np.pi / 4))\n\n # The third point is orthogonal from the query vector hence at a distance\n # exactly one:\n assert_almost_equal(dists[2], 1)\n\n # The last point is almost colinear but with opposite sign to the query\n # therefore it has a cosine 'distance' very close to the maximum possible\n # value of 2.\n assert_almost_equal(dists[3], 2, decimal=5)\n\n # If we query with a radius of one, all the samples except the last sample\n # should be included in the results. This means that the third sample\n # is lying on the boundary of the radius query:\n exact_dists, exact_idx = nnbrs.radius_neighbors(query, radius=1)\n approx_dists, approx_idx = lsfh.radius_neighbors(query, radius=1)\n\n assert_array_equal(np.sort(exact_idx[0]), [0, 1, 2])\n assert_array_equal(np.sort(approx_idx[0]), [0, 1, 2])\n assert_array_almost_equal(np.sort(exact_dists[0]), dists[:-1])\n assert_array_almost_equal(np.sort(approx_dists[0]), dists[:-1])\n\n # If we perform the same query with a slightly lower radius, the third\n # point of the dataset that lay on the boundary of the previous query\n # is now rejected:\n eps = np.finfo(np.float64).eps\n exact_dists, exact_idx = nnbrs.radius_neighbors(query, radius=1 - eps)\n approx_dists, approx_idx = lsfh.radius_neighbors(query, radius=1 - eps)\n\n assert_array_equal(np.sort(exact_idx[0]), [0, 1])\n assert_array_equal(np.sort(approx_idx[0]), [0, 1])\n assert_array_almost_equal(np.sort(exact_dists[0]), dists[:-2])\n assert_array_almost_equal(np.sort(approx_dists[0]), dists[:-2])\n\ndef test_distances():\n # Checks whether returned neighbors are from closest to farthest.\n n_samples = 12\n n_features = 2\n n_iter = 10\n rng = np.random.RandomState(42)\n X = rng.rand(n_samples, n_features)\n\n lshf = ignore_warnings(LSHForest, category=DeprecationWarning)()\n ignore_warnings(lshf.fit)(X)\n\n for i in range(n_iter):\n n_neighbors = rng.randint(0, n_samples)\n query = X[rng.randint(0, n_samples)].reshape(1, -1)\n distances, neighbors = lshf.kneighbors(query,\n n_neighbors=n_neighbors,\n return_distance=True)\n\n # Returned neighbors should be from closest to farthest, that is\n # increasing distance values.\n assert_true(np.all(np.diff(distances[0]) >= 0))\n\n # Note: the radius_neighbors method does not guarantee the order of\n # the results.\n\ndef test_fit():\n # Checks whether `fit` method sets all attribute values correctly.\n n_samples = 12\n n_features = 2\n n_estimators = 5\n rng = np.random.RandomState(42)\n X = rng.rand(n_samples, n_features)\n\n lshf = ignore_warnings(LSHForest, category=DeprecationWarning)(\n n_estimators=n_estimators)\n ignore_warnings(lshf.fit)(X)\n\n # _input_array = X\n assert_array_equal(X, lshf._fit_X)\n # A hash function g(p) for each tree\n assert_equal(n_estimators, len(lshf.hash_functions_))\n # Hash length = 32\n assert_equal(32, lshf.hash_functions_[0].components_.shape[0])\n # Number of trees_ in the forest\n assert_equal(n_estimators, len(lshf.trees_))\n # Each tree has entries for every data point\n assert_equal(n_samples, len(lshf.trees_[0]))\n # Original indices after sorting the hashes\n assert_equal(n_estimators, len(lshf.original_indices_))\n # Each set of original indices in a tree has entries for every data point\n assert_equal(n_samples, len(lshf.original_indices_[0]))\n\ndef test_partial_fit():\n # Checks whether inserting array is consistent with fitted data.\n # `partial_fit` method should set all attribute values correctly.\n n_samples = 12\n n_samples_partial_fit = 3\n n_features = 2\n rng = np.random.RandomState(42)\n X = rng.rand(n_samples, n_features)\n X_partial_fit = rng.rand(n_samples_partial_fit, n_features)\n\n lshf = ignore_warnings(LSHForest, category=DeprecationWarning)()\n\n # Test unfitted estimator\n ignore_warnings(lshf.partial_fit)(X)\n assert_array_equal(X, lshf._fit_X)\n\n ignore_warnings(lshf.fit)(X)\n\n # Insert wrong dimension\n assert_raises(ValueError, lshf.partial_fit,\n np.random.randn(n_samples_partial_fit, n_features - 1))\n\n ignore_warnings(lshf.partial_fit)(X_partial_fit)\n\n # size of _input_array = samples + 1 after insertion\n assert_equal(lshf._fit_X.shape[0],\n n_samples + n_samples_partial_fit)\n # size of original_indices_[1] = samples + 1\n assert_equal(len(lshf.original_indices_[0]),\n n_samples + n_samples_partial_fit)\n # size of trees_[1] = samples + 1\n assert_equal(len(lshf.trees_[1]),\n n_samples + n_samples_partial_fit)\n\ndef test_hash_functions():\n # Checks randomness of hash functions.\n # Variance and mean of each hash function (projection vector)\n # should be different from flattened array of hash functions.\n # If hash functions are not randomly built (seeded with\n # same value), variances and means of all functions are equal.\n n_samples = 12\n n_features = 2\n n_estimators = 5\n rng = np.random.RandomState(42)\n X = rng.rand(n_samples, n_features)\n\n lshf = ignore_warnings(LSHForest, category=DeprecationWarning)(\n n_estimators=n_estimators,\n random_state=rng.randint(0, np.iinfo(np.int32).max))\n ignore_warnings(lshf.fit)(X)\n\n hash_functions = []\n for i in range(n_estimators):\n hash_functions.append(lshf.hash_functions_[i].components_)\n\n for i in range(n_estimators):\n assert_not_equal(np.var(hash_functions),\n np.var(lshf.hash_functions_[i].components_))\n\n for i in range(n_estimators):\n assert_not_equal(np.mean(hash_functions),\n np.mean(lshf.hash_functions_[i].components_))\n\ndef test_candidates():\n # Checks whether candidates are sufficient.\n # This should handle the cases when number of candidates is 0.\n # User should be warned when number of candidates is less than\n # requested number of neighbors.\n X_train = np.array([[5, 5, 2], [21, 5, 5], [1, 1, 1], [8, 9, 1],\n [6, 10, 2]], dtype=np.float32)\n X_test = np.array([7, 10, 3], dtype=np.float32).reshape(1, -1)\n\n # For zero candidates\n lshf = ignore_warnings(LSHForest, category=DeprecationWarning)(\n min_hash_match=32)\n ignore_warnings(lshf.fit)(X_train)\n\n message = (\"Number of candidates is not sufficient to retrieve\"\n \" %i neighbors with\"\n \" min_hash_match = %i. Candidates are filled up\"\n \" uniformly from unselected\"\n \" indices.\" % (3, 32))\n assert_warns_message(UserWarning, message, lshf.kneighbors,\n X_test, n_neighbors=3)\n distances, neighbors = lshf.kneighbors(X_test, n_neighbors=3)\n assert_equal(distances.shape[1], 3)\n\n # For candidates less than n_neighbors\n lshf = ignore_warnings(LSHForest, category=DeprecationWarning)(\n min_hash_match=31)\n ignore_warnings(lshf.fit)(X_train)\n\n message = (\"Number of candidates is not sufficient to retrieve\"\n \" %i neighbors with\"\n \" min_hash_match = %i. Candidates are filled up\"\n \" uniformly from unselected\"\n \" indices.\" % (5, 31))\n assert_warns_message(UserWarning, message, lshf.kneighbors,\n X_test, n_neighbors=5)\n distances, neighbors = lshf.kneighbors(X_test, n_neighbors=5)\n assert_equal(distances.shape[1], 5)\n\ndef test_graphs():\n # Smoke tests for graph methods.\n n_samples_sizes = [5, 10, 20]\n n_features = 3\n rng = np.random.RandomState(42)\n\n for n_samples in n_samples_sizes:\n X = rng.rand(n_samples, n_features)\n lshf = ignore_warnings(LSHForest, category=DeprecationWarning)(\n min_hash_match=0)\n ignore_warnings(lshf.fit)(X)\n\n kneighbors_graph = lshf.kneighbors_graph(X)\n radius_neighbors_graph = lshf.radius_neighbors_graph(X)\n\n assert_equal(kneighbors_graph.shape[0], n_samples)\n assert_equal(kneighbors_graph.shape[1], n_samples)\n assert_equal(radius_neighbors_graph.shape[0], n_samples)\n assert_equal(radius_neighbors_graph.shape[1], n_samples)\n\ndef test_sparse_input():\n # note: Fixed random state in sp.rand is not supported in older scipy.\n # The test should succeed regardless.\n X1 = sp.rand(50, 100)\n X2 = sp.rand(10, 100)\n forest_sparse = ignore_warnings(LSHForest, category=DeprecationWarning)(\n radius=1, random_state=0).fit(X1)\n forest_dense = ignore_warnings(LSHForest, category=DeprecationWarning)(\n radius=1, random_state=0).fit(X1.A)\n\n d_sparse, i_sparse = forest_sparse.kneighbors(X2, return_distance=True)\n d_dense, i_dense = forest_dense.kneighbors(X2.A, return_distance=True)\n\n assert_almost_equal(d_sparse, d_dense)\n assert_almost_equal(i_sparse, i_dense)\n\n d_sparse, i_sparse = forest_sparse.radius_neighbors(X2,\n return_distance=True)\n d_dense, i_dense = forest_dense.radius_neighbors(X2.A,\n return_distance=True)\n assert_equal(d_sparse.shape, d_dense.shape)\n for a, b in zip(d_sparse, d_dense):\n assert_almost_equal(a, b)\n for a, b in zip(i_sparse, i_dense):\n assert_almost_equal(a, b)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements cp862.py from bhansa/fireball (path: pyvenv/Lib/encodings/cp862.py)."}, {"role": "assistant", "content": "# pyvenv/Lib/encodings/cp862.py (from bhansa/fireball, license: gpl-3.0)\n\n\"\"\" Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP862.TXT' with gencodec.py.\n\n\"\"\"#\"\n\nimport codecs\n\n### Codec APIs\n\nclass Codec(codecs.Codec):\n\n def encode(self,input,errors='strict'):\n return codecs.charmap_encode(input,errors,encoding_map)\n\n def decode(self,input,errors='strict'):\n return codecs.charmap_decode(input,errors,decoding_table)\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n def encode(self, input, final=False):\n return codecs.charmap_encode(input,self.errors,encoding_map)[0]\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n def decode(self, input, final=False):\n return codecs.charmap_decode(input,self.errors,decoding_table)[0]\n\nclass StreamWriter(Codec,codecs.StreamWriter):\n pass\n\nclass StreamReader(Codec,codecs.StreamReader):\n pass\n\n### encodings module API\n\ndef getregentry():\n return codecs.CodecInfo(\n name='cp862',\n encode=Codec().encode,\n decode=Codec().decode,\n incrementalencoder=IncrementalEncoder,\n incrementaldecoder=IncrementalDecoder,\n streamreader=StreamReader,\n streamwriter=StreamWriter,\n )\n\n### Decoding Map\n\ndecoding_map = codecs.make_identity_dict(range(256))\ndecoding_map.update({\n 0x0080: 0x05d0, # HEBREW LETTER ALEF\n 0x0081: 0x05d1, # HEBREW LETTER BET\n 0x0082: 0x05d2, # HEBREW LETTER GIMEL\n 0x0083: 0x05d3, # HEBREW LETTER DALET\n 0x0084: 0x05d4, # HEBREW LETTER HE\n 0x0085: 0x05d5, # HEBREW LETTER VAV\n 0x0086: 0x05d6, # HEBREW LETTER ZAYIN\n 0x0087: 0x05d7, # HEBREW LETTER HET\n 0x0088: 0x05d8, # HEBREW LETTER TET\n 0x0089: 0x05d9, # HEBREW LETTER YOD\n 0x008a: 0x05da, # HEBREW LETTER FINAL KAF\n 0x008b: 0x05db, # HEBREW LETTER KAF\n 0x008c: 0x05dc, # HEBREW LETTER LAMED\n 0x008d: 0x05dd, # HEBREW LETTER FINAL MEM\n 0x008e: 0x05de, # HEBREW LETTER MEM\n 0x008f: 0x05df, # HEBREW LETTER FINAL NUN\n 0x0090: 0x05e0, # HEBREW LETTER NUN\n 0x0091: 0x05e1, # HEBREW LETTER SAMEKH\n 0x0092: 0x05e2, # HEBREW LETTER AYIN\n 0x0093: 0x05e3, # HEBREW LETTER FINAL PE\n 0x0094: 0x05e4, # HEBREW LETTER PE\n 0x0095: 0x05e5, # HEBREW LETTER FINAL TSADI\n 0x0096: 0x05e6, # HEBREW LETTER TSADI\n 0x0097: 0x05e7, # HEBREW LETTER QOF\n 0x0098: 0x05e8, # HEBREW LETTER RESH\n 0x0099: 0x05e9, # HEBREW LETTER SHIN\n 0x009a: 0x05ea, # HEBREW LETTER TAV\n 0x009b: 0x00a2, # CENT SIGN\n 0x009c: 0x00a3, # POUND SIGN\n 0x009d: 0x00a5, # YEN SIGN\n 0x009e: 0x20a7, # PESETA SIGN\n 0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK\n 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE\n 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE\n 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE\n 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE\n 0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE\n 0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE\n 0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR\n 0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR\n 0x00a8: 0x00bf, # INVERTED QUESTION MARK\n 0x00a9: 0x2310, # REVERSED NOT SIGN\n 0x00aa: 0x00ac, # NOT SIGN\n 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF\n 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER\n 0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK\n 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK\n 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK\n 0x00b0: 0x2591, # LIGHT SHADE\n 0x00b1: 0x2592, # MEDIUM SHADE\n 0x00b2: 0x2593, # DARK SHADE\n 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL\n 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT\n 0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE\n 0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE\n 0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE\n 0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE\n 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT\n 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL\n 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT\n 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT\n 0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE\n 0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE\n 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT\n 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT\n 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL\n 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL\n 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT\n 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL\n 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL\n 0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE\n 0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE\n 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT\n 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT\n 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL\n 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL\n 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT\n 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL\n 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL\n 0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE\n 0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE\n 0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE\n 0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE\n 0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE\n 0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE\n 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE\n 0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE\n 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE\n 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE\n 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT\n 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT\n 0x00db: 0x2588, # FULL BLOCK\n 0x00dc: 0x2584, # LOWER HALF BLOCK\n 0x00dd: 0x258c, # LEFT HALF BLOCK\n 0x00de: 0x2590, # RIGHT HALF BLOCK\n 0x00df: 0x2580, # UPPER HALF BLOCK\n 0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA\n 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S (GERMAN)\n 0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA\n 0x00e3: 0x03c0, # GREEK SMALL LETTER PI\n 0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA\n 0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA\n 0x00e6: 0x00b5, # MICRO SIGN\n 0x00e7: 0x03c4, # GREEK SMALL LETTER TAU\n 0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI\n 0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA\n 0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA\n 0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA\n 0x00ec: 0x221e, # INFINITY\n 0x00ed: 0x03c6, # GREEK SMALL LETTER PHI\n 0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON\n 0x00ef: 0x2229, # INTERSECTION\n 0x00f0: 0x2261, # IDENTICAL TO\n 0x00f1: 0x00b1, # PLUS-MINUS SIGN\n 0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO\n 0x00f3: 0x2264, # LESS-THAN OR EQUAL TO\n 0x00f4: 0x2320, # TOP HALF INTEGRAL\n 0x00f5: 0x2321, # BOTTOM HALF INTEGRAL\n 0x00f6: 0x00f7, # DIVISION SIGN\n 0x00f7: 0x2248, # ALMOST EQUAL TO\n 0x00f8: 0x00b0, # DEGREE SIGN\n 0x00f9: 0x2219, # BULLET OPERATOR\n 0x00fa: 0x00b7, # MIDDLE DOT\n 0x00fb: 0x221a, # SQUARE ROOT\n 0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N\n 0x00fd: 0x00b2, # SUPERSCRIPT TWO\n 0x00fe: 0x25a0, # BLACK SQUARE\n 0x00ff: 0x00a0, # NO-BREAK SPACE\n})\n\n### Decoding Table\n\ndecoding_table = (\n '\\x00' # 0x0000 -> NULL\n '\\x01' # 0x0001 -> START OF HEADING\n '\\x02' # 0x0002 -> START OF TEXT\n '\\x03' # 0x0003 -> END OF TEXT\n '\\x04' # 0x0004 -> END OF TRANSMISSION\n '\\x05' # 0x0005 -> ENQUIRY\n '\\x06' # 0x0006 -> ACKNOWLEDGE\n '\\x07' # 0x0007 -> BELL\n '\\x08' # 0x0008 -> BACKSPACE\n '\\t' # 0x0009 -> HORIZONTAL TABULATION\n '\\n' # 0x000a -> LINE FEED\n '\\x0b' # 0x000b -> VERTICAL TABULATION\n '\\x0c' # 0x000c -> FORM FEED\n '\\r' # 0x000d -> CARRIAGE RETURN\n '\\x0e' # 0x000e -> SHIFT OUT\n '\\x0f' # 0x000f -> SHIFT IN\n '\\x10' # 0x0010 -> DATA LINK ESCAPE\n '\\x11' # 0x0011 -> DEVICE CONTROL ONE\n '\\x12' # 0x0012 -> DEVICE CONTROL TWO\n '\\x13' # 0x0013 -> DEVICE CONTROL THREE\n '\\x14' # 0x0014 -> DEVICE CONTROL FOUR\n '\\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE\n '\\x16' # 0x0016 -> SYNCHRONOUS IDLE\n '\\x17' # 0x0017 -> END OF TRANSMISSION BLOCK\n '\\x18' # 0x0018 -> CANCEL\n '\\x19' # 0x0019 -> END OF MEDIUM\n '\\x1a' # 0x001a -> SUBSTITUTE\n '\\x1b' # 0x001b -> ESCAPE\n '\\x1c' # 0x001c -> FILE SEPARATOR\n '\\x1d' # 0x001d -> GROUP SEPARATOR\n '\\x1e' # 0x001e -> RECORD SEPARATOR\n '\\x1f' # 0x001f -> UNIT SEPARATOR\n ' ' # 0x0020 -> SPACE\n '!' # 0x0021 -> EXCLAMATION MARK\n '\"' # 0x0022 -> QUOTATION MARK\n '#' # 0x0023 -> NUMBER SIGN\n '$' # 0x0024 -> DOLLAR SIGN\n '%' # 0x0025 -> PERCENT SIGN\n '&' # 0x0026 -> AMPERSAND\n \"'\" # 0x0027 -> APOSTROPHE\n '(' # 0x0028 -> LEFT PARENTHESIS\n ')' # 0x0029 -> RIGHT PARENTHESIS\n '*' # 0x002a -> ASTERISK\n '+' # 0x002b -> PLUS SIGN\n ',' # 0x002c -> COMMA\n '-' # 0x002d -> HYPHEN-MINUS\n '.' # 0x002e -> FULL STOP\n '/' # 0x002f -> SOLIDUS\n '0' # 0x0030 -> DIGIT ZERO\n '1' # 0x0031 -> DIGIT ONE\n '2' # 0x0032 -> DIGIT TWO\n '3' # 0x0033 -> DIGIT THREE\n '4' # 0x0034 -> DIGIT FOUR\n '5' # 0x0035 -> DIGIT FIVE\n '6' # 0x0036 -> DIGIT SIX\n '7' # 0x0037 -> DIGIT SEVEN\n '8' # 0x0038 -> DIGIT EIGHT\n '9' # 0x0039 -> DIGIT NINE\n ':' # 0x003a -> COLON\n ';' # 0x003b -> SEMICOLON\n '<' # 0x003c -> LESS-THAN SIGN\n '=' # 0x003d -> EQUALS SIGN\n '>' # 0x003e -> GREATER-THAN SIGN\n '?' # 0x003f -> QUESTION MARK\n '@' # 0x0040 -> COMMERCIAL AT\n 'A' # 0x0041 -> LATIN CAPITAL LETTER A\n 'B' # 0x0042 -> LATIN CAPITAL LETTER B\n 'C' # 0x0043 -> LATIN CAPITAL LETTER C\n 'D' # 0x0044 -> LATIN CAPITAL LETTER D\n 'E' # 0x0045 -> LATIN CAPITAL LETTER E\n 'F' # 0x0046 -> LATIN CAPITAL LETTER F\n 'G' # 0x0047 -> LATIN CAPITAL LETTER G\n 'H' # 0x0048 -> LATIN CAPITAL LETTER H\n 'I' # 0x0049 -> LATIN CAPITAL LETTER I\n 'J' # 0x004a -> LATIN CAPITAL LETTER J\n 'K' # 0x004b -> LATIN CAPITAL LETTER K\n 'L' # 0x004c -> LATIN CAPITAL LETTER L\n 'M' # 0x004d -> LATIN CAPITAL LETTER M\n 'N' # 0x004e -> LATIN CAPITAL LETTER N\n 'O' # 0x004f -> LATIN CAPITAL LETTER O\n 'P' # 0x0050 -> LATIN CAPITAL LETTER P\n 'Q' # 0x0051 -> LATIN CAPITAL LETTER Q\n 'R' # 0x0052 -> LATIN CAPITAL LETTER R\n 'S' # 0x0053 -> LATIN CAPITAL LETTER S\n 'T' # 0x0054 -> LATIN CAPITAL LETTER T\n 'U' # 0x0055 -> LATIN CAPITAL LETTER U\n 'V' # 0x0056 -> LATIN CAPITAL LETTER V\n 'W' # 0x0057 -> LATIN CAPITAL LETTER W\n 'X' # 0x0058 -> LATIN CAPITAL LETTER X\n 'Y' # 0x0059 -> LATIN CAPITAL LETTER Y\n 'Z' # 0x005a -> LATIN CAPITAL LETTER Z\n '[' # 0x005b -> LEFT SQUARE BRACKET\n '\\\\' # 0x005c -> REVERSE SOLIDUS\n ']' # 0x005d -> RIGHT SQUARE BRACKET\n '^' # 0x005e -> CIRCUMFLEX ACCENT\n '_' # 0x005f -> LOW LINE\n '`' # 0x0060 -> GRAVE ACCENT\n 'a' # 0x0061 -> LATIN SMALL LETTER A\n 'b' # 0x0062 -> LATIN SMALL LETTER B\n 'c' # 0x0063 -> LATIN SMALL LETTER C\n 'd' # 0x0064 -> LATIN SMALL LETTER D\n 'e' # 0x0065 -> LATIN SMALL LETTER E\n 'f' # 0x0066 -> LATIN SMALL LETTER F\n 'g' # 0x0067 -> LATIN SMALL LETTER G\n 'h' # 0x0068 -> LATIN SMALL LETTER H\n 'i' # 0x0069 -> LATIN SMALL LETTER I\n 'j' # 0x006a -> LATIN SMALL LETTER J\n 'k' # 0x006b -> LATIN SMALL LETTER K\n 'l' # 0x006c -> LATIN SMALL LETTER L\n 'm' # 0x006d -> LATIN SMALL LETTER M\n 'n' # 0x006e -> LATIN SMALL LETTER N\n 'o' # 0x006f -> LATIN SMALL LETTER O\n 'p' # 0x0070 -> LATIN SMALL LETTER P\n 'q' # 0x0071 -> LATIN SMALL LETTER Q\n 'r' # 0x0072 -> LATIN SMALL LETTER R\n 's' # 0x0073 -> LATIN SMALL LETTER S\n 't' # 0x0074 -> LATIN SMALL LETTER T\n 'u' # 0x0075 -> LATIN SMALL LETTER U\n 'v' # 0x0076 -> LATIN SMALL LETTER V\n 'w' # 0x0077 -> LATIN SMALL LETTER W\n 'x' # 0x0078 -> LATIN SMALL LETTER X\n 'y' # 0x0079 -> LATIN SMALL LETTER Y\n 'z' # 0x007a -> LATIN SMALL LETTER Z\n '{' # 0x007b -> LEFT CURLY BRACKET\n '|' # 0x007c -> VERTICAL LINE\n '}' # 0x007d -> RIGHT CURLY BRACKET\n '~' # 0x007e -> TILDE\n '\\x7f' # 0x007f -> DELETE\n '\\u05d0' # 0x0080 -> HEBREW LETTER ALEF\n '\\u05d1' # 0x0081 -> HEBREW LETTER BET\n '\\u05d2' # 0x0082 -> HEBREW LETTER GIMEL\n '\\u05d3' # 0x0083 -> HEBREW LETTER DALET\n '\\u05d4' # 0x0084 -> HEBREW LETTER HE\n '\\u05d5' # 0x0085 -> HEBREW LETTER VAV\n '\\u05d6' # 0x0086 -> HEBREW LETTER ZAYIN\n '\\u05d7' # 0x0087 -> HEBREW LETTER HET\n '\\u05d8' # 0x0088 -> HEBREW LETTER TET\n '\\u05d9' # 0x0089 -> HEBREW LETTER YOD\n '\\u05da' # 0x008a -> HEBREW LETTER FINAL KAF\n '\\u05db' # 0x008b -> HEBREW LETTER KAF\n '\\u05dc' # 0x008c -> HEBREW LETTER LAMED\n '\\u05dd' # 0x008d -> HEBREW LETTER FINAL MEM\n '\\u05de' # 0x008e -> HEBREW LETTER MEM\n '\\u05df' # 0x008f -> HEBREW LETTER FINAL NUN\n '\\u05e0' # 0x0090 -> HEBREW LETTER NUN\n '\\u05e1' # 0x0091 -> HEBREW LETTER SAMEKH\n '\\u05e2' # 0x0092 -> HEBREW LETTER AYIN\n '\\u05e3' # 0x0093 -> HEBREW LETTER FINAL PE\n '\\u05e4' # 0x0094 -> HEBREW LETTER PE\n '\\u05e5' # 0x0095 -> HEBREW LETTER FINAL TSADI\n '\\u05e6' # 0x0096 -> HEBREW LETTER TSADI\n '\\u05e7' # 0x0097 -> HEBREW LETTER QOF\n '\\u05e8' # 0x0098 -> HEBREW LETTER RESH\n '\\u05e9' # 0x0099 -> HEBREW LETTER SHIN\n '\\u05ea' # 0x009a -> HEBREW LETTER TAV\n '\\xa2' # 0x009b -> CENT SIGN\n '\\xa3' # 0x009c -> POUND SIGN\n '\\xa5' # 0x009d -> YEN SIGN\n '\\u20a7' # 0x009e -> PESETA SIGN\n '\\u0192' # 0x009f -> LATIN SMALL LETTER F WITH HOOK\n '\\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE\n '\\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE\n '\\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE\n '\\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE\n '\\xf1' # 0x00a4 -> LATIN SMALL LETTER N WITH TILDE\n '\\xd1' # 0x00a5 -> LATIN CAPITAL LETTER N WITH TILDE\n '\\xaa' # 0x00a6 -> FEMININE ORDINAL INDICATOR\n '\\xba' # 0x00a7 -> MASCULINE ORDINAL INDICATOR\n '\\xbf' # 0x00a8 -> INVERTED QUESTION MARK\n '\\u2310' # 0x00a9 -> REVERSED NOT SIGN\n '\\xac' # 0x00aa -> NOT SIGN\n '\\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF\n '\\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER\n '\\xa1' # 0x00ad -> INVERTED EXCLAMATION MARK\n '\\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK\n '\\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK\n '\\u2591' # 0x00b0 -> LIGHT SHADE\n '\\u2592' # 0x00b1 -> MEDIUM SHADE\n '\\u2593' # 0x00b2 -> DARK SHADE\n '\\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL\n '\\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT\n '\\u2561' # 0x00b5 -> BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE\n '\\u2562' # 0x00b6 -> BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE\n '\\u2556' # 0x00b7 -> BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE\n '\\u2555' # 0x00b8 -> BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE\n '\\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT\n '\\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL\n '\\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT\n '\\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT\n '\\u255c' # 0x00bd -> BOX DRAWINGS UP DOUBLE AND LEFT SINGLE\n '\\u255b' # 0x00be -> BOX DRAWINGS UP SINGLE AND LEFT DOUBLE\n '\\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT\n '\\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT\n '\\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL\n '\\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL\n '\\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT\n '\\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL\n '\\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL\n '\\u255e' # 0x00c6 -> BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE\n '\\u255f' # 0x00c7 -> BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE\n '\\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT\n '\\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT\n '\\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL\n '\\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL\n '\\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT\n '\\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL\n '\\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL\n '\\u2567' # 0x00cf -> BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE\n '\\u2568' # 0x00d0 -> BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE\n '\\u2564' # 0x00d1 -> BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE\n '\\u2565' # 0x00d2 -> BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE\n '\\u2559' # 0x00d3 -> BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE\n '\\u2558' # 0x00d4 -> BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE\n '\\u2552' # 0x00d5 -> BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE\n '\\u2553' # 0x00d6 -> BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE\n '\\u256b' # 0x00d7 -> BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE\n '\\u256a' # 0x00d8 -> BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE\n '\\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT\n '\\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT\n '\\u2588' # 0x00db -> FULL BLOCK\n '\\u2584' # 0x00dc -> LOWER HALF BLOCK\n '\\u258c' # 0x00dd -> LEFT HALF BLOCK\n '\\u2590' # 0x00de -> RIGHT HALF BLOCK\n '\\u2580' # 0x00df -> UPPER HALF BLOCK\n '\\u03b1' # 0x00e0 -> GREEK SMALL LETTER ALPHA\n '\\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S (GERMAN)\n '\\u0393' # 0x00e2 -> GREEK CAPITAL LETTER GAMMA\n '\\u03c0' # 0x00e3 -> GREEK SMALL LETTER PI\n '\\u03a3' # 0x00e4 -> GREEK CAPITAL LETTER SIGMA\n '\\u03c3' # 0x00e5 -> GREEK SMALL LETTER SIGMA\n '\\xb5' # 0x00e6 -> MICRO SIGN\n '\\u03c4' # 0x00e7 -> GREEK SMALL LETTER TAU\n '\\u03a6' # 0x00e8 -> GREEK CAPITAL LETTER PHI\n '\\u0398' # 0x00e9 -> GREEK CAPITAL LETTER THETA\n '\\u03a9' # 0x00ea -> GREEK CAPITAL LETTER OMEGA\n '\\u03b4' # 0x00eb -> GREEK SMALL LETTER DELTA\n '\\u221e' # 0x00ec -> INFINITY\n '\\u03c6' # 0x00ed -> GREEK SMALL LETTER PHI\n '\\u03b5' # 0x00ee -> GREEK SMALL LETTER EPSILON\n '\\u2229' # 0x00ef -> INTERSECTION\n '\\u2261' # 0x00f0 -> IDENTICAL TO\n '\\xb1' # 0x00f1 -> PLUS-MINUS SIGN\n '\\u2265' # 0x00f2 -> GREATER-THAN OR EQUAL TO\n '\\u2264' # 0x00f3 -> LESS-THAN OR EQUAL TO\n '\\u2320' # 0x00f4 -> TOP HALF INTEGRAL\n '\\u2321' # 0x00f5 -> BOTTOM HALF INTEGRAL\n '\\xf7' # 0x00f6 -> DIVISION SIGN\n '\\u2248' # 0x00f7 -> ALMOST EQUAL TO\n '\\xb0' # 0x00f8 -> DEGREE SIGN\n '\\u2219' # 0x00f9 -> BULLET OPERATOR\n '\\xb7' # 0x00fa -> MIDDLE DOT\n '\\u221a' # 0x00fb -> SQUARE ROOT\n '\\u207f' # 0x00fc -> SUPERSCRIPT LATIN SMALL LETTER N\n '\\xb2' # 0x00fd -> SUPERSCRIPT TWO\n '\\u25a0' # 0x00fe -> BLACK SQUARE\n '\\xa0' # 0x00ff -> NO-BREAK SPACE\n)\n\n### Encoding Map\n\nencoding_map = {\n 0x0000: 0x0000, # NULL\n 0x0001: 0x0001, # START OF HEADING\n 0x0002: 0x0002, # START OF TEXT\n 0x0003: 0x0003, # END OF TEXT\n 0x0004: 0x0004, # END OF TRANSMISSION\n 0x0005: 0x0005, # ENQUIRY\n 0x0006: 0x0006, # ACKNOWLEDGE\n 0x0007: 0x0007, # BELL\n 0x0008: 0x0008, # BACKSPACE\n 0x0009: 0x0009, # HORIZONTAL TABULATION\n 0x000a: 0x000a, # LINE FEED\n 0x000b: 0x000b, # VERTICAL TABULATION\n 0x000c: 0x000c, # FORM FEED\n 0x000d: 0x000d, # CARRIAGE RETURN\n 0x000e: 0x000e, # SHIFT OUT\n 0x000f: 0x000f, # SHIFT IN\n 0x0010: 0x0010, # DATA LINK ESCAPE\n 0x0011: 0x0011, # DEVICE CONTROL ONE\n 0x0012: 0x0012, # DEVICE CONTROL TWO\n 0x0013: 0x0013, # DEVICE CONTROL THREE\n 0x0014: 0x0014, # DEVICE CONTROL FOUR\n 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE\n 0x0016: 0x0016, # SYNCHRONOUS IDLE\n 0x0017: 0x0017, # END OF TRANSMISSION BLOCK\n 0x0018: 0x0018, # CANCEL\n 0x0019: 0x0019, # END OF MEDIUM\n 0x001a: 0x001a, # SUBSTITUTE\n 0x001b: 0x001b, # ESCAPE\n 0x001c: 0x001c, # FILE SEPARATOR\n 0x001d: 0x001d, # GROUP SEPARATOR\n 0x001e: 0x001e, # RECORD SEPARATOR\n 0x001f: 0x001f, # UNIT SEPARATOR\n 0x0020: 0x0020, # SPACE\n 0x0021: 0x0021, # EXCLAMATION MARK\n 0x0022: 0x0022, # QUOTATION MARK\n 0x0023: 0x0023, # NUMBER SIGN\n 0x0024: 0x0024, # DOLLAR SIGN\n 0x0025: 0x0025, # PERCENT SIGN\n 0x0026: 0x0026, # AMPERSAND\n 0x0027: 0x0027, # APOSTROPHE\n 0x0028: 0x0028, # LEFT PARENTHESIS\n 0x0029: 0x0029, # RIGHT PARENTHESIS\n 0x002a: 0x002a, # ASTERISK\n 0x002b: 0x002b, # PLUS SIGN\n 0x002c: 0x002c, # COMMA\n 0x002d: 0x002d, # HYPHEN-MINUS\n 0x002e: 0x002e, # FULL STOP\n 0x002f: 0x002f, # SOLIDUS\n 0x0030: 0x0030, # DIGIT ZERO\n 0x0031: 0x0031, # DIGIT ONE\n 0x0032: 0x0032, # DIGIT TWO\n 0x0033: 0x0033, # DIGIT THREE\n 0x0034: 0x0034, # DIGIT FOUR\n 0x0035: 0x0035, # DIGIT FIVE\n 0x0036: 0x0036, # DIGIT SIX\n 0x0037: 0x0037, # DIGIT SEVEN\n 0x0038: 0x0038, # DIGIT EIGHT\n 0x0039: 0x0039, # DIGIT NINE\n 0x003a: 0x003a, # COLON\n 0x003b: 0x003b, # SEMICOLON\n 0x003c: 0x003c, # LESS-THAN SIGN\n 0x003d: 0x003d, # EQUALS SIGN\n 0x003e: 0x003e, # GREATER-THAN SIGN\n 0x003f: 0x003f, # QUESTION MARK\n 0x0040: 0x0040, # COMMERCIAL AT\n 0x0041: 0x0041, # LATIN CAPITAL LETTER A\n 0x0042: 0x0042, # LATIN CAPITAL LETTER B\n 0x0043: 0x0043, # LATIN CAPITAL LETTER C\n 0x0044: 0x0044, # LATIN CAPITAL LETTER D\n 0x0045: 0x0045, # LATIN CAPITAL LETTER E\n 0x0046: 0x0046, # LATIN CAPITAL LETTER F\n 0x0047: 0x0047, # LATIN CAPITAL LETTER G\n 0x0048: 0x0048, # LATIN CAPITAL LETTER H\n 0x0049: 0x0049, # LATIN CAPITAL LETTER I\n 0x004a: 0x004a, # LATIN CAPITAL LETTER J\n 0x004b: 0x004b, # LATIN CAPITAL LETTER K\n 0x004c: 0x004c, # LATIN CAPITAL LETTER L\n 0x004d: 0x004d, # LATIN CAPITAL LETTER M\n 0x004e: 0x004e, # LATIN CAPITAL LETTER N\n 0x004f: 0x004f, # LATIN CAPITAL LETTER O\n 0x0050: 0x0050, # LATIN CAPITAL LETTER P\n 0x0051: 0x0051, # LATIN CAPITAL LETTER Q\n 0x0052: 0x0052, # LATIN CAPITAL LETTER R\n 0x0053: 0x0053, # LATIN CAPITAL LETTER S\n 0x0054: 0x0054, # LATIN CAPITAL LETTER T\n 0x0055: 0x0055, # LATIN CAPITAL LETTER U\n 0x0056: 0x0056, # LATIN CAPITAL LETTER V\n 0x0057: 0x0057, # LATIN CAPITAL LETTER W\n 0x0058: 0x0058, # LATIN CAPITAL LETTER X\n 0x0059: 0x0059, # LATIN CAPITAL LETTER Y\n 0x005a: 0x005a, # LATIN CAPITAL LETTER Z\n 0x005b: 0x005b, # LEFT SQUARE BRACKET\n 0x005c: 0x005c, # REVERSE SOLIDUS\n 0x005d: 0x005d, # RIGHT SQUARE BRACKET\n 0x005e: 0x005e, # CIRCUMFLEX ACCENT\n 0x005f: 0x005f, # LOW LINE\n 0x0060: 0x0060, # GRAVE ACCENT\n 0x0061: 0x0061, # LATIN SMALL LETTER A\n 0x0062: 0x0062, # LATIN SMALL LETTER B\n 0x0063: 0x0063, # LATIN SMALL LETTER C\n 0x0064: 0x0064, # LATIN SMALL LETTER D\n 0x0065: 0x0065, # LATIN SMALL LETTER E\n 0x0066: 0x0066, # LATIN SMALL LETTER F\n 0x0067: 0x0067, # LATIN SMALL LETTER G\n 0x0068: 0x0068, # LATIN SMALL LETTER H\n 0x0069: 0x0069, # LATIN SMALL LETTER I\n 0x006a: 0x006a, # LATIN SMALL LETTER J\n 0x006b: 0x006b, # LATIN SMALL LETTER K\n 0x006c: 0x006c, # LATIN SMALL LETTER L\n 0x006d: 0x006d, # LATIN SMALL LETTER M\n 0x006e: 0x006e, # LATIN SMALL LETTER N\n 0x006f: 0x006f, # LATIN SMALL LETTER O\n 0x0070: 0x0070, # LATIN SMALL LETTER P\n 0x0071: 0x0071, # LATIN SMALL LETTER Q\n 0x0072: 0x0072, # LATIN SMALL LETTER R\n 0x0073: 0x0073, # LATIN SMALL LETTER S\n 0x0074: 0x0074, # LATIN SMALL LETTER T\n 0x0075: 0x0075, # LATIN SMALL LETTER U\n 0x0076: 0x0076, # LATIN SMALL LETTER V\n 0x0077: 0x0077, # LATIN SMALL LETTER W\n 0x0078: 0x0078, # LATIN SMALL LETTER X\n 0x0079: 0x0079, # LATIN SMALL LETTER Y\n 0x007a: 0x007a, # LATIN SMALL LETTER Z\n 0x007b: 0x007b, # LEFT CURLY BRACKET\n 0x007c: 0x007c, # VERTICAL LINE\n 0x007d: 0x007d, # RIGHT CURLY BRACKET\n 0x007e: 0x007e, # TILDE\n 0x007f: 0x007f, # DELETE\n 0x00a0: 0x00ff, # NO-BREAK SPACE\n 0x00a1: 0x00ad, # INVERTED EXCLAMATION MARK\n 0x00a2: 0x009b, # CENT SIGN\n 0x00a3: 0x009c, # POUND SIGN\n 0x00a5: 0x009d, # YEN SIGN\n 0x00aa: 0x00a6, # FEMININE ORDINAL INDICATOR\n 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK\n 0x00ac: 0x00aa, # NOT SIGN\n 0x00b0: 0x00f8, # DEGREE SIGN\n 0x00b1: 0x00f1, # PLUS-MINUS SIGN\n 0x00b2: 0x00fd, # SUPERSCRIPT TWO\n 0x00b5: 0x00e6, # MICRO SIGN\n 0x00b7: 0x00fa, # MIDDLE DOT\n 0x00ba: 0x00a7, # MASCULINE ORDINAL INDICATOR\n 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK\n 0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER\n 0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF\n 0x00bf: 0x00a8, # INVERTED QUESTION MARK\n 0x00d1: 0x00a5, # LATIN CAPITAL LETTER N WITH TILDE\n 0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S (GERMAN)\n 0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE\n 0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE\n 0x00f1: 0x00a4, # LATIN SMALL LETTER N WITH TILDE\n 0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE\n 0x00f7: 0x00f6, # DIVISION SIGN\n 0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE\n 0x0192: 0x009f, # LATIN SMALL LETTER F WITH HOOK\n 0x0393: 0x00e2, # GREEK CAPITAL LETTER GAMMA\n 0x0398: 0x00e9, # GREEK CAPITAL LETTER THETA\n 0x03a3: 0x00e4, # GREEK CAPITAL LETTER SIGMA\n 0x03a6: 0x00e8, # GREEK CAPITAL LETTER PHI\n 0x03a9: 0x00ea, # GREEK CAPITAL LETTER OMEGA\n 0x03b1: 0x00e0, # GREEK SMALL LETTER ALPHA\n 0x03b4: 0x00eb, # GREEK SMALL LETTER DELTA\n 0x03b5: 0x00ee, # GREEK SMALL LETTER EPSILON\n 0x03c0: 0x00e3, # GREEK SMALL LETTER PI\n 0x03c3: 0x00e5, # GREEK SMALL LETTER SIGMA\n 0x03c4: 0x00e7, # GREEK SMALL LETTER TAU\n 0x03c6: 0x00ed, # GREEK SMALL LETTER PHI\n 0x05d0: 0x0080, # HEBREW LETTER ALEF\n 0x05d1: 0x0081, # HEBREW LETTER BET\n 0x05d2: 0x0082, # HEBREW LETTER GIMEL\n 0x05d3: 0x0083, # HEBREW LETTER DALET\n 0x05d4: 0x0084, # HEBREW LETTER HE\n 0x05d5: 0x0085, # HEBREW LETTER VAV\n 0x05d6: 0x0086, # HEBREW LETTER ZAYIN\n 0x05d7: 0x0087, # HEBREW LETTER HET\n 0x05d8: 0x0088, # HEBREW LETTER TET\n 0x05d9: 0x0089, # HEBREW LETTER YOD\n 0x05da: 0x008a, # HEBREW LETTER FINAL KAF\n 0x05db: 0x008b, # HEBREW LETTER KAF\n 0x05dc: 0x008c, # HEBREW LETTER LAMED\n 0x05dd: 0x008d, # HEBREW LETTER FINAL MEM\n 0x05de: 0x008e, # HEBREW LETTER MEM\n 0x05df: 0x008f, # HEBREW LETTER FINAL NUN\n 0x05e0: 0x0090, # HEBREW LETTER NUN\n 0x05e1: 0x0091, # HEBREW LETTER SAMEKH\n 0x05e2: 0x0092, # HEBREW LETTER AYIN\n 0x05e3: 0x0093, # HEBREW LETTER FINAL PE\n 0x05e4: 0x0094, # HEBREW LETTER PE\n 0x05e5: 0x0095, # HEBREW LETTER FINAL TSADI\n 0x05e6: 0x0096, # HEBREW LETTER TSADI\n 0x05e7: 0x0097, # HEBREW LETTER QOF\n 0x05e8: 0x0098, # HEBREW LETTER RESH\n 0x05e9: 0x0099, # HEBREW LETTER SHIN\n 0x05ea: 0x009a, # HEBREW LETTER TAV\n 0x207f: 0x00fc, # SUPERSCRIPT LATIN SMALL LETTER N\n 0x20a7: 0x009e, # PESETA SIGN\n 0x2219: 0x00f9, # BULLET OPERATOR\n 0x221a: 0x00fb, # SQUARE ROOT\n 0x221e: 0x00ec, # INFINITY\n 0x2229: 0x00ef, # INTERSECTION\n 0x2248: 0x00f7, # ALMOST EQUAL TO\n 0x2261: 0x00f0, # IDENTICAL TO\n 0x2264: 0x00f3, # LESS-THAN OR EQUAL TO\n 0x2265: 0x00f2, # GREATER-THAN OR EQUAL TO\n 0x2310: 0x00a9, # REVERSED NOT SIGN\n 0x2320: 0x00f4, # TOP HALF INTEGRAL\n 0x2321: 0x00f5, # BOTTOM HALF INTEGRAL\n 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL\n 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL\n 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT\n 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT\n 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT\n 0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT\n 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT\n 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT\n 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL\n 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL\n 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL\n 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL\n 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL\n 0x2552: 0x00d5, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE\n 0x2553: 0x00d6, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE\n 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT\n 0x2555: 0x00b8, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE\n 0x2556: 0x00b7, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE\n 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT\n 0x2558: 0x00d4, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE\n 0x2559: 0x00d3, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE\n 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT\n 0x255b: 0x00be, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE\n 0x255c: 0x00bd, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE\n 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT\n 0x255e: 0x00c6, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE\n 0x255f: 0x00c7, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE\n 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT\n 0x2561: 0x00b5, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE\n 0x2562: 0x00b6, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE\n 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT\n 0x2564: 0x00d1, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE\n 0x2565: 0x00d2, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE\n 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL\n 0x2567: 0x00cf, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE\n 0x2568: 0x00d0, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE\n 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL\n 0x256a: 0x00d8, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE\n 0x256b: 0x00d7, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE\n 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL\n 0x2580: 0x00df, # UPPER HALF BLOCK\n 0x2584: 0x00dc, # LOWER HALF BLOCK\n 0x2588: 0x00db, # FULL BLOCK\n 0x258c: 0x00dd, # LEFT HALF BLOCK\n 0x2590: 0x00de, # RIGHT HALF BLOCK\n 0x2591: 0x00b0, # LIGHT SHADE\n 0x2592: 0x00b1, # MEDIUM SHADE\n 0x2593: 0x00b2, # DARK SHADE\n 0x25a0: 0x00fe, # BLACK SQUARE\n}"}]} {"messages": [{"role": "user", "content": "Write Python code that implements 0003_auto__add_developer__add_frontendimage__add_field_page_published__add_.py from hadronproject/HadronWeb (path: apps/frontend/migrations/0003_auto__add_developer__add_frontendimage__add_field_page_published__add_.py)."}, {"role": "assistant", "content": "# apps/frontend/migrations/0003_auto__add_developer__add_frontendimage__add_field_page_published__add_.py (from hadronproject/HadronWeb, license: gpl-3.0)\n\n# -*- coding: utf-8 -*-\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Adding model 'Developer'\n db.create_table('frontend_developer', (\n ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('name', self.gf('django.db.models.fields.CharField')(max_length=128)),\n ('lastname', self.gf('django.db.models.fields.CharField')(max_length=128)),\n ('alias', self.gf('django.db.models.fields.CharField')(max_length=128)),\n ('occupation', self.gf('django.db.models.fields.CharField')(max_length=512)),\n ('roles', self.gf('django.db.models.fields.CharField')(max_length=512)),\n ('website', self.gf('django.db.models.fields.URLField')(max_length=200, null=True)),\n ('interests', self.gf('django.db.models.fields.CharField')(max_length=512)),\n ('published', self.gf('django.db.models.fields.NullBooleanField')(null=True, blank=True)),\n ))\n db.send_create_signal('frontend', ['Developer'])\n\n # Adding model 'FrontendImage'\n db.create_table('frontend_frontendimage', (\n ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('developer', self.gf('django.db.models.fields.related.ForeignKey')(related_name='images', to=orm['frontend.Developer'])),\n ('image', self.gf('django.db.models.fields.files.ImageField')(max_length=100)),\n ))\n db.send_create_signal('frontend', ['FrontendImage'])\n\n # Adding field 'Page.published'\n db.add_column('frontend_page', 'published',\n self.gf('django.db.models.fields.NullBooleanField')(null=True, blank=True),\n keep_default=False)\n\n # Adding field 'News.published'\n db.add_column('frontend_news', 'published',\n self.gf('django.db.models.fields.NullBooleanField')(null=True, blank=True),\n keep_default=False)\n\n def backwards(self, orm):\n # Deleting model 'Developer'\n db.delete_table('frontend_developer')\n\n # Deleting model 'FrontendImage'\n db.delete_table('frontend_frontendimage')\n\n # Deleting field 'Page.published'\n db.delete_column('frontend_page', 'published')\n\n # Deleting field 'News.published'\n db.delete_column('frontend_news', 'published')\n\n models = {\n 'auth.group': {\n 'Meta': {'object_name': 'Group'},\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),\n 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['auth.Permission']\", 'symmetrical': 'False', 'blank': 'True'})\n },\n 'auth.permission': {\n 'Meta': {'ordering': \"('content_type__app_label', 'content_type__model', 'codename')\", 'unique_together': \"(('content_type', 'codename'),)\", 'object_name': 'Permission'},\n 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['contenttypes.ContentType']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})\n },\n 'auth.user': {\n 'Meta': {'object_name': 'User'},\n 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),\n 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),\n 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),\n 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['auth.Group']\", 'symmetrical': 'False', 'blank': 'True'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),\n 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),\n 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),\n 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),\n 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['auth.Permission']\", 'symmetrical': 'False', 'blank': 'True'}),\n 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})\n },\n 'contenttypes.contenttype': {\n 'Meta': {'ordering': \"('name',)\", 'unique_together': \"(('app_label', 'model'),)\", 'object_name': 'ContentType', 'db_table': \"'django_content_type'\"},\n 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})\n },\n 'frontend.developer': {\n 'Meta': {'ordering': \"['-id']\", 'object_name': 'Developer'},\n 'alias': ('django.db.models.fields.CharField', [], {'max_length': '128'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'interests': ('django.db.models.fields.CharField', [], {'max_length': '512'}),\n 'lastname': ('django.db.models.fields.CharField', [], {'max_length': '128'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}),\n 'occupation': ('django.db.models.fields.CharField', [], {'max_length': '512'}),\n 'published': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),\n 'roles': ('django.db.models.fields.CharField', [], {'max_length': '512'}),\n 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'})\n },\n 'frontend.frontendimage': {\n 'Meta': {'object_name': 'FrontendImage'},\n 'developer': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'images'\", 'to': \"orm['frontend.Developer']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'})\n },\n 'frontend.news': {\n 'Meta': {'ordering': \"['-id']\", 'object_name': 'News'},\n 'created_at': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),\n 'entry': ('django.db.models.fields.TextField', [], {}),\n 'entry_html': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'last_modified': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'blank': 'True'}),\n 'published': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),\n 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'blank': 'True'}),\n 'title': ('django.db.models.fields.CharField', [], {'max_length': '256'}),\n 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['auth.User']\"})\n },\n 'frontend.page': {\n 'Meta': {'ordering': \"['-id']\", 'object_name': 'Page'},\n 'created_at': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),\n 'entry': ('django.db.models.fields.TextField', [], {}),\n 'entry_html': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'published': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),\n 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'blank': 'True'}),\n 'title': ('django.db.models.fields.CharField', [], {'max_length': '256'}),\n 'updated_at': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'blank': 'True'}),\n 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['auth.User']\"})\n }\n }\n\n complete_apps = ['frontend']"}]} {"messages": [{"role": "user", "content": "Write Python code that implements order.py from madan96/sympy (path: sympy/series/order.py)."}, {"role": "assistant", "content": "# sympy/series/order.py (from madan96/sympy, license: bsd-3-clause)\n\nfrom __future__ import print_function, division\n\nfrom sympy.core import S, sympify, Expr, Rational, Symbol, Dummy\nfrom sympy.core import Add, Mul, expand_power_base, expand_log\nfrom sympy.core.cache import cacheit\nfrom sympy.core.compatibility import default_sort_key, is_sequence\nfrom sympy.core.containers import Tuple\nfrom sympy.utilities.iterables import uniq\nfrom sympy.sets.sets import Complement\n\nclass Order(Expr):\n r\"\"\" Represents the limiting behavior of some function\n\n The order of a function characterizes the function based on the limiting\n behavior of the function as it goes to some limit. Only taking the limit\n point to be a number is currently supported. This is expressed in\n big O notation [1]_.\n\n The formal definition for the order of a function `g(x)` about a point `a`\n is such that `g(x) = O(f(x))` as `x \\rightarrow a` if and only if for any\n `\\delta > 0` there exists a `M > 0` such that `|g(x)| \\leq M|f(x)|` for\n `|x-a| < \\delta`. This is equivalent to `\\lim_{x \\rightarrow a}\n \\sup |g(x)/f(x)| < \\infty`.\n\n Let's illustrate it on the following example by taking the expansion of\n `\\sin(x)` about 0:\n\n .. math ::\n \\sin(x) = x - x^3/3! + O(x^5)\n\n where in this case `O(x^5) = x^5/5! - x^7/7! + \\cdots`. By the definition\n of `O`, for any `\\delta > 0` there is an `M` such that:\n\n .. math ::\n |x^5/5! - x^7/7! + ....| <= M|x^5| \\text{ for } |x| < \\delta\n\n or by the alternate definition:\n\n .. math ::\n \\lim_{x \\rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| < \\infty\n\n which surely is true, because\n\n .. math ::\n \\lim_{x \\rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| = 1/5!\n\n As it is usually used, the order of a function can be intuitively thought\n of representing all terms of powers greater than the one specified. For\n example, `O(x^3)` corresponds to any terms proportional to `x^3,\n x^4,\\ldots` and any higher power. For a polynomial, this leaves terms\n proportional to `x^2`, `x` and constants.\n\n Examples\n ========\n\n >>> from sympy import O, oo, cos, pi\n >>> from sympy.abc import x, y\n\n >>> O(x + x**2)\n O(x)\n >>> O(x + x**2, (x, 0))\n O(x)\n >>> O(x + x**2, (x, oo))\n O(x**2, (x, oo))\n\n >>> O(1 + x*y)\n O(1, x, y)\n >>> O(1 + x*y, (x, 0), (y, 0))\n O(1, x, y)\n >>> O(1 + x*y, (x, oo), (y, oo))\n O(x*y, (x, oo), (y, oo))\n\n >>> O(1) in O(1, x)\n True\n >>> O(1, x) in O(1)\n False\n >>> O(x) in O(1, x)\n True\n >>> O(x**2) in O(x)\n True\n\n >>> O(x)*x\n O(x**2)\n >>> O(x) - O(x)\n O(x)\n >>> O(cos(x))\n O(1)\n >>> O(cos(x), (x, pi/2))\n O(x - pi/2, (x, pi/2))\n\n References\n ==========\n\n .. [1] `Big O notation `_\n\n Notes\n =====\n\n In ``O(f(x), x)`` the expression ``f(x)`` is assumed to have a leading\n term. ``O(f(x), x)`` is automatically transformed to\n ``O(f(x).as_leading_term(x),x)``.\n\n ``O(expr*f(x), x)`` is ``O(f(x), x)``\n\n ``O(expr, x)`` is ``O(1)``\n\n ``O(0, x)`` is 0.\n\n Multivariate O is also supported:\n\n ``O(f(x, y), x, y)`` is transformed to\n ``O(f(x, y).as_leading_term(x,y).as_leading_term(y), x, y)``\n\n In the multivariate case, it is assumed the limits w.r.t. the various\n symbols commute.\n\n If no symbols are passed then all symbols in the expression are used\n and the limit point is assumed to be zero.\n\n \"\"\"\n\n is_Order = True\n\n __slots__ = []\n\n @cacheit\n def __new__(cls, expr, *args, **kwargs):\n expr = sympify(expr)\n\n if not args:\n if expr.is_Order:\n variables = expr.variables\n point = expr.point\n else:\n variables = list(expr.free_symbols)\n point = [S.Zero]*len(variables)\n else:\n args = list(args if is_sequence(args) else [args])\n variables, point = [], []\n if is_sequence(args[0]):\n for a in args:\n v, p = list(map(sympify, a))\n variables.append(v)\n point.append(p)\n else:\n variables = list(map(sympify, args))\n point = [S.Zero]*len(variables)\n\n if not all(v.is_Symbol for v in variables):\n raise TypeError('Variables are not symbols, got %s' % variables)\n\n if len(list(uniq(variables))) != len(variables):\n raise ValueError('Variables are supposed to be unique symbols, got %s' % variables)\n\n if expr.is_Order:\n expr_vp = dict(expr.args[1:])\n new_vp = dict(expr_vp)\n vp = dict(zip(variables, point))\n for v, p in vp.items():\n if v in new_vp.keys():\n if p != new_vp[v]:\n raise NotImplementedError(\n \"Mixing Order at different points is not supported.\")\n else:\n new_vp[v] = p\n if set(expr_vp.keys()) == set(new_vp.keys()):\n return expr\n else:\n variables = list(new_vp.keys())\n point = [new_vp[v] for v in variables]\n\n if expr is S.NaN:\n return S.NaN\n\n if any(x in p.free_symbols for x in variables for p in point):\n raise ValueError('Got %s as a point.' % point)\n\n if variables:\n if any(p != point[0] for p in point):\n raise NotImplementedError\n if point[0] is S.Infinity:\n s = {k: 1/Dummy() for k in variables}\n rs = {1/v: 1/k for k, v in s.items()}\n elif point[0] is not S.Zero:\n s = dict((k, Dummy() + point[0]) for k in variables)\n rs = dict((v - point[0], k - point[0]) for k, v in s.items())\n else:\n s = ()\n rs = ()\n\n expr = expr.subs(s)\n\n if expr.is_Add:\n from sympy import expand_multinomial\n expr = expand_multinomial(expr)\n\n if s:\n args = tuple([r[0] for r in rs.items()])\n else:\n args = tuple(variables)\n\n if len(variables) > 1:\n # XXX: better way? We need this expand() to\n # workaround e.g: expr = x*(x + y).\n # (x*(x + y)).as_leading_term(x, y) currently returns\n # x*y (wrong order term!). That's why we want to deal with\n # expand()'ed expr (handled in \"if expr.is_Add\" branch below).\n expr = expr.expand()\n\n if expr.is_Add:\n lst = expr.extract_leading_order(args)\n expr = Add(*[f.expr for (e, f) in lst])\n\n elif expr:\n expr = expr.as_leading_term(*args)\n expr = expr.as_independent(*args, as_Add=False)[1]\n\n expr = expand_power_base(expr)\n expr = expand_log(expr)\n\n if len(args) == 1:\n # The definition of O(f(x)) symbol explicitly stated that\n # the argument of f(x) is irrelevant. That's why we can\n # combine some power exponents (only \"on top\" of the\n # expression tree for f(x)), e.g.:\n # x**p * (-x)**q -> x**(p+q) for real p, q.\n x = args[0]\n margs = list(Mul.make_args(\n expr.as_independent(x, as_Add=False)[1]))\n\n for i, t in enumerate(margs):\n if t.is_Pow:\n b, q = t.args\n if b in (x, -x) and q.is_real and not q.has(x):\n margs[i] = x**q\n elif b.is_Pow and not b.exp.has(x):\n b, r = b.args\n if b in (x, -x) and r.is_real:\n margs[i] = x**(r*q)\n elif b.is_Mul and b.args[0] is S.NegativeOne:\n b = -b\n if b.is_Pow and not b.exp.has(x):\n b, r = b.args\n if b in (x, -x) and r.is_real:\n margs[i] = x**(r*q)\n\n expr = Mul(*margs)\n\n expr = expr.subs(rs)\n\n if expr is S.Zero:\n return expr\n\n if expr.is_Order:\n expr = expr.expr\n\n if not expr.has(*variables):\n expr = S.One\n\n # create Order instance:\n vp = dict(zip(variables, point))\n variables.sort(key=default_sort_key)\n point = [vp[v] for v in variables]\n args = (expr,) + Tuple(*zip(variables, point))\n obj = Expr.__new__(cls, *args)\n return obj\n\n def _eval_nseries(self, x, n, logx):\n return self\n\n @property\n def expr(self):\n return self.args[0]\n\n @property\n def variables(self):\n if self.args[1:]:\n return tuple(x[0] for x in self.args[1:])\n else:\n return ()\n\n @property\n def point(self):\n if self.args[1:]:\n return tuple(x[1] for x in self.args[1:])\n else:\n return ()\n\n @property\n def free_symbols(self):\n return self.expr.free_symbols | set(self.variables)\n\n def _eval_power(b, e):\n if e.is_Number and e.is_nonnegative:\n return b.func(b.expr ** e, *b.args[1:])\n if e == O(1):\n return b\n return\n\n def as_expr_variables(self, order_symbols):\n if order_symbols is None:\n order_symbols = self.args[1:]\n else:\n if not all(o[1] == order_symbols[0][1] for o in order_symbols) and \\\n not all(p == self.point[0] for p in self.point):\n raise NotImplementedError('Order at points other than 0 '\n 'or oo not supported, got %s as a point.' % point)\n if order_symbols and order_symbols[0][1] != self.point[0]:\n raise NotImplementedError(\n \"Multiplying Order at different points is not supported.\")\n order_symbols = dict(order_symbols)\n for s, p in dict(self.args[1:]).items():\n if s not in order_symbols.keys():\n order_symbols[s] = p\n order_symbols = sorted(order_symbols.items(), key=lambda x: default_sort_key(x[0]))\n return self.expr, tuple(order_symbols)\n\n def removeO(self):\n return S.Zero\n\n def getO(self):\n return self\n\n @cacheit\n def contains(self, expr):\n \"\"\"\n Return True if expr belongs to Order(self.expr, \\*self.variables).\n Return False if self belongs to expr.\n Return None if the inclusion relation cannot be determined\n (e.g. when self and expr have different symbols).\n \"\"\"\n from sympy import powsimp\n if expr is S.Zero:\n return True\n if expr is S.NaN:\n return False\n if expr.is_Order:\n if not all(p == expr.point[0] for p in expr.point) and \\\n not all(p == self.point[0] for p in self.point):\n raise NotImplementedError('Order at points other than 0 '\n 'or oo not supported, got %s as a point.' % point)\n else:\n # self and/or expr is O(1):\n if any(not p for p in [expr.point, self.point]):\n point = self.point + expr.point\n if point:\n point = point[0]\n else:\n point = S.Zero\n else:\n point = self.point[0]\n if expr.expr == self.expr:\n # O(1) + O(1), O(1) + O(1, x), etc.\n return all([x in self.args[1:] for x in expr.args[1:]])\n if expr.expr.is_Add:\n return all([self.contains(x) for x in expr.expr.args])\n if self.expr.is_Add:\n return any([self.func(x, *self.args[1:]).contains(expr)\n for x in self.expr.args])\n if self.variables and expr.variables:\n common_symbols = tuple(\n [s for s in self.variables if s in expr.variables])\n elif self.variables:\n common_symbols = self.variables\n else:\n common_symbols = expr.variables\n if not common_symbols:\n return None\n if (self.expr.is_Pow and self.expr.base.is_Symbol\n and self.expr.exp.is_positive):\n if expr.expr.is_Pow and self.expr.base == expr.expr.base:\n return not (self.expr.exp-expr.expr.exp).is_positive\n if expr.expr.is_Mul:\n for arg in expr.expr.args:\n if (arg.is_Pow and self.expr.base == arg.base\n and (expr.expr/arg).is_number):\n r = (self.expr.exp-arg.exp).is_positive\n if not (r is None):\n return not r\n r = None\n ratio = self.expr/expr.expr\n ratio = powsimp(ratio, deep=True, combine='exp')\n for s in common_symbols:\n l = ratio.limit(s, point)\n from sympy.series.limits import Limit\n if not isinstance(l, Limit):\n l = l != 0\n else:\n l = None\n if r is None:\n r = l\n else:\n if r != l:\n return\n return r\n if (self.expr.is_Pow and self.expr.base.is_Symbol\n and self.expr.exp.is_positive):\n if expr.is_Pow and self.expr.base == expr.base:\n return not (self.expr.exp-expr.exp).is_positive\n if expr.is_Mul:\n for arg in expr.args:\n if (arg.is_Pow and self.expr.base == arg.base\n and (expr/arg).is_number):\n r = (self.expr.exp-arg.exp).is_positive\n if not (r is None):\n return not r\n obj = self.func(expr, *self.args[1:])\n return self.contains(obj)\n\n def __contains__(self, other):\n result = self.contains(other)\n if result is None:\n raise TypeError('contains did not evaluate to a bool')\n return result\n\n def _eval_subs(self, old, new):\n if old in self.variables:\n newexpr = self.expr.subs(old, new)\n i = self.variables.index(old)\n newvars = list(self.variables)\n newpt = list(self.point)\n if new.is_Symbol:\n newvars[i] = new\n else:\n syms = new.free_symbols\n if len(syms) == 1 or old in syms:\n if old in syms:\n var = self.variables[i]\n else:\n var = syms.pop()\n # First, try to substitute self.point in the \"new\"\n # expr to see if this is a fixed point.\n # E.g. O(y).subs(y, sin(x))\n point = new.subs(var, self.point[i])\n if point != self.point[i]:\n from sympy.solvers.solveset import solveset\n d = Dummy()\n sol = solveset(old - new.subs(var, d), d)\n if isinstance(sol, Complement):\n e1 = sol.args[0]\n e2 = sol.args[1]\n sol = set(e1) - set(e2)\n res = [dict(zip((d, ), sol))]\n point = d.subs(res[0]).limit(old, self.point[i])\n newvars[i] = var\n newpt[i] = point\n elif old not in syms:\n del newvars[i], newpt[i]\n if not syms and new == self.point[i]:\n newvars.extend(syms)\n newpt.extend([S.Zero]*len(syms))\n else:\n return\n return Order(newexpr, *zip(newvars, newpt))\n\n def _eval_conjugate(self):\n expr = self.expr._eval_conjugate()\n if expr is not None:\n return self.func(expr, *self.args[1:])\n\n def _eval_derivative(self, x):\n return self.func(self.expr.diff(x), *self.args[1:]) or self\n\n def _eval_transpose(self):\n expr = self.expr._eval_transpose()\n if expr is not None:\n return self.func(expr, *self.args[1:])\n\n def _sage_(self):\n #XXX: SAGE doesn't have Order yet. Let's return 0 instead.\n return Rational(0)._sage_()\n\nO = Order"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test-perf-jsbeautifier.py from JumpLink/jade2html2jade (path: ThirdParty/js-beautify/python/jsbeautifier/tests/test-perf-jsbeautifier.py)."}, {"role": "assistant", "content": "# ThirdParty/js-beautify/python/jsbeautifier/tests/test-perf-jsbeautifier.py (from JumpLink/jade2html2jade, license: mit)\n\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport copy\nimport jsbeautifier\noptions = jsbeautifier.default_options()\noptions.wrap_line_length = 80\ndata = ''\ndata_min = ''\n\ndef beautifier_test_underscore():\n jsbeautifier.beautify(data, options)\n \ndef beautifier_test_underscore_min():\n jsbeautifier.beautify(data_min, options)\n\ndef report_perf(fn):\n import timeit\n iter = 50\n time = timeit.timeit(fn + \"()\", setup=\"from __main__ import \" + fn + \"; gc.enable()\", number=iter)\n print(fn + \": \" + str(iter/time) + \" cycles/sec\")\n \nif __name__ == '__main__':\n dirname = os.path.dirname(os.path.abspath(__file__))\n underscore_file = os.path.join(dirname, \"../../../\", \"test/underscore.js\")\n underscore_min_file = os.path.join(dirname, \"../../../\", \"test/underscore-min.js\")\n data = copy.copy(''.join(open(underscore_file).readlines()))\n data_min = copy.copy(''.join(open(underscore_min_file).readlines()))\n \n # warm up\n beautifier_test_underscore()\n beautifier_test_underscore_min()\n \n report_perf(\"beautifier_test_underscore\")\n report_perf(\"beautifier_test_underscore_min\")"}]} {"messages": [{"role": "user", "content": "Write Python code that implements internal.py from fifengine/fifengine (path: engine/python/fife/extensions/pychan/internal.py)."}, {"role": "assistant", "content": "# engine/python/fife/extensions/pychan/internal.py (from fifengine/fifengine, license: lgpl-2.1)\n\n# -*- coding: utf-8 -*-\n\n# ####################################################################\n# Copyright (C) 2005-2019 by the FIFE team\n# http://www.fifengine.net\n# This file is part of FIFE.\n#\n# FIFE is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n# ####################################################################\n\nfrom __future__ import absolute_import\nfrom builtins import str\nfrom builtins import map\nfrom builtins import object\nfrom .compat import fifechan, fife, in_fife\nfrom fife.extensions import fife_timer as timer\nfrom . import fonts\nfrom .exceptions import *\nfrom traceback import print_exc\n\ndef get_manager():\n\t\"\"\"\n\tGet the manager from inside pychan.\n\n\tTo avoid cyclic imports write::\n\t from internal import get_manager\n\t\"\"\"\n\treturn Manager.manager\n\ndef screen_width():\n\treturn get_manager().hook.screen_width\n\ndef screen_height():\n\treturn get_manager().hook.screen_height\n\nclass Manager(object):\n\tmanager = None\n\n\tdef __init__(self, hook, debug = False, compat_layout = False):\n\t\tsuper(Manager,self).__init__()\n\t\tself.hook = hook\n\t\tself.debug = debug\n\t\tself.compat_layout = compat_layout\n\t\tself.unicodePolicy = ('ignore',)\n\n\t\tif in_fife:\n\t\t\tif not hook.engine.getEventManager():\n\t\t\t\traise InitializationError(\"No event manager installed.\")\n\t\t\tif not hook.guimanager:\n\t\t\t\traise InitializationError(\"No GUI manager installed.\")\n\t\ttimer.init(hook.engine.getTimeManager())\n\n\t\tself.fonts = {}\n\t\t#glyphs = ' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-+/:();%`\\'*#=[]\"'\n\t\tself.fonts['default'] = hook.default_font\n\n\t\tself.styles = {}\n\t\tself.addStyle('default',DEFAULT_STYLE)\n\n\t\tManager.manager = self\n\n\t\t# Setup synchronous dialogs\n\t\tself.mainLoop = None\n\t\tself.breakFromMainLoop = None\n\t\tself.can_execute = False\n\n\t\timport weakref\n\t\tself.allTopHierachyWidgets = weakref.WeakKeyDictionary()\n\n\t\tself.allWidgets = set()\n\n\t\t# Autopos\n\t\tfrom .autoposition import placeWidget\n\t\tself.placeWidget = placeWidget\n\n\tdef addWidget(self, widget):\n\t\t\"\"\"\n\t\tAdds Widget to the manager. So the manager \"owns\" the Widget.\n\t\tNote: As long as the wiget is in self.allWidgets the Python\n\t\tGC can not free it.\n\t\t\"\"\"\n\t\tif not widget._added:\n\t\t\twidget._added = True\n\t\t\tself.allWidgets.add(widget)\n\n\tdef removeWidget(self, widget):\n\t\t\"\"\"\n\t\tRemoves Widget from the manager.\n\t\tNote: As long as the wiget is in self.allWidgets the Python\n\t\tGC can not free it.\n\t\t\"\"\"\n\t\tif widget._added:\n\t\t\twidget._added = False\n\t\t\tself.allWidgets.remove(widget)\n\t\t\t\n\tdef setupModalExecution(self,mainLoop,breakFromMainLoop):\n\t\t\"\"\"\n\t\tSetup synchronous execution of dialogs.\n\t\t\"\"\"\n\t\tself.mainLoop = mainLoop\n\t\tself.breakFromMainLoop = breakFromMainLoop\n\t\tself.can_execute = True\n\n\tdef addTopWidget(self, widget):\n\t\t\"\"\"\n\t\tAdds a top hierachy widget to Fifechan and place it on the screen.\n\t\tUsed by L{Widget.show} - do not use directly.\n\t\t\"\"\"\n\t\tif not widget._top_added:\n\t\t\tassert widget not in self.allTopHierachyWidgets\n\t\t\twidget._top_added = True\n\t\t\tself.allTopHierachyWidgets[widget] = 1\n\t\t\tself.hook.add_widget(widget.real_widget)\n\n\tdef removeTopWidget(self, widget):\n\t\t\"\"\"\n\t\tRemoves a top hierachy widget from Fifechan.\n\t\tUsed by L{Widget.hide} - do not use directly.\n\t\t\"\"\"\n\t\tif widget._top_added:\n\t\t\tassert widget in self.allTopHierachyWidgets\n\t\t\twidget._top_added = False\n\t\t\tself.hook.remove_widget(widget.real_widget)\n\t\t\tdel self.allTopHierachyWidgets[widget]\n\n\tdef getConsole(self):\n\t\t\"\"\"\n\t\tGets a reference to the console\n\t\t\"\"\"\n\t\treturn self.hook.console\n\n\tdef getDefaultFont(self):\n\t\t\"\"\"\n\t\tReturns the default font\n\t\t\"\"\"\n\t\treturn self.fonts['default']\n\n\tdef setDefaultFont(self,name):\n\t\tself.fonts['default'] = self.getFont(name)\n\n\tdef getFont(self,name):\n\t\t\"\"\"\n\t\tB{pending deprecation}\n\n\t\tReturns a GuiFont identified by its name.\n\n\t\t@param name: A string identifier from the font definitions in pychans config files.\n\t\t\"\"\"\n\t\tif in_fife:\n\t\t\tfont = self.fonts.get(name)\n\t\t\tif isinstance(font,fife.GuiFont):\n\t\t\t\treturn font\n\t\t\tif hasattr(font,\"font\") and isinstance(getattr(font,\"font\"),fife.GuiFont):\n\t\t\t\treturn font.font\n\t\t\traise InitializationError(\"Couldn't find the font '%s'. Please load the xml file.\" % str(name))\n\t\telse:\n\t\t\treturn self.hook.get_font(name)\n\n\tdef createFont(self, path=\"\", size=0, glyphs=\"\"):\n\t\t\"\"\"\n\t\tCreates and returns a GuiFont from the GUI Manager\n\t\t\"\"\"\n\t\treturn self.hook.create_font(path,size,glyphs)\n\n\tdef releaseFont(self, font):\n\t\t\"\"\"\n\t\tReleases a font from memory. Expects a fifechan.GuiFont. \n\t\t\n\t\t@todo: This needs to be tested. Also should add a way to release\n\t\ta font by name (fonts.Font).\n\t\t\"\"\"\n\t\tif not isinstance(font,fifechan.GuiFont):\n\t\t\traise InitializationError(\"PyChan Manager expected a fifechan.GuiFont instance, not %s.\" % repr(font))\n\t\tself.hook.release_font(font)\n\n\tdef addFont(self,font):\n\t\t\"\"\"\n\t\tB{deprecated}\n\n\t\tAdd a font to the font registry. It's not necessary to call this directly.\n\t\tBut it expects a L{fonts.Font} instance and throws an L{InitializationError}\n\t\totherwise.\n\n\t\t@param font: A L{fonts.Font} instance.\n\t\t\"\"\"\n\t\tif not isinstance(font,fonts.Font):\n\t\t\traise InitializationError(\"PyChan Manager expected a fonts.Font instance, not %s.\" % repr(font))\n\t\tself.fonts[font.name] = font\n\n\tdef addStyle(self,name,style):\n\t\tstyle = self._remapStyleKeys(style)\n\n\t\tfor k,v in list(self.styles.get('default',{}).items()):\n\t\t\tstyle[k] = style.get(k,v)\n\t\tself.styles[name] = style\n\n\tdef stylize(self,widget, style, **kwargs):\n\t\tstyle = self.styles[style]\n\t\tfor k,v in list(style.get('default',{}).items()):\n\t\t\tv = kwargs.get(k,v)\n\t\t\tsetattr(widget,k,v)\n\n\t\tcls = widget.__class__\n\t\tfor applicable,specstyle in list(style.items()):\n\t\t\tif not isinstance(applicable,tuple):\n\t\t\t\tapplicable = (applicable,)\n\t\t\tif cls in applicable:\n\t\t\t\tfor k,v in list(specstyle.items()):\n\t\t\t\t\tv = kwargs.get(k,v)\n\t\t\t\t\tsetattr(widget,k,v)\n\n\tdef _remapStyleKeys(self,style):\n\t\t\"\"\"\n\t\tTranslate style selectors to tuples of widget classes. (internal)\n\t\t\"\"\"\n\t\t# Remap class names, create copy:\n\t\tdef _toClass(class_):\n\t\t\tfrom . import widgets\n\t\t\tif class_ == \"default\":\n\t\t\t\treturn class_\n\n\t\t\tif type(class_) == type(widgets.Widget) and issubclass(class_,widgets.Widget):\n\t\t\t\treturn class_\n\t\t\tif str(class_) not in widgets.WIDGETS:\n\t\t\t\traise InitializationError(\"Can't resolve %s to a widget class.\" % repr(class_))\n\t\t\treturn widgets.WIDGETS[str(class_)]\n\n\t\tstyle_copy = {}\n\t\tfor k,v in list(style.items()):\n\t\t\tif isinstance(k,tuple):\n\t\t\t\tnew_k = tuple(map(_toClass,k))\n\t\t\telse:\n\t\t\t\tnew_k = _toClass(k)\n\t\t\tstyle_copy[new_k] = v\n\t\treturn style_copy\n\n\tdef loadImage(self,filename,gui=True):\n\t\tif not filename:\n\t\t\t raise InitializationError(\"Empty Image file.\")\n\t\treturn self.hook.load_image(filename,gui)\n\n# Default Widget style.\n\nDEFAULT_STYLE = {\n\t'default' : {\n\t\t'border_size': 0,\n\t\t'margins': (0,0),\n\t\t'base_color' : fifechan.Color(28,28,28),\n\t\t'foreground_color' : fifechan.Color(255,255,255),\n\t\t'background_color' : fifechan.Color(50,50,50),\n\t\t'selection_color' : fifechan.Color(80,80,80),\n\t\t'font' : 'default'\n\t},\n\t'Button' : {\n\t\t'border_size': 2,\n\t\t'margins' : (5,2),\n\t\t'min_size' : (15,10),\n\t},\n\t'CheckBox' : {\n\t\t'border_size': 0,\n\t},\n\t'RadioButton' : {\n\t\t'border_size': 0,\n\t\t'background_color' : fifechan.Color(0,0,0),\n\t},\n\t'Label' : {\n\t\t'border_size': 0,\n\t\t'background_color' : fifechan.Color(50,50,50,0)\n\t},\n\t'ListBox' : {\n\t\t'border_size': 0,\n\t},\n\t'Window' : {\n\t\t'border_size': 0,\n\t\t'margins': (5,5),\n\t\t'opaque' : True,\n\t\t'padding':2,\n\t\t'titlebar_height' : 25,\n\t\t'background_image' : None,\n\t},\n\t'TextBox' : {\n\t},\n\t('Container','HBox','VBox') : {\n\t\t'border_size': 0,\n\t\t'margins': (0,0),\n\t\t'padding':2,\n\t\t'opaque' : True,\n\t\t'background_image' : None,\n\t}\n}"}]} {"messages": [{"role": "user", "content": "Write Python code that implements runall.py from ruibarreira/linuxtrail (path: usr/lib/python2.7/dist-packages/reportlab/graphics/samples/runall.py)."}, {"role": "assistant", "content": "# usr/lib/python2.7/dist-packages/reportlab/graphics/samples/runall.py (from ruibarreira/linuxtrail, license: gpl-3.0)\n\n# runs all the GUIedit charts in this directory -\n# makes a PDF sample for eaxh existing chart type\nimport sys\nimport glob\nimport inspect\nimport types\n\ndef moduleClasses(mod):\n def P(obj, m=mod.__name__, CT=type):\n return (type(obj)==CT and obj.__module__==m)\n try:\n return inspect.getmembers(mod, P)[0][1]\n except:\n return None\n\ndef getclass(f):\n return moduleClasses(__import__(f))\n\ndef run(format, VERBOSE=0):\n formats = format.split( ',')\n for i in range(0, len(formats)):\n formats[i] == formats[i].strip().lower()\n allfiles = glob.glob('*.py')\n allfiles.sort()\n for fn in allfiles:\n f = fn.split('.')[0]\n c = getclass(f)\n if c != None:\n print(c.__name__)\n try:\n for fmt in formats:\n if fmt:\n c().save(formats=[fmt],outDir='.',fnRoot=c.__name__)\n if VERBOSE:\n print(\" %s.%s\" % (c.__name__, fmt))\n except:\n print(\" COULDN'T CREATE '%s.%s'!\" % (c.__name__, format))\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 1:\n run('pdf,pict,png')\n else:\n try:\n if sys.argv[1] == \"-h\":\n print('usage: runall.py [FORMAT] [-h]')\n print(' if format is supplied is should be one or more of pdf,gif,eps,png etc')\n print(' if format is missing the following formats are assumed: pdf,pict,png')\n print(' -h prints this message')\n else:\n t = sys.argv[1:]\n for f in t:\n run(f)\n except:\n print('usage: runall.py [FORMAT][-h]')\n print(' if format is supplied is should be one or more of pdf,gif,eps,png etc')\n print(' if format is missing the following formats are assumed: pdf,pict,png')\n print(' -h prints this message')\n raise"}]} {"messages": [{"role": "user", "content": "Write Python code that implements bibtexml.py from oseledets/pybtex (path: pybtex/database/input/bibtexml.py)."}, {"role": "assistant", "content": "# pybtex/database/input/bibtexml.py (from oseledets/pybtex, license: mit)\n\n# Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Andrey Golovizin\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom xml.etree import cElementTree as ET\nfrom pybtex.database import Entry, Person\nfrom pybtex.database.input import BaseParser\n\nbibtexns = '{http://bibtexml.sf.net/}'\n\ndef remove_ns(s):\n if s.startswith(bibtexns):\n return s[len(bibtexns):]\n\nclass Parser(BaseParser):\n default_suffix = '.xml'\n\n def parse_stream(self, stream):\n t = ET.parse(stream)\n entries = t.findall(bibtexns + 'entry')\n self.data.add_entries(self.process_entry(entry) for entry in entries)\n return self.data\n\n def process_entry(self, entry):\n def process_person(person_entry, role):\n persons = person_entry.findall(bibtexns + 'person')\n if persons:\n for person in persons:\n process_person(person, role)\n else:\n text = person_entry.text.strip()\n if text:\n e.add_person(Person(text), role)\n else:\n names = {}\n for name in person_entry.getchildren():\n names[remove_ns(name.tag)] = name.text\n e.add_person(Person(**names), role)\n \n\n id_ = entry.get('id')\n item = entry.getchildren()[0]\n type = remove_ns(item.tag)\n e = Entry(type)\n for field in item.getchildren():\n field_name = remove_ns(field.tag)\n if field_name in Person.valid_roles:\n process_person(field, field_name)\n else:\n field_text = field.text if field.text is not None else ''\n e.fields[field_name] = field_text\n return id_, e"}]} {"messages": [{"role": "user", "content": "Write Python code that implements universaldetector.py from jpush/jbox (path: Server/venv/lib/python3.5/site-packages/pip/_vendor/requests/packages/chardet/universaldetector.py)."}, {"role": "assistant", "content": "# Server/venv/lib/python3.5/site-packages/pip/_vendor/requests/packages/chardet/universaldetector.py (from jpush/jbox, license: mit)\n\n######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Universal charset detector code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 2001\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n# Mark Pilgrim - port to Python\n# Shy Shalom - original C code\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301 USA\n######################### END LICENSE BLOCK #########################\n\nfrom . import constants\nimport sys\nimport codecs\nfrom .latin1prober import Latin1Prober # windows-1252\nfrom .mbcsgroupprober import MBCSGroupProber # multi-byte character sets\nfrom .sbcsgroupprober import SBCSGroupProber # single-byte character sets\nfrom .escprober import EscCharSetProber # ISO-2122, etc.\nimport re\n\nMINIMUM_THRESHOLD = 0.20\nePureAscii = 0\neEscAscii = 1\neHighbyte = 2\n\nclass UniversalDetector:\n def __init__(self):\n self._highBitDetector = re.compile(b'[\\x80-\\xFF]')\n self._escDetector = re.compile(b'(\\033|~{)')\n self._mEscCharSetProber = None\n self._mCharSetProbers = []\n self.reset()\n\n def reset(self):\n self.result = {'encoding': None, 'confidence': 0.0}\n self.done = False\n self._mStart = True\n self._mGotData = False\n self._mInputState = ePureAscii\n self._mLastChar = b''\n if self._mEscCharSetProber:\n self._mEscCharSetProber.reset()\n for prober in self._mCharSetProbers:\n prober.reset()\n\n def feed(self, aBuf):\n if self.done:\n return\n\n aLen = len(aBuf)\n if not aLen:\n return\n\n if not self._mGotData:\n # If the data starts with BOM, we know it is UTF\n if aBuf[:3] == codecs.BOM_UTF8:\n # EF BB BF UTF-8 with BOM\n self.result = {'encoding': \"UTF-8-SIG\", 'confidence': 1.0}\n elif aBuf[:4] == codecs.BOM_UTF32_LE:\n # FF FE 00 00 UTF-32, little-endian BOM\n self.result = {'encoding': \"UTF-32LE\", 'confidence': 1.0}\n elif aBuf[:4] == codecs.BOM_UTF32_BE:\n # 00 00 FE FF UTF-32, big-endian BOM\n self.result = {'encoding': \"UTF-32BE\", 'confidence': 1.0}\n elif aBuf[:4] == b'\\xFE\\xFF\\x00\\x00':\n # FE FF 00 00 UCS-4, unusual octet order BOM (3412)\n self.result = {\n 'encoding': \"X-ISO-10646-UCS-4-3412\",\n 'confidence': 1.0\n }\n elif aBuf[:4] == b'\\x00\\x00\\xFF\\xFE':\n # 00 00 FF FE UCS-4, unusual octet order BOM (2143)\n self.result = {\n 'encoding': \"X-ISO-10646-UCS-4-2143\",\n 'confidence': 1.0\n }\n elif aBuf[:2] == codecs.BOM_LE:\n # FF FE UTF-16, little endian BOM\n self.result = {'encoding': \"UTF-16LE\", 'confidence': 1.0}\n elif aBuf[:2] == codecs.BOM_BE:\n # FE FF UTF-16, big endian BOM\n self.result = {'encoding': \"UTF-16BE\", 'confidence': 1.0}\n\n self._mGotData = True\n if self.result['encoding'] and (self.result['confidence'] > 0.0):\n self.done = True\n return\n\n if self._mInputState == ePureAscii:\n if self._highBitDetector.search(aBuf):\n self._mInputState = eHighbyte\n elif ((self._mInputState == ePureAscii) and\n self._escDetector.search(self._mLastChar + aBuf)):\n self._mInputState = eEscAscii\n\n self._mLastChar = aBuf[-1:]\n\n if self._mInputState == eEscAscii:\n if not self._mEscCharSetProber:\n self._mEscCharSetProber = EscCharSetProber()\n if self._mEscCharSetProber.feed(aBuf) == constants.eFoundIt:\n self.result = {'encoding': self._mEscCharSetProber.get_charset_name(),\n 'confidence': self._mEscCharSetProber.get_confidence()}\n self.done = True\n elif self._mInputState == eHighbyte:\n if not self._mCharSetProbers:\n self._mCharSetProbers = [MBCSGroupProber(), SBCSGroupProber(),\n Latin1Prober()]\n for prober in self._mCharSetProbers:\n if prober.feed(aBuf) == constants.eFoundIt:\n self.result = {'encoding': prober.get_charset_name(),\n 'confidence': prober.get_confidence()}\n self.done = True\n break\n\n def close(self):\n if self.done:\n return\n if not self._mGotData:\n if constants._debug:\n sys.stderr.write('no data received!\\n')\n return\n self.done = True\n\n if self._mInputState == ePureAscii:\n self.result = {'encoding': 'ascii', 'confidence': 1.0}\n return self.result\n\n if self._mInputState == eHighbyte:\n proberConfidence = None\n maxProberConfidence = 0.0\n maxProber = None\n for prober in self._mCharSetProbers:\n if not prober:\n continue\n proberConfidence = prober.get_confidence()\n if proberConfidence > maxProberConfidence:\n maxProberConfidence = proberConfidence\n maxProber = prober\n if maxProber and (maxProberConfidence > MINIMUM_THRESHOLD):\n self.result = {'encoding': maxProber.get_charset_name(),\n 'confidence': maxProber.get_confidence()}\n return self.result\n\n if constants._debug:\n sys.stderr.write('no probers hit minimum threshhold\\n')\n for prober in self._mCharSetProbers[0].mProbers:\n if not prober:\n continue\n sys.stderr.write('%s confidence = %s\\n' %\n (prober.get_charset_name(),\n prober.get_confidence()))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test.py from azlanismail/prismgames (path: examples/games/car/networkx/tests/test.py)."}, {"role": "assistant", "content": "# examples/games/car/networkx/tests/test.py (from azlanismail/prismgames, license: gpl-2.0)\n\n#!/usr/bin/env python\nimport sys\nfrom os import path,getcwd\n\ndef run(verbosity=1,doctest=False,numpy=True):\n \"\"\"Run NetworkX tests.\n\n Parameters\n ----------\n verbosity: integer, optional\n Level of detail in test reports. Higher numbers provide more detail. \n\n doctest: bool, optional\n True to run doctests in code modules\n\n numpy: bool, optional\n True to test modules dependent on numpy\n \"\"\"\n try:\n import nose\n except ImportError:\n raise ImportError(\\\n \"The nose package is needed to run the NetworkX tests.\")\n\n sys.stderr.write(\"Running NetworkX tests:\")\n nx_install_dir=path.join(path.dirname(__file__), path.pardir)\n # stop if running from source directory\n if getcwd() == path.abspath(path.join(nx_install_dir,path.pardir)):\n raise RuntimeError(\"Can't run tests from source directory.\\n\"\n \"Run 'nosetests' from the command line.\")\n\n argv=[' ','--verbosity=%d'%verbosity,\n '-w',nx_install_dir,\n '-exe']\n if doctest:\n argv.extend(['--with-doctest','--doctest-extension=txt'])\n if not numpy:\n argv.extend(['-A not numpy'])\n\n nose.run(argv=argv)\n\nif __name__==\"__main__\":\n run()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements pushalot.py from patsissons/Flexget (path: flexget/plugins/output/pushalot.py)."}, {"role": "assistant", "content": "# flexget/plugins/output/pushalot.py (from patsissons/Flexget, license: mit)\n\nfrom __future__ import unicode_literals, division, absolute_import\nimport logging\n\nfrom flexget import plugin\nfrom flexget.event import event\nfrom flexget.utils import json\nfrom flexget.utils.template import RenderError\nfrom flexget.config_schema import one_or_more\n\nlog = logging.getLogger(\"pushalot\")\n\npushalot_url = \"https://pushalot.com/api/sendmessage\"\n\nclass OutputPushalot(object):\n \"\"\"\n Example::\n\n pushalot:\n token: Authorization token (can also be a list of tokens) - Required\n title: (default: task name -- accepts Jinja2)\n body: (default: \"{{series_name}} {{series_id}}\" -- accepts Jinja2)\n link: (default: \"{{imdb_url}}\" -- accepts Jinja2)\n linktitle: (default: (none) -- accepts Jinja2)\n important: (default is False)\n silent: (default: (none) -- accepts Jinja2)\n source: (default is \"FlexGet\")\n timetolive: (no default sent, default is set by Pushalot)\n\n Configuration parameters are also supported from entries (eg. through set).\n \"\"\"\n default_body = \"{% if series_name is defined %}{{tvdb_series_name|d(series_name)}} \" \\\n \"{{series_id}} {{tvdb_ep_name|d('')}}{% elif imdb_name is defined %}{{imdb_name}} \"\\\n \"{{imdb_year}}{% else %}{{title}}{% endif %}\"\n schema = {\n 'type': 'object',\n 'properties': {\n 'token': one_or_more({'type': 'string'}),\n 'title': {'type': 'string', 'default': \"Task {{task}}\"},\n 'body': {'type': 'string', 'default': default_body},\n 'link': {'type': 'string', 'default': '{% if imdb_url is defined %}{{imdb_url}}{% endif %}'},\n 'linktitle': {'type': 'string', 'default': ''},\n 'important': {'type': 'boolean', 'default': False},\n 'silent': {'type': 'boolean', 'default': False},\n 'image': {'type': 'string', 'default': ''},\n 'source': {'type': 'string', 'default': 'FlexGet'},\n 'timetolive': {'type': 'integer', 'default': 0},\n },\n 'required': ['token'],\n 'additionalProperties': False\n }\n\n # Run last to make sure other outputs are successful before sending notification\n @plugin.priority(0)\n def on_task_output(self, task, config):\n\n # Support for multiple tokens\n tokens = config[\"token\"]\n if not isinstance(tokens, list):\n tokens = [tokens]\n\n # Loop through the provided entries\n for entry in task.accepted:\n\n title = config[\"title\"]\n body = config[\"body\"]\n link = config[\"link\"]\n linktitle = config[\"linktitle\"]\n important = config[\"important\"]\n silent = config[\"silent\"]\n image = config[\"image\"]\n source = config[\"source\"]\n timetolive = config[\"timetolive\"] \n\n # Attempt to render the title field\n try:\n title = entry.render(title)\n except RenderError as e:\n log.warning(\"Problem rendering 'title': %s\" % e)\n title = \"Download started\"\n\n # Attempt to render the body field\n try:\n body = entry.render(body)\n except RenderError as e:\n log.warning(\"Problem rendering 'body': %s\" % e)\n body = entry[\"title\"]\n\n # Attempt to render the link field\n try:\n link = entry.render(link)\n except RenderError as e:\n log.warning(\"Problem rendering 'link': %s\" % e)\n link = entry.get(\"imdb_url\", \"\")\n\n # Attempt to render the linktitle field\n try:\n linktitle = entry.render(linktitle)\n except RenderError as e:\n log.warning(\"Problem rendering 'linktitle': %s\" % e)\n linktitle = \"\"\n\n try:\n image = entry.render(image)\n except RenderError as e:\n log.warning(\"Problem rendering 'image': %s\" % e)\n image = \"\"\n\n for token in tokens:\n # Build the request\n data = {\"AuthorizationToken\": token, \"title\": title, \"body\": body,\n \"link\": link, \"linktitle\": linktitle, \"important\": important,\n \"silent\": silent, \"image\": image, \"source\": source,\n \"timetolive\": timetolive}\n # Check for test mode\n if task.options.test:\n log.info(\"Test mode. Pushalot notification would be:\")\n log.info(\" Title: %s\" % title)\n log.info(\" body: %s\" % body)\n log.info(\" link: %s\" % link)\n log.info(\" link Title: %s\" % linktitle)\n log.info(\" token: %s\" % token)\n log.info(\" important: %s\" % important)\n log.info(\" silent: %s\" % silent)\n log.info(\" image: %s\" % image)\n log.info(\" source: %s\" % source)\n log.info(\" timetolive: %s\" % timetolive)\n # Test mode. Skip remainder.\n continue\n\n # Make the request\n response = task.requests.post(pushalot_url, data=data, raise_status=False)\n\n # Check if it succeeded\n request_status = response.status_code\n\n # error codes and bodys from Pushalot API\n if request_status == 200:\n log.debug(\"Pushalot notification sent\")\n elif request_status == 500:\n log.debug(\"Pushalot notification failed, Pushalot API having issues\")\n # TODO: Implement retrying. API requests 5 seconds between retries.\n elif request_status >= 400:\n errors = json.loads(response.content)\n log.error(\"Pushalot API error: %s\" % errors['Description'])\n else:\n log.error(\"Unknown error when sending Pushalot notification\")\n\n@event('plugin.register')\ndef register_plugin():\n plugin.register(OutputPushalot, \"pushalot\", api_ver=2)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements origin.py from aristotle-tek/cuny-bdif (path: AWS/ec2/lib/boto-2.34.0/boto/cloudfront/origin.py)."}, {"role": "assistant", "content": "# AWS/ec2/lib/boto-2.34.0/boto/cloudfront/origin.py (from aristotle-tek/cuny-bdif, license: mit)\n\n# Copyright (c) 2006-2010 Mitch Garnaat http://garnaat.org/\n# Copyright (c) 2010, Eucalyptus Systems, Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish, dis-\n# tribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the fol-\n# lowing conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-\n# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, \n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n\nfrom boto.cloudfront.identity import OriginAccessIdentity\n\ndef get_oai_value(origin_access_identity):\n if isinstance(origin_access_identity, OriginAccessIdentity):\n return origin_access_identity.uri()\n else:\n return origin_access_identity\n \nclass S3Origin(object):\n \"\"\"\n Origin information to associate with the distribution.\n If your distribution will use an Amazon S3 origin,\n then you use the S3Origin element.\n \"\"\"\n\n def __init__(self, dns_name=None, origin_access_identity=None):\n \"\"\"\n :param dns_name: The DNS name of your Amazon S3 bucket to\n associate with the distribution.\n For example: mybucket.s3.amazonaws.com.\n :type dns_name: str\n \n :param origin_access_identity: The CloudFront origin access\n identity to associate with the\n distribution. If you want the\n distribution to serve private content,\n include this element; if you want the\n distribution to serve public content,\n remove this element.\n :type origin_access_identity: str\n \n \"\"\"\n self.dns_name = dns_name\n self.origin_access_identity = origin_access_identity\n\n def __repr__(self):\n return '' % self.dns_name\n\n def startElement(self, name, attrs, connection):\n return None\n\n def endElement(self, name, value, connection):\n if name == 'DNSName':\n self.dns_name = value\n elif name == 'OriginAccessIdentity':\n self.origin_access_identity = value\n else:\n setattr(self, name, value)\n\n def to_xml(self):\n s = ' \\n'\n s += ' %s\\n' % self.dns_name\n if self.origin_access_identity:\n val = get_oai_value(self.origin_access_identity)\n s += ' %s\\n' % val\n s += ' \\n'\n return s\n \nclass CustomOrigin(object):\n \"\"\"\n Origin information to associate with the distribution.\n If your distribution will use a non-Amazon S3 origin,\n then you use the CustomOrigin element.\n \"\"\"\n\n def __init__(self, dns_name=None, http_port=80, https_port=443,\n origin_protocol_policy=None):\n \"\"\"\n :param dns_name: The DNS name of your Amazon S3 bucket to\n associate with the distribution.\n For example: mybucket.s3.amazonaws.com.\n :type dns_name: str\n \n :param http_port: The HTTP port the custom origin listens on.\n :type http_port: int\n \n :param https_port: The HTTPS port the custom origin listens on.\n :type http_port: int\n \n :param origin_protocol_policy: The origin protocol policy to\n apply to your origin. If you\n specify http-only, CloudFront\n will use HTTP only to access the origin.\n If you specify match-viewer, CloudFront\n will fetch from your origin using HTTP\n or HTTPS, based on the protocol of the\n viewer request.\n :type origin_protocol_policy: str\n \n \"\"\"\n self.dns_name = dns_name\n self.http_port = http_port\n self.https_port = https_port\n self.origin_protocol_policy = origin_protocol_policy\n\n def __repr__(self):\n return '' % self.dns_name\n\n def startElement(self, name, attrs, connection):\n return None\n\n def endElement(self, name, value, connection):\n if name == 'DNSName':\n self.dns_name = value\n elif name == 'HTTPPort':\n try:\n self.http_port = int(value)\n except ValueError:\n self.http_port = value\n elif name == 'HTTPSPort':\n try:\n self.https_port = int(value)\n except ValueError:\n self.https_port = value\n elif name == 'OriginProtocolPolicy':\n self.origin_protocol_policy = value\n else:\n setattr(self, name, value)\n\n def to_xml(self):\n s = ' \\n'\n s += ' %s\\n' % self.dns_name\n s += ' %d\\n' % self.http_port\n s += ' %d\\n' % self.https_port\n s += ' %s\\n' % self.origin_protocol_policy\n s += ' \\n'\n return s"}]} {"messages": [{"role": "user", "content": "Write Python code that implements backbone.py from ahmadia/bokeh (path: bokeh/server/views/backbone.py)."}, {"role": "assistant", "content": "# bokeh/server/views/backbone.py (from ahmadia/bokeh, license: bsd-3-clause)\n\nfrom __future__ import absolute_import\n\nimport logging\nlog = logging.getLogger(__name__)\n\nfrom flask import request, jsonify\n\nfrom bokeh import protocol\n\nfrom .bbauth import (\n handle_auth_error\n)\nfrom ..app import bokeh_app\nfrom ..crossdomain import crossdomain\nfrom ..serverbb import get_temporary_docid, BokehServerTransaction\nfrom ..views import make_json\nfrom ..models import docs\n\ndef init_bokeh(clientdoc):\n request.bokeh_server_document = clientdoc\n clientdoc.autostore = False\n clientdoc.autoadd = False\n\n@bokeh_app.route(\"/bokeh/bb//gc\", methods=['POST'])\n@handle_auth_error\ndef gc(docid):\n # client = request.headers.get('client', 'python') # todo: not used?\n doc = docs.Doc.load(bokeh_app.servermodel_storage, docid)\n bokehuser = bokeh_app.current_user()\n temporary_docid = get_temporary_docid(request, docid)\n t = BokehServerTransaction(\n bokehuser, doc, 'rw', temporary_docid=temporary_docid\n )\n t.load(gc=True)\n t.save()\n return jsonify(status='success')\n\n# bulk upsert\n@bokeh_app.route(\"/bokeh/bb//bulkupsert\", methods=['POST'])\n@handle_auth_error\ndef bulk_upsert(docid):\n ''' Update or insert new objects for a given :class:`Document `.\n\n :param docid: id of the :class:`Document `\n to update or insert into\n\n :status 200: when user is authorized\n :status 401: when user is not authorized\n\n '''\n # endpoint is only used by python, therefore we don't process\n # callbacks here\n client = request.headers.get('client', 'python')\n doc = docs.Doc.load(bokeh_app.servermodel_storage, docid)\n bokehuser = bokeh_app.current_user()\n temporary_docid = get_temporary_docid(request, docid)\n t = BokehServerTransaction(\n bokehuser, doc, 'rw', temporary_docid=temporary_docid\n )\n t.load()\n clientdoc = t.clientdoc\n data = protocol.deserialize_json(request.data.decode('utf-8'))\n if client == 'python':\n clientdoc.load(*data, events='none', dirty=True)\n else:\n clientdoc.load(*data, events='existing', dirty=True)\n t.save()\n msg = ws_update(clientdoc, t.write_docid, t.changed)\n return make_json(msg)\n\ndef ws_update(clientdoc, docid, models):\n log.debug(\"sending wsupdate to %s\", docid)\n attrs = clientdoc.dump(*models)\n msg = protocol.serialize_json({'msgtype' : 'modelpush',\n 'modelspecs' : attrs\n })\n bokeh_app.publisher.send(\"bokehplot:\" + docid, msg)\n return msg\n\ndef ws_delete(clientdoc, docid, models):\n attrs = clientdoc.dump(*models)\n msg = {\n 'msgtype' : 'modeldel',\n 'modelspecs' : attrs,\n }\n msg = protocol.serialize_json(msg)\n bokeh_app.wsmanager.send(\"bokehplot:\" + docid, msg)\n return msg\n\n# backbone functionality\n@bokeh_app.route(\"/bokeh/bb///\", methods=['POST'])\n@handle_auth_error\ndef create(docid, typename):\n ''' Update or insert new objects for a given :class:`Document `.\n\n :param docid: id of the :class:`Document `\n to update or insert into\n\n :status 200: when user is authorized\n :status 401: when user is not authorized\n\n '''\n doc = docs.Doc.load(bokeh_app.servermodel_storage, docid)\n bokehuser = bokeh_app.current_user()\n temporary_docid = get_temporary_docid(request, docid)\n t = BokehServerTransaction(\n bokehuser, doc, 'rw', temporary_docid=temporary_docid\n )\n t.load()\n modeldata = protocol.deserialize_json(request.data.decode('utf-8'))\n modeldata = [{'type' : typename,\n 'attributes' : modeldata}]\n t.clientdoc.load(*modeldata, dirty=True)\n t.save()\n ws_update(t.clientdoc, t.write_docid, modeldata)\n return protocol.serialize_json(modeldata[0]['attributes'])\n\n@handle_auth_error\ndef _bulkget(docid, typename=None):\n doc = docs.Doc.load(bokeh_app.servermodel_storage, docid)\n bokehuser = bokeh_app.current_user()\n temporary_docid = get_temporary_docid(request, docid)\n t = BokehServerTransaction(\n bokehuser, doc, 'r', temporary_docid=temporary_docid\n )\n t.load()\n clientdoc = t.clientdoc\n all_models = clientdoc._models.values()\n if typename is not None:\n attrs = clientdoc.dump(*[x for x in all_models \\\n if x.__view_model__==typename])\n attrs = [x['attributes'] for x in attrs]\n return make_json(protocol.serialize_json(attrs))\n else:\n attrs = clientdoc.dump(*all_models)\n return make_json(protocol.serialize_json(attrs))\n\n@bokeh_app.route(\"/bokeh/bb//\", methods=['GET'])\ndef bulkget_without_typename(docid):\n ''' Retrieve all objects for a given :class:`Document `.\n\n :param docid: id of the :class:`Document `\n to update or insert into\n\n :status 200: when user is authorized\n :status 401: when user is not authorized\n\n '''\n return _bulkget(docid)\n\n@bokeh_app.route(\"/bokeh/bb///\", methods=['GET'])\ndef bulkget_with_typename(docid, typename):\n ''' Retrieve all objects of a specified typename for a\n given :class:`Document `.\n\n :param docid: id of the :class:`Document `\n to update or insert into\n :param typename: the type of objects to find and return\n\n :status 200: when user is authorized\n :status 401: when user is not authorized\n\n '''\n return _bulkget(docid, typename)\n\n@crossdomain(origin=\"*\", methods=['PATCH', 'GET', 'PUT'], headers=None)\ndef _handle_specific_model(docid, typename, id, method):\n if method == 'PUT':\n return update(docid, typename, id)\n elif method == 'PATCH':\n return update(docid, typename, id)\n elif method == 'GET':\n return getbyid(docid, typename, id)\n elif method == 'DELETE':\n return delete(docid, typename, id)\n\n# route for working with individual models\n@bokeh_app.route(\"/bokeh/bb////\", methods=['GET', 'OPTIONS'])\ndef _handle_specific_model_get(docid, typename, id):\n ''' Retrieve a specific model with a given id and typename for a\n given :class:`Document `.\n\n :param docid: id of the :class:`Document `\n to update or insert into\n :param typename: the type of objects to find and return\n :param id: unique id of the object to retrieve\n\n :status 200: when user is authorized\n :status 401: when user is not authorized\n\n '''\n return _handle_specific_model(docid, typename, id, request.method)\n\n@bokeh_app.route(\"/bokeh/bb////\", methods=['PUT'])\ndef _handle_specific_model_put(docid, typename, id):\n ''' Update a specific model with a given id and typename for a\n given :class:`Document `.\n\n :param docid: id of the :class:`Document `\n to update or insert into\n :param typename: the type of objects to find and return\n :param id: unique id of the object to retrieve\n\n :status 200: when user is authorized\n :status 401: when user is not authorized\n\n '''\n return _handle_specific_model(docid, typename, id, request.method)\n\n@bokeh_app.route(\"/bokeh/bb////\", methods=['PATCH'])\ndef _handle_specific_model_patch(docid, typename, id):\n ''' Update a specific model with a given id and typename for a\n given :class:`Document `.\n\n :param docid: id of the :class:`Document `\n to update or insert into\n :param typename: the type of objects to find and return\n :param id: unique id of the object to retrieve\n\n :status 200: when user is authorized\n :status 401: when user is not authorized\n\n '''\n return _handle_specific_model(docid, typename, id, request.method)\n\n@bokeh_app.route(\"/bokeh/bb////\", methods=['DELETE'])\ndef _handle_specific_model_delete(docid, typename, id):\n ''' Delete a specific model with a given id and typename for a\n given :class:`Document `.\n\n :param docid: id of the :class:`Document `\n to update or insert into\n :param typename: the type of objects to find and return\n :param id: unique id of the object to retrieve\n\n :status 200: when user is authorized\n :status 401: when user is not authorized\n\n '''\n return _handle_specific_model(docid, typename, id, request.method)\n\n# individual model methods\n@handle_auth_error\ndef getbyid(docid, typename, id):\n doc = docs.Doc.load(bokeh_app.servermodel_storage, docid)\n bokehuser = bokeh_app.current_user()\n temporary_docid = get_temporary_docid(request, docid)\n t = BokehServerTransaction(\n bokehuser, doc, 'r', temporary_docid=temporary_docid\n )\n t.load()\n clientdoc = t.clientdoc\n attr = clientdoc.dump(clientdoc._models[id])[0]['attributes']\n return make_json(protocol.serialize_json(attr))\n\n@handle_auth_error\ndef update(docid, typename, id):\n \"\"\"we need to distinguish between writing and patching models\n namely in writing, we shouldn't remove unspecified attrs\n (we currently don't handle this correctly)\n \"\"\"\n doc = docs.Doc.load(bokeh_app.servermodel_storage, docid)\n bokehuser = bokeh_app.current_user()\n temporary_docid = get_temporary_docid(request, docid)\n t = BokehServerTransaction(\n bokehuser, doc, 'rw', temporary_docid=temporary_docid\n )\n t.load()\n modeldata = protocol.deserialize_json(request.data.decode('utf-8'))\n ### horrible hack, we need to pop off the noop object if it exists\n modeldata.pop('noop', None)\n clientdoc = t.clientdoc\n log.info(\"loading done %s\", len(clientdoc._models.values()))\n # patch id is not passed...\n modeldata['id'] = id\n modeldata = {'type' : typename,\n 'attributes' : modeldata}\n clientdoc.load(modeldata, events='existing', dirty=True)\n t.save()\n ws_update(clientdoc, t.write_docid, t.changed)\n # backbone expects us to send back attrs of this model, but it doesn't\n # make sense to do so because we modify other models, and we want this to\n # all go out over the websocket channel\n return make_json(protocol.serialize_json({'noop' : True}))\n\n@handle_auth_error\ndef delete(docid, typename, id):\n #I don't think this works right now\n obj = 'No this does not work, because obj is not defined, should it be an arg?'\n doc = docs.Doc.load(bokeh_app.servermodel_storage, docid)\n bokehuser = bokeh_app.current_user()\n temporary_docid = get_temporary_docid(request, docid)\n t = BokehServerTransaction(\n bokehuser, doc, 'rw', temporary_docid=temporary_docid\n )\n clientdoc = t.clientdoc\n model = clientdoc._models[id]\n bokeh_app.backbone_storage.del_obj(t.write_docid, obj)\n t.save()\n ws_delete(clientdoc, t.write_docid, [model])\n return make_json(protocol.serialize_json(clientdoc.dump(model)[0]['attributes']))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements oc_serviceaccount_secret.py from rhdedgar/openshift-tools (path: openshift/installer/vendored/openshift-ansible-3.6.173/roles/lib_openshift/src/class/oc_serviceaccount_secret.py)."}, {"role": "assistant", "content": "# openshift/installer/vendored/openshift-ansible-3.6.173/roles/lib_openshift/src/class/oc_serviceaccount_secret.py (from rhdedgar/openshift-tools, license: apache-2.0)\n\n# pylint: skip-file\n# flake8: noqa\n\nclass OCServiceAccountSecret(OpenShiftCLI):\n ''' Class to wrap the oc command line tools '''\n\n kind = 'sa'\n def __init__(self, config, verbose=False):\n ''' Constructor for OpenshiftOC '''\n super(OCServiceAccountSecret, self).__init__(config.namespace, kubeconfig=config.kubeconfig, verbose=verbose)\n self.config = config\n self.verbose = verbose\n self._service_account = None\n\n @property\n def service_account(self):\n ''' Property for the service account '''\n if not self._service_account:\n self.get()\n return self._service_account\n\n @service_account.setter\n def service_account(self, data):\n ''' setter for the service account '''\n self._service_account = data\n\n def exists(self, in_secret):\n ''' verifies if secret exists in the service account '''\n result = self.service_account.find_secret(in_secret)\n if not result:\n return False\n return True\n\n def get(self):\n ''' get the service account definition from the master '''\n sao = self._get(OCServiceAccountSecret.kind, self.config.name)\n if sao['returncode'] == 0:\n self.service_account = ServiceAccount(content=sao['results'][0])\n sao['results'] = self.service_account.get('secrets')\n return sao\n\n def delete(self):\n ''' delete secrets '''\n\n modified = []\n for rem_secret in self.config.secrets:\n modified.append(self.service_account.delete_secret(rem_secret))\n\n if any(modified):\n return self._replace_content(OCServiceAccountSecret.kind, self.config.name, self.service_account.yaml_dict)\n\n return {'returncode': 0, 'changed': False}\n\n def put(self):\n ''' place secrets into sa '''\n modified = False\n for add_secret in self.config.secrets:\n if not self.service_account.find_secret(add_secret):\n self.service_account.add_secret(add_secret)\n modified = True\n\n if modified:\n return self._replace_content(OCServiceAccountSecret.kind, self.config.name, self.service_account.yaml_dict)\n\n return {'returncode': 0, 'changed': False}\n\n @staticmethod\n # pylint: disable=too-many-return-statements,too-many-branches\n # TODO: This function should be refactored into its individual parts.\n def run_ansible(params, check_mode):\n ''' run the ansible idempotent code '''\n\n sconfig = ServiceAccountConfig(params['service_account'],\n params['namespace'],\n params['kubeconfig'],\n [params['secret']],\n None)\n\n oc_sa_sec = OCServiceAccountSecret(sconfig, verbose=params['debug'])\n\n state = params['state']\n\n api_rval = oc_sa_sec.get()\n\n #####\n # Get\n #####\n if state == 'list':\n return {'changed': False, 'results': api_rval['results'], 'state': \"list\"}\n\n ########\n # Delete\n ########\n if state == 'absent':\n if oc_sa_sec.exists(params['secret']):\n\n if check_mode:\n return {'changed': True, 'msg': 'Would have removed the \" + \\\n \"secret from the service account.'}\n\n api_rval = oc_sa_sec.delete()\n\n return {'changed': True, 'results': api_rval, 'state': \"absent\"}\n\n return {'changed': False, 'state': \"absent\"}\n\n if state == 'present':\n ########\n # Create\n ########\n if not oc_sa_sec.exists(params['secret']):\n\n if check_mode:\n return {'changed': True, 'msg': 'Would have added the ' + \\\n 'secret to the service account.'}\n\n # Create it here\n api_rval = oc_sa_sec.put()\n if api_rval['returncode'] != 0:\n return {'failed': True, 'msg': api_rval}\n\n # return the created object\n api_rval = oc_sa_sec.get()\n\n if api_rval['returncode'] != 0:\n return {'failed': True, 'msg': api_rval}\n\n return {'changed': True, 'results': api_rval, 'state': \"present\"}\n\n return {'changed': False, 'results': api_rval, 'state': \"present\"}\n\n return {'failed': True,\n 'changed': False,\n 'msg': 'Unknown state passed. %s' % state,\n 'state': 'unknown'}"}]} {"messages": [{"role": "user", "content": "Write Python code that implements virt.py from cmelange/ansible (path: lib/ansible/modules/cloud/misc/virt.py)."}, {"role": "assistant", "content": "# lib/ansible/modules/cloud/misc/virt.py (from cmelange/ansible, license: gpl-3.0)\n\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nVirt management features\n\nCopyright 2007, 2012 Red Hat, Inc\nMichael DeHaan \nSeth Vidal \n\nThis software may be freely redistributed under the terms of the GNU\ngeneral public license.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\"\"\"\n\nANSIBLE_METADATA = {'metadata_version': '1.0',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\nDOCUMENTATION = '''\n---\nmodule: virt\nshort_description: Manages virtual machines supported by libvirt\ndescription:\n - Manages virtual machines supported by I(libvirt).\nversion_added: \"0.2\"\noptions:\n name:\n description:\n - name of the guest VM being managed. Note that VM must be previously\n defined with xml.\n required: true\n default: null\n aliases: []\n state:\n description:\n - Note that there may be some lag for state requests like C(shutdown)\n since these refer only to VM states. After starting a guest, it may not\n be immediately accessible.\n required: false\n choices: [ \"running\", \"shutdown\", \"destroyed\", \"paused\" ]\n default: \"no\"\n command:\n description:\n - in addition to state management, various non-idempotent commands are available. See examples\n required: false\n choices: [\"create\",\"status\", \"start\", \"stop\", \"pause\", \"unpause\",\n \"shutdown\", \"undefine\", \"destroy\", \"get_xml\",\n \"freemem\", \"list_vms\", \"info\", \"nodeinfo\", \"virttype\", \"define\"]\n autostart:\n description:\n - start VM at host startup\n choices: [True, False]\n version_added: \"2.3\"\n default: null\n uri:\n description:\n - libvirt connection uri\n required: false\n default: qemu:///system\n xml:\n description:\n - XML document used with the define command\n required: false\n default: null\nrequirements:\n - \"python >= 2.6\"\n - \"libvirt-python\"\nauthor:\n - \"Ansible Core Team\"\n - \"Michael DeHaan\"\n - \"Seth Vidal\"\n'''\n\nEXAMPLES = '''\n# a playbook task line:\n- virt:\n name: alpha\n state: running\n\n# /usr/bin/ansible invocations\n# ansible host -m virt -a \"name=alpha command=status\"\n# ansible host -m virt -a \"name=alpha command=get_xml\"\n# ansible host -m virt -a \"name=alpha command=create uri=lxc:///\"\n\n---\n# a playbook example of defining and launching an LXC guest\ntasks:\n - name: define vm\n virt:\n name: foo\n command: define\n xml: \"{{ lookup('template', 'container-template.xml.j2') }}\"\n uri: 'lxc:///'\n - name: start vm\n virt:\n name: foo\n state: running\n uri: 'lxc:///'\n'''\n\nRETURN = '''\n# for list_vms command\nlist_vms:\n description: The list of vms defined on the remote system\n type: dictionary\n returned: success\n sample: [\n \"build.example.org\",\n \"dev.example.org\"\n ]\n# for status command\nstatus:\n description: The status of the VM, among running, crashed, paused and shutdown\n type: string\n sample: \"success\"\n returned: success\n'''\nVIRT_FAILED = 1\nVIRT_SUCCESS = 0\nVIRT_UNAVAILABLE=2\n\nimport sys\n\ntry:\n import libvirt\nexcept ImportError:\n HAS_VIRT = False\nelse:\n HAS_VIRT = True\n\nALL_COMMANDS = []\nVM_COMMANDS = ['create','status', 'start', 'stop', 'pause', 'unpause',\n 'shutdown', 'undefine', 'destroy', 'get_xml', 'define']\nHOST_COMMANDS = ['freemem', 'list_vms', 'info', 'nodeinfo', 'virttype']\nALL_COMMANDS.extend(VM_COMMANDS)\nALL_COMMANDS.extend(HOST_COMMANDS)\n\nVIRT_STATE_NAME_MAP = {\n 0 : \"running\",\n 1 : \"running\",\n 2 : \"running\",\n 3 : \"paused\",\n 4 : \"shutdown\",\n 5 : \"shutdown\",\n 6 : \"crashed\"\n}\n\nclass VMNotFound(Exception):\n pass\n\nclass LibvirtConnection(object):\n\n def __init__(self, uri, module):\n\n self.module = module\n\n cmd = \"uname -r\"\n rc, stdout, stderr = self.module.run_command(cmd)\n\n if \"xen\" in stdout:\n conn = libvirt.open(None)\n elif \"esx\" in uri:\n auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT], [], None]\n conn = libvirt.openAuth(uri, auth)\n else:\n conn = libvirt.open(uri)\n\n if not conn:\n raise Exception(\"hypervisor connection failure\")\n\n self.conn = conn\n\n def find_vm(self, vmid):\n \"\"\"\n Extra bonus feature: vmid = -1 returns a list of everything\n \"\"\"\n conn = self.conn\n\n vms = []\n\n # this block of code borrowed from virt-manager:\n # get working domain's name\n ids = conn.listDomainsID()\n for id in ids:\n vm = conn.lookupByID(id)\n vms.append(vm)\n # get defined domain\n names = conn.listDefinedDomains()\n for name in names:\n vm = conn.lookupByName(name)\n vms.append(vm)\n\n if vmid == -1:\n return vms\n\n for vm in vms:\n if vm.name() == vmid:\n return vm\n\n raise VMNotFound(\"virtual machine %s not found\" % vmid)\n\n def shutdown(self, vmid):\n return self.find_vm(vmid).shutdown()\n\n def pause(self, vmid):\n return self.suspend(self.conn,vmid)\n\n def unpause(self, vmid):\n return self.resume(self.conn,vmid)\n\n def suspend(self, vmid):\n return self.find_vm(vmid).suspend()\n\n def resume(self, vmid):\n return self.find_vm(vmid).resume()\n\n def create(self, vmid):\n return self.find_vm(vmid).create()\n\n def destroy(self, vmid):\n return self.find_vm(vmid).destroy()\n\n def undefine(self, vmid):\n return self.find_vm(vmid).undefine()\n\n def get_status2(self, vm):\n state = vm.info()[0]\n return VIRT_STATE_NAME_MAP.get(state,\"unknown\")\n\n def get_status(self, vmid):\n state = self.find_vm(vmid).info()[0]\n return VIRT_STATE_NAME_MAP.get(state,\"unknown\")\n\n def nodeinfo(self):\n return self.conn.getInfo()\n\n def get_type(self):\n return self.conn.getType()\n\n def get_xml(self, vmid):\n vm = self.conn.lookupByName(vmid)\n return vm.XMLDesc(0)\n\n def get_maxVcpus(self, vmid):\n vm = self.conn.lookupByName(vmid)\n return vm.maxVcpus()\n\n def get_maxMemory(self, vmid):\n vm = self.conn.lookupByName(vmid)\n return vm.maxMemory()\n\n def getFreeMemory(self):\n return self.conn.getFreeMemory()\n\n def get_autostart(self, vmid):\n vm = self.conn.lookupByName(vmid)\n return vm.autostart()\n\n def set_autostart(self, vmid, val):\n vm = self.conn.lookupByName(vmid)\n return vm.setAutostart(val)\n\n def define_from_xml(self, xml):\n return self.conn.defineXML(xml)\n\nclass Virt(object):\n\n def __init__(self, uri, module):\n self.module = module\n self.uri = uri\n\n def __get_conn(self):\n self.conn = LibvirtConnection(self.uri, self.module)\n return self.conn\n\n def get_vm(self, vmid):\n self.__get_conn()\n return self.conn.find_vm(vmid)\n\n def state(self):\n vms = self.list_vms()\n state = []\n for vm in vms:\n state_blurb = self.conn.get_status(vm)\n state.append(\"%s %s\" % (vm,state_blurb))\n return state\n\n def info(self):\n vms = self.list_vms()\n info = dict()\n for vm in vms:\n data = self.conn.find_vm(vm).info()\n # libvirt returns maxMem, memory, and cpuTime as long()'s, which\n # xmlrpclib tries to convert to regular int's during serialization.\n # This throws exceptions, so convert them to strings here and\n # assume the other end of the xmlrpc connection can figure things\n # out or doesn't care.\n info[vm] = {\n \"state\" : VIRT_STATE_NAME_MAP.get(data[0],\"unknown\"),\n \"maxMem\" : str(data[1]),\n \"memory\" : str(data[2]),\n \"nrVirtCpu\" : data[3],\n \"cpuTime\" : str(data[4]),\n }\n info[vm][\"autostart\"] = self.conn.get_autostart(vm)\n\n return info\n\n def nodeinfo(self):\n self.__get_conn()\n info = dict()\n data = self.conn.nodeinfo()\n info = {\n \"cpumodel\" : str(data[0]),\n \"phymemory\" : str(data[1]),\n \"cpus\" : str(data[2]),\n \"cpumhz\" : str(data[3]),\n \"numanodes\" : str(data[4]),\n \"sockets\" : str(data[5]),\n \"cpucores\" : str(data[6]),\n \"cputhreads\" : str(data[7])\n }\n return info\n\n def list_vms(self, state=None):\n self.conn = self.__get_conn()\n vms = self.conn.find_vm(-1)\n results = []\n for x in vms:\n try:\n if state:\n vmstate = self.conn.get_status2(x)\n if vmstate == state:\n results.append(x.name())\n else:\n results.append(x.name())\n except:\n pass\n return results\n\n def virttype(self):\n return self.__get_conn().get_type()\n\n def autostart(self, vmid, as_flag):\n self.conn = self.__get_conn()\n # Change autostart flag only if needed\n if self.conn.get_autostart(vmid) != as_flag:\n self.conn.set_autostart(vmid, as_flag)\n return True\n\n return False\n\n def freemem(self):\n self.conn = self.__get_conn()\n return self.conn.getFreeMemory()\n\n def shutdown(self, vmid):\n \"\"\" Make the machine with the given vmid stop running. Whatever that takes. \"\"\"\n self.__get_conn()\n self.conn.shutdown(vmid)\n return 0\n\n def pause(self, vmid):\n \"\"\" Pause the machine with the given vmid. \"\"\"\n\n self.__get_conn()\n return self.conn.suspend(vmid)\n\n def unpause(self, vmid):\n \"\"\" Unpause the machine with the given vmid. \"\"\"\n\n self.__get_conn()\n return self.conn.resume(vmid)\n\n def create(self, vmid):\n \"\"\" Start the machine via the given vmid \"\"\"\n\n self.__get_conn()\n return self.conn.create(vmid)\n\n def start(self, vmid):\n \"\"\" Start the machine via the given id/name \"\"\"\n\n self.__get_conn()\n return self.conn.create(vmid)\n\n def destroy(self, vmid):\n \"\"\" Pull the virtual power from the virtual domain, giving it virtually no time to virtually shut down. \"\"\"\n self.__get_conn()\n return self.conn.destroy(vmid)\n\n def undefine(self, vmid):\n \"\"\" Stop a domain, and then wipe it from the face of the earth. (delete disk/config file) \"\"\"\n\n self.__get_conn()\n return self.conn.undefine(vmid)\n\n def status(self, vmid):\n \"\"\"\n Return a state suitable for server consumption. Aka, codes.py values, not XM output.\n \"\"\"\n self.__get_conn()\n return self.conn.get_status(vmid)\n\n def get_xml(self, vmid):\n \"\"\"\n Receive a Vm id as input\n Return an xml describing vm config returned by a libvirt call\n \"\"\"\n\n self.__get_conn()\n return self.conn.get_xml(vmid)\n\n def get_maxVcpus(self, vmid):\n \"\"\"\n Gets the max number of VCPUs on a guest\n \"\"\"\n\n self.__get_conn()\n return self.conn.get_maxVcpus(vmid)\n\n def get_max_memory(self, vmid):\n \"\"\"\n Gets the max memory on a guest\n \"\"\"\n\n self.__get_conn()\n return self.conn.get_MaxMemory(vmid)\n\n def define(self, xml):\n \"\"\"\n Define a guest with the given xml\n \"\"\"\n self.__get_conn()\n return self.conn.define_from_xml(xml)\n\ndef core(module):\n\n state = module.params.get('state', None)\n autostart = module.params.get('autostart', None)\n guest = module.params.get('name', None)\n command = module.params.get('command', None)\n uri = module.params.get('uri', None)\n xml = module.params.get('xml', None)\n\n v = Virt(uri, module)\n res = {}\n\n if state and command=='list_vms':\n res = v.list_vms(state=state)\n if not isinstance(res, dict):\n res = { command: res }\n return VIRT_SUCCESS, res\n\n if state:\n if not guest:\n module.fail_json(msg = \"state change requires a guest specified\")\n\n if state == 'running':\n if v.status(guest) is 'paused':\n res['changed'] = True\n res['msg'] = v.unpause(guest)\n elif v.status(guest) is not 'running':\n res['changed'] = True\n res['msg'] = v.start(guest)\n elif state == 'shutdown':\n if v.status(guest) is not 'shutdown':\n res['changed'] = True\n res['msg'] = v.shutdown(guest)\n elif state == 'destroyed':\n if v.status(guest) is not 'shutdown':\n res['changed'] = True\n res['msg'] = v.destroy(guest)\n elif state == 'paused':\n if v.status(guest) is 'running':\n res['changed'] = True\n res['msg'] = v.pause(guest)\n else:\n module.fail_json(msg=\"unexpected state\")\n\n return VIRT_SUCCESS, res\n\n if autostart is not None and v.autostart(guest, autostart):\n res['changed'] = True\n\n if command:\n if command in VM_COMMANDS:\n if not guest:\n module.fail_json(msg = \"%s requires 1 argument: guest\" % command)\n if command == 'define':\n if not xml:\n module.fail_json(msg = \"define requires xml argument\")\n try:\n v.get_vm(guest)\n except VMNotFound:\n v.define(xml)\n res = {'changed': True, 'created': guest}\n return VIRT_SUCCESS, res\n res = getattr(v, command)(guest)\n if not isinstance(res, dict):\n res = { command: res }\n return VIRT_SUCCESS, res\n\n elif hasattr(v, command):\n res = getattr(v, command)()\n if not isinstance(res, dict):\n res = { command: res }\n return VIRT_SUCCESS, res\n\n else:\n module.fail_json(msg=\"Command %s not recognized\" % basecmd)\n\n module.fail_json(msg=\"expected state or command parameter to be specified\")\n\ndef main():\n\n module = AnsibleModule(argument_spec=dict(\n name = dict(aliases=['guest']),\n state = dict(choices=['running', 'shutdown', 'destroyed', 'paused']),\n autostart = dict(type='bool'),\n command = dict(choices=ALL_COMMANDS),\n uri = dict(default='qemu:///system'),\n xml = dict(),\n ))\n\n if not HAS_VIRT:\n module.fail_json(\n msg='The `libvirt` module is not importable. Check the requirements.'\n )\n\n rc = VIRT_SUCCESS\n try:\n rc, result = core(module)\n except Exception:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n if rc != 0: # something went wrong emit the msg\n module.fail_json(rc=rc, msg=result)\n else:\n module.exit_json(**result)\n\n# import module snippets\nfrom ansible.module_utils.basic import *\nfrom ansible.module_utils.pycompat24 import get_exception\n\nif __name__ == '__main__':\n main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_new_session.py from mach6/selenium (path: py/test/unit/selenium/webdriver/remote/test_new_session.py)."}, {"role": "assistant", "content": "# py/test/unit/selenium/webdriver/remote/test_new_session.py (from mach6/selenium, license: apache-2.0)\n\n# Licensed to the Software Freedom Conservancy (SFC) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The SFC licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom copy import deepcopy\nfrom importlib import import_module\n\nimport pytest\n\nfrom selenium.webdriver import DesiredCapabilities\nfrom selenium.webdriver.remote.command import Command\nfrom selenium.webdriver.remote.webdriver import WebDriver\n\ndef test_converts_oss_capabilities_to_w3c(mocker):\n mock = mocker.patch('selenium.webdriver.remote.webdriver.WebDriver.execute')\n oss_caps = {'platform': 'WINDOWS', 'version': '11', 'acceptSslCerts': True}\n w3c_caps = {'platformName': 'windows', 'browserVersion': '11', 'acceptInsecureCerts': True}\n WebDriver(desired_capabilities=deepcopy(oss_caps))\n expected_params = {'capabilities': {'firstMatch': [{}], 'alwaysMatch': w3c_caps},\n 'desiredCapabilities': oss_caps}\n mock.assert_called_with(Command.NEW_SESSION, expected_params)\n\ndef test_converts_proxy_type_value_to_lowercase_for_w3c(mocker):\n mock = mocker.patch('selenium.webdriver.remote.webdriver.WebDriver.execute')\n oss_caps = {'proxy': {'proxyType': 'MANUAL', 'httpProxy': 'foo'}}\n w3c_caps = {'proxy': {'proxyType': 'manual', 'httpProxy': 'foo'}}\n WebDriver(desired_capabilities=deepcopy(oss_caps))\n expected_params = {'capabilities': {'firstMatch': [{}], 'alwaysMatch': w3c_caps},\n 'desiredCapabilities': oss_caps}\n mock.assert_called_with(Command.NEW_SESSION, expected_params)\n\n@pytest.mark.parametrize('browser_name', ['firefox', 'chrome', 'ie', 'opera'])\ndef test_accepts_firefox_options_to_remote_driver(mocker, browser_name):\n options = import_module('selenium.webdriver.{}.options'.format(browser_name))\n caps_name = browser_name.upper() if browser_name != 'ie' else 'INTERNETEXPLORER'\n mock = mocker.patch('selenium.webdriver.remote.webdriver.WebDriver.start_session')\n\n opts = options.Options()\n opts.add_argument('foo')\n expected_caps = getattr(DesiredCapabilities, caps_name)\n caps = expected_caps.copy()\n expected_caps.update(opts.to_capabilities())\n\n WebDriver(desired_capabilities=caps, options=opts)\n mock.assert_called_with(expected_caps, None)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements package.py from lgarren/spack (path: var/spack/repos/builtin/packages/libelf/package.py)."}, {"role": "assistant", "content": "# var/spack/repos/builtin/packages/libelf/package.py (from lgarren/spack, license: lgpl-2.1)\n\n##############################################################################\n# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.\n# Produced at the Lawrence Livermore National Laboratory.\n#\n# This file is part of Spack.\n# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.\n# LLNL-CODE-647188\n#\n# For details, see https://github.com/llnl/spack\n# Please also see the NOTICE and LICENSE files for our notice and the LGPL.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License (as\n# published by the Free Software Foundation) version 2.1, February 1999.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and\n# conditions of the GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n##############################################################################\nfrom spack import *\n\nclass Libelf(AutotoolsPackage):\n \"\"\"libelf lets you read, modify or create ELF object files in an\n architecture-independent way. The library takes care of size\n and endian issues, e.g. you can process a file for SPARC\n processors on an Intel-based system.\"\"\"\n\n homepage = \"http://www.mr511.de/software/english.html\"\n url = \"http://www.mr511.de/software/libelf-0.8.13.tar.gz\"\n\n version('0.8.13', '4136d7b4c04df68b686570afa26988ac')\n version('0.8.12', 'e21f8273d9f5f6d43a59878dc274fec7')\n\n provides('elf@0')\n\n def configure_args(self):\n args = [\"--enable-shared\",\n \"--disable-dependency-tracking\",\n \"--disable-debug\"]\n return args\n\n def install(self, spec, prefix):\n make('install', parallel=False)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements feature_rbf.py from domob1812/bitcoin (path: test/functional/feature_rbf.py)."}, {"role": "assistant", "content": "# test/functional/feature_rbf.py (from domob1812/bitcoin, license: mit)\n\n#!/usr/bin/env python3\n# Copyright (c) 2014-2020 The Bitcoin Core developers\n# Distributed under the MIT software license, see the accompanying\n# file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\"\"\"Test the RBF code.\"\"\"\n\nfrom decimal import Decimal\n\nfrom test_framework.blocktools import COINBASE_MATURITY\nfrom test_framework.messages import COIN, COutPoint, CTransaction, CTxIn, CTxOut, BIP125_SEQUENCE_NUMBER\nfrom test_framework.script import CScript, OP_DROP\nfrom test_framework.test_framework import BitcoinTestFramework\nfrom test_framework.util import assert_equal, assert_raises_rpc_error, satoshi_round\nfrom test_framework.script_util import DUMMY_P2WPKH_SCRIPT, DUMMY_2_P2WPKH_SCRIPT\nfrom test_framework.wallet import MiniWallet\n\nMAX_REPLACEMENT_LIMIT = 100\n\ndef txToHex(tx):\n return tx.serialize().hex()\n\ndef make_utxo(node, amount, confirmed=True, scriptPubKey=DUMMY_P2WPKH_SCRIPT):\n \"\"\"Create a txout with a given amount and scriptPubKey\n\n Mines coins as needed.\n\n confirmed - txouts created will be confirmed in the blockchain;\n unconfirmed otherwise.\n \"\"\"\n fee = 1 * COIN\n while node.getbalance() < satoshi_round((amount + fee) / COIN):\n node.generate(COINBASE_MATURITY)\n\n new_addr = node.getnewaddress()\n txid = node.sendtoaddress(new_addr, satoshi_round((amount + fee) / COIN))\n tx1 = node.getrawtransaction(txid, 1)\n txid = int(txid, 16)\n i, _ = next(filter(lambda vout: new_addr == vout[1]['scriptPubKey']['address'], enumerate(tx1['vout'])))\n\n tx2 = CTransaction()\n tx2.vin = [CTxIn(COutPoint(txid, i))]\n tx2.vout = [CTxOut(amount, scriptPubKey)]\n tx2.rehash()\n\n signed_tx = node.signrawtransactionwithwallet(txToHex(tx2))\n\n txid = node.sendrawtransaction(signed_tx['hex'], 0)\n\n # If requested, ensure txouts are confirmed.\n if confirmed:\n mempool_size = len(node.getrawmempool())\n while mempool_size > 0:\n node.generate(1)\n new_size = len(node.getrawmempool())\n # Error out if we have something stuck in the mempool, as this\n # would likely be a bug.\n assert new_size < mempool_size\n mempool_size = new_size\n\n return COutPoint(int(txid, 16), 0)\n\nclass ReplaceByFeeTest(BitcoinTestFramework):\n def set_test_params(self):\n self.num_nodes = 1\n self.extra_args = [\n [\n \"-acceptnonstdtxn=1\",\n \"-maxorphantx=1000\",\n \"-limitancestorcount=50\",\n \"-limitancestorsize=101\",\n \"-limitdescendantcount=200\",\n \"-limitdescendantsize=101\",\n ],\n ]\n self.supports_cli = False\n\n def skip_test_if_missing_module(self):\n self.skip_if_no_wallet()\n\n def run_test(self):\n make_utxo(self.nodes[0], 1 * COIN)\n\n # Ensure nodes are synced\n self.sync_all()\n\n self.log.info(\"Running test simple doublespend...\")\n self.test_simple_doublespend()\n\n self.log.info(\"Running test doublespend chain...\")\n self.test_doublespend_chain()\n\n self.log.info(\"Running test doublespend tree...\")\n self.test_doublespend_tree()\n\n self.log.info(\"Running test replacement feeperkb...\")\n self.test_replacement_feeperkb()\n\n self.log.info(\"Running test spends of conflicting outputs...\")\n self.test_spends_of_conflicting_outputs()\n\n self.log.info(\"Running test new unconfirmed inputs...\")\n self.test_new_unconfirmed_inputs()\n\n self.log.info(\"Running test too many replacements...\")\n self.test_too_many_replacements()\n\n self.log.info(\"Running test opt-in...\")\n self.test_opt_in()\n\n self.log.info(\"Running test RPC...\")\n self.test_rpc()\n\n self.log.info(\"Running test prioritised transactions...\")\n self.test_prioritised_transactions()\n\n self.log.info(\"Running test no inherited signaling...\")\n self.test_no_inherited_signaling()\n\n self.log.info(\"Passed\")\n\n def test_simple_doublespend(self):\n \"\"\"Simple doublespend\"\"\"\n tx0_outpoint = make_utxo(self.nodes[0], int(1.1 * COIN))\n\n # make_utxo may have generated a bunch of blocks, so we need to sync\n # before we can spend the coins generated, or else the resulting\n # transactions might not be accepted by our peers.\n self.sync_all()\n\n tx1a = CTransaction()\n tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n tx1a.vout = [CTxOut(1 * COIN, DUMMY_P2WPKH_SCRIPT)]\n tx1a_hex = txToHex(tx1a)\n tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, 0)\n\n self.sync_all()\n\n # Should fail because we haven't changed the fee\n tx1b = CTransaction()\n tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n tx1b.vout = [CTxOut(1 * COIN, DUMMY_2_P2WPKH_SCRIPT)]\n tx1b_hex = txToHex(tx1b)\n\n # This will raise an exception due to insufficient fee\n assert_raises_rpc_error(-26, \"insufficient fee\", self.nodes[0].sendrawtransaction, tx1b_hex, 0)\n\n # Extra 0.1 BTC fee\n tx1b = CTransaction()\n tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n tx1b.vout = [CTxOut(int(0.9 * COIN), DUMMY_P2WPKH_SCRIPT)]\n tx1b_hex = txToHex(tx1b)\n # Works when enabled\n tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, 0)\n\n mempool = self.nodes[0].getrawmempool()\n\n assert tx1a_txid not in mempool\n assert tx1b_txid in mempool\n\n assert_equal(tx1b_hex, self.nodes[0].getrawtransaction(tx1b_txid))\n\n def test_doublespend_chain(self):\n \"\"\"Doublespend of a long chain\"\"\"\n\n initial_nValue = 50 * COIN\n tx0_outpoint = make_utxo(self.nodes[0], initial_nValue)\n\n prevout = tx0_outpoint\n remaining_value = initial_nValue\n chain_txids = []\n while remaining_value > 10 * COIN:\n remaining_value -= 1 * COIN\n tx = CTransaction()\n tx.vin = [CTxIn(prevout, nSequence=0)]\n tx.vout = [CTxOut(remaining_value, CScript([1, OP_DROP] * 15 + [1]))]\n tx_hex = txToHex(tx)\n txid = self.nodes[0].sendrawtransaction(tx_hex, 0)\n chain_txids.append(txid)\n prevout = COutPoint(int(txid, 16), 0)\n\n # Whether the double-spend is allowed is evaluated by including all\n # child fees - 40 BTC - so this attempt is rejected.\n dbl_tx = CTransaction()\n dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n dbl_tx.vout = [CTxOut(initial_nValue - 30 * COIN, DUMMY_P2WPKH_SCRIPT)]\n dbl_tx_hex = txToHex(dbl_tx)\n\n # This will raise an exception due to insufficient fee\n assert_raises_rpc_error(-26, \"insufficient fee\", self.nodes[0].sendrawtransaction, dbl_tx_hex, 0)\n\n # Accepted with sufficient fee\n dbl_tx = CTransaction()\n dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n dbl_tx.vout = [CTxOut(1 * COIN, DUMMY_P2WPKH_SCRIPT)]\n dbl_tx_hex = txToHex(dbl_tx)\n self.nodes[0].sendrawtransaction(dbl_tx_hex, 0)\n\n mempool = self.nodes[0].getrawmempool()\n for doublespent_txid in chain_txids:\n assert doublespent_txid not in mempool\n\n def test_doublespend_tree(self):\n \"\"\"Doublespend of a big tree of transactions\"\"\"\n\n initial_nValue = 50 * COIN\n tx0_outpoint = make_utxo(self.nodes[0], initial_nValue)\n\n def branch(prevout, initial_value, max_txs, tree_width=5, fee=0.0001 * COIN, _total_txs=None):\n if _total_txs is None:\n _total_txs = [0]\n if _total_txs[0] >= max_txs:\n return\n\n txout_value = (initial_value - fee) // tree_width\n if txout_value < fee:\n return\n\n vout = [CTxOut(txout_value, CScript([i+1]))\n for i in range(tree_width)]\n tx = CTransaction()\n tx.vin = [CTxIn(prevout, nSequence=0)]\n tx.vout = vout\n tx_hex = txToHex(tx)\n\n assert len(tx.serialize()) < 100000\n txid = self.nodes[0].sendrawtransaction(tx_hex, 0)\n yield tx\n _total_txs[0] += 1\n\n txid = int(txid, 16)\n\n for i, txout in enumerate(tx.vout):\n for x in branch(COutPoint(txid, i), txout_value,\n max_txs,\n tree_width=tree_width, fee=fee,\n _total_txs=_total_txs):\n yield x\n\n fee = int(0.0001 * COIN)\n n = MAX_REPLACEMENT_LIMIT\n tree_txs = list(branch(tx0_outpoint, initial_nValue, n, fee=fee))\n assert_equal(len(tree_txs), n)\n\n # Attempt double-spend, will fail because too little fee paid\n dbl_tx = CTransaction()\n dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n dbl_tx.vout = [CTxOut(initial_nValue - fee * n, DUMMY_P2WPKH_SCRIPT)]\n dbl_tx_hex = txToHex(dbl_tx)\n # This will raise an exception due to insufficient fee\n assert_raises_rpc_error(-26, \"insufficient fee\", self.nodes[0].sendrawtransaction, dbl_tx_hex, 0)\n\n # 1 BTC fee is enough\n dbl_tx = CTransaction()\n dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n dbl_tx.vout = [CTxOut(initial_nValue - fee * n - 1 * COIN, DUMMY_P2WPKH_SCRIPT)]\n dbl_tx_hex = txToHex(dbl_tx)\n self.nodes[0].sendrawtransaction(dbl_tx_hex, 0)\n\n mempool = self.nodes[0].getrawmempool()\n\n for tx in tree_txs:\n tx.rehash()\n assert tx.hash not in mempool\n\n # Try again, but with more total transactions than the \"max txs\n # double-spent at once\" anti-DoS limit.\n for n in (MAX_REPLACEMENT_LIMIT + 1, MAX_REPLACEMENT_LIMIT * 2):\n fee = int(0.0001 * COIN)\n tx0_outpoint = make_utxo(self.nodes[0], initial_nValue)\n tree_txs = list(branch(tx0_outpoint, initial_nValue, n, fee=fee))\n assert_equal(len(tree_txs), n)\n\n dbl_tx = CTransaction()\n dbl_tx.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n dbl_tx.vout = [CTxOut(initial_nValue - 2 * fee * n, DUMMY_P2WPKH_SCRIPT)]\n dbl_tx_hex = txToHex(dbl_tx)\n # This will raise an exception\n assert_raises_rpc_error(-26, \"too many potential replacements\", self.nodes[0].sendrawtransaction, dbl_tx_hex, 0)\n\n for tx in tree_txs:\n tx.rehash()\n self.nodes[0].getrawtransaction(tx.hash)\n\n def test_replacement_feeperkb(self):\n \"\"\"Replacement requires fee-per-KB to be higher\"\"\"\n tx0_outpoint = make_utxo(self.nodes[0], int(1.1 * COIN))\n\n tx1a = CTransaction()\n tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n tx1a.vout = [CTxOut(1 * COIN, DUMMY_P2WPKH_SCRIPT)]\n tx1a_hex = txToHex(tx1a)\n self.nodes[0].sendrawtransaction(tx1a_hex, 0)\n\n # Higher fee, but the fee per KB is much lower, so the replacement is\n # rejected.\n tx1b = CTransaction()\n tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n tx1b.vout = [CTxOut(int(0.001 * COIN), CScript([b'a' * 999000]))]\n tx1b_hex = txToHex(tx1b)\n\n # This will raise an exception due to insufficient fee\n assert_raises_rpc_error(-26, \"insufficient fee\", self.nodes[0].sendrawtransaction, tx1b_hex, 0)\n\n def test_spends_of_conflicting_outputs(self):\n \"\"\"Replacements that spend conflicting tx outputs are rejected\"\"\"\n utxo1 = make_utxo(self.nodes[0], int(1.2 * COIN))\n utxo2 = make_utxo(self.nodes[0], 3 * COIN)\n\n tx1a = CTransaction()\n tx1a.vin = [CTxIn(utxo1, nSequence=0)]\n tx1a.vout = [CTxOut(int(1.1 * COIN), DUMMY_P2WPKH_SCRIPT)]\n tx1a_hex = txToHex(tx1a)\n tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, 0)\n\n tx1a_txid = int(tx1a_txid, 16)\n\n # Direct spend an output of the transaction we're replacing.\n tx2 = CTransaction()\n tx2.vin = [CTxIn(utxo1, nSequence=0), CTxIn(utxo2, nSequence=0)]\n tx2.vin.append(CTxIn(COutPoint(tx1a_txid, 0), nSequence=0))\n tx2.vout = tx1a.vout\n tx2_hex = txToHex(tx2)\n\n # This will raise an exception\n assert_raises_rpc_error(-26, \"bad-txns-spends-conflicting-tx\", self.nodes[0].sendrawtransaction, tx2_hex, 0)\n\n # Spend tx1a's output to test the indirect case.\n tx1b = CTransaction()\n tx1b.vin = [CTxIn(COutPoint(tx1a_txid, 0), nSequence=0)]\n tx1b.vout = [CTxOut(1 * COIN, DUMMY_P2WPKH_SCRIPT)]\n tx1b_hex = txToHex(tx1b)\n tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, 0)\n tx1b_txid = int(tx1b_txid, 16)\n\n tx2 = CTransaction()\n tx2.vin = [CTxIn(utxo1, nSequence=0), CTxIn(utxo2, nSequence=0),\n CTxIn(COutPoint(tx1b_txid, 0))]\n tx2.vout = tx1a.vout\n tx2_hex = txToHex(tx2)\n\n # This will raise an exception\n assert_raises_rpc_error(-26, \"bad-txns-spends-conflicting-tx\", self.nodes[0].sendrawtransaction, tx2_hex, 0)\n\n def test_new_unconfirmed_inputs(self):\n \"\"\"Replacements that add new unconfirmed inputs are rejected\"\"\"\n confirmed_utxo = make_utxo(self.nodes[0], int(1.1 * COIN))\n unconfirmed_utxo = make_utxo(self.nodes[0], int(0.1 * COIN), False)\n\n tx1 = CTransaction()\n tx1.vin = [CTxIn(confirmed_utxo)]\n tx1.vout = [CTxOut(1 * COIN, DUMMY_P2WPKH_SCRIPT)]\n tx1_hex = txToHex(tx1)\n self.nodes[0].sendrawtransaction(tx1_hex, 0)\n\n tx2 = CTransaction()\n tx2.vin = [CTxIn(confirmed_utxo), CTxIn(unconfirmed_utxo)]\n tx2.vout = tx1.vout\n tx2_hex = txToHex(tx2)\n\n # This will raise an exception\n assert_raises_rpc_error(-26, \"replacement-adds-unconfirmed\", self.nodes[0].sendrawtransaction, tx2_hex, 0)\n\n def test_too_many_replacements(self):\n \"\"\"Replacements that evict too many transactions are rejected\"\"\"\n # Try directly replacing more than MAX_REPLACEMENT_LIMIT\n # transactions\n\n # Start by creating a single transaction with many outputs\n initial_nValue = 10 * COIN\n utxo = make_utxo(self.nodes[0], initial_nValue)\n fee = int(0.0001 * COIN)\n split_value = int((initial_nValue - fee) / (MAX_REPLACEMENT_LIMIT + 1))\n\n outputs = []\n for _ in range(MAX_REPLACEMENT_LIMIT + 1):\n outputs.append(CTxOut(split_value, CScript([1])))\n\n splitting_tx = CTransaction()\n splitting_tx.vin = [CTxIn(utxo, nSequence=0)]\n splitting_tx.vout = outputs\n splitting_tx_hex = txToHex(splitting_tx)\n\n txid = self.nodes[0].sendrawtransaction(splitting_tx_hex, 0)\n txid = int(txid, 16)\n\n # Now spend each of those outputs individually\n for i in range(MAX_REPLACEMENT_LIMIT + 1):\n tx_i = CTransaction()\n tx_i.vin = [CTxIn(COutPoint(txid, i), nSequence=0)]\n tx_i.vout = [CTxOut(split_value - fee, DUMMY_P2WPKH_SCRIPT)]\n tx_i_hex = txToHex(tx_i)\n self.nodes[0].sendrawtransaction(tx_i_hex, 0)\n\n # Now create doublespend of the whole lot; should fail.\n # Need a big enough fee to cover all spending transactions and have\n # a higher fee rate\n double_spend_value = (split_value - 100 * fee) * (MAX_REPLACEMENT_LIMIT + 1)\n inputs = []\n for i in range(MAX_REPLACEMENT_LIMIT + 1):\n inputs.append(CTxIn(COutPoint(txid, i), nSequence=0))\n double_tx = CTransaction()\n double_tx.vin = inputs\n double_tx.vout = [CTxOut(double_spend_value, CScript([b'a']))]\n double_tx_hex = txToHex(double_tx)\n\n # This will raise an exception\n assert_raises_rpc_error(-26, \"too many potential replacements\", self.nodes[0].sendrawtransaction, double_tx_hex, 0)\n\n # If we remove an input, it should pass\n double_tx = CTransaction()\n double_tx.vin = inputs[0:-1]\n double_tx.vout = [CTxOut(double_spend_value, CScript([b'a']))]\n double_tx_hex = txToHex(double_tx)\n self.nodes[0].sendrawtransaction(double_tx_hex, 0)\n\n def test_opt_in(self):\n \"\"\"Replacing should only work if orig tx opted in\"\"\"\n tx0_outpoint = make_utxo(self.nodes[0], int(1.1 * COIN))\n\n # Create a non-opting in transaction\n tx1a = CTransaction()\n tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0xffffffff)]\n tx1a.vout = [CTxOut(1 * COIN, DUMMY_P2WPKH_SCRIPT)]\n tx1a_hex = txToHex(tx1a)\n tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, 0)\n\n # This transaction isn't shown as replaceable\n assert_equal(self.nodes[0].getmempoolentry(tx1a_txid)['bip125-replaceable'], False)\n\n # Shouldn't be able to double-spend\n tx1b = CTransaction()\n tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n tx1b.vout = [CTxOut(int(0.9 * COIN), DUMMY_P2WPKH_SCRIPT)]\n tx1b_hex = txToHex(tx1b)\n\n # This will raise an exception\n assert_raises_rpc_error(-26, \"txn-mempool-conflict\", self.nodes[0].sendrawtransaction, tx1b_hex, 0)\n\n tx1_outpoint = make_utxo(self.nodes[0], int(1.1 * COIN))\n\n # Create a different non-opting in transaction\n tx2a = CTransaction()\n tx2a.vin = [CTxIn(tx1_outpoint, nSequence=0xfffffffe)]\n tx2a.vout = [CTxOut(1 * COIN, DUMMY_P2WPKH_SCRIPT)]\n tx2a_hex = txToHex(tx2a)\n tx2a_txid = self.nodes[0].sendrawtransaction(tx2a_hex, 0)\n\n # Still shouldn't be able to double-spend\n tx2b = CTransaction()\n tx2b.vin = [CTxIn(tx1_outpoint, nSequence=0)]\n tx2b.vout = [CTxOut(int(0.9 * COIN), DUMMY_P2WPKH_SCRIPT)]\n tx2b_hex = txToHex(tx2b)\n\n # This will raise an exception\n assert_raises_rpc_error(-26, \"txn-mempool-conflict\", self.nodes[0].sendrawtransaction, tx2b_hex, 0)\n\n # Now create a new transaction that spends from tx1a and tx2a\n # opt-in on one of the inputs\n # Transaction should be replaceable on either input\n\n tx1a_txid = int(tx1a_txid, 16)\n tx2a_txid = int(tx2a_txid, 16)\n\n tx3a = CTransaction()\n tx3a.vin = [CTxIn(COutPoint(tx1a_txid, 0), nSequence=0xffffffff),\n CTxIn(COutPoint(tx2a_txid, 0), nSequence=0xfffffffd)]\n tx3a.vout = [CTxOut(int(0.9 * COIN), CScript([b'c'])), CTxOut(int(0.9 * COIN), CScript([b'd']))]\n tx3a_hex = txToHex(tx3a)\n\n tx3a_txid = self.nodes[0].sendrawtransaction(tx3a_hex, 0)\n\n # This transaction is shown as replaceable\n assert_equal(self.nodes[0].getmempoolentry(tx3a_txid)['bip125-replaceable'], True)\n\n tx3b = CTransaction()\n tx3b.vin = [CTxIn(COutPoint(tx1a_txid, 0), nSequence=0)]\n tx3b.vout = [CTxOut(int(0.5 * COIN), DUMMY_P2WPKH_SCRIPT)]\n tx3b_hex = txToHex(tx3b)\n\n tx3c = CTransaction()\n tx3c.vin = [CTxIn(COutPoint(tx2a_txid, 0), nSequence=0)]\n tx3c.vout = [CTxOut(int(0.5 * COIN), DUMMY_P2WPKH_SCRIPT)]\n tx3c_hex = txToHex(tx3c)\n\n self.nodes[0].sendrawtransaction(tx3b_hex, 0)\n # If tx3b was accepted, tx3c won't look like a replacement,\n # but make sure it is accepted anyway\n self.nodes[0].sendrawtransaction(tx3c_hex, 0)\n\n def test_prioritised_transactions(self):\n # Ensure that fee deltas used via prioritisetransaction are\n # correctly used by replacement logic\n\n # 1. Check that feeperkb uses modified fees\n tx0_outpoint = make_utxo(self.nodes[0], int(1.1 * COIN))\n\n tx1a = CTransaction()\n tx1a.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n tx1a.vout = [CTxOut(1 * COIN, DUMMY_P2WPKH_SCRIPT)]\n tx1a_hex = txToHex(tx1a)\n tx1a_txid = self.nodes[0].sendrawtransaction(tx1a_hex, 0)\n\n # Higher fee, but the actual fee per KB is much lower.\n tx1b = CTransaction()\n tx1b.vin = [CTxIn(tx0_outpoint, nSequence=0)]\n tx1b.vout = [CTxOut(int(0.001 * COIN), CScript([b'a' * 740000]))]\n tx1b_hex = txToHex(tx1b)\n\n # Verify tx1b cannot replace tx1a.\n assert_raises_rpc_error(-26, \"insufficient fee\", self.nodes[0].sendrawtransaction, tx1b_hex, 0)\n\n # Use prioritisetransaction to set tx1a's fee to 0.\n self.nodes[0].prioritisetransaction(txid=tx1a_txid, fee_delta=int(-0.1 * COIN))\n\n # Now tx1b should be able to replace tx1a\n tx1b_txid = self.nodes[0].sendrawtransaction(tx1b_hex, 0)\n\n assert tx1b_txid in self.nodes[0].getrawmempool()\n\n # 2. Check that absolute fee checks use modified fee.\n tx1_outpoint = make_utxo(self.nodes[0], int(1.1 * COIN))\n\n tx2a = CTransaction()\n tx2a.vin = [CTxIn(tx1_outpoint, nSequence=0)]\n tx2a.vout = [CTxOut(1 * COIN, DUMMY_P2WPKH_SCRIPT)]\n tx2a_hex = txToHex(tx2a)\n self.nodes[0].sendrawtransaction(tx2a_hex, 0)\n\n # Lower fee, but we'll prioritise it\n tx2b = CTransaction()\n tx2b.vin = [CTxIn(tx1_outpoint, nSequence=0)]\n tx2b.vout = [CTxOut(int(1.01 * COIN), DUMMY_P2WPKH_SCRIPT)]\n tx2b.rehash()\n tx2b_hex = txToHex(tx2b)\n\n # Verify tx2b cannot replace tx2a.\n assert_raises_rpc_error(-26, \"insufficient fee\", self.nodes[0].sendrawtransaction, tx2b_hex, 0)\n\n # Now prioritise tx2b to have a higher modified fee\n self.nodes[0].prioritisetransaction(txid=tx2b.hash, fee_delta=int(0.1 * COIN))\n\n # tx2b should now be accepted\n tx2b_txid = self.nodes[0].sendrawtransaction(tx2b_hex, 0)\n\n assert tx2b_txid in self.nodes[0].getrawmempool()\n\n def test_rpc(self):\n us0 = self.nodes[0].listunspent()[0]\n ins = [us0]\n outs = {self.nodes[0].getnewaddress(): Decimal(1.0000000)}\n rawtx0 = self.nodes[0].createrawtransaction(ins, outs, 0, True)\n rawtx1 = self.nodes[0].createrawtransaction(ins, outs, 0, False)\n json0 = self.nodes[0].decoderawtransaction(rawtx0)\n json1 = self.nodes[0].decoderawtransaction(rawtx1)\n assert_equal(json0[\"vin\"][0][\"sequence\"], 4294967293)\n assert_equal(json1[\"vin\"][0][\"sequence\"], 4294967295)\n\n rawtx2 = self.nodes[0].createrawtransaction([], outs)\n frawtx2a = self.nodes[0].fundrawtransaction(rawtx2, {\"replaceable\": True})\n frawtx2b = self.nodes[0].fundrawtransaction(rawtx2, {\"replaceable\": False})\n\n json0 = self.nodes[0].decoderawtransaction(frawtx2a['hex'])\n json1 = self.nodes[0].decoderawtransaction(frawtx2b['hex'])\n assert_equal(json0[\"vin\"][0][\"sequence\"], 4294967293)\n assert_equal(json1[\"vin\"][0][\"sequence\"], 4294967294)\n\n def test_no_inherited_signaling(self):\n wallet = MiniWallet(self.nodes[0])\n wallet.scan_blocks(start=76, num=1)\n confirmed_utxo = wallet.get_utxo()\n\n # Create an explicitly opt-in parent transaction\n optin_parent_tx = wallet.send_self_transfer(\n from_node=self.nodes[0],\n utxo_to_spend=confirmed_utxo,\n sequence=BIP125_SEQUENCE_NUMBER,\n fee_rate=Decimal('0.01'),\n )\n assert_equal(True, self.nodes[0].getmempoolentry(optin_parent_tx['txid'])['bip125-replaceable'])\n\n replacement_parent_tx = wallet.create_self_transfer(\n from_node=self.nodes[0],\n utxo_to_spend=confirmed_utxo,\n sequence=BIP125_SEQUENCE_NUMBER,\n fee_rate=Decimal('0.02'),\n )\n\n # Test if parent tx can be replaced.\n res = self.nodes[0].testmempoolaccept(rawtxs=[replacement_parent_tx['hex']])[0]\n\n # Parent can be replaced.\n assert_equal(res['allowed'], True)\n\n # Create an opt-out child tx spending the opt-in parent\n parent_utxo = wallet.get_utxo(txid=optin_parent_tx['txid'])\n optout_child_tx = wallet.send_self_transfer(\n from_node=self.nodes[0],\n utxo_to_spend=parent_utxo,\n sequence=0xffffffff,\n fee_rate=Decimal('0.01'),\n )\n\n # Reports true due to inheritance\n assert_equal(True, self.nodes[0].getmempoolentry(optout_child_tx['txid'])['bip125-replaceable'])\n\n replacement_child_tx = wallet.create_self_transfer(\n from_node=self.nodes[0],\n utxo_to_spend=parent_utxo,\n sequence=0xffffffff,\n fee_rate=Decimal('0.02'),\n mempool_valid=False,\n )\n\n # Broadcast replacement child tx\n # BIP 125 :\n # 1. The original transactions signal replaceability explicitly or through inheritance as described in the above\n # Summary section.\n # The original transaction (`optout_child_tx`) doesn't signal RBF but its parent (`optin_parent_tx`) does.\n # The replacement transaction (`replacement_child_tx`) should be able to replace the original transaction.\n # See CVE-2021-31876 for further explanations.\n assert_equal(True, self.nodes[0].getmempoolentry(optin_parent_tx['txid'])['bip125-replaceable'])\n assert_raises_rpc_error(-26, 'txn-mempool-conflict', self.nodes[0].sendrawtransaction, replacement_child_tx[\"hex\"], 0)\n\nif __name__ == '__main__':\n ReplaceByFeeTest().main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements csvfile.py from 47lining/ansible (path: lib/ansible/runner/lookup_plugins/csvfile.py)."}, {"role": "assistant", "content": "# lib/ansible/runner/lookup_plugins/csvfile.py (from 47lining/ansible, license: gpl-3.0)\n\n# (c) 2013, Jan-Piet Mens \n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\nfrom ansible import utils, errors\nimport os\nimport codecs\nimport csv\n\nclass LookupModule(object):\n\n def __init__(self, basedir=None, **kwargs):\n self.basedir = basedir\n\n def read_csv(self, filename, key, delimiter, dflt=None, col=1):\n\n try:\n f = codecs.open(filename, 'r', encoding='utf-8')\n creader = csv.reader(f, delimiter=delimiter)\n\n for row in creader:\n if row[0] == key:\n return row[int(col)]\n except Exception, e:\n raise errors.AnsibleError(\"csvfile: %s\" % str(e))\n\n return dflt\n\n def run(self, terms, inject=None, **kwargs):\n\n terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject)\n\n if isinstance(terms, basestring):\n terms = [ terms ]\n\n ret = []\n for term in terms:\n params = term.split()\n key = params[0]\n\n paramvals = {\n 'file' : 'ansible.csv',\n 'default' : None,\n 'delimiter' : \"TAB\",\n 'col' : \"1\", # column to return\n }\n\n # parameters specified?\n try:\n for param in params[1:]:\n name, value = param.split('=')\n assert(name in paramvals)\n paramvals[name] = value\n except (ValueError, AssertionError), e:\n raise errors.AnsibleError(e)\n\n if paramvals['delimiter'] == 'TAB':\n paramvals['delimiter'] = \"\\t\"\n\n path = utils.path_dwim(self.basedir, paramvals['file'])\n\n var = self.read_csv(path, key, paramvals['delimiter'], paramvals['default'], paramvals['col'])\n if var is not None:\n if type(var) is list:\n for v in var:\n ret.append(v)\n else:\n ret.append(var)\n return ret"}]} {"messages": [{"role": "user", "content": "Write Python code that implements traffic_lights.py from zafar-hussain/or-tools (path: examples/python/traffic_lights.py)."}, {"role": "assistant", "content": "# examples/python/traffic_lights.py (from zafar-hussain/or-tools, license: apache-2.0)\n\n# Copyright 2010 Hakan Kjellerstrand hakank@bonetmail.com\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\n\n Traffic lights problem in Google CP Solver.\n\n CSPLib problem 16\n http://www.cs.st-andrews.ac.uk/~ianm/CSPLib/prob/prob016/index.html\n '''\n Specification:\n Consider a four way traffic junction with eight traffic lights. Four of the\n traffic\n lights are for the vehicles and can be represented by the variables V1 to V4\n with domains\n {r,ry,g,y} (for red, red-yellow, green and yellow). The other four traffic\n lights are\n for the pedestrians and can be represented by the variables P1 to P4 with\n domains {r,g}.\n\n The constraints on these variables can be modelled by quaternary constraints\n on\n (Vi, Pi, Vj, Pj ) for 1<=i<=4, j=(1+i)mod 4 which allow just the tuples\n {(r,r,g,g), (ry,r,y,r), (g,g,r,r), (y,r,ry,r)}.\n\n It would be interesting to consider other types of junction (e.g. five roads\n intersecting) as well as modelling the evolution over time of the traffic\n light sequence.\n ...\n\n Results\n Only 2^2 out of the 2^12 possible assignments are solutions.\n\n (V1,P1,V2,P2,V3,P3,V4,P4) =\n {(r,r,g,g,r,r,g,g), (ry,r,y,r,ry,r,y,r), (g,g,r,r,g,g,r,r),\n (y,r,ry,r,y,r,ry,r)}\n [(1,1,3,3,1,1,3,3), ( 2,1,4,1, 2,1,4,1), (3,3,1,1,3,3,1,1), (4,1, 2,1,4,1,\n 2,1)}\n\n The problem has relative few constraints, but each is very tight. Local\n propagation\n appears to be rather ineffective on this problem.\n\n '''\n\n Note: In this model we use only the constraint solver.AllowedAssignments().\n\n Compare with these models:\n * MiniZinc: http://www.hakank.org/minizinc/traffic_lights.mzn\n * Comet : http://www.hakank.org/comet/traffic_lights.co\n * ECLiPSe : http://www.hakank.org/eclipse/traffic_lights.ecl\n * Gecode : http://hakank.org/gecode/traffic_lights.cpp\n * SICStus : http://hakank.org/sicstus/traffic_lights.pl\n\n This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)\n Also see my other Google CP Solver models:\n http://www.hakank.org/google_or_tools/\n\n\"\"\"\n\nimport string\nimport sys\n\nfrom ortools.constraint_solver import pywrapcp\n\ndef main(base=10, start=1, len1=1, len2=4):\n\n # Create the solver.\n solver = pywrapcp.Solver(\"Traffic lights\")\n\n #\n # data\n #\n n = 4\n r, ry, g, y = range(n)\n lights = [\"r\", \"ry\", \"g\", \"y\"]\n\n # The allowed combinations\n allowed = []\n allowed.extend([(r, r, g, g),\n (ry, r, y, r),\n (g, g, r, r),\n (y, r, ry, r)])\n\n #\n # declare variables\n #\n V = [solver.IntVar(0, n - 1, \"V[%i]\" % i) for i in range(n)]\n P = [solver.IntVar(0, n - 1, \"P[%i]\" % i) for i in range(n)]\n\n #\n # constraints\n #\n for i in range(n):\n for j in range(n):\n if j == (1 + i) % n:\n solver.Add(solver.AllowedAssignments((V[i], P[i], V[j], P[j]), allowed))\n\n #\n # Search and result\n #\n db = solver.Phase(V + P,\n solver.INT_VAR_SIMPLE,\n solver.INT_VALUE_DEFAULT)\n\n solver.NewSearch(db)\n num_solutions = 0\n while solver.NextSolution():\n for i in range(n):\n print \"%+2s %+2s\" % (lights[V[i].Value()], lights[P[i].Value()]),\n print\n num_solutions += 1\n\n solver.EndSearch()\n\n print\n print \"num_solutions:\", num_solutions\n print \"failures:\", solver.Failures()\n print \"branches:\", solver.Branches()\n print \"WallTime:\", solver.WallTime()\n print\n\nif __name__ == \"__main__\":\n main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements sfplugin-test-wrapper.py from abramhindle/marsyas-fork (path: scripts/sfplugin-test-wrapper.py)."}, {"role": "assistant", "content": "# scripts/sfplugin-test-wrapper.py (from abramhindle/marsyas-fork, license: gpl-2.0)\n\n#!/usr/bin/env python\n\nimport os\nimport sys\nimport subprocess\nimport shutil\nimport commands\n\ndef runCommand(workingDir, bextractLocation, sfpluginLocation, extraBextractCmdArgs,\n mfFileLocation, outputMplFile, testFile, goodFilename):\n os.chdir(workingDir)\n\n bextractCmd = (\"%s %s -t %s -p %s\") % (bextractLocation, extraBextractCmdArgs, mfFileLocation, outputMplFile)\n a = commands.getoutput(bextractCmd)\n\n sfpluginCmd = (\"%s -pl %s %s\") % (sfpluginLocation, outputMplFile, testFile)\n a = commands.getoutput(sfpluginCmd)\n\n returnCode = compareSfpluginOutput(a, goodFilename)\n return returnCode\n \n\ndef compareSfpluginOutput(oneData, twoFilename):\n oneLines = oneData.split(\"\\n\")\n twoLines = open(twoFilename).readlines()\n for a, b in zip(oneLines, twoLines):\n if a.rstrip() != b.rstrip():\n return False\n return True\n\nif __name__ == \"__main__\":\n try:\n workingDir = sys.argv[1]\n bextractLocation = sys.argv[2]\n sfpluginLocation = sys.argv[3]\n extraBextractCmdArgs = sys.argv[4]\n mfFileLocation = sys.argv[5]\n outputMplFile = sys.argv[6]\n testFile = sys.argv[7]\n goodFilename = sys.argv[8]\n except:\n print \"Syntax: cmake-test-wrapper.py WORKING_DIR ENV_VARS CMD ARG1 ARG2 ... ARGn \"\n sys.exit(0)\n\n returnCode = runCommand(workingDir, bextractLocation, sfpluginLocation, extraBextractCmdArgs,\n mfFileLocation, outputMplFile, testFile, goodFilename)\n\n sys.exit(returnCode)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_user_service.py from Kalyzee/edx-platform (path: common/djangoapps/xblock_django/tests/test_user_service.py)."}, {"role": "assistant", "content": "# common/djangoapps/xblock_django/tests/test_user_service.py (from Kalyzee/edx-platform, license: agpl-3.0)\n\n\"\"\"\nTests for the DjangoXBlockUserService.\n\"\"\"\nfrom django.test import TestCase\nfrom xblock_django.user_service import (\n DjangoXBlockUserService,\n ATTR_KEY_IS_AUTHENTICATED,\n ATTR_KEY_USER_ID,\n ATTR_KEY_USERNAME,\n ATTR_KEY_USER_IS_STAFF,\n)\nfrom student.models import anonymous_id_for_user\nfrom student.tests.factories import UserFactory, AnonymousUserFactory\nfrom opaque_keys.edx.keys import CourseKey\n\nclass UserServiceTestCase(TestCase):\n \"\"\"\n Tests for the DjangoXBlockUserService.\n \"\"\"\n def setUp(self):\n super(UserServiceTestCase, self).setUp()\n self.user = UserFactory(username=\"tester\", email=\"test@tester.com\")\n self.user.profile.name = \"Test Tester\"\n self.anon_user = AnonymousUserFactory()\n\n def assert_is_anon_xb_user(self, xb_user):\n \"\"\"\n A set of assertions for an anonymous XBlockUser.\n \"\"\"\n self.assertFalse(xb_user.opt_attrs[ATTR_KEY_IS_AUTHENTICATED])\n self.assertIsNone(xb_user.full_name)\n self.assertListEqual(xb_user.emails, [])\n\n def assert_xblock_user_matches_django(self, xb_user, dj_user):\n \"\"\"\n A set of assertions for comparing a XBlockUser to a django User\n \"\"\"\n self.assertTrue(xb_user.opt_attrs[ATTR_KEY_IS_AUTHENTICATED])\n self.assertEqual(xb_user.emails[0], dj_user.email)\n self.assertEqual(xb_user.full_name, dj_user.profile.name)\n self.assertEqual(xb_user.opt_attrs[ATTR_KEY_USERNAME], dj_user.username)\n self.assertEqual(xb_user.opt_attrs[ATTR_KEY_USER_ID], dj_user.id)\n self.assertFalse(xb_user.opt_attrs[ATTR_KEY_USER_IS_STAFF])\n\n def test_convert_anon_user(self):\n \"\"\"\n Tests for convert_django_user_to_xblock_user behavior when django user is AnonymousUser.\n \"\"\"\n django_user_service = DjangoXBlockUserService(self.anon_user)\n xb_user = django_user_service.get_current_user()\n self.assertTrue(xb_user.is_current_user)\n self.assert_is_anon_xb_user(xb_user)\n\n def test_convert_authenticate_user(self):\n \"\"\"\n Tests for convert_django_user_to_xblock_user behavior when django user is User.\n \"\"\"\n django_user_service = DjangoXBlockUserService(self.user)\n xb_user = django_user_service.get_current_user()\n self.assertTrue(xb_user.is_current_user)\n self.assert_xblock_user_matches_django(xb_user, self.user)\n\n def test_get_anonymous_user_id_returns_none_for_non_staff_users(self):\n \"\"\"\n Tests for anonymous_user_id method to return None if user is Non-Staff.\n \"\"\"\n django_user_service = DjangoXBlockUserService(self.user, user_is_staff=False)\n\n anonymous_user_id = django_user_service.get_anonymous_user_id(username=self.user.username, course_id='edx/toy/2012_Fall')\n self.assertIsNone(anonymous_user_id)\n\n def test_get_anonymous_user_id_returns_none_for_non_existing_users(self):\n \"\"\"\n Tests for anonymous_user_id method to return None username does not exist in system.\n \"\"\"\n django_user_service = DjangoXBlockUserService(self.user, user_is_staff=True)\n\n anonymous_user_id = django_user_service.get_anonymous_user_id(username=\"No User\", course_id='edx/toy/2012_Fall')\n self.assertIsNone(anonymous_user_id)\n\n def test_get_anonymous_user_id_returns_id_for_existing_users(self):\n \"\"\"\n Tests for anonymous_user_id method returns anonymous user id for a user.\n \"\"\"\n course_key = CourseKey.from_string('edX/toy/2012_Fall')\n anon_user_id = anonymous_id_for_user(\n user=self.user,\n course_id=course_key,\n save=True\n )\n\n django_user_service = DjangoXBlockUserService(self.user, user_is_staff=True)\n anonymous_user_id = django_user_service.get_anonymous_user_id(\n username=self.user.username,\n course_id='edX/toy/2012_Fall'\n )\n\n self.assertEqual(anonymous_user_id, anon_user_id)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements ceskatelevize.py from rbrito/pkg-youtube-dl (path: youtube_dl/extractor/ceskatelevize.py)."}, {"role": "assistant", "content": "# youtube_dl/extractor/ceskatelevize.py (from rbrito/pkg-youtube-dl, license: unlicense)\n\n# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport re\n\nfrom .common import InfoExtractor\nfrom ..compat import (\n compat_urllib_parse_unquote,\n compat_urllib_parse_urlparse,\n)\nfrom ..utils import (\n ExtractorError,\n float_or_none,\n sanitized_Request,\n unescapeHTML,\n update_url_query,\n urlencode_postdata,\n USER_AGENTS,\n)\n\nclass CeskaTelevizeIE(InfoExtractor):\n _VALID_URL = r'https?://(?:www\\.)?ceskatelevize\\.cz/ivysilani/(?:[^/?#&]+/)*(?P[^/#?]+)'\n _TESTS = [{\n 'url': 'http://www.ceskatelevize.cz/ivysilani/ivysilani/10441294653-hyde-park-civilizace/214411058091220',\n 'info_dict': {\n 'id': '61924494877246241',\n 'ext': 'mp4',\n 'title': 'Hyde Park Civilizace: Život v Grónsku',\n 'description': 'md5:3fec8f6bb497be5cdb0c9e8781076626',\n 'thumbnail': r're:^https?://.*\\.jpg',\n 'duration': 3350,\n },\n 'params': {\n # m3u8 download\n 'skip_download': True,\n },\n }, {\n 'url': 'http://www.ceskatelevize.cz/ivysilani/10441294653-hyde-park-civilizace/215411058090502/bonus/20641-bonus-01-en',\n 'info_dict': {\n 'id': '61924494877028507',\n 'ext': 'mp4',\n 'title': 'Hyde Park Civilizace: Bonus 01 - En',\n 'description': 'English Subtittles',\n 'thumbnail': r're:^https?://.*\\.jpg',\n 'duration': 81.3,\n },\n 'params': {\n # m3u8 download\n 'skip_download': True,\n },\n }, {\n # live stream\n 'url': 'http://www.ceskatelevize.cz/ivysilani/zive/ct4/',\n 'info_dict': {\n 'id': 402,\n 'ext': 'mp4',\n 'title': r're:^ČT Sport \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}$',\n 'is_live': True,\n },\n 'params': {\n # m3u8 download\n 'skip_download': True,\n },\n 'skip': 'Georestricted to Czech Republic',\n }, {\n 'url': 'http://www.ceskatelevize.cz/ivysilani/embed/iFramePlayer.php?hash=d6a3e1370d2e4fa76296b90bad4dfc19673b641e&IDEC=217 562 22150/0004&channelID=1&width=100%25',\n 'only_matching': True,\n }]\n\n def _real_extract(self, url):\n playlist_id = self._match_id(url)\n\n webpage = self._download_webpage(url, playlist_id)\n\n NOT_AVAILABLE_STRING = 'This content is not available at your territory due to limited copyright.'\n if '%s

' % NOT_AVAILABLE_STRING in webpage:\n raise ExtractorError(NOT_AVAILABLE_STRING, expected=True)\n\n type_ = None\n episode_id = None\n\n playlist = self._parse_json(\n self._search_regex(\n r'getPlaylistUrl\\(\\[({.+?})\\]', webpage, 'playlist',\n default='{}'), playlist_id)\n if playlist:\n type_ = playlist.get('type')\n episode_id = playlist.get('id')\n\n if not type_:\n type_ = self._html_search_regex(\n r'getPlaylistUrl\\(\\[\\{\"type\":\"(.+?)\",\"id\":\".+?\"\\}\\],',\n webpage, 'type')\n if not episode_id:\n episode_id = self._html_search_regex(\n r'getPlaylistUrl\\(\\[\\{\"type\":\".+?\",\"id\":\"(.+?)\"\\}\\],',\n webpage, 'episode_id')\n\n data = {\n 'playlist[0][type]': type_,\n 'playlist[0][id]': episode_id,\n 'requestUrl': compat_urllib_parse_urlparse(url).path,\n 'requestSource': 'iVysilani',\n }\n\n entries = []\n\n for user_agent in (None, USER_AGENTS['Safari']):\n req = sanitized_Request(\n 'https://www.ceskatelevize.cz/ivysilani/ajax/get-client-playlist',\n data=urlencode_postdata(data))\n\n req.add_header('Content-type', 'application/x-www-form-urlencoded')\n req.add_header('x-addr', '127.0.0.1')\n req.add_header('X-Requested-With', 'XMLHttpRequest')\n if user_agent:\n req.add_header('User-Agent', user_agent)\n req.add_header('Referer', url)\n\n playlistpage = self._download_json(req, playlist_id, fatal=False)\n\n if not playlistpage:\n continue\n\n playlist_url = playlistpage['url']\n if playlist_url == 'error_region':\n raise ExtractorError(NOT_AVAILABLE_STRING, expected=True)\n\n req = sanitized_Request(compat_urllib_parse_unquote(playlist_url))\n req.add_header('Referer', url)\n\n playlist_title = self._og_search_title(webpage, default=None)\n playlist_description = self._og_search_description(webpage, default=None)\n\n playlist = self._download_json(req, playlist_id, fatal=False)\n if not playlist:\n continue\n\n playlist = playlist.get('playlist')\n if not isinstance(playlist, list):\n continue\n\n playlist_len = len(playlist)\n\n for num, item in enumerate(playlist):\n is_live = item.get('type') == 'LIVE'\n formats = []\n for format_id, stream_url in item.get('streamUrls', {}).items():\n if 'drmOnly=true' in stream_url:\n continue\n if 'playerType=flash' in stream_url:\n stream_formats = self._extract_m3u8_formats(\n stream_url, playlist_id, 'mp4', 'm3u8_native',\n m3u8_id='hls-%s' % format_id, fatal=False)\n else:\n stream_formats = self._extract_mpd_formats(\n stream_url, playlist_id,\n mpd_id='dash-%s' % format_id, fatal=False)\n # See https://github.com/ytdl-org/youtube-dl/issues/12119#issuecomment-280037031\n if format_id == 'audioDescription':\n for f in stream_formats:\n f['source_preference'] = -10\n formats.extend(stream_formats)\n\n if user_agent and len(entries) == playlist_len:\n entries[num]['formats'].extend(formats)\n continue\n\n item_id = item.get('id') or item['assetId']\n title = item['title']\n\n duration = float_or_none(item.get('duration'))\n thumbnail = item.get('previewImageUrl')\n\n subtitles = {}\n if item.get('type') == 'VOD':\n subs = item.get('subtitles')\n if subs:\n subtitles = self.extract_subtitles(episode_id, subs)\n\n if playlist_len == 1:\n final_title = playlist_title or title\n if is_live:\n final_title = self._live_title(final_title)\n else:\n final_title = '%s (%s)' % (playlist_title, title)\n\n entries.append({\n 'id': item_id,\n 'title': final_title,\n 'description': playlist_description if playlist_len == 1 else None,\n 'thumbnail': thumbnail,\n 'duration': duration,\n 'formats': formats,\n 'subtitles': subtitles,\n 'is_live': is_live,\n })\n\n for e in entries:\n self._sort_formats(e['formats'])\n\n return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)\n\n def _get_subtitles(self, episode_id, subs):\n original_subtitles = self._download_webpage(\n subs[0]['url'], episode_id, 'Downloading subtitles')\n srt_subs = self._fix_subtitles(original_subtitles)\n return {\n 'cs': [{\n 'ext': 'srt',\n 'data': srt_subs,\n }]\n }\n\n @staticmethod\n def _fix_subtitles(subtitles):\n \"\"\" Convert millisecond-based subtitles to SRT \"\"\"\n\n def _msectotimecode(msec):\n \"\"\" Helper utility to convert milliseconds to timecode \"\"\"\n components = []\n for divider in [1000, 60, 60, 100]:\n components.append(msec % divider)\n msec //= divider\n return '{3:02}:{2:02}:{1:02},{0:03}'.format(*components)\n\n def _fix_subtitle(subtitle):\n for line in subtitle.splitlines():\n m = re.match(r'^\\s*([0-9]+);\\s*([0-9]+)\\s+([0-9]+)\\s*$', line)\n if m:\n yield m.group(1)\n start, stop = (_msectotimecode(int(t)) for t in m.groups()[1:])\n yield '{0} --> {1}'.format(start, stop)\n else:\n yield line\n\n return '\\r\\n'.join(_fix_subtitle(subtitles))\n\nclass CeskaTelevizePoradyIE(InfoExtractor):\n _VALID_URL = r'https?://(?:www\\.)?ceskatelevize\\.cz/porady/(?:[^/?#&]+/)*(?P[^/#?]+)'\n _TESTS = [{\n # video with 18+ caution trailer\n 'url': 'http://www.ceskatelevize.cz/porady/10520528904-queer/215562210900007-bogotart/',\n 'info_dict': {\n 'id': '215562210900007-bogotart',\n 'title': 'Queer: Bogotart',\n 'description': 'Alternativní průvodce současným queer světem',\n },\n 'playlist': [{\n 'info_dict': {\n 'id': '61924494876844842',\n 'ext': 'mp4',\n 'title': 'Queer: Bogotart (Varování 18+)',\n 'duration': 10.2,\n },\n }, {\n 'info_dict': {\n 'id': '61924494877068022',\n 'ext': 'mp4',\n 'title': 'Queer: Bogotart (Queer)',\n 'thumbnail': r're:^https?://.*\\.jpg',\n 'duration': 1558.3,\n },\n }],\n 'params': {\n # m3u8 download\n 'skip_download': True,\n },\n }, {\n # iframe embed\n 'url': 'http://www.ceskatelevize.cz/porady/10614999031-neviditelni/21251212048/',\n 'only_matching': True,\n }]\n\n def _real_extract(self, url):\n video_id = self._match_id(url)\n\n webpage = self._download_webpage(url, video_id)\n\n data_url = update_url_query(unescapeHTML(self._search_regex(\n (r']*\\bdata-url=([\"\\'])(?P(?:(?!\\1).)+)\\1',\n r']+\\bsrc=([\"\\'])(?P(?:https?:)?//(?:www\\.)?ceskatelevize\\.cz/ivysilani/embed/iFramePlayer\\.php.*?)\\1'),\n webpage, 'iframe player url', group='url')), query={\n 'autoStart': 'true',\n })\n\n return self.url_result(data_url, ie=CeskaTelevizeIE.ie_key())"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_volume_driver.py from srajag/nova (path: nova/tests/virt/baremetal/test_volume_driver.py)."}, {"role": "assistant", "content": "# nova/tests/virt/baremetal/test_volume_driver.py (from srajag/nova, license: apache-2.0)\n\n# Copyright (c) 2012 NTT DOCOMO, INC.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Tests for baremetal volume driver.\"\"\"\n\nfrom oslo.config import cfg\n\nfrom nova import exception\nfrom nova import test\nfrom nova.virt.baremetal import volume_driver\nfrom nova.virt import fake\nfrom nova.virt.libvirt import volume as libvirt_volume\n\nCONF = cfg.CONF\n\nSHOW_OUTPUT = \"\"\"Target 1: iqn.2010-10.org.openstack:volume-00000001\n System information:\n Driver: iscsi\n State: ready\n I_T nexus information:\n I_T nexus: 8\n Initiator: iqn.1993-08.org.debian:01:7780c6a16b4\n Connection: 0\n IP Address: 172.17.12.10\n LUN information:\n LUN: 0\n Type: controller\n SCSI ID: IET 00010000\n SCSI SN: beaf10\n Size: 0 MB, Block size: 1\n Online: Yes\n Removable media: No\n Readonly: No\n Backing store type: null\n Backing store path: None\n Backing store flags:\n LUN: 1\n Type: disk\n SCSI ID: IET 00010001\n SCSI SN: beaf11\n Size: 1074 MB, Block size: 512\n Online: Yes\n Removable media: No\n Readonly: No\n Backing store type: rdwr\n Backing store path: /dev/nova-volumes/volume-00000001\n Backing store flags:\n Account information:\n ACL information:\n ALL\nTarget 2: iqn.2010-10.org.openstack:volume-00000002\n System information:\n Driver: iscsi\n State: ready\n I_T nexus information:\n LUN information:\n LUN: 0\n Type: controller\n SCSI ID: IET 00020000\n SCSI SN: beaf20\n Size: 0 MB, Block size: 1\n Online: Yes\n Removable media: No\n Readonly: No\n Backing store type: null\n Backing store path: None\n Backing store flags:\n LUN: 1\n Type: disk\n SCSI ID: IET 00020001\n SCSI SN: beaf21\n Size: 2147 MB, Block size: 512\n Online: Yes\n Removable media: No\n Readonly: No\n Backing store type: rdwr\n Backing store path: /dev/nova-volumes/volume-00000002\n Backing store flags:\n Account information:\n ACL information:\n ALL\nTarget 1000001: iqn.2010-10.org.openstack.baremetal:1000001-dev.vdc\n System information:\n Driver: iscsi\n State: ready\n I_T nexus information:\n LUN information:\n LUN: 0\n Type: controller\n SCSI ID: IET f42410000\n SCSI SN: beaf10000010\n Size: 0 MB, Block size: 1\n Online: Yes\n Removable media: No\n Readonly: No\n Backing store type: null\n Backing store path: None\n Backing store flags:\n LUN: 1\n Type: disk\n SCSI ID: IET f42410001\n SCSI SN: beaf10000011\n Size: 1074 MB, Block size: 512\n Online: Yes\n Removable media: No\n Readonly: No\n Backing store type: rdwr\n Backing store path: /dev/disk/by-path/ip-172.17.12.10:3260-iscsi-\\\niqn.2010-10.org.openstack:volume-00000001-lun-1\n Backing store flags:\n Account information:\n ACL information:\n ALL\n\"\"\"\n\ndef fake_show_tgtadm():\n return SHOW_OUTPUT\n\nclass BareMetalVolumeTestCase(test.NoDBTestCase):\n\n def setUp(self):\n super(BareMetalVolumeTestCase, self).setUp()\n self.stubs.Set(volume_driver, '_show_tgtadm', fake_show_tgtadm)\n\n def test_list_backingstore_path(self):\n l = volume_driver._list_backingstore_path()\n self.assertEqual(len(l), 3)\n self.assertIn('/dev/nova-volumes/volume-00000001', l)\n self.assertIn('/dev/nova-volumes/volume-00000002', l)\n self.assertIn('/dev/disk/by-path/ip-172.17.12.10:3260-iscsi-'\n 'iqn.2010-10.org.openstack:volume-00000001-lun-1', l)\n\n def test_get_next_tid(self):\n tid = volume_driver._get_next_tid()\n self.assertEqual(1000002, tid)\n\n def test_find_tid_found(self):\n tid = volume_driver._find_tid(\n 'iqn.2010-10.org.openstack.baremetal:1000001-dev.vdc')\n self.assertEqual(1000001, tid)\n\n def test_find_tid_not_found(self):\n tid = volume_driver._find_tid(\n 'iqn.2010-10.org.openstack.baremetal:1000002-dev.vdc')\n self.assertIsNone(tid)\n\n def test_get_iqn(self):\n self.flags(iscsi_iqn_prefix='iqn.2012-12.a.b', group='baremetal')\n iqn = volume_driver._get_iqn('instname', '/dev/vdx')\n self.assertEqual('iqn.2012-12.a.b:instname-dev-vdx', iqn)\n\nclass FakeConf(object):\n def __init__(self, source_path):\n self.source_path = source_path\n\nclass BareMetalLibVirtVolumeDriverTestCase(test.TestCase):\n\n def setUp(self):\n super(BareMetalLibVirtVolumeDriverTestCase, self).setUp()\n self.flags(volume_drivers=[\n 'fake=nova.virt.libvirt.volume.LibvirtFakeVolumeDriver',\n 'fake2=nova.virt.libvirt.volume.LibvirtFakeVolumeDriver',\n ], group='libvirt')\n self.driver = volume_driver.LibvirtVolumeDriver(fake.FakeVirtAPI())\n self.disk_info = {\n 'dev': 'vdc',\n 'bus': 'baremetal',\n 'type': 'baremetal',\n }\n self.connection_info = {'driver_volume_type': 'fake'}\n self.mount_point = '/dev/vdc'\n self.mount_device = 'vdc'\n self.source_path = '/dev/sdx'\n self.instance = {'uuid': '12345678-1234-1234-1234-123467890123456',\n 'name': 'instance-00000001'}\n self.fixed_ips = [{'address': '10.2.3.4'},\n {'address': '172.16.17.18'},\n ]\n self.iqn = 'iqn.fake:instance-00000001-dev-vdc'\n self.tid = 100\n\n def test_init_loads_volume_drivers(self):\n self.assertIsInstance(self.driver.volume_drivers['fake'],\n libvirt_volume.LibvirtFakeVolumeDriver)\n self.assertIsInstance(self.driver.volume_drivers['fake2'],\n libvirt_volume.LibvirtFakeVolumeDriver)\n self.assertEqual(len(self.driver.volume_drivers), 2)\n\n def test_fake_connect_volume(self):\n \"\"\"Check connect_volume returns without exceptions.\"\"\"\n self.driver._connect_volume(self.connection_info,\n self.disk_info)\n\n def test_volume_driver_method_ok(self):\n fake_driver = self.driver.volume_drivers['fake']\n self.mox.StubOutWithMock(fake_driver, 'connect_volume')\n fake_driver.connect_volume(self.connection_info, self.disk_info)\n self.mox.ReplayAll()\n self.driver._connect_volume(self.connection_info,\n self.disk_info)\n\n def test_volume_driver_method_driver_type_not_found(self):\n self.connection_info['driver_volume_type'] = 'qwerty'\n self.assertRaises(exception.VolumeDriverNotFound,\n self.driver._connect_volume,\n self.connection_info,\n self.disk_info)\n\n def test_publish_iscsi(self):\n self.mox.StubOutWithMock(volume_driver, '_get_iqn')\n self.mox.StubOutWithMock(volume_driver, '_get_next_tid')\n self.mox.StubOutWithMock(volume_driver, '_create_iscsi_export_tgtadm')\n self.mox.StubOutWithMock(volume_driver, '_allow_iscsi_tgtadm')\n volume_driver._get_iqn(self.instance['name'], self.mount_point).\\\n AndReturn(self.iqn)\n volume_driver._get_next_tid().AndReturn(self.tid)\n volume_driver._create_iscsi_export_tgtadm(self.source_path,\n self.tid,\n self.iqn)\n volume_driver._allow_iscsi_tgtadm(self.tid,\n self.fixed_ips[0]['address'])\n volume_driver._allow_iscsi_tgtadm(self.tid,\n self.fixed_ips[1]['address'])\n self.mox.ReplayAll()\n self.driver._publish_iscsi(self.instance,\n self.mount_point,\n self.fixed_ips,\n self.source_path)\n\n def test_depublish_iscsi_ok(self):\n self.mox.StubOutWithMock(volume_driver, '_get_iqn')\n self.mox.StubOutWithMock(volume_driver, '_find_tid')\n self.mox.StubOutWithMock(volume_driver, '_delete_iscsi_export_tgtadm')\n volume_driver._get_iqn(self.instance['name'], self.mount_point).\\\n AndReturn(self.iqn)\n volume_driver._find_tid(self.iqn).AndReturn(self.tid)\n volume_driver._delete_iscsi_export_tgtadm(self.tid)\n self.mox.ReplayAll()\n self.driver._depublish_iscsi(self.instance, self.mount_point)\n\n def test_depublish_iscsi_do_nothing_if_tid_is_not_found(self):\n self.mox.StubOutWithMock(volume_driver, '_get_iqn')\n self.mox.StubOutWithMock(volume_driver, '_find_tid')\n volume_driver._get_iqn(self.instance['name'], self.mount_point).\\\n AndReturn(self.iqn)\n volume_driver._find_tid(self.iqn).AndReturn(None)\n self.mox.ReplayAll()\n self.driver._depublish_iscsi(self.instance, self.mount_point)\n\n def test_attach_volume(self):\n self.mox.StubOutWithMock(volume_driver, '_get_fixed_ips')\n self.mox.StubOutWithMock(self.driver, '_connect_volume')\n self.mox.StubOutWithMock(self.driver, '_publish_iscsi')\n volume_driver._get_fixed_ips(self.instance).AndReturn(self.fixed_ips)\n self.driver._connect_volume(self.connection_info, self.disk_info).\\\n AndReturn(FakeConf(self.source_path))\n self.driver._publish_iscsi(self.instance, self.mount_point,\n self.fixed_ips, self.source_path)\n self.mox.ReplayAll()\n self.driver.attach_volume(self.connection_info,\n self.instance,\n self.mount_point)\n\n def test_detach_volume(self):\n self.mox.StubOutWithMock(volume_driver, '_get_iqn')\n self.mox.StubOutWithMock(volume_driver, '_find_tid')\n self.mox.StubOutWithMock(volume_driver, '_delete_iscsi_export_tgtadm')\n self.mox.StubOutWithMock(self.driver, '_disconnect_volume')\n volume_driver._get_iqn(self.instance['name'], self.mount_point).\\\n AndReturn(self.iqn)\n volume_driver._find_tid(self.iqn).AndReturn(self.tid)\n volume_driver._delete_iscsi_export_tgtadm(self.tid)\n self.driver._disconnect_volume(self.connection_info,\n self.mount_device)\n self.mox.ReplayAll()\n self.driver.detach_volume(self.connection_info,\n self.instance,\n self.mount_point)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements Range.py from sensysnetworks/uClinux (path: user/python/Demo/classes/Range.py)."}, {"role": "assistant", "content": "# user/python/Demo/classes/Range.py (from sensysnetworks/uClinux, license: gpl-2.0)\n\n# Example of a generator: re-implement the built-in range function\n# without actually constructing the list of values. (It turns out\n# that the built-in function is about 20 times faster -- that's why\n# it's built-in. :-)\n\n# Wrapper function to emulate the complicated range() arguments\n\ndef range(*a):\n\tif len(a) == 1:\n\t\tstart, stop, step = 0, a[0], 1\n\telif len(a) == 2:\n\t\tstart, stop = a\n\t\tstep = 1\n\telif len(a) == 3:\n\t\tstart, stop, step = a\n\telse:\n\t\traise TypeError, 'range() needs 1-3 arguments'\n\treturn Range(start, stop, step)\n\t\n\n# Class implementing a range object.\n# To the user the instances feel like immutable sequences\n# (and you can't concatenate or slice them)\n\nclass Range:\n\n\t# initialization -- should be called only by range() above\n\tdef __init__(self, start, stop, step):\n\t\tif step == 0:\n\t\t\traise ValueError, 'range() called with zero step'\n\t\tself.start = start\n\t\tself.stop = stop\n\t\tself.step = step\n\t\tself.len = max(0, int((self.stop - self.start) / self.step))\n\n\t# implement `x` and is also used by print x\n\tdef __repr__(self):\n\t\treturn 'range' + `self.start, self.stop, self.step`\n\n\t# implement len(x)\n\tdef __len__(self):\n\t\treturn self.len\n\n\t# implement x[i]\n\tdef __getitem__(self, i):\n\t\tif 0 <= i < self.len:\n\t\t\treturn self.start + self.step * i\n\t\telse:\n\t\t\traise IndexError, 'range[i] index out of range'\n\n# Small test program\n\ndef test():\n\timport time, __builtin__\n\tprint range(10), range(-10, 10), range(0, 10, 2)\n\tfor i in range(100, -100, -10): print i,\n\tprint\n\tt1 = time.time()\n\tfor i in range(1000):\n\t\tpass\n\tt2 = time.time()\n\tfor i in __builtin__.range(1000):\n\t\tpass\n\tt3 = time.time()\n\tprint t2-t1, 'sec (class)'\n\tprint t3-t2, 'sec (built-in)'\n\ntest()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements xmlifBase.py from magicrub/mavlink (path: pymavlink/generator/lib/genxmlif/xmlifBase.py)."}, {"role": "assistant", "content": "# pymavlink/generator/lib/genxmlif/xmlifBase.py (from magicrub/mavlink, license: lgpl-3.0)\n\n#\n# genxmlif, Release 0.9.0\n# file: xmlifbase.py\n#\n# XML interface base classes\n#\n# history:\n# 2005-04-25 rl created\n# 2006-08-18 rl some methods for XML schema validation support added\n# 2007-05-25 rl performance optimization (caching) added, bugfixes for XPath handling\n# 2007-07-04 rl complete re-design, API classes moved to xmlifApi.py\n#\n# Copyright (c) 2005-2008 by Roland Leuthe. All rights reserved.\n#\n# --------------------------------------------------------------------\n# The generic XML interface is\n#\n# Copyright (c) 2005-2008 by Roland Leuthe\n#\n# By obtaining, using, and/or copying this software and/or its\n# associated documentation, you agree that you have read, understood,\n# and will comply with the following terms and conditions:\n#\n# Permission to use, copy, modify, and distribute this software and\n# its associated documentation for any purpose and without fee is\n# hereby granted, provided that the above copyright notice appears in\n# all copies, and that both that copyright notice and this permission\n# notice appear in supporting documentation, and that the name of\n# the author not be used in advertising or publicity\n# pertaining to distribution of the software without specific, written\n# prior permission.\n#\n# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD\n# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-\n# ABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR\n# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY\n# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\n# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS\n# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE\n# OF THIS SOFTWARE.\n# --------------------------------------------------------------------\n\n__author__ = \"Roland Leuthe \"\n__date__ = \"28 July 2008\"\n__version__ = \"0.9\"\n\nfrom xml.dom import XML_NAMESPACE, XMLNS_NAMESPACE\nfrom xmlifUtils import NsNameTupleFactory, convertToAbsUrl\n\n########################################\n# XmlIf builder extension base class\n# All not implemented methods have to be overloaded by the derived class!!\n#\n\nclass XmlIfBuilderExtensionBase:\n \"\"\"XmlIf builder extension base class.\n \n This class provides additional data (e.g. line numbers or caches) \n for an element node which are stored in the element node object during parsing.\n \"\"\"\n\n def __init__ (self, filePath, absUrl, treeWrapper, elementWrapperClass):\n \"\"\"Constructor for this class\n \n Input parameter:\n filePath: contains the file path of the corresponding XML file\n absUrl: contains the absolute URL of the corresponding XML file\n \"\"\"\n self.filePath = filePath\n self.absUrl = absUrl\n self.baseUrlStack = [absUrl, ]\n self.treeWrapper = treeWrapper\n self.elementWrapperClass = elementWrapperClass\n\n def startElementHandler (self, curNode, startLineNumber, curNs, attributes=[]):\n \"\"\"Called by the XML parser at creation of an element node.\n \n Input parameter:\n curNode: current element node\n startLineNumber: first line number of the element tag in XML file\n curNs: namespaces visible for this element node\n attributes: list of attributes and their values for this element node \n (same sequence as int he XML file)\n \"\"\"\n \n elementWrapper = self.elementWrapperClass(curNode, self.treeWrapper, curNs, initAttrSeq=0)\n \n elementWrapper.baseUrl = self.__getBaseUrl(elementWrapper)\n elementWrapper.absUrl = self.absUrl\n elementWrapper.filePath = self.filePath\n elementWrapper.startLineNumber = startLineNumber\n elementWrapper.curNs.extend ([(\"xml\", XML_NAMESPACE), (\"xmlns\", XMLNS_NAMESPACE)])\n\n if attributes != []:\n for i in range (0, len(attributes), 2):\n elementWrapper.attributeSequence.append(attributes[i])\n else:\n attrList = elementWrapper.getAttributeDict().keys()\n attrList.sort()\n elementWrapper.attributeSequence.extend (attrList)\n\n self.baseUrlStack.insert (0, elementWrapper.baseUrl)\n\n def endElementHandler (self, curNode, endLineNumber):\n \"\"\"Called by the XML parser after creation of an element node.\n \n Input parameter:\n curNode: current element node\n endLineNumber: last line number of the element tag in XML file\n \"\"\"\n curNode.xmlIfExtElementWrapper.endLineNumber = endLineNumber\n self.baseUrlStack.pop (0)\n\n def __getBaseUrl (self, elementWrapper):\n \"\"\"Retrieve base URL for the given element node.\n \n Input parameter:\n elementWrapper: wrapper of current element node\n \"\"\"\n nsNameBaseAttr = NsNameTupleFactory ((XML_NAMESPACE, \"base\"))\n if elementWrapper.hasAttribute(nsNameBaseAttr):\n return convertToAbsUrl (elementWrapper.getAttribute(nsNameBaseAttr), self.baseUrlStack[0])\n else:\n return self.baseUrlStack[0]"}]} {"messages": [{"role": "user", "content": "Write Python code that implements ipython_helper.py from e-mission/e-mission-server (path: emission/analysis/plotting/leaflet_osm/ipython_helper.py)."}, {"role": "assistant", "content": "# emission/analysis/plotting/leaflet_osm/ipython_helper.py (from e-mission/e-mission-server, license: bsd-3-clause)\n\n\"\"\"\nHelper functions that can display leaflet maps inline in an ipython notebook\n\"\"\"\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import str\nfrom builtins import range\nfrom builtins import *\n\nimport branca.element as bre\n \ndef inline_map(m):\n \"\"\"\n Embeds the HTML source of the map directly into the IPython notebook.\n \n This method will not work if the map depends on any files (json data). Also this uses\n the HTML5 srcdoc attribute, which may not be supported in all browsers.\n \"\"\"\n fig = bre.Figure()\n fig.add_subplot(1,1,1).add_child(m)\n return fig\n\ndef inline_maps(map_list):\n \"\"\"\n Embeds the HTML source of the map_list directly into the IPython notebook.\n \n This method will not work if the map depends on any files (json data). Also this uses\n the HTML5 srcdoc attribute, which may not be supported in all browsers.\n\n map_list: 2-D array of maps. dimensions should be [nRows][nCols]. The method will throw a RuntimeError if not\n nRows: Number of rows\n nCols: Number of columns\n \"\"\"\n ncols = 2\n nrows = (len(map_list)/ncols) + 1\n fig = bre.Figure()\n for i, m in enumerate(map_list):\n fig.add_subplot(nrows,ncols,i+1).add_child(m)\n return fig"}]} {"messages": [{"role": "user", "content": "Write Python code that implements hdfs_wordcount.py from nilsgrabbert/spark (path: examples/src/main/python/streaming/hdfs_wordcount.py)."}, {"role": "assistant", "content": "# examples/src/main/python/streaming/hdfs_wordcount.py (from nilsgrabbert/spark, license: apache-2.0)\n\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\n Counts words in new text files created in the given directory\n Usage: hdfs_wordcount.py \n is the directory that Spark Streaming will use to find and read new text files.\n\n To run this on your local machine on directory `localdir`, run this example\n $ bin/spark-submit examples/src/main/python/streaming/hdfs_wordcount.py localdir\n\n Then create a text file in `localdir` and the words in the file will get counted.\n\"\"\"\nfrom __future__ import print_function\n\nimport sys\n\nfrom pyspark import SparkContext\nfrom pyspark.streaming import StreamingContext\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Usage: hdfs_wordcount.py \", file=sys.stderr)\n exit(-1)\n\n sc = SparkContext(appName=\"PythonStreamingHDFSWordCount\")\n ssc = StreamingContext(sc, 1)\n\n lines = ssc.textFileStream(sys.argv[1])\n counts = lines.flatMap(lambda line: line.split(\" \"))\\\n .map(lambda x: (x, 1))\\\n .reduceByKey(lambda a, b: a+b)\n counts.pprint()\n\n ssc.start()\n ssc.awaitTermination()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements psycopg1.py from williamfeng323/py-web (path: flask/lib/python3.6/site-packages/psycopg2/psycopg1.py)."}, {"role": "assistant", "content": "# flask/lib/python3.6/site-packages/psycopg2/psycopg1.py (from williamfeng323/py-web, license: mit)\n\n\"\"\"psycopg 1.1.x compatibility module\n\nThis module uses the new style connection and cursor types to build a psycopg\n1.1.1.x compatibility layer. It should be considered a temporary hack to run\nold code while porting to psycopg 2. Import it as follows::\n\n from psycopg2 import psycopg1 as psycopg\n\"\"\"\n# psycopg/psycopg1.py - psycopg 1.1.x compatibility module\n#\n# Copyright (C) 2003-2010 Federico Di Gregorio \n#\n# psycopg2 is free software: you can redistribute it and/or modify it\n# under the terms of the GNU Lesser General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# In addition, as a special exception, the copyright holders give\n# permission to link this program with the OpenSSL library (or with\n# modified versions of OpenSSL that use the same license as OpenSSL),\n# and distribute linked combinations including the two.\n#\n# You must obey the GNU Lesser General Public License in all respects for\n# all of the code used other than OpenSSL.\n#\n# psycopg2 is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n# License for more details.\n\nfrom psycopg2 import _psycopg as _2psycopg # noqa\nfrom psycopg2.extensions import cursor as _2cursor\nfrom psycopg2.extensions import connection as _2connection\n\nfrom psycopg2 import * # noqa\nfrom psycopg2 import extensions as _ext\n_2connect = connect\n\ndef connect(*args, **kwargs):\n \"\"\"connect(dsn, ...) -> new psycopg 1.1.x compatible connection object\"\"\"\n kwargs['connection_factory'] = connection\n conn = _2connect(*args, **kwargs)\n conn.set_isolation_level(_ext.ISOLATION_LEVEL_READ_COMMITTED)\n return conn\n\nclass connection(_2connection):\n \"\"\"psycopg 1.1.x connection.\"\"\"\n\n def cursor(self):\n \"\"\"cursor() -> new psycopg 1.1.x compatible cursor object\"\"\"\n return _2connection.cursor(self, cursor_factory=cursor)\n\n def autocommit(self, on_off=1):\n \"\"\"autocommit(on_off=1) -> switch autocommit on (1) or off (0)\"\"\"\n if on_off > 0:\n self.set_isolation_level(_ext.ISOLATION_LEVEL_AUTOCOMMIT)\n else:\n self.set_isolation_level(_ext.ISOLATION_LEVEL_READ_COMMITTED)\n\nclass cursor(_2cursor):\n \"\"\"psycopg 1.1.x cursor.\n\n Note that this cursor implements the exact procedure used by psycopg 1 to\n build dictionaries out of result rows. The DictCursor in the\n psycopg.extras modules implements a much better and faster algorithm.\n \"\"\"\n\n def __build_dict(self, row):\n res = {}\n for i in range(len(self.description)):\n res[self.description[i][0]] = row[i]\n return res\n\n def dictfetchone(self):\n row = _2cursor.fetchone(self)\n if row:\n return self.__build_dict(row)\n else:\n return row\n\n def dictfetchmany(self, size):\n res = []\n rows = _2cursor.fetchmany(self, size)\n for row in rows:\n res.append(self.__build_dict(row))\n return res\n\n def dictfetchall(self):\n res = []\n rows = _2cursor.fetchall(self)\n for row in rows:\n res.append(self.__build_dict(row))\n return res"}]} {"messages": [{"role": "user", "content": "Write Python code that implements forms.py from chrisfranzen/django (path: django/contrib/flatpages/tests/forms.py)."}, {"role": "assistant", "content": "# django/contrib/flatpages/tests/forms.py (from chrisfranzen/django, license: bsd-3-clause)\n\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.contrib.flatpages.forms import FlatpageForm\nfrom django.contrib.flatpages.models import FlatPage\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.utils import translation\n\n@override_settings(SITE_ID=1)\nclass FlatpageAdminFormTests(TestCase):\n fixtures = ['example_site']\n\n def setUp(self):\n self.form_data = {\n 'title': \"A test page\",\n 'content': \"This is a test\",\n 'sites': [settings.SITE_ID],\n }\n\n def test_flatpage_admin_form_url_validation(self):\n \"The flatpage admin form correctly validates urls\"\n self.assertTrue(FlatpageForm(data=dict(url='/new_flatpage/', **self.form_data)).is_valid())\n self.assertTrue(FlatpageForm(data=dict(url='/some.special~chars/', **self.form_data)).is_valid())\n self.assertTrue(FlatpageForm(data=dict(url='/some.very_special~chars-here/', **self.form_data)).is_valid())\n\n self.assertFalse(FlatpageForm(data=dict(url='/a space/', **self.form_data)).is_valid())\n self.assertFalse(FlatpageForm(data=dict(url='/a % char/', **self.form_data)).is_valid())\n self.assertFalse(FlatpageForm(data=dict(url='/a ! char/', **self.form_data)).is_valid())\n self.assertFalse(FlatpageForm(data=dict(url='/a & char/', **self.form_data)).is_valid())\n self.assertFalse(FlatpageForm(data=dict(url='/a ? char/', **self.form_data)).is_valid())\n\n def test_flatpage_requires_leading_slash(self):\n form = FlatpageForm(data=dict(url='no_leading_slash/', **self.form_data))\n with translation.override('en'):\n self.assertFalse(form.is_valid())\n self.assertEqual(form.errors['url'], [\"URL is missing a leading slash.\"])\n\n @override_settings(APPEND_SLASH=True,\n MIDDLEWARE_CLASSES=('django.middleware.common.CommonMiddleware',))\n def test_flatpage_requires_trailing_slash_with_append_slash(self):\n form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data))\n with translation.override('en'):\n self.assertFalse(form.is_valid())\n self.assertEqual(form.errors['url'], [\"URL is missing a trailing slash.\"])\n\n @override_settings(APPEND_SLASH=False,\n MIDDLEWARE_CLASSES=('django.middleware.common.CommonMiddleware',))\n def test_flatpage_doesnt_requires_trailing_slash_without_append_slash(self):\n form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data))\n self.assertTrue(form.is_valid())\n\n def test_flatpage_admin_form_url_uniqueness_validation(self):\n \"The flatpage admin form correctly enforces url uniqueness among flatpages of the same site\"\n data = dict(url='/myflatpage1/', **self.form_data)\n\n FlatpageForm(data=data).save()\n\n f = FlatpageForm(data=data)\n\n self.assertFalse(f.is_valid())\n\n self.assertEqual(\n f.errors,\n {'__all__': ['Flatpage with url /myflatpage1/ already exists for site example.com']})\n\n def test_flatpage_admin_form_edit(self):\n \"\"\"\n Existing flatpages can be edited in the admin form without triggering\n the url-uniqueness validation.\n\n \"\"\"\n existing = FlatPage.objects.create(\n url=\"/myflatpage1/\", title=\"Some page\", content=\"The content\")\n existing.sites.add(settings.SITE_ID)\n\n data = dict(url='/myflatpage1/', **self.form_data)\n\n f = FlatpageForm(data=data, instance=existing)\n\n self.assertTrue(f.is_valid(), f.errors)\n\n updated = f.save()\n\n self.assertEqual(updated.title, \"A test page\")\n\n def test_flatpage_nosites(self):\n data = dict(url='/myflatpage1/', **self.form_data)\n data.update({'sites': ''})\n\n f = FlatpageForm(data=data)\n\n self.assertFalse(f.is_valid())\n\n self.assertEqual(\n f.errors,\n {'sites': [translation.ugettext('This field is required.')]})"}]} {"messages": [{"role": "user", "content": "Write Python code that implements 0002_auto__chg_field_hit_added.py from jmcbailey/django-cached-hitcount (path: cached_hitcount/south_migrations/0002_auto__chg_field_hit_added.py)."}, {"role": "assistant", "content": "# cached_hitcount/south_migrations/0002_auto__chg_field_hit_added.py (from jmcbailey/django-cached-hitcount, license: gpl-3.0)\n\n# -*- coding: utf-8 -*-\nfrom south.utils import datetime_utils as datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n\n # Changing field 'Hit.added'\n db.alter_column(u'cached_hitcount_hit', 'added', self.gf('django.db.models.fields.DateField')())\n\n def backwards(self, orm):\n\n # Changing field 'Hit.added'\n db.alter_column(u'cached_hitcount_hit', 'added', self.gf('django.db.models.fields.DateTimeField')())\n\n models = {\n u'cached_hitcount.blacklistip': {\n 'Meta': {'object_name': 'BlacklistIP'},\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'ip': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40'})\n },\n u'cached_hitcount.hit': {\n 'Meta': {'ordering': \"('-hits',)\", 'object_name': 'Hit'},\n 'added': ('django.db.models.fields.DateField', [], {'default': 'datetime.datetime(2014, 2, 28, 0, 0)'}),\n 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'content_type_set_for_hit'\", 'to': u\"orm['contenttypes.ContentType']\"}),\n 'hits': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'object_pk': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})\n },\n u'contenttypes.contenttype': {\n 'Meta': {'ordering': \"('name',)\", 'unique_together': \"(('app_label', 'model'),)\", 'object_name': 'ContentType', 'db_table': \"'django_content_type'\"},\n 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})\n }\n }\n\n complete_apps = ['cached_hitcount']"}]} {"messages": [{"role": "user", "content": "Write Python code that implements qotd.py from andresriancho/qotd (path: qotd/qotd.py)."}, {"role": "assistant", "content": "# qotd/qotd.py (from andresriancho/qotd, license: gpl-3.0)\n\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2010 Yuen Ho Wong\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nfrom __future__ import with_statement\n\nimport re\nimport os\nimport random\nimport copy\nimport time\nfrom BaseHTTPServer import BaseHTTPRequestHandler\nfrom datetime import datetime, date\nfrom urllib2 import urlopen, URLError\nfrom cPickle import dump, load, HIGHEST_PROTOCOL\nfrom xml.sax import make_parser, SAXException\nfrom xml.sax.handler import ContentHandler, property_xml_string\n\nDOT_FILE_PATH = os.path.join(os.path.expanduser(\"~\"), \".qotd\")\n\nclass Quote(object):\n def __init__(self, author=None, content=None, pubDate=None, printed=False):\n self.author = author\n self.content = content\n self.pubDate = pubDate\n self.printed = printed\n\n def __cmp__(self, other):\n if self.pubDate < other.pubDate:\n return -1\n elif self.pubDate == other.pubDate:\n return 0\n elif self.pubDate > other.pubDate:\n return 1\n\n def __str__(self):\n # Replace the Unicode replacement character often found in the RSS feed\n # with a space and then encode the Unicode string to a UTF8 byte string\n # as per the __str__ protocol demands.\n return ((self.content or u'') + u'\\n-- ' + (self.author or u'')).replace(u'\\ufffd', u' ').encode('utf8')\n\nclass QOTDFeedHandler(ContentHandler):\n def __init__(self):\n self.quotes = []\n self.quote = None\n self.in_item = False\n self.in_title = False\n self.in_description = False\n self.in_pubDate = False\n self.lexing_tag = False\n self.in_tag = False\n # Hack to recover from a few unrecognized\n # unicode chars bombing out the whole script\n self.has_valid_content = False\n\n def startElement(self, name, attrs):\n if name == 'item':\n self.in_item = True\n self.quote = Quote()\n elif name == 'title' and self.in_item:\n self.in_title = True\n elif name == 'description' and self.in_item:\n self.in_description = True\n elif name == 'pubDate' and self.in_item:\n self.in_pubDate = True\n\n def characters(self, content):\n if self.in_item:\n if self.in_title:\n self.quote.author = content\n elif self.in_pubDate:\n st_time = time.strptime(content, u\"%a, %d %b %Y %H:%M:%S %Z\")\n self.quote.pubDate = date.fromtimestamp(time.mktime(st_time))\n elif self.in_description:\n if content == '<':\n self.lexing_tag = True\n elif content == '>':\n self.lexing_tag = False\n elif content.isspace():\n return\n elif content.startswith('/'):\n if self.lexing_tag:\n self.in_tag = False\n else:\n self.in_tag = True\n else:\n if self.in_tag:\n return\n elif not self.lexing_tag and not self.in_tag:\n l = re.findall(ur'\".+\"', content)\n if l:\n self.quote.content = l[0]\n self.has_valid_content = True\n\n def endElement(self, name):\n if name == 'item':\n self.in_item = False\n if self.has_valid_content:\n self.quotes.append(self.quote)\n self.has_valid_content = False\n elif name == 'title' and self.in_item:\n self.in_title = False\n elif name == 'description' and self.in_item:\n self.in_description = False\n elif name == 'pubDate' and self.in_item:\n self.in_pubDate = False\n\ndef update_quotes_cache():\n quotes = None\n resp = urlopen(\"http://www.quotationspage.com/data/qotd.rss\")\n parser = make_parser()\n handler = QOTDFeedHandler()\n parser.setContentHandler(handler)\n try:\n parser.parse(resp)\n except SAXException, e:\n print 'Error parsing qotd.rss', e\n pass\n else:\n quotes = copy.deepcopy(handler.quotes)\n resp = urlopen('http://www.quotationspage.com/data/mqotd.rss')\n parser = make_parser()\n handler = QOTDFeedHandler()\n parser.setContentHandler(handler)\n try:\n parser.parse(resp)\n except SAXException, e:\n print 'Error parsng mqotd.rss', e\n pass\n quotes += handler.quotes\n # Cache the quotes for a day\n with open(DOT_FILE_PATH, 'w') as dotfile:\n dump(quotes, dotfile, HIGHEST_PROTOCOL)\n return quotes\n\ndef main():\n dotfilestatinfo = None\n try:\n dotfilestatinfo = os.stat(DOT_FILE_PATH)\n except (IOError, OSError):\n try:\n print random.choice(update_quotes_cache())\n return 0\n except URLError, e:\n if hasattr(e, 'code'):\n print 'QuoteOfTheDay: Error %d: %s' % (e.code, BaseHTTPRequestHandler.responses[e.code][1])\n elif hasattr(e, 'reason'):\n print 'QuoteOfTheDay: IO or URL Error: ' + str(e.reason)\n return 1\n\n lastmod = datetime.fromtimestamp(dotfilestatinfo.st_mtime)\n\n if (datetime.now() - lastmod).days < 1:\n with open(DOT_FILE_PATH) as dotfile:\n print random.choice(load(dotfile))\n else:\n try:\n print random.choice(update_quotes_cache())\n except URLError, e:\n if hasattr(e, 'code'):\n print 'QuoteOfTheDay: Error %d: %s' % (e.code, BaseHTTPRequestHandler.responses[e.code][1])\n elif hasattr(e, 'reason'):\n print 'QuoteOfTheDay: IO or URL Error: ' + str(e.reason)\n return 1\n\n return 0"}]} {"messages": [{"role": "user", "content": "Write Python code that implements filetransfer.py from michaelgira23/JEREMY (path: Skype4Py/filetransfer.py)."}, {"role": "assistant", "content": "# Skype4Py/filetransfer.py (from michaelgira23/JEREMY, license: bsd-3-clause)\n\n\"\"\"File transfers.\n\"\"\"\n__docformat__ = 'restructuredtext en'\n\nimport os\n\nfrom utils import *\n\nclass FileTransfer(Cached):\n \"\"\"Represents a file transfer.\n \"\"\"\n _ValidateHandle = int\n\n def __repr__(self):\n return Cached.__repr__(self, 'Id')\n\n def _Alter(self, AlterName, Args=None):\n return self._Owner._Alter('FILETRANSFER', self.Id, AlterName, Args)\n\n def _Property(self, PropName, Set=None):\n return self._Owner._Property('FILETRANSFER', self.Id, PropName, Set)\n\n def _GetBytesPerSecond(self):\n return int(self._Property('BYTESPERSECOND'))\n\n BytesPerSecond = property(_GetBytesPerSecond,\n doc=\"\"\"Transfer speed in bytes per second.\n\n :type: int\n \"\"\")\n\n def _GetBytesTransferred(self):\n return long(self._Property('BYTESTRANSFERRED'))\n\n BytesTransferred = property(_GetBytesTransferred,\n doc=\"\"\"Number of bytes transferred.\n\n :type: long\n \"\"\")\n\n def _GetFailureReason(self):\n return str(self._Property('FAILUREREASON'))\n\n FailureReason = property(_GetFailureReason,\n doc=\"\"\"Transfer failure reason.\n\n :type: `enums`.fileTransferFailureReason*\n \"\"\")\n\n def _GetFileName(self):\n return os.path.basename(self.FilePath)\n\n FileName = property(_GetFileName,\n doc=\"\"\"Name of the transferred file.\n\n :type: str\n \"\"\")\n\n def _GetFilePath(self):\n return unicode2path(self._Property('FILEPATH'))\n\n FilePath = property(_GetFilePath,\n doc=\"\"\"Full path to the transferred file.\n\n :type: str\n \"\"\")\n\n def _GetFileSize(self):\n return long(self._Property('FILESIZE'))\n\n FileSize = property(_GetFileSize,\n doc=\"\"\"Size of the transferred file in bytes.\n\n :type: long\n \"\"\")\n\n def _GetFinishDatetime(self):\n from datetime import datetime\n return datetime.fromtimestamp(self.FinishTime)\n\n FinishDatetime = property(_GetFinishDatetime,\n doc=\"\"\"File transfer end date and time.\n\n :type: datetime.datetime\n \"\"\")\n\n def _GetFinishTime(self):\n return float(self._Property('FINISHTIME'))\n\n FinishTime = property(_GetFinishTime,\n doc=\"\"\"File transfer end timestamp.\n\n :type: float\n \"\"\")\n\n def _GetId(self):\n return self._Handle\n\n Id = property(_GetId,\n doc=\"\"\"Unique file transfer Id.\n\n :type: int\n \"\"\")\n\n def _GetPartnerDisplayName(self):\n return self._Property('PARTNER_DISPNAME')\n\n PartnerDisplayName = property(_GetPartnerDisplayName,\n doc=\"\"\"File transfer partner DisplayName.\n\n :type: unicode\n \"\"\")\n\n def _GetPartnerHandle(self):\n return str(self._Property('PARTNER_HANDLE'))\n\n PartnerHandle = property(_GetPartnerHandle,\n doc=\"\"\"File transfer partner Skypename.\n\n :type: str\n \"\"\")\n\n def _GetStartDatetime(self):\n from datetime import datetime\n return datetime.fromtimestamp(self.StartTime)\n\n StartDatetime = property(_GetStartDatetime,\n doc=\"\"\"File transfer start date and time.\n\n :type: datetime.datetime\n \"\"\")\n\n def _GetStartTime(self):\n return float(self._Property('STARTTIME'))\n\n StartTime = property(_GetStartTime,\n doc=\"\"\"File transfer start timestamp.\n\n :type: float\n \"\"\")\n\n def _GetStatus(self):\n return str(self._Property('STATUS'))\n\n Status = property(_GetStatus,\n doc=\"\"\"File transfer status.\n\n :type: `enums`.fileTransferStatus*\n \"\"\")\n\n def _GetType(self):\n return str(self._Property('TYPE'))\n\n Type = property(_GetType,\n doc=\"\"\"File transfer type.\n\n :type: `enums`.fileTransferType*\n \"\"\")\n\nclass FileTransferCollection(CachedCollection):\n _CachedType = FileTransfer"}]} {"messages": [{"role": "user", "content": "Write Python code that implements maxuploadtarget.py from scippio/bitcoin (path: qa/rpc-tests/maxuploadtarget.py)."}, {"role": "assistant", "content": "# qa/rpc-tests/maxuploadtarget.py (from scippio/bitcoin, license: mit)\n\n#!/usr/bin/env python2\n#\n# Distributed under the MIT/X11 software license, see the accompanying\n# file COPYING or http://www.opensource.org/licenses/mit-license.php.\n#\n\nfrom test_framework.mininode import *\nfrom test_framework.test_framework import BitcoinTestFramework\nfrom test_framework.util import *\nfrom test_framework.comptool import wait_until\nimport time\n\n'''\nTest behavior of -maxuploadtarget.\n\n* Verify that getdata requests for old blocks (>1week) are dropped\nif uploadtarget has been reached.\n* Verify that getdata requests for recent blocks are respecteved even\nif uploadtarget has been reached.\n* Verify that the upload counters are reset after 24 hours.\n'''\n\n# TestNode: bare-bones \"peer\". Used mostly as a conduit for a test to sending\n# p2p messages to a node, generating the messages in the main testing logic.\nclass TestNode(NodeConnCB):\n def __init__(self):\n NodeConnCB.__init__(self)\n self.connection = None\n self.ping_counter = 1\n self.last_pong = msg_pong()\n self.block_receive_map = {}\n\n def add_connection(self, conn):\n self.connection = conn\n self.peer_disconnected = False\n\n def on_inv(self, conn, message):\n pass\n\n # Track the last getdata message we receive (used in the test)\n def on_getdata(self, conn, message):\n self.last_getdata = message\n\n def on_block(self, conn, message):\n message.block.calc_sha256()\n try:\n self.block_receive_map[message.block.sha256] += 1\n except KeyError as e:\n self.block_receive_map[message.block.sha256] = 1\n\n # Spin until verack message is received from the node.\n # We use this to signal that our test can begin. This\n # is called from the testing thread, so it needs to acquire\n # the global lock.\n def wait_for_verack(self):\n def veracked():\n return self.verack_received\n return wait_until(veracked, timeout=10)\n\n def wait_for_disconnect(self):\n def disconnected():\n return self.peer_disconnected\n return wait_until(disconnected, timeout=10)\n\n # Wrapper for the NodeConn's send_message function\n def send_message(self, message):\n self.connection.send_message(message)\n\n def on_pong(self, conn, message):\n self.last_pong = message\n\n def on_close(self, conn):\n self.peer_disconnected = True\n\n # Sync up with the node after delivery of a block\n def sync_with_ping(self, timeout=30):\n def received_pong():\n return (self.last_pong.nonce == self.ping_counter)\n self.connection.send_message(msg_ping(nonce=self.ping_counter))\n success = wait_until(received_pong, timeout)\n self.ping_counter += 1\n return success\n\nclass MaxUploadTest(BitcoinTestFramework):\n def __init__(self):\n self.utxo = []\n self.txouts = gen_return_txouts()\n \n def add_options(self, parser):\n parser.add_option(\"--testbinary\", dest=\"testbinary\",\n default=os.getenv(\"BITCOIND\", \"bitcoind\"),\n help=\"bitcoind binary to test\")\n\n def setup_chain(self):\n initialize_chain_clean(self.options.tmpdir, 2)\n\n def setup_network(self):\n # Start a node with maxuploadtarget of 200 MB (/24h)\n self.nodes = []\n self.nodes.append(start_node(0, self.options.tmpdir, [\"-debug\", \"-maxuploadtarget=200\", \"-blockmaxsize=999000\"]))\n\n def mine_full_block(self, node, address):\n # Want to create a full block\n # We'll generate a 66k transaction below, and 14 of them is close to the 1MB block limit\n for j in xrange(14):\n if len(self.utxo) < 14:\n self.utxo = node.listunspent()\n inputs=[]\n outputs = {}\n t = self.utxo.pop()\n inputs.append({ \"txid\" : t[\"txid\"], \"vout\" : t[\"vout\"]})\n remchange = t[\"amount\"] - Decimal(\"0.001000\")\n outputs[address]=remchange\n # Create a basic transaction that will send change back to ourself after account for a fee\n # And then insert the 128 generated transaction outs in the middle rawtx[92] is where the #\n # of txouts is stored and is the only thing we overwrite from the original transaction\n rawtx = node.createrawtransaction(inputs, outputs)\n newtx = rawtx[0:92]\n newtx = newtx + self.txouts\n newtx = newtx + rawtx[94:]\n # Appears to be ever so slightly faster to sign with SIGHASH_NONE\n signresult = node.signrawtransaction(newtx,None,None,\"NONE\")\n txid = node.sendrawtransaction(signresult[\"hex\"], True)\n # Mine a full sized block which will be these transactions we just created\n node.generate(1)\n\n def run_test(self):\n # Before we connect anything, we first set the time on the node\n # to be in the past, otherwise things break because the CNode\n # time counters can't be reset backward after initialization\n old_time = int(time.time() - 2*60*60*24*7)\n self.nodes[0].setmocktime(old_time)\n\n # Generate some old blocks\n self.nodes[0].generate(130)\n\n # test_nodes[0] will only request old blocks\n # test_nodes[1] will only request new blocks\n # test_nodes[2] will test resetting the counters\n test_nodes = []\n connections = []\n\n for i in xrange(3):\n test_nodes.append(TestNode())\n connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_nodes[i]))\n test_nodes[i].add_connection(connections[i])\n\n NetworkThread().start() # Start up network handling in another thread\n [x.wait_for_verack() for x in test_nodes]\n\n # Test logic begins here\n\n # Now mine a big block\n self.mine_full_block(self.nodes[0], self.nodes[0].getnewaddress())\n\n # Store the hash; we'll request this later\n big_old_block = self.nodes[0].getbestblockhash()\n old_block_size = self.nodes[0].getblock(big_old_block, True)['size']\n big_old_block = int(big_old_block, 16)\n\n # Advance to two days ago\n self.nodes[0].setmocktime(int(time.time()) - 2*60*60*24)\n\n # Mine one more block, so that the prior block looks old\n self.mine_full_block(self.nodes[0], self.nodes[0].getnewaddress())\n\n # We'll be requesting this new block too\n big_new_block = self.nodes[0].getbestblockhash()\n new_block_size = self.nodes[0].getblock(big_new_block)['size']\n big_new_block = int(big_new_block, 16)\n\n # test_nodes[0] will test what happens if we just keep requesting the\n # the same big old block too many times (expect: disconnect)\n\n getdata_request = msg_getdata()\n getdata_request.inv.append(CInv(2, big_old_block))\n\n max_bytes_per_day = 200*1024*1024\n daily_buffer = 144 * 1000000\n max_bytes_available = max_bytes_per_day - daily_buffer\n success_count = max_bytes_available / old_block_size\n\n # 144MB will be reserved for relaying new blocks, so expect this to\n # succeed for ~70 tries.\n for i in xrange(success_count):\n test_nodes[0].send_message(getdata_request)\n test_nodes[0].sync_with_ping()\n assert_equal(test_nodes[0].block_receive_map[big_old_block], i+1)\n\n assert_equal(len(self.nodes[0].getpeerinfo()), 3)\n # At most a couple more tries should succeed (depending on how long \n # the test has been running so far).\n for i in xrange(3):\n test_nodes[0].send_message(getdata_request)\n test_nodes[0].wait_for_disconnect()\n assert_equal(len(self.nodes[0].getpeerinfo()), 2)\n print \"Peer 0 disconnected after downloading old block too many times\"\n\n # Requesting the current block on test_nodes[1] should succeed indefinitely,\n # even when over the max upload target.\n # We'll try 200 times\n getdata_request.inv = [CInv(2, big_new_block)]\n for i in xrange(200):\n test_nodes[1].send_message(getdata_request)\n test_nodes[1].sync_with_ping()\n assert_equal(test_nodes[1].block_receive_map[big_new_block], i+1)\n\n print \"Peer 1 able to repeatedly download new block\"\n\n # But if test_nodes[1] tries for an old block, it gets disconnected too.\n getdata_request.inv = [CInv(2, big_old_block)]\n test_nodes[1].send_message(getdata_request)\n test_nodes[1].wait_for_disconnect()\n assert_equal(len(self.nodes[0].getpeerinfo()), 1)\n\n print \"Peer 1 disconnected after trying to download old block\"\n\n print \"Advancing system time on node to clear counters...\"\n\n # If we advance the time by 24 hours, then the counters should reset,\n # and test_nodes[2] should be able to retrieve the old block.\n self.nodes[0].setmocktime(int(time.time()))\n test_nodes[2].sync_with_ping()\n test_nodes[2].send_message(getdata_request)\n test_nodes[2].sync_with_ping()\n assert_equal(test_nodes[2].block_receive_map[big_old_block], 1)\n\n print \"Peer 2 able to download old block\"\n\n [c.disconnect_node() for c in connections]\n\n #stop and start node 0 with 1MB maxuploadtarget, whitelist 127.0.0.1\n print \"Restarting nodes with -whitelist=127.0.0.1\"\n stop_node(self.nodes[0], 0)\n self.nodes[0] = start_node(0, self.options.tmpdir, [\"-debug\", \"-whitelist=127.0.0.1\", \"-maxuploadtarget=1\", \"-blockmaxsize=999000\"])\n\n #recreate/reconnect 3 test nodes\n test_nodes = []\n connections = []\n\n for i in xrange(3):\n test_nodes.append(TestNode())\n connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_nodes[i]))\n test_nodes[i].add_connection(connections[i])\n\n NetworkThread().start() # Start up network handling in another thread\n [x.wait_for_verack() for x in test_nodes]\n\n #retrieve 20 blocks which should be enough to break the 1MB limit\n getdata_request.inv = [CInv(2, big_new_block)]\n for i in xrange(20):\n test_nodes[1].send_message(getdata_request)\n test_nodes[1].sync_with_ping()\n assert_equal(test_nodes[1].block_receive_map[big_new_block], i+1)\n\n getdata_request.inv = [CInv(2, big_old_block)]\n test_nodes[1].send_message(getdata_request)\n test_nodes[1].wait_for_disconnect()\n assert_equal(len(self.nodes[0].getpeerinfo()), 3) #node is still connected because of the whitelist\n\n print \"Peer 1 still connected after trying to download old block (whitelisted)\"\n\n [c.disconnect_node() for c in connections]\n\nif __name__ == '__main__':\n MaxUploadTest().main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements saved_model.py from hsaputra/tensorflow (path: tensorflow/python/saved_model/saved_model.py)."}, {"role": "assistant", "content": "# tensorflow/python/saved_model/saved_model.py (from hsaputra/tensorflow, license: apache-2.0)\n\n# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Convenience functions to save a model.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# pylint: disable=unused-import\nfrom tensorflow.python.saved_model import builder\nfrom tensorflow.python.saved_model import constants\nfrom tensorflow.python.saved_model import loader\nfrom tensorflow.python.saved_model import main_op\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model import signature_def_utils\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.saved_model import utils\n# pylint: enable=unused-import\n# pylint: disable=wildcard-import\nfrom tensorflow.python.saved_model.simple_save import *\n# pylint: enable=wildcard-import\n\nfrom tensorflow.python.util.all_util import remove_undocumented\n\n_allowed_symbols = [\n \"builder\",\n \"constants\",\n \"loader\",\n \"main_op\",\n \"signature_constants\",\n \"signature_def_utils\",\n \"simple_save\",\n \"tag_constants\",\n \"utils\",\n]\nremove_undocumented(__name__, _allowed_symbols)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements hello_auto.py from maximmbed/mbed (path: tools/host_tests/hello_auto.py)."}, {"role": "assistant", "content": "# tools/host_tests/hello_auto.py (from maximmbed/mbed, license: apache-2.0)\n\n\"\"\"\nmbed SDK\nCopyright (c) 2011-2013 ARM Limited\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nclass HelloTest():\n HELLO_WORLD = \"Hello World\"\n\n def test(self, selftest):\n c = selftest.mbed.serial_readline()\n if c is None:\n return selftest.RESULT_IO_SERIAL\n selftest.notify(\"Read %d bytes:\"% len(c))\n selftest.notify(c.strip())\n\n result = True\n # Because we can have targetID here let's try to decode\n if len(c) < len(self.HELLO_WORLD):\n result = False\n else:\n result = self.HELLO_WORLD in c\n return selftest.RESULT_SUCCESS if result else selftest.RESULT_FAILURE"}]} {"messages": [{"role": "user", "content": "Write Python code that implements save_to_mysql.py from keysona/python (path: burness/0002/save_to_mysql.py)."}, {"role": "assistant", "content": "# burness/0002/save_to_mysql.py (from keysona/python, license: mit)\n\n#-*- coding: utf-8-*-\nimport mysql.connector\n\nconfig = {\n 'user': 'root',\n 'password': 'root',\n 'host': '127.0.0.1',\n 'database': 'test',\n 'raise_on_warnings': True,\n}\n\nclass save_keys_to_mysql:\n\tdef __init__(self,path):\n\t\tself.path=path\n\t\tprint(self.path)\n\tdef __conn(self,**conf):\n\t\ttry:\n\t\t\tconn=mysql.connector.connect(**conf)\n\t\t\tprint(conn)\n\t\texcept mysql.connector.Error as err:\n\t\t\tif err.errno == errorcode.ER_ACCESS_DENIED_ERROR:\n\t\t\t\tprint(\"something is wrong with your user name or password\")\n\t\t\telif err.errno == errorcode.ER_BAD_DB_ERROR:\n\t\t\t\tprnt(\"database does not exists\")\n\t\t\telse:\n\t\t\t\tprint(err)\n\t\treturn conn\n\t\t#print(self.conn)\n\n\tdef save_to_mysql(self,**conf):\n\t\tconn=self.__conn(**conf)\n\t\tpath=self.path\n\t\tcursor=conn.cursor()\n\t\tcursor.execute('drop table if exists act_keys')\n\t\tcursor.execute('create table act_keys (id int(8) primary key, act_keys varchar(50))')\n\t\trow=0\n\t\twith open('keys_text.txt','r') as f:\n\t\t\tfor line in f.readlines():\n\t\t\t\t#row_no='0000'+str(row)\n\t\t\t\tact_keys=line.rstrip()\n\t\t\t\tcursor.execute('insert into act_keys (id, act_keys) values (%s, %s)',[row,act_keys])\n\t\t\t\trow+=1\n\t\tconn.commit()\n\t\tcursor.close()\n\t\tconn.close()\n\n\tdef see_all(self,**conf):\n\t\tconn=self.__conn(**conf)\n\t\tcursor=conn.cursor()\n\t\tcursor.execute('select * from act_keys')\n\t\tvalues=cursor.fetchall()\n\t\tprint(values)\n\t\tcursor.close()\n\t\tconn.close()\n\ntest=save_keys_to_mysql('keys_text.txt')\ntest.save_to_mysql(**config)\ntest.see_all(**config)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements io.py from fitermay/intellij-community (path: python/helpers/py2only/docutils/io.py)."}, {"role": "assistant", "content": "# python/helpers/py2only/docutils/io.py (from fitermay/intellij-community, license: apache-2.0)\n\n# $Id: io.py 7596 2013-01-25 13:42:17Z milde $\n# Author: David Goodger \n# Copyright: This module has been placed in the public domain.\n\n\"\"\"\nI/O classes provide a uniform API for low-level input and output. Subclasses\nexist for a variety of input/output mechanisms.\n\"\"\"\n\n__docformat__ = 'reStructuredText'\n\nimport sys\nimport os\nimport re\nimport codecs\nfrom docutils import TransformSpec\nfrom docutils._compat import b\nfrom docutils.utils.error_reporting import locale_encoding, ErrorString, ErrorOutput\n\nclass InputError(IOError): pass\nclass OutputError(IOError): pass\n\ndef check_encoding(stream, encoding):\n \"\"\"Test, whether the encoding of `stream` matches `encoding`.\n\n Returns\n\n :None: if `encoding` or `stream.encoding` are not a valid encoding\n argument (e.g. ``None``) or `stream.encoding is missing.\n :True: if the encoding argument resolves to the same value as `encoding`,\n :False: if the encodings differ.\n \"\"\"\n try:\n return codecs.lookup(stream.encoding) == codecs.lookup(encoding)\n except (LookupError, AttributeError, TypeError):\n return None\n\nclass Input(TransformSpec):\n\n \"\"\"\n Abstract base class for input wrappers.\n \"\"\"\n\n component_type = 'input'\n\n default_source_path = None\n\n def __init__(self, source=None, source_path=None, encoding=None,\n error_handler='strict'):\n self.encoding = encoding\n \"\"\"Text encoding for the input source.\"\"\"\n\n self.error_handler = error_handler\n \"\"\"Text decoding error handler.\"\"\"\n\n self.source = source\n \"\"\"The source of input data.\"\"\"\n\n self.source_path = source_path\n \"\"\"A text reference to the source.\"\"\"\n\n if not source_path:\n self.source_path = self.default_source_path\n\n self.successful_encoding = None\n \"\"\"The encoding that successfully decoded the source data.\"\"\"\n\n def __repr__(self):\n return '%s: source=%r, source_path=%r' % (self.__class__, self.source,\n self.source_path)\n\n def read(self):\n raise NotImplementedError\n\n def decode(self, data):\n \"\"\"\n Decode a string, `data`, heuristically.\n Raise UnicodeError if unsuccessful.\n\n The client application should call ``locale.setlocale`` at the\n beginning of processing::\n\n locale.setlocale(locale.LC_ALL, '')\n \"\"\"\n if self.encoding and self.encoding.lower() == 'unicode':\n assert isinstance(data, unicode), (\n 'input encoding is \"unicode\" '\n 'but input is not a unicode object')\n if isinstance(data, unicode):\n # Accept unicode even if self.encoding != 'unicode'.\n return data\n if self.encoding:\n # We believe the user/application when the encoding is\n # explicitly given.\n encodings = [self.encoding]\n else:\n data_encoding = self.determine_encoding_from_data(data)\n if data_encoding:\n # If the data declares its encoding (explicitly or via a BOM),\n # we believe it.\n encodings = [data_encoding]\n else:\n # Apply heuristics only if no encoding is explicitly given and\n # no BOM found. Start with UTF-8, because that only matches\n # data that *IS* UTF-8:\n encodings = ['utf-8', 'latin-1']\n if locale_encoding:\n encodings.insert(1, locale_encoding)\n for enc in encodings:\n try:\n decoded = unicode(data, enc, self.error_handler)\n self.successful_encoding = enc\n # Return decoded, removing BOMs.\n return decoded.replace(u'\\ufeff', u'')\n except (UnicodeError, LookupError), err:\n error = err # in Python 3, the is\n # local to the except clause\n raise UnicodeError(\n 'Unable to decode input data. Tried the following encodings: '\n '%s.\\n(%s)' % (', '.join([repr(enc) for enc in encodings]),\n ErrorString(error)))\n\n coding_slug = re.compile(b(\"coding[:=]\\s*([-\\w.]+)\"))\n \"\"\"Encoding declaration pattern.\"\"\"\n\n byte_order_marks = ((codecs.BOM_UTF8, 'utf-8'), # 'utf-8-sig' new in v2.5\n (codecs.BOM_UTF16_BE, 'utf-16-be'),\n (codecs.BOM_UTF16_LE, 'utf-16-le'),)\n \"\"\"Sequence of (start_bytes, encoding) tuples for encoding detection.\n The first bytes of input data are checked against the start_bytes strings.\n A match indicates the given encoding.\"\"\"\n\n def determine_encoding_from_data(self, data):\n \"\"\"\n Try to determine the encoding of `data` by looking *in* `data`.\n Check for a byte order mark (BOM) or an encoding declaration.\n \"\"\"\n # check for a byte order mark:\n for start_bytes, encoding in self.byte_order_marks:\n if data.startswith(start_bytes):\n return encoding\n # check for an encoding declaration pattern in first 2 lines of file:\n for line in data.splitlines()[:2]:\n match = self.coding_slug.search(line)\n if match:\n return match.group(1).decode('ascii')\n return None\n\nclass Output(TransformSpec):\n\n \"\"\"\n Abstract base class for output wrappers.\n \"\"\"\n\n component_type = 'output'\n\n default_destination_path = None\n\n def __init__(self, destination=None, destination_path=None,\n encoding=None, error_handler='strict'):\n self.encoding = encoding\n \"\"\"Text encoding for the output destination.\"\"\"\n\n self.error_handler = error_handler or 'strict'\n \"\"\"Text encoding error handler.\"\"\"\n\n self.destination = destination\n \"\"\"The destination for output data.\"\"\"\n\n self.destination_path = destination_path\n \"\"\"A text reference to the destination.\"\"\"\n\n if not destination_path:\n self.destination_path = self.default_destination_path\n\n def __repr__(self):\n return ('%s: destination=%r, destination_path=%r'\n % (self.__class__, self.destination, self.destination_path))\n\n def write(self, data):\n \"\"\"`data` is a Unicode string, to be encoded by `self.encode`.\"\"\"\n raise NotImplementedError\n\n def encode(self, data):\n if self.encoding and self.encoding.lower() == 'unicode':\n assert isinstance(data, unicode), (\n 'the encoding given is \"unicode\" but the output is not '\n 'a Unicode string')\n return data\n if not isinstance(data, unicode):\n # Non-unicode (e.g. bytes) output.\n return data\n else:\n return data.encode(self.encoding, self.error_handler)\n\nclass FileInput(Input):\n\n \"\"\"\n Input for single, simple file-like objects.\n \"\"\"\n def __init__(self, source=None, source_path=None,\n encoding=None, error_handler='strict',\n autoclose=True, handle_io_errors=None, mode='rU'):\n \"\"\"\n :Parameters:\n - `source`: either a file-like object (which is read directly), or\n `None` (which implies `sys.stdin` if no `source_path` given).\n - `source_path`: a path to a file, which is opened and then read.\n - `encoding`: the expected text encoding of the input file.\n - `error_handler`: the encoding error handler to use.\n - `autoclose`: close automatically after read (except when\n `sys.stdin` is the source).\n - `handle_io_errors`: ignored, deprecated, will be removed.\n - `mode`: how the file is to be opened (see standard function\n `open`). The default 'rU' provides universal newline support\n for text files.\n \"\"\"\n Input.__init__(self, source, source_path, encoding, error_handler)\n self.autoclose = autoclose\n self._stderr = ErrorOutput()\n\n if source is None:\n if source_path:\n # Specify encoding in Python 3\n if sys.version_info >= (3,0):\n kwargs = {'encoding': self.encoding,\n 'errors': self.error_handler}\n else:\n kwargs = {}\n\n try:\n self.source = open(source_path, mode, **kwargs)\n except IOError, error:\n raise InputError(error.errno, error.strerror, source_path)\n else:\n self.source = sys.stdin\n elif (sys.version_info >= (3,0) and\n check_encoding(self.source, self.encoding) is False):\n # TODO: re-open, warn or raise error?\n raise UnicodeError('Encoding clash: encoding given is \"%s\" '\n 'but source is opened with encoding \"%s\".' %\n (self.encoding, self.source.encoding))\n if not source_path:\n try:\n self.source_path = self.source.name\n except AttributeError:\n pass\n\n def read(self):\n \"\"\"\n Read and decode a single file and return the data (Unicode string).\n \"\"\"\n try: # In Python < 2.5, try...except has to be nested in try...finally.\n try:\n if self.source is sys.stdin and sys.version_info >= (3,0):\n # read as binary data to circumvent auto-decoding\n data = self.source.buffer.read()\n # normalize newlines\n data = b('\\n').join(data.splitlines()) + b('\\n')\n else:\n data = self.source.read()\n except (UnicodeError, LookupError), err: # (in Py3k read() decodes)\n if not self.encoding and self.source_path:\n # re-read in binary mode and decode with heuristics\n b_source = open(self.source_path, 'rb')\n data = b_source.read()\n b_source.close()\n # normalize newlines\n data = b('\\n').join(data.splitlines()) + b('\\n')\n else:\n raise\n finally:\n if self.autoclose:\n self.close()\n return self.decode(data)\n\n def readlines(self):\n \"\"\"\n Return lines of a single file as list of Unicode strings.\n \"\"\"\n return self.read().splitlines(True)\n\n def close(self):\n if self.source is not sys.stdin:\n self.source.close()\n\nclass FileOutput(Output):\n\n \"\"\"\n Output for single, simple file-like objects.\n \"\"\"\n\n mode = 'w'\n \"\"\"The mode argument for `open()`.\"\"\"\n # 'wb' for binary (e.g. OpenOffice) files (see also `BinaryFileOutput`).\n # (Do not use binary mode ('wb') for text files, as this prevents the\n # conversion of newlines to the system specific default.)\n\n def __init__(self, destination=None, destination_path=None,\n encoding=None, error_handler='strict', autoclose=True,\n handle_io_errors=None, mode=None):\n \"\"\"\n :Parameters:\n - `destination`: either a file-like object (which is written\n directly) or `None` (which implies `sys.stdout` if no\n `destination_path` given).\n - `destination_path`: a path to a file, which is opened and then\n written.\n - `encoding`: the text encoding of the output file.\n - `error_handler`: the encoding error handler to use.\n - `autoclose`: close automatically after write (except when\n `sys.stdout` or `sys.stderr` is the destination).\n - `handle_io_errors`: ignored, deprecated, will be removed.\n - `mode`: how the file is to be opened (see standard function\n `open`). The default is 'w', providing universal newline\n support for text files.\n \"\"\"\n Output.__init__(self, destination, destination_path,\n encoding, error_handler)\n self.opened = True\n self.autoclose = autoclose\n if mode is not None:\n self.mode = mode\n self._stderr = ErrorOutput()\n if destination is None:\n if destination_path:\n self.opened = False\n else:\n self.destination = sys.stdout\n elif (# destination is file-type object -> check mode:\n mode and hasattr(self.destination, 'mode')\n and mode != self.destination.mode):\n print >>self._stderr, ('Warning: Destination mode \"%s\" '\n 'differs from specified mode \"%s\"' %\n (self.destination.mode, mode))\n if not destination_path:\n try:\n self.destination_path = self.destination.name\n except AttributeError:\n pass\n\n def open(self):\n # Specify encoding in Python 3.\n if sys.version_info >= (3,0) and 'b' not in self.mode:\n kwargs = {'encoding': self.encoding,\n 'errors': self.error_handler}\n else:\n kwargs = {}\n try:\n self.destination = open(self.destination_path, self.mode, **kwargs)\n except IOError, error:\n raise OutputError(error.errno, error.strerror,\n self.destination_path)\n self.opened = True\n\n def write(self, data):\n \"\"\"Encode `data`, write it to a single file, and return it.\n\n With Python 3 or binary output mode, `data` is returned unchanged,\n except when specified encoding and output encoding differ.\n \"\"\"\n if not self.opened:\n self.open()\n if ('b' not in self.mode and sys.version_info < (3,0)\n or check_encoding(self.destination, self.encoding) is False\n ):\n if sys.version_info >= (3,0) and os.linesep != '\\n':\n data = data.replace('\\n', os.linesep) # fix endings\n data = self.encode(data)\n\n try: # In Python < 2.5, try...except has to be nested in try...finally.\n try:\n self.destination.write(data)\n except TypeError, e:\n if sys.version_info >= (3,0) and isinstance(data, bytes):\n try:\n self.destination.buffer.write(data)\n except AttributeError:\n if check_encoding(self.destination, \n self.encoding) is False:\n raise ValueError('Encoding of %s (%s) differs \\n'\n ' from specified encoding (%s)' %\n (self.destination_path or 'destination',\n self.destination.encoding, self.encoding))\n else:\n raise e\n except (UnicodeError, LookupError), err:\n raise UnicodeError(\n 'Unable to encode output data. output-encoding is: '\n '%s.\\n(%s)' % (self.encoding, ErrorString(err)))\n finally:\n if self.autoclose:\n self.close()\n return data\n\n def close(self):\n if self.destination not in (sys.stdout, sys.stderr):\n self.destination.close()\n self.opened = False\n\nclass BinaryFileOutput(FileOutput):\n \"\"\"\n A version of docutils.io.FileOutput which writes to a binary file.\n \"\"\"\n # Used by core.publish_cmdline_to_binary() which in turn is used by\n # rst2odt (OpenOffice writer)\n mode = 'wb'\n\nclass StringInput(Input):\n\n \"\"\"\n Direct string input.\n \"\"\"\n\n default_source_path = ''\n\n def read(self):\n \"\"\"Decode and return the source string.\"\"\"\n return self.decode(self.source)\n\nclass StringOutput(Output):\n\n \"\"\"\n Direct string output.\n \"\"\"\n\n default_destination_path = ''\n\n def write(self, data):\n \"\"\"Encode `data`, store it in `self.destination`, and return it.\"\"\"\n self.destination = self.encode(data)\n return self.destination\n\nclass NullInput(Input):\n\n \"\"\"\n Degenerate input: read nothing.\n \"\"\"\n\n default_source_path = 'null input'\n\n def read(self):\n \"\"\"Return a null string.\"\"\"\n return u''\n\nclass NullOutput(Output):\n\n \"\"\"\n Degenerate output: write nothing.\n \"\"\"\n\n default_destination_path = 'null output'\n\n def write(self, data):\n \"\"\"Do nothing ([don't even] send data to the bit bucket).\"\"\"\n pass\n\nclass DocTreeInput(Input):\n\n \"\"\"\n Adapter for document tree input.\n\n The document tree must be passed in the ``source`` parameter.\n \"\"\"\n\n default_source_path = 'doctree input'\n\n def read(self):\n \"\"\"Return the document tree.\"\"\"\n return self.source"}]} {"messages": [{"role": "user", "content": "Write Python code that implements admin_modify.py from KellyChan/Python (path: javascript/backbone/backbone-templates/backbone-fileupload/venvs/lib/python2.7/site-packages/django/contrib/admin/templatetags/admin_modify.py)."}, {"role": "assistant", "content": "# javascript/backbone/backbone-templates/backbone-fileupload/venvs/lib/python2.7/site-packages/django/contrib/admin/templatetags/admin_modify.py (from KellyChan/Python, license: mit)\n\nfrom django import template\n\nregister = template.Library()\n\n@register.inclusion_tag('admin/prepopulated_fields_js.html', takes_context=True)\ndef prepopulated_fields_js(context):\n \"\"\"\n Creates a list of prepopulated_fields that should render Javascript for\n the prepopulated fields for both the admin form and inlines.\n \"\"\"\n prepopulated_fields = []\n if context['add'] and 'adminform' in context:\n prepopulated_fields.extend(context['adminform'].prepopulated_fields)\n if 'inline_admin_formsets' in context:\n for inline_admin_formset in context['inline_admin_formsets']:\n for inline_admin_form in inline_admin_formset:\n if inline_admin_form.original is None:\n prepopulated_fields.extend(inline_admin_form.prepopulated_fields)\n context.update({'prepopulated_fields': prepopulated_fields})\n return context\n\n@register.inclusion_tag('admin/submit_line.html', takes_context=True)\ndef submit_row(context):\n \"\"\"\n Displays the row of buttons for delete and save.\n \"\"\"\n opts = context['opts']\n change = context['change']\n is_popup = context['is_popup']\n save_as = context['save_as']\n return {\n 'onclick_attrib': (opts.get_ordered_objects() and change\n and 'onclick=\"submitOrderForm();\"' or ''),\n 'show_delete_link': (not is_popup and context['has_delete_permission']\n and (change or context['show_delete'])),\n 'show_save_as_new': not is_popup and change and save_as,\n 'show_save_and_add_another': context['has_add_permission'] and\n not is_popup and (not save_as or context['add']),\n 'show_save_and_continue': not is_popup and context['has_change_permission'],\n 'is_popup': is_popup,\n 'show_save': True\n }\n\n@register.filter\ndef cell_count(inline_admin_form):\n \"\"\"Returns the number of cells used in a tabular inline\"\"\"\n count = 1 # Hidden cell with hidden 'id' field\n for fieldset in inline_admin_form:\n # Loop through all the fields (one per cell)\n for line in fieldset:\n for field in line:\n count += 1\n if inline_admin_form.formset.can_delete:\n # Delete checkbox\n count += 1\n return count"}]} {"messages": [{"role": "user", "content": "Write Python code that implements utilities.py from zeroSteiner/smoke-zephyr (path: smoke_zephyr/utilities.py)."}, {"role": "assistant", "content": "# smoke_zephyr/utilities.py (from zeroSteiner/smoke-zephyr, license: bsd-3-clause)\n\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# smoke_zephyr/utilities.py\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of the project nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\nimport collections\nimport functools\nimport inspect\nimport ipaddress\nimport itertools\nimport logging\nimport os\nimport random\nimport re\nimport shutil\nimport string\nimport subprocess\nimport sys\nimport time\nimport unittest\nimport urllib.parse\nimport urllib.request\nimport weakref\n\nEMAIL_REGEX = re.compile(r'^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,6}$', flags=re.IGNORECASE)\n\nclass AttributeDict(dict):\n\t\"\"\"\n\tThis class allows dictionary keys to be accessed as attributes. For\n\texample: ``ad = AttributeDict(test=1); ad['test'] == ad.test``\n\t\"\"\"\n\t__getattr__ = dict.__getitem__\n\t__setattr__ = dict.__setitem__\n\nclass BruteforceGenerator(object):\n\t\"\"\"\n\tThis class allows itarating sequences for bruteforcing.\n\t\"\"\"\n\t# requirments = itertools\n\tdef __init__(self, startlen, endlen=None, charset=None):\n\t\t\"\"\"\n\t\t:param int startlen: The minimum sequence size to generate.\n\t\t:param int endlen: The maximum sequence size to generate.\n\t\t:param charset: The characters to include in the resulting sequences.\n\t\t\"\"\"\n\t\tself.startlen = startlen\n\t\tif endlen is None:\n\t\t\tself.endlen = startlen\n\t\telse:\n\t\t\tself.endlen = endlen\n\t\tif charset is None:\n\t\t\tcharset = list(map(chr, range(0, 256)))\n\t\telif isinstance(charset, str):\n\t\t\tcharset = list(charset)\n\t\telif isinstance(charset, bytes):\n\t\t\tcharset = list(map(chr, charset))\n\t\tcharset.sort()\n\t\tself.charset = tuple(charset)\n\t\tself.length = self.startlen\n\t\tself._product = itertools.product(self.charset, repeat=self.length)\n\t\tself._next = self.__next__\n\n\tdef __iter__(self):\n\t\treturn self\n\n\tdef __next__(self):\n\t\treturn self.next()\n\n\tdef next(self):\n\t\ttry:\n\t\t\tvalue = next(self._product)\n\t\texcept StopIteration:\n\t\t\tif self.length == self.endlen:\n\t\t\t\traise StopIteration\n\t\t\tself.length += 1\n\t\t\tself._product = itertools.product(self.charset, repeat=self.length)\n\t\t\tvalue = next(self._product)\n\t\treturn ''.join(value)\n\n_ArgSpec = collections.namedtuple('_ArgSpec', ('args', 'varargs', 'keywords', 'defaults'))\nclass Cache(object):\n\t\"\"\"\n\tThis class provides a simple to use cache object which can be applied\n\tas a decorator.\n\t\"\"\"\n\tdef __init__(self, timeout):\n\t\t\"\"\"\n\t\t:param timeout: The amount of time in seconds that a cached\n\t\t\tresult will be considered valid for.\n\t\t:type timeout: int, str\n\t\t\"\"\"\n\t\tif isinstance(timeout, str):\n\t\t\ttimeout = parse_timespan(timeout)\n\t\tself.cache_timeout = timeout\n\t\tself._target_function = None\n\t\tself._target_function_arg_spec = None\n\t\tself.__cache = {}\n\t\tself.__obj = None\n\n\tdef __get__(self, instance, _):\n\t\tself.__obj = instance\n\t\treturn self\n\n\tdef __call__(self, *args, **kwargs):\n\t\tif not getattr(self, '_target_function', False):\n\t\t\ttarget_function = args[0]\n\t\t\tif not inspect.isfunction(target_function) and not inspect.ismethod(target_function):\n\t\t\t\traise RuntimeError('the cached object must be a function or method')\n\t\t\targ_spec = inspect.getfullargspec(target_function) # pylint: disable=W1505\n\t\t\targ_spec = _ArgSpec(args=arg_spec.args, varargs=arg_spec.varargs, keywords=arg_spec.kwonlyargs, defaults=arg_spec.defaults)\n\t\t\tif arg_spec.varargs or arg_spec.keywords:\n\t\t\t\traise RuntimeError('the cached function can not use dynamic args or kwargs')\n\t\t\tself._target_function = target_function\n\t\t\tself._target_function_arg_spec = arg_spec\n\t\t\treturn functools.wraps(target_function)(self)\n\n\t\tself.cache_clean()\n\t\tif self.__obj is not None:\n\t\t\targs = (self.__obj,) + args\n\t\t\tself.__obj = None\n\t\t\tis_method = True\n\t\telse:\n\t\t\tis_method = False\n\t\targs = self._flatten_args(args, kwargs)\n\t\tif is_method:\n\t\t\tinst = args.popleft()\n\t\t\targs = tuple(args)\n\t\t\tref = weakref.ref(inst, functools.partial(self._ref_callback, args))\n\t\t\tcache_args = (ref,) + args\n\t\t\targs = (inst,) + args\n\t\telse:\n\t\t\tcache_args = tuple(args)\n\t\t\targs = tuple(args)\n\t\tresult, expiration = self.__cache.get(cache_args, (None, 0))\n\t\tif expiration > time.time():\n\t\t\treturn result\n\t\tresult = self._target_function(*args)\n\t\tself.__cache[cache_args] = (result, time.time() + self.cache_timeout)\n\t\treturn result\n\n\tdef __repr__(self):\n\t\treturn \"\".format(self._target_function.__name__, id(self._target_function))\n\n\tdef _flatten_args(self, args, kwargs):\n\t\tflattened_args = collections.deque(args)\n\t\targ_spec = self._target_function_arg_spec\n\n\t\targ_spec_defaults = (arg_spec.defaults or [])\n\t\tdefault_args = tuple(arg_spec.args[:-len(arg_spec_defaults)])\n\t\tdefault_kwargs = dict(zip(arg_spec.args[-len(arg_spec_defaults):], arg_spec_defaults))\n\n\t\tfor arg_id in range(len(args), len(arg_spec.args)):\n\t\t\targ_name = arg_spec.args[arg_id]\n\t\t\tif arg_name in default_args:\n\t\t\t\tif not arg_name in kwargs:\n\t\t\t\t\traise TypeError(\"{0}() missing required argument '{1}'\".format(self._target_function.__name__, arg_name))\n\t\t\t\tflattened_args.append(kwargs.pop(arg_name))\n\t\t\telse:\n\t\t\t\tflattened_args.append(kwargs.pop(arg_name, default_kwargs[arg_name]))\n\n\t\tif kwargs:\n\t\t\tunexpected_kwargs = tuple(\"'{0}'\".format(a) for a in kwargs.keys())\n\t\t\traise TypeError(\"{0}() got an unexpected keyword argument{1} {2}\".format(self._target_function.__name__, ('' if len(unexpected_kwargs) == 1 else 's'), ', '.join(unexpected_kwargs)))\n\t\treturn flattened_args\n\n\tdef _ref_callback(self, args, ref):\n\t\targs = (ref,) + args\n\t\tself.__cache.pop(args, None)\n\n\tdef cache_clean(self):\n\t\t\"\"\"\n\t\tRemove expired items from the cache.\n\t\t\"\"\"\n\t\tnow = time.time()\n\t\tkeys_for_removal = collections.deque()\n\t\tfor key, (_, expiration) in self.__cache.items():\n\t\t\tif expiration < now:\n\t\t\t\tkeys_for_removal.append(key)\n\t\tfor key in keys_for_removal:\n\t\t\tdel self.__cache[key]\n\n\tdef cache_clear(self):\n\t\t\"\"\"\n\t\tRemove all items from the cache.\n\t\t\"\"\"\n\t\tself.__cache = {}\n\nclass FileWalker(object):\n\t\"\"\"\n\tThis class is used to easily iterate over files and subdirectories of a\n\tspecified parent directory.\n\t\"\"\"\n\tdef __init__(self, filespath, absolute_path=False, skip_files=False, skip_dirs=False, filter_func=None, follow_links=False, max_depth=None):\n\t\t\"\"\"\n\t\t.. versionchanged:: 1.4.0\n\t\t\tAdded the *follow_links* and *max_depth* parameters.\n\n\t\t:param str filespath: A path to either a file or a directory. If\n\t\t\ta file is passed then that will be the only file returned\n\t\t\tduring the iteration. If a directory is passed, all files and\n\t\t\tsubdirectories will be recursively returned during the iteration.\n\t\t:param bool absolute_path: Whether or not the absolute path or a\n\t\t\trelative path should be returned.\n\t\t:param bool skip_files: Whether or not to skip files.\n\t\t:param bool skip_dirs: Whether or not to skip directories.\n\t\t:param function filter_func: If defined, the filter_func function will\n\t\t\tbe called for each path (with the path as the one and only argument)\n\t\t\tand if the function returns false the path will be skipped.\n\t\t:param bool follow_links: Whether or not to follow directories pointed\n\t\t\tto by symlinks.\n\t\t:param max_depth: A maximum depth to recurse into.\n\t\t\"\"\"\n\t\tif not (os.path.isfile(filespath) or os.path.isdir(filespath)):\n\t\t\traise Exception(filespath + ' is neither a file or directory')\n\t\tif absolute_path:\n\t\t\tself.filespath = os.path.abspath(filespath)\n\t\telse:\n\t\t\tself.filespath = os.path.relpath(filespath)\n\t\tself.skip_files = skip_files\n\t\tself.skip_dirs = skip_dirs\n\t\tself.filter_func = filter_func\n\t\tself.follow_links = follow_links\n\t\tself.max_depth = float('inf') if max_depth is None else max_depth\n\t\tif os.path.isdir(self.filespath):\n\t\t\tself._walk = None\n\t\t\tself._next = self._next_dir\n\t\telif os.path.isfile(self.filespath):\n\t\t\tself._next = self._next_file\n\n\tdef __iter__(self):\n\t\treturn self._next()\n\n\tdef _skip(self, cur_file):\n\t\tif self.skip_files and os.path.isfile(cur_file):\n\t\t\treturn True\n\t\tif self.skip_dirs and os.path.isdir(cur_file):\n\t\t\treturn True\n\t\tif self.filter_func is not None:\n\t\t\tif not self.filter_func(cur_file):\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef _next_dir(self):\n\t\tfor root, dirs, files in os.walk(self.filespath, followlinks=self.follow_links):\n\t\t\tif root == self.filespath:\n\t\t\t\tdepth = 0\n\t\t\telse:\n\t\t\t\tdepth = os.path.relpath(root, start=self.filespath).count(os.path.sep) + 1\n\t\t\tif depth >= self.max_depth:\n\t\t\t\tcontinue\n\t\t\tfor entry in itertools.chain(dirs, files):\n\t\t\t\tcurrent_path = os.path.join(root, entry)\n\t\t\t\tif not self._skip(current_path):\n\t\t\t\t\tyield current_path\n\t\tif self.max_depth >= 0 and not self._skip(self.filespath):\n\t\t\tyield self.filespath\n\n\tdef _next_file(self):\n\t\tif self.max_depth >= 0 and not self._skip(self.filespath):\n\t\t\tyield self.filespath\n\nclass SectionConfigParser(object):\n\t\"\"\"\n\tProxy access to a section of a ConfigParser object.\n\t\"\"\"\n\t__version__ = '0.2'\n\tdef __init__(self, section_name, config_parser):\n\t\t\"\"\"\n\t\t:param str section_name: Name of the section to proxy access for.\n\t\t:param config_parser: ConfigParser object to proxy access for.\n\t\t:type config_parse: :py:class:`ConfigParser.ConfigParser`\n\t\t\"\"\"\n\t\tself.section_name = section_name\n\t\tself.config_parser = config_parser\n\n\tdef _get_raw(self, option, opt_type, default=None):\n\t\tget_func = getattr(self.config_parser, 'get' + opt_type)\n\t\tif default is None:\n\t\t\treturn get_func(self.section_name, option)\n\t\telif self.config_parser.has_option(self.section_name, option):\n\t\t\treturn get_func(self.section_name, option)\n\t\telse:\n\t\t\treturn default\n\n\tdef get(self, option, default=None):\n\t\t\"\"\"\n\t\tRetrieve *option* from the config, returning *default* if it\n\t\tis not present.\n\n\t\t:param str option: The name of the value to return.\n\t\t:param default: Default value to return if the option does not exist.\n\t\t\"\"\"\n\t\treturn self._get_raw(option, '', default)\n\n\tdef getint(self, option, default=None):\n\t\t\"\"\"\n\t\tRetrieve *option* from the config, returning *default* if it\n\t\tis not present.\n\n\t\t:param str option: The name of the value to return.\n\t\t:param default: Default value to return if the option does not exist.\n\t\t:rtype: int\n\t\t\"\"\"\n\t\treturn self._get_raw(option, 'int', default)\n\n\tdef getfloat(self, option, default=None):\n\t\t\"\"\"\n\t\tRetrieve *option* from the config, returning *default* if it\n\t\tis not present.\n\n\t\t:param str option: The name of the value to return.\n\t\t:param default: Default value to return if the option does not exist.\n\t\t:rtype: float\n\t\t\"\"\"\n\t\treturn self._get_raw(option, 'float', default)\n\n\tdef getboolean(self, option, default=None):\n\t\t\"\"\"\n\t\tRetrieve *option* from the config, returning *default* if it\n\t\tis not present.\n\n\t\t:param str option: The name of the value to return.\n\t\t:param default: Default value to return if the option does not exist.\n\t\t:rtype: bool\n\t\t\"\"\"\n\t\treturn self._get_raw(option, 'boolean', default)\n\n\tdef has_option(self, option):\n\t\t\"\"\"\n\t\tCheck that *option* exists in the configuration file.\n\n\t\t:param str option: The name of the option to check.\n\t\t:rtype: bool\n\t\t\"\"\"\n\t\treturn self.config_parser.has_option(self.section_name, option)\n\n\tdef options(self):\n\t\t\"\"\"\n\t\tGet a list of all options that are present in the section of the\n\t\tconfiguration.\n\n\t\t:return: A list of all set options.\n\t\t:rtype: list\n\t\t\"\"\"\n\t\treturn self.config_parser.options(self.section_name)\n\n\tdef items(self):\n\t\t\"\"\"\n\t\tReturn all options and their values in the form of a list of tuples.\n\n\t\t:return: A list of all values and options.\n\t\t:rtype: list\n\t\t\"\"\"\n\t\treturn self.config_parser.items(self.section_name)\n\n\tdef set(self, option, value):\n\t\t\"\"\"\n\t\tSet an option to an arbitrary value.\n\n\t\t:param str option: The name of the option to set.\n\t\t:param value: The value to set the option to.\n\t\t\"\"\"\n\t\tself.config_parser.set(self.section_name, option, value)\n\nclass TestCase(unittest.TestCase):\n\t\"\"\"\n\tThis class provides additional functionality over the built in\n\t:py:class:`unittest.TestCase` object, including better compatibility for\n\tmethods across Python 2.x and Python 3.x.\n\t\"\"\"\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(TestCase, self).__init__(*args, **kwargs)\n\t\tif not hasattr(self, 'assertRegex') and hasattr(self, 'assertRegexpMatches'):\n\t\t\tself.assertRegex = self.assertRegexpMatches\n\t\tif not hasattr(self, 'assertNotRegex') and hasattr(self, 'assertNotRegexpMatches'):\n\t\t\tself.assertNotRegex = self.assertNotRegexpMatches\n\t\tif not hasattr(self, 'assertRaisesRegex') and hasattr(self, 'assertRaisesRegexp'):\n\t\t\tself.assertRaisesRegex = self.assertRaisesRegexp\n\ndef configure_stream_logger(logger='', level=None, formatter='%(levelname)-8s %(message)s'):\n\t\"\"\"\n\tConfigure the default stream handler for logging messages to the console,\n\tremove other logging handlers, and enable capturing warnings.\n\n\t.. versionadded:: 1.3.0\n\n\t:param str logger: The logger to add the stream handler for.\n\t:param level: The level to set the logger to, will default to WARNING if no level is specified.\n\t:type level: None, int, str\n\t:param formatter: The format to use for logging messages to the console.\n\t:type formatter: str, :py:class:`logging.Formatter`\n\t:return: The new configured stream handler.\n\t:rtype: :py:class:`logging.StreamHandler`\n\t\"\"\"\n\tlevel = level or logging.WARNING\n\tif isinstance(level, str):\n\t\tlevel = getattr(logging, level, None)\n\t\tif level is None:\n\t\t\traise ValueError('invalid log level: ' + level)\n\troot_logger = logging.getLogger('')\n\tfor handler in root_logger.handlers:\n\t\troot_logger.removeHandler(handler)\n\n\tlogging.getLogger(logger).setLevel(logging.DEBUG)\n\tconsole_log_handler = logging.StreamHandler()\n\tconsole_log_handler.setLevel(level)\n\tif isinstance(formatter, str):\n\t\tformatter = logging.Formatter(formatter)\n\telif not isinstance(formatter, logging.Formatter):\n\t\traise TypeError('formatter must be an instance of logging.Formatter')\n\tconsole_log_handler.setFormatter(formatter)\n\tlogging.getLogger(logger).addHandler(console_log_handler)\n\tlogging.captureWarnings(True)\n\treturn console_log_handler\n\ndef download(url, filename=None):\n\t\"\"\"\n\tDownload a file from a url and save it to disk.\n\n\t:param str url: The URL to fetch the file from.\n\t:param str filename: The destination file to write the data to.\n\t\"\"\"\n\t# requirements os, shutil, urllib.parse, urllib.request\n\tif not filename:\n\t\turl_parts = urllib.parse.urlparse(url)\n\t\tfilename = os.path.basename(url_parts.path)\n\turl_h = urllib.request.urlopen(url)\n\twith open(filename, 'wb') as file_h:\n\t\tshutil.copyfileobj(url_h, file_h)\n\turl_h.close()\n\treturn\n\ndef escape_single_quote(unescaped):\n\t\"\"\"\n\tEscape a string containing single quotes and backslashes with backslashes.\n\tThis is useful when a string is evaluated in some way.\n\n\t:param str unescaped: The string to escape.\n\t:return: The escaped string.\n\t:rtype: str\n\t\"\"\"\n\t# requirements = re\n\treturn re.sub(r'(\\'|\\\\)', r'\\\\\\1', unescaped)\n\ndef format_bytes_size(val):\n\t\"\"\"\n\tTake a number of bytes and convert it to a human readable number.\n\n\t:param int val: The number of bytes to format.\n\t:return: The size in a human readable format.\n\t:rtype: str\n\t\"\"\"\n\tif not val:\n\t\treturn '0 bytes'\n\tfor sz_name in ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']:\n\t\tif val < 1024.0:\n\t\t\treturn \"{0:.2f} {1}\".format(val, sz_name)\n\t\tval /= 1024.0\n\traise OverflowError()\n\ndef grep(expression, file, flags=0, invert=False):\n\t\"\"\"\n\tSearch a file and return a list of all lines that match a regular expression.\n\n\t:param str expression: The regex to search for.\n\t:param file: The file to search in.\n\t:type file: str, file\n\t:param int flags: The regex flags to use when searching.\n\t:param bool invert: Select non matching lines instead.\n\t:return: All the matching lines.\n\t:rtype: list\n\t\"\"\"\n\t# requirements = re\n\tif isinstance(file, str):\n\t\tfile = open(file)\n\tlines = []\n\tfor line in file:\n\t\tif bool(re.search(expression, line, flags=flags)) ^ invert:\n\t\t\tlines.append(line)\n\treturn lines\n\ndef is_valid_email_address(email_address):\n\t\"\"\"\n\tCheck that the string specified appears to be a valid email address.\n\n\t:param str email_address: The email address to validate.\n\t:return: Whether the email address appears to be valid or not.\n\t:rtype: bool\n\t\"\"\"\n\t# requirements = re\n\treturn EMAIL_REGEX.match(email_address) != None\n\ndef get_ip_list(ip_network, mask=None):\n\t\"\"\"\n\tQuickly convert an IPv4 or IPv6 network (CIDR or Subnet) to a list\n\tof individual IPs in their string representation.\n\n\t:param str ip_network:\n\t:param int mask:\n\t:return: list\n\t\"\"\"\n\tif mask and '/' not in ip_network:\n\t\tnet = ipaddress.ip_network(\"{0}/{1}\".format(ip_network, mask))\n\telif '/' not in ip_network:\n\t\treturn [str(ipaddress.ip_address(ip_network))]\n\telse:\n\t\tnet = ipaddress.ip_network(ip_network)\n\thosts = net.hosts()\n\tif net.netmask == ipaddress.IPv4Address('255.255.255.255') and sys.version_info > (3, 9):\n\t\t# see: https://github.com/zeroSteiner/smoke-zephyr/issues/8\n\t\thosts = []\n\treturn [host.__str__() for host in hosts]\n\ndef sort_ipv4_list(ip_list, unique=True):\n\t\"\"\"\n\tSorts a provided list of IPv4 addresses. Optionally can remove duplicate values\n\tSupports IPv4 addresses with ports included (ex: [10.11.12.13:80, 10.11.12.13:8080])\n\n\t:param ip_list: (list) iterable of IPv4 Addresses\n\t:param unique: (bool) removes duplicate values if true\n\t:return: sorted list of IP addresses\n\t\"\"\"\n\tif unique:\n\t\tip_list = list(set(ip_list))\n\tipv4_list = sorted([i.rstrip(':') for i in ip_list], key=lambda ip: (\n\t\tint(ip.split(\".\")[0]),\n\t\tint(ip.split(\".\")[1]),\n\t\tint(ip.split(\".\")[2]),\n\t\tint(ip.split(\".\")[3].split(':')[0]),\n\t\tint(ip.split(\":\")[1]) if \":\" in ip else 0\n\t))\n\treturn ipv4_list\n\ndef open_uri(uri):\n\t\"\"\"\n\tOpen a URI in a platform intelligent way. On Windows this will use\n\t'cmd.exe /c start' and on Linux this will use gvfs-open or xdg-open\n\tdepending on which is available. If no suitable application can be\n\tfound to open the URI, a RuntimeError will be raised.\n\n\t.. versionadded:: 1.3.0\n\n\t:param str uri: The URI to open.\n\t\"\"\"\n\tclose_fds = True\n\tstartupinfo = None\n\tproc_args = []\n\tif sys.platform.startswith('win'):\n\t\tproc_args.append(which('cmd.exe'))\n\t\tproc_args.append('/c')\n\t\tproc_args.append('start')\n\t\turi = uri.replace('&', '^&')\n\t\tclose_fds = False\n\t\tstartupinfo = subprocess.STARTUPINFO()\n\t\tstartupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n\t\tstartupinfo.wShowWindow = subprocess.SW_HIDE\n\telif which('gvfs-open'):\n\t\tproc_args.append(which('gvfs-open'))\n\telif which('xdg-open'):\n\t\tproc_args.append(which('xdg-open'))\n\telse:\n\t\traise RuntimeError('could not find suitable application to open uri')\n\tproc_args.append(uri)\n\tproc_h = subprocess.Popen(proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=close_fds, startupinfo=startupinfo)\n\treturn proc_h.wait() == 0\n\ndef parse_case_camel_to_snake(camel):\n\t\"\"\"\n\tConvert a string from CamelCase to snake_case.\n\n\t:param str camel: The CamelCase string to convert.\n\t:return: The snake_case version of string.\n\t:rtype: str\n\t\"\"\"\n\t# requirements = re\n\treturn re.sub('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))', r'_\\1', camel).lower()\n\ndef parse_case_snake_to_camel(snake, upper_first=True):\n\t\"\"\"\n\tConvert a string from snake_case to CamelCase.\n\n\t:param str snake: The snake_case string to convert.\n\t:param bool upper_first: Whether or not to capitalize the first\n\t\tcharacter of the string.\n\t:return: The CamelCase version of string.\n\t:rtype: str\n\t\"\"\"\n\tsnake = snake.split('_')\n\tfirst_part = snake[0]\n\tif upper_first:\n\t\tfirst_part = first_part.title()\n\treturn first_part + ''.join(word.title() for word in snake[1:])\n\ndef parse_server(server, default_port):\n\t\"\"\"\n\tConvert a server string to a tuple suitable for passing to connect, for\n\texample converting 'www.google.com:443' to ('www.google.com', 443).\n\n\t:param str server: The server string to convert.\n\t:param int default_port: The port to use in case one is not specified\n\t\tin the server string.\n\t:return: The parsed server information.\n\t:rtype: tuple\n\t\"\"\"\n\tserver = server.rsplit(':', 1)\n\thost = server[0]\n\tif host.startswith('[') and host.endswith(']'):\n\t\thost = host[1:-1]\n\tif len(server) == 1:\n\t\treturn (host, default_port)\n\tport = server[1]\n\tif not port:\n\t\tport = default_port\n\telse:\n\t\tport = int(port)\n\treturn (host, port)\n\ndef parse_timespan(timedef):\n\t\"\"\"\n\tConvert a string timespan definition to seconds, for example converting\n\t'1m30s' to 90. If *timedef* is already an int, the value will be returned\n\tunmodified.\n\n\t:param timedef: The timespan definition to convert to seconds.\n\t:type timedef: int, str\n\t:return: The converted value in seconds.\n\t:rtype: int\n\t\"\"\"\n\tif isinstance(timedef, int):\n\t\treturn timedef\n\tconverter_order = ('w', 'd', 'h', 'm', 's')\n\tconverters = {\n\t\t'w': 604800,\n\t\t'd': 86400,\n\t\t'h': 3600,\n\t\t'm': 60,\n\t\t's': 1\n\t}\n\ttimedef = timedef.lower()\n\tif timedef.isdigit():\n\t\treturn int(timedef)\n\telif len(timedef) == 0:\n\t\treturn 0\n\tseconds = -1\n\tfor spec in converter_order:\n\t\ttimedef = timedef.split(spec)\n\t\tif len(timedef) == 1:\n\t\t\ttimedef = timedef[0]\n\t\t\tcontinue\n\t\telif len(timedef) > 2 or not timedef[0].isdigit():\n\t\t\tseconds = -1\n\t\t\tbreak\n\t\tadjustment = converters[spec]\n\t\tseconds = max(seconds, 0)\n\t\tseconds += (int(timedef[0]) * adjustment)\n\t\ttimedef = timedef[1]\n\t\tif not len(timedef):\n\t\t\tbreak\n\tif seconds < 0:\n\t\traise ValueError('invalid time format')\n\treturn seconds\n\ndef parse_to_slug(words, maxlen=24):\n\t\"\"\"\n\tParse a string into a slug format suitable for use in URLs and other\n\tcharacter restricted applications. Only utf-8 strings are supported at this\n\ttime.\n\n\t:param str words: The words to parse.\n\t:param int maxlen: The maximum length of the slug.\n\t:return: The parsed words as a slug.\n\t:rtype: str\n\t\"\"\"\n\tslug = ''\n\tmaxlen = min(maxlen, len(words))\n\tfor c in words:\n\t\tif len(slug) == maxlen:\n\t\t\tbreak\n\t\tc = ord(c)\n\t\tif c == 0x27:\n\t\t\tcontinue\n\t\telif c >= 0x30 and c <= 0x39:\n\t\t\tslug += chr(c)\n\t\telif c >= 0x41 and c <= 0x5a:\n\t\t\tslug += chr(c + 0x20)\n\t\telif c >= 0x61 and c <= 0x7a:\n\t\t\tslug += chr(c)\n\t\telif len(slug) and slug[-1] != '-':\n\t\t\tslug += '-'\n\tif len(slug) and slug[-1] == '-':\n\t\tslug = slug[:-1]\n\treturn slug\n\ndef random_string_alphanumeric(size):\n\t\"\"\"\n\tGenerate a random string of *size* length consisting of mixed case letters\n\tand numbers. This function is not meant for cryptographic purposes.\n\n\t:param int size: The length of the string to return.\n\t:return: A string consisting of random characters.\n\t:rtype: str\n\t\"\"\"\n\t# requirements = random, string\n\treturn ''.join(random.choice(string.ascii_letters + string.digits) for x in range(size))\n\ndef random_string_lower_numeric(size):\n\t\"\"\"\n\tGenerate a random string of *size* length consisting of lowercase letters\n\tand numbers. This function is not meant for cryptographic purposes.\n\n\t:param int size: The length of the string to return.\n\t:return: A string consisting of random characters.\n\t:rtype: str\n\t\"\"\"\n\t# requirements = random, string\n\treturn ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(size))\n\ndef selection_collision(selections, poolsize):\n\t\"\"\"\n\tCalculate the probability that two random values selected from an arbitrary\n\tsized pool of unique values will be equal. This is commonly known as the\n\t\"Birthday Problem\".\n\n\t:param int selections: The number of random selections.\n\t:param int poolsize: The number of unique random values in the pool to choose from.\n\t:rtype: float\n\t:return: The chance that a collision will occur as a percentage.\n\t\"\"\"\n\t# requirments = sys\n\tprobability = 100.0\n\tpoolsize = float(poolsize)\n\tfor i in range(selections):\n\t\tprobability = probability * (poolsize - i) / poolsize\n\tprobability = (100.0 - probability)\n\treturn probability\n\ndef unescape_single_quote(escaped):\n\t\"\"\"\n\tUnescape a string which uses backslashes to escape single quotes.\n\n\t:param str escaped: The string to unescape.\n\t:return: The unescaped string.\n\t:rtype: str\n\t\"\"\"\n\tescaped = escaped.replace('\\\\\\\\', '\\\\')\n\tescaped = escaped.replace('\\\\\\'', '\\'')\n\treturn escaped\n\ndef unique(seq, key=None):\n\t\"\"\"\n\tCreate a unique list or tuple from a provided list or tuple and preserve the\n\torder.\n\n\t:param seq: The list or tuple to preserve unique items from.\n\t:type seq: list, tuple\n\t:param key: If key is provided it will be called during the\n\t\tcomparison process.\n\t:type key: function, None\n\t\"\"\"\n\tif key is None:\n\t\tkey = lambda x: x\n\tpreserved_type = type(seq)\n\tif preserved_type not in (list, tuple):\n\t\traise TypeError(\"unique argument 1 must be list or tuple, not {0}\".format(preserved_type.__name__))\n\tseen = []\n\tresult = []\n\tfor item in seq:\n\t\tmarker = key(item)\n\t\tif marker in seen:\n\t\t\tcontinue\n\t\tseen.append(marker)\n\t\tresult.append(item)\n\treturn preserved_type(result)\n\ndef weighted_choice(choices, weight):\n\t\"\"\"\n\tMake a random selection from the specified choices. Apply the *weight*\n\tfunction to each to return a positive integer representing shares of\n\tselection pool the choice should received. The *weight* function is passed a\n\tsingle argument of the choice from the *choices* iterable.\n\n\t:param choices: The choices to select from.\n\t:type choices: list, tuple\n\t:param weight: The function used for gather weight information for choices.\n\t:type weight: function\n\t:return: A randomly selected choice from the provided *choices*.\n\t\"\"\"\n\t# requirements = random\n\tweights = []\n\t# get weight values for each of the choices\n\tfor choice in choices:\n\t\tchoice_weight = weight(choice)\n\t\tif not (isinstance(choice_weight, int) and choice_weight > 0):\n\t\t\traise TypeError('weight results must be positive integers')\n\t\tweights.append(choice_weight)\n\n\t# make a selection within the acceptable range\n\tselection = random.randint(0, sum(weights) - 1)\n\n\t# find and return the corresponding choice\n\tfor idx, choice in enumerate(choices):\n\t\tif selection < sum(weights[:idx + 1]):\n\t\t\treturn choice\n\traise RuntimeError('no selection could be made')\n\ndef which(program):\n\t\"\"\"\n\tLocate an executable binary's full path by its name.\n\n\t:param str program: The executables name.\n\t:return: The full path to the executable.\n\t:rtype: str\n\t\"\"\"\n\t# requirements = os\n\tis_exe = lambda fpath: (os.path.isfile(fpath) and os.access(fpath, os.X_OK))\n\tfor path in os.environ['PATH'].split(os.pathsep):\n\t\tpath = path.strip('\"')\n\t\texe_file = os.path.join(path, program)\n\t\tif is_exe(exe_file):\n\t\t\treturn exe_file\n\tif is_exe(program):\n\t\treturn os.path.abspath(program)\n\treturn None\n\ndef xfrange(start, stop=None, step=1):\n\t\"\"\"\n\tIterate through an arithmetic progression.\n\n\t:param start: Starting number.\n\t:type start: float, int, long\n\t:param stop: Stopping number.\n\t:type stop: float, int, long\n\t:param step: Stepping size.\n\t:type step: float, int, long\n\t\"\"\"\n\tif stop is None:\n\t\tstop = start\n\t\tstart = 0.0\n\tstart = float(start)\n\twhile start < stop:\n\t\tyield start\n\t\tstart += step"}]} {"messages": [{"role": "user", "content": "Write Python code that implements auditmessages.py from atopuzov/nitro-python (path: nssrc/com/citrix/netscaler/nitro/resource/config/audit/auditmessages.py)."}, {"role": "assistant", "content": "# nssrc/com/citrix/netscaler/nitro/resource/config/audit/auditmessages.py (from atopuzov/nitro-python, license: apache-2.0)\n\n#\n# Copyright (c) 2008-2015 Citrix Systems, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource\nfrom nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response\nfrom nssrc.com.citrix.netscaler.nitro.service.options import options\nfrom nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception\n\nfrom nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util\n\nclass auditmessages(base_resource) :\n\t\"\"\" Configuration for audit message resource. \"\"\"\n\tdef __init__(self) :\n\t\tself._loglevel = []\n\t\tself._numofmesgs = 0\n\t\tself._value = \"\"\n\t\tself.___count = 0\n\n\t@property\n\tdef loglevel(self) :\n\t\tur\"\"\"Audit log level filter, which specifies the types of events to display. \n\t\tThe following loglevels are valid:\n\t\t* ALL - All events.\n\t\t* EMERGENCY - Events that indicate an immediate crisis on the server.\n\t\t* ALERT - Events that might require action.\n\t\t* CRITICAL - Events that indicate an imminent server crisis.\n\t\t* ERROR - Events that indicate some type of error.\n\t\t* WARNING - Events that require action in the near future.\n\t\t* NOTICE - Events that the administrator should know about.\n\t\t* INFORMATIONAL - All but low-level events.\n\t\t* DEBUG - All events, in extreme detail.
Possible values = ALL, EMERGENCY, ALERT, CRITICAL, ERROR, WARNING, NOTICE, INFORMATIONAL, DEBUG.\n\t\t\"\"\"\n\t\ttry :\n\t\t\treturn self._loglevel\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t@loglevel.setter\n\tdef loglevel(self, loglevel) :\n\t\tur\"\"\"Audit log level filter, which specifies the types of events to display. \n\t\tThe following loglevels are valid:\n\t\t* ALL - All events.\n\t\t* EMERGENCY - Events that indicate an immediate crisis on the server.\n\t\t* ALERT - Events that might require action.\n\t\t* CRITICAL - Events that indicate an imminent server crisis.\n\t\t* ERROR - Events that indicate some type of error.\n\t\t* WARNING - Events that require action in the near future.\n\t\t* NOTICE - Events that the administrator should know about.\n\t\t* INFORMATIONAL - All but low-level events.\n\t\t* DEBUG - All events, in extreme detail.
Possible values = ALL, EMERGENCY, ALERT, CRITICAL, ERROR, WARNING, NOTICE, INFORMATIONAL, DEBUG\n\t\t\"\"\"\n\t\ttry :\n\t\t\tself._loglevel = loglevel\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t@property\n\tdef numofmesgs(self) :\n\t\tur\"\"\"Number of log messages to be displayed.
Default value: 20
Minimum length = 1
Maximum length = 256.\n\t\t\"\"\"\n\t\ttry :\n\t\t\treturn self._numofmesgs\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t@numofmesgs.setter\n\tdef numofmesgs(self, numofmesgs) :\n\t\tur\"\"\"Number of log messages to be displayed.
Default value: 20
Minimum length = 1
Maximum length = 256\n\t\t\"\"\"\n\t\ttry :\n\t\t\tself._numofmesgs = numofmesgs\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t@property\n\tdef value(self) :\n\t\tur\"\"\"The Audit message.\n\t\t\"\"\"\n\t\ttry :\n\t\t\treturn self._value\n\t\texcept Exception as e:\n\t\t\traise e\n\n\tdef _get_nitro_response(self, service, response) :\n\t\tur\"\"\" converts nitro response into object and returns the object array in case of get request.\n\t\t\"\"\"\n\t\ttry :\n\t\t\tresult = service.payload_formatter.string_to_resource(auditmessages_response, response, self.__class__.__name__)\n\t\t\tif(result.errorcode != 0) :\n\t\t\t\tif (result.errorcode == 444) :\n\t\t\t\t\tservice.clear_session(self)\n\t\t\t\tif result.severity :\n\t\t\t\t\tif (result.severity == \"ERROR\") :\n\t\t\t\t\t\traise nitro_exception(result.errorcode, str(result.message), str(result.severity))\n\t\t\t\telse :\n\t\t\t\t\traise nitro_exception(result.errorcode, str(result.message), str(result.severity))\n\t\t\treturn result.auditmessages\n\t\texcept Exception as e :\n\t\t\traise e\n\n\tdef _get_object_name(self) :\n\t\tur\"\"\" Returns the value of object identifier argument\n\t\t\"\"\"\n\t\ttry :\n\t\t\treturn 0\n\t\texcept Exception as e :\n\t\t\traise e\n\n\t@classmethod\n\tdef get(cls, client, name=\"\", option_=\"\") :\n\t\tur\"\"\" Use this API to fetch all the auditmessages resources that are configured on netscaler.\n\t\t\"\"\"\n\t\ttry :\n\t\t\tif not name :\n\t\t\t\tobj = auditmessages()\n\t\t\t\tresponse = obj.get_resources(client, option_)\n\t\t\treturn response\n\t\texcept Exception as e :\n\t\t\traise e\n\n\t@classmethod\n\tdef get_args(cls, client, args) :\n\t\tur\"\"\" Use this API to fetch all the auditmessages resources that are configured on netscaler.\n\t# This uses auditmessages_args which is a way to provide additional arguments while fetching the resources.\n\t\t\"\"\"\n\t\ttry :\n\t\t\tobj = auditmessages()\n\t\t\toption_ = options()\n\t\t\toption_.args = nitro_util.object_to_string_withoutquotes(args)\n\t\t\tresponse = obj.get_resources(client, option_)\n\t\t\treturn response\n\t\texcept Exception as e :\n\t\t\traise e\n\n\t@classmethod\n\tdef get_filtered(cls, client, filter_) :\n\t\tur\"\"\" Use this API to fetch filtered set of auditmessages resources.\n\t\tfilter string should be in JSON format.eg: \"port:80,servicetype:HTTP\".\n\t\t\"\"\"\n\t\ttry :\n\t\t\tobj = auditmessages()\n\t\t\toption_ = options()\n\t\t\toption_.filter = filter_\n\t\t\tresponse = obj.getfiltered(client, option_)\n\t\t\treturn response\n\t\texcept Exception as e :\n\t\t\traise e\n\n\t@classmethod\n\tdef count(cls, client) :\n\t\tur\"\"\" Use this API to count the auditmessages resources configured on NetScaler.\n\t\t\"\"\"\n\t\ttry :\n\t\t\tobj = auditmessages()\n\t\t\toption_ = options()\n\t\t\toption_.count = True\n\t\t\tresponse = obj.get_resources(client, option_)\n\t\t\tif response :\n\t\t\t\treturn response[0].__dict__['___count']\n\t\t\treturn 0\n\t\texcept Exception as e :\n\t\t\traise e\n\n\t@classmethod\n\tdef count_filtered(cls, client, filter_) :\n\t\tur\"\"\" Use this API to count filtered the set of auditmessages resources.\n\t\tFilter string should be in JSON format.eg: \"port:80,servicetype:HTTP\".\n\t\t\"\"\"\n\t\ttry :\n\t\t\tobj = auditmessages()\n\t\t\toption_ = options()\n\t\t\toption_.count = True\n\t\t\toption_.filter = filter_\n\t\t\tresponse = obj.getfiltered(client, option_)\n\t\t\tif response :\n\t\t\t\treturn response[0].__dict__['___count']\n\t\t\treturn 0\n\t\texcept Exception as e :\n\t\t\traise e\n\n\tclass Loglevel:\n\t\tALL = \"ALL\"\n\t\tEMERGENCY = \"EMERGENCY\"\n\t\tALERT = \"ALERT\"\n\t\tCRITICAL = \"CRITICAL\"\n\t\tERROR = \"ERROR\"\n\t\tWARNING = \"WARNING\"\n\t\tNOTICE = \"NOTICE\"\n\t\tINFORMATIONAL = \"INFORMATIONAL\"\n\t\tDEBUG = \"DEBUG\"\n\nclass auditmessages_response(base_response) :\n\tdef __init__(self, length=1) :\n\t\tself.auditmessages = []\n\t\tself.errorcode = 0\n\t\tself.message = \"\"\n\t\tself.severity = \"\"\n\t\tself.sessionid = \"\"\n\t\tself.auditmessages = [auditmessages() for _ in range(length)]"}]} {"messages": [{"role": "user", "content": "Write Python code that implements TestExpressionCmd.py from apple/swift-lldb (path: packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py)."}, {"role": "assistant", "content": "# packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py (from apple/swift-lldb, license: apache-2.0)\n\n\"\"\"Test lldb's expression evaluations and collect statistics.\"\"\"\n\nfrom __future__ import print_function\n\nimport sys\nimport lldb\nfrom lldbsuite.test.decorators import *\nfrom lldbsuite.test.lldbbench import *\nfrom lldbsuite.test.lldbtest import *\nfrom lldbsuite.test import configuration\nfrom lldbsuite.test import lldbutil\n\nclass ExpressionEvaluationCase(BenchBase):\n\n mydir = TestBase.compute_mydir(__file__)\n\n def setUp(self):\n BenchBase.setUp(self)\n self.source = 'main.cpp'\n self.line_to_break = line_number(\n self.source, '// Set breakpoint here.')\n self.count = 25\n\n @benchmarks_test\n @expectedFailureAll(\n oslist=[\"windows\"],\n bugnumber=\"llvm.org/pr22274: need a pexpect replacement for windows\")\n def test_expr_cmd(self):\n \"\"\"Test lldb's expression commands and collect statistics.\"\"\"\n self.build()\n self.exe_name = 'a.out'\n\n print()\n self.run_lldb_repeated_exprs(self.exe_name, self.count)\n print(\"lldb expr cmd benchmark:\", self.stopwatch)\n\n def run_lldb_repeated_exprs(self, exe_name, count):\n import pexpect\n exe = self.getBuildArtifact(exe_name)\n\n # Set self.child_prompt, which is \"(lldb) \".\n self.child_prompt = '(lldb) '\n prompt = self.child_prompt\n\n # Reset the stopwatch now.\n self.stopwatch.reset()\n for i in range(count):\n # So that the child gets torn down after the test.\n self.child = pexpect.spawn(\n '%s %s %s' %\n (lldbtest_config.lldbExec, self.lldbOption, exe))\n child = self.child\n\n # Turn on logging for what the child sends back.\n if self.TraceOn():\n child.logfile_read = sys.stdout\n\n child.expect_exact(prompt)\n child.sendline(\n 'breakpoint set -f %s -l %d' %\n (self.source, self.line_to_break))\n child.expect_exact(prompt)\n child.sendline('run')\n child.expect_exact(prompt)\n expr_cmd1 = 'expr ptr[j]->point.x'\n expr_cmd2 = 'expr ptr[j]->point.y'\n\n with self.stopwatch:\n child.sendline(expr_cmd1)\n child.expect_exact(prompt)\n child.sendline(expr_cmd2)\n child.expect_exact(prompt)\n\n child.sendline('quit')\n try:\n self.child.expect(pexpect.EOF)\n except:\n pass\n\n self.child = None"}]} {"messages": [{"role": "user", "content": "Write Python code that implements config.py from ageazrael/godot (path: modules/mono/config.py)."}, {"role": "assistant", "content": "# modules/mono/config.py (from ageazrael/godot, license: mit)\n\nimport imp\nimport os\nimport sys\n\nfrom SCons.Script import BoolVariable, Environment, Variables\n\nmonoreg = imp.load_source('mono_reg_utils', 'modules/mono/mono_reg_utils.py')\n\ndef find_file_in_dir(directory, files, prefix='', extension=''):\n if not extension.startswith('.'):\n extension = '.' + extension\n for curfile in files:\n if os.path.isfile(os.path.join(directory, prefix + curfile + extension)):\n return curfile\n return ''\n\ndef can_build(platform):\n if platform in [\"javascript\"]:\n return False # Not yet supported\n return True\n\ndef is_enabled():\n # The module is disabled by default. Use module_mono_enabled=yes to enable it.\n return False\n\ndef copy_file_no_replace(src_dir, dst_dir, name):\n from shutil import copyfile\n\n src_path = os.path.join(src_dir, name)\n dst_path = os.path.join(dst_dir, name)\n need_copy = True\n\n if not os.path.isdir(dst_dir):\n os.mkdir(dst_dir)\n elif os.path.exists(dst_path):\n need_copy = False\n\n if need_copy:\n copyfile(src_path, dst_path)\n\ndef configure(env):\n env.use_ptrcall = True\n env.add_module_version_string(\"mono\")\n\n envvars = Variables()\n envvars.Add(BoolVariable('mono_static', 'Statically link mono', False))\n envvars.Update(env)\n\n bits = env['bits']\n\n mono_static = env['mono_static']\n\n mono_lib_names = ['mono-2.0-sgen', 'monosgen-2.0']\n\n if env['platform'] == 'windows':\n if mono_static:\n raise RuntimeError('mono-static: Not supported on Windows')\n\n if bits == '32':\n if os.getenv('MONO32_PREFIX'):\n mono_root = os.getenv('MONO32_PREFIX')\n elif os.name == 'nt':\n mono_root = monoreg.find_mono_root_dir(bits)\n else:\n if os.getenv('MONO64_PREFIX'):\n mono_root = os.getenv('MONO64_PREFIX')\n elif os.name == 'nt':\n mono_root = monoreg.find_mono_root_dir(bits)\n\n if not mono_root:\n raise RuntimeError('Mono installation directory not found')\n\n mono_lib_path = os.path.join(mono_root, 'lib')\n\n env.Append(LIBPATH=mono_lib_path)\n env.Append(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))\n\n mono_lib_name = find_file_in_dir(mono_lib_path, mono_lib_names, extension='.lib')\n\n if not mono_lib_name:\n raise RuntimeError('Could not find mono library in: ' + mono_lib_path)\n\n if os.getenv('VCINSTALLDIR'):\n env.Append(LINKFLAGS=mono_lib_name + Environment()['LIBSUFFIX'])\n else:\n env.Append(LIBS=mono_lib_name)\n\n mono_bin_path = os.path.join(mono_root, 'bin')\n\n mono_dll_name = find_file_in_dir(mono_bin_path, mono_lib_names, extension='.dll')\n\n if not mono_dll_name:\n raise RuntimeError('Could not find mono shared library in: ' + mono_bin_path)\n\n copy_file_no_replace(mono_bin_path, 'bin', mono_dll_name + '.dll')\n else:\n sharedlib_ext = '.dylib' if sys.platform == 'darwin' else '.so'\n\n mono_root = ''\n\n if bits == '32':\n if os.getenv('MONO32_PREFIX'):\n mono_root = os.getenv('MONO32_PREFIX')\n else:\n if os.getenv('MONO64_PREFIX'):\n mono_root = os.getenv('MONO64_PREFIX')\n\n if mono_root:\n mono_lib_path = os.path.join(mono_root, 'lib')\n\n env.Append(LIBPATH=mono_lib_path)\n env.Append(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))\n\n mono_lib = find_file_in_dir(mono_lib_path, mono_lib_names, prefix='lib', extension='.a')\n\n if not mono_lib:\n raise RuntimeError('Could not find mono library in: ' + mono_lib_path)\n\n env.Append(CPPFLAGS=['-D_REENTRANT'])\n\n if mono_static:\n mono_lib_file = os.path.join(mono_lib_path, 'lib' + mono_lib + '.a')\n\n if sys.platform == \"darwin\":\n env.Append(LINKFLAGS=['-Wl,-force_load,' + mono_lib_file])\n elif sys.platform == \"linux\" or sys.platform == \"linux2\":\n env.Append(LINKFLAGS=['-Wl,-whole-archive', mono_lib_file, '-Wl,-no-whole-archive'])\n else:\n raise RuntimeError('mono-static: Not supported on this platform')\n else:\n env.Append(LIBS=[mono_lib])\n\n if sys.platform == \"darwin\":\n env.Append(LIBS=['iconv', 'pthread'])\n elif sys.platform == \"linux\" or sys.platform == \"linux2\":\n env.Append(LIBS=['m', 'rt', 'dl', 'pthread'])\n\n if not mono_static:\n mono_so_name = find_file_in_dir(mono_lib_path, mono_lib_names, prefix='lib', extension=sharedlib_ext)\n\n if not mono_so_name:\n raise RuntimeError('Could not find mono shared library in: ' + mono_lib_path)\n\n copy_file_no_replace(mono_lib_path, 'bin', 'lib' + mono_so_name + sharedlib_ext)\n else:\n if mono_static:\n raise RuntimeError('mono-static: Not supported with pkg-config. Specify a mono prefix manually')\n\n env.ParseConfig('pkg-config monosgen-2 --cflags --libs')\n\n mono_lib_path = ''\n mono_so_name = ''\n\n tmpenv = Environment()\n tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L')\n\n for hint_dir in tmpenv['LIBPATH']:\n name_found = find_file_in_dir(hint_dir, mono_lib_names, prefix='lib', extension=sharedlib_ext)\n if name_found:\n mono_lib_path = hint_dir\n mono_so_name = name_found\n break\n\n if not mono_so_name:\n raise RuntimeError('Could not find mono shared library in: ' + str(tmpenv['LIBPATH']))\n\n copy_file_no_replace(mono_lib_path, 'bin', 'lib' + mono_so_name + sharedlib_ext)\n\n env.Append(LINKFLAGS='-rdynamic')\n\ndef get_doc_classes():\n return [\"@C#\", \"CSharpScript\", \"GodotSharp\"]\n\ndef get_doc_path():\n return \"doc_classes\""}]} {"messages": [{"role": "user", "content": "Write Python code that implements summary_report.py from ryepdx/shipping_api (path: report/summary_report.py)."}, {"role": "assistant", "content": "# report/summary_report.py (from ryepdx/shipping_api, license: agpl-3.0)\n\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nimport time\nfrom openerp.report import report_sxw\n\nclass summary_report_print(report_sxw.rml_parse):\n def __init__(self, cr, uid, name, context):\n super(summary_report_print, self).__init__(cr, uid, name, context)\n self.localcontext.update({\n 'time': time,\n 'get_total': self.get_total,\n 'get_items': self.get_items,\n })\n\n def get_total(self):\n ship_ids = self.pool.get('shipping.move').search(self.cr, self.uid, [('state', '=', 'ready_pick')])\n return str(len(ship_ids))\n \n def get_items(self):\n ret = {}\n ship_ids = self.pool.get('shipping.move').search(self.cr, self.uid, [('state', '=', 'ready_pick')])\n if ship_ids:\n for ship_id in self.pool.get('shipping.move').browse(self.cr, self.uid, ship_ids):\n key = ship_id.service and ship_id.service.description or ''\n ret[key] = 1 + ret.get(key, 0)\n return ret.items()\n\nreport_sxw.report_sxw(\n 'report.summary_report_print',\n 'shipping.move',\n 'addons/shipping_api/report/summary_report.rml',\n parser=summary_report_print\n)\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:"}]} {"messages": [{"role": "user", "content": "Write Python code that implements validators.py from sangoma/sangoma-sbc-provisioning (path: common/attr/validators.py)."}, {"role": "assistant", "content": "# common/attr/validators.py (from sangoma/sangoma-sbc-provisioning, license: gpl-2.0)\n\n\"\"\"\nCommonly useful validators.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom ._make import attr, attributes\n\n@attributes(repr=False, slots=True)\nclass _InstanceOfValidator(object):\n type = attr()\n\n def __call__(self, inst, attr, value):\n \"\"\"\n We use a callable class to be able to change the ``__repr__``.\n \"\"\"\n if not isinstance(value, self.type):\n raise TypeError(\n \"'{name}' must be {type!r} (got {value!r} that is a \"\n \"{actual!r}).\"\n .format(name=attr.name, type=self.type,\n actual=value.__class__, value=value),\n attr, self.type, value,\n )\n\n def __repr__(self):\n return (\n \"\"\n .format(type=self.type)\n )\n\ndef instance_of(type):\n \"\"\"\n A validator that raises a :exc:`TypeError` if the initializer is called\n with a wrong type for this particular attribute (checks are perfomed using\n :func:`isinstance` therefore it's also valid to pass a tuple of types).\n\n :param type: The type to check for.\n :type type: type or tuple of types\n\n The :exc:`TypeError` is raised with a human readable error message, the\n attribute (of type :class:`attr.Attribute`), the expected type, and the\n value it got.\n \"\"\"\n return _InstanceOfValidator(type)\n\n@attributes(repr=False, slots=True)\nclass _ProvidesValidator(object):\n interface = attr()\n\n def __call__(self, inst, attr, value):\n \"\"\"\n We use a callable class to be able to change the ``__repr__``.\n \"\"\"\n if not self.interface.providedBy(value):\n raise TypeError(\n \"'{name}' must provide {interface!r} which {value!r} \"\n \"doesn't.\"\n .format(name=attr.name, interface=self.interface, value=value),\n attr, self.interface, value,\n )\n\n def __repr__(self):\n return (\n \"\"\n .format(interface=self.interface)\n )\n\ndef provides(interface):\n \"\"\"\n A validator that raises a :exc:`TypeError` if the initializer is called\n with an object that does not provide the requested *interface* (checks are\n performed using ``interface.providedBy(value)`` (see `zope.interface\n `_).\n\n :param interface: The interface to check for.\n :type interface: zope.interface.Interface\n\n The :exc:`TypeError` is raised with a human readable error message, the\n attribute (of type :class:`attr.Attribute`), the expected interface, and\n the value it got.\n \"\"\"\n return _ProvidesValidator(interface)\n\n@attributes(repr=False, slots=True)\nclass _OptionalValidator(object):\n validator = attr()\n\n def __call__(self, inst, attr, value):\n if value is None:\n return\n return self.validator(inst, attr, value)\n\n def __repr__(self):\n return (\n \"\"\n .format(type=repr(self.validator))\n )\n\ndef optional(validator):\n \"\"\"\n A validator that makes an attribute optional. An optional attribute is one\n which can be set to ``None`` in addition to satisfying the requirements of\n the sub-validator.\n\n :param validator: A validator that is used for non-``None`` values.\n \"\"\"\n return _OptionalValidator(validator)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements IPeakTest.py from ScreamingUdder/mantid (path: Framework/PythonInterface/test/python/mantid/geometry/IPeakTest.py)."}, {"role": "assistant", "content": "# Framework/PythonInterface/test/python/mantid/geometry/IPeakTest.py (from ScreamingUdder/mantid, license: gpl-3.0)\n\nimport unittest\nfrom mantid.kernel import V3D\nfrom mantid.simpleapi import CreateSimulationWorkspace, CreatePeaksWorkspace\nimport numpy as np\nimport numpy.testing as npt\n\nclass IPeakTest(unittest.TestCase):\n\n def setUp(self):\n # IPeak cannot currently be instatiated so this is a quick way\n # getting a handle to a peak object\n ws = CreateSimulationWorkspace(\"SXD\", BinParams=\"1,1,10\")\n peaks = CreatePeaksWorkspace(ws, 1)\n self._peak = peaks.getPeak(0)\n\n # tolerance for differences in q vectors that a recomputed\n # on every call.\n self._tolerance = 1e-2\n\n def test_set_detector_id_with_valid_id(self):\n det_id = 101\n self._peak.setDetectorID(det_id)\n self.assertEqual(self._peak.getDetectorID(), det_id)\n\n def test_set_detector_id_with_invalid_id(self):\n det_id = -1\n self.assertRaises(RuntimeError, self._peak.setDetectorID, det_id)\n\n def test_set_run_number(self):\n run_number = 101\n self._peak.setRunNumber(run_number)\n self.assertEqual(self._peak.getRunNumber(), run_number)\n\n def test_set_monitor_count(self):\n mon_count = 3\n self._peak.setMonitorCount(mon_count)\n self.assertEqual(self._peak.getMonitorCount(), mon_count)\n\n def test_set_hkl_all_at_once(self):\n H, K, L = 1, 2, 3\n self._peak.setHKL(H, K, L)\n\n self.assertEqual(self._peak.getH(), H)\n self.assertEqual(self._peak.getK(), K)\n self.assertEqual(self._peak.getL(), L)\n\n def test_set_hkl_individually(self):\n H, K, L = 1, 2, 3\n self._peak.setH(H)\n self._peak.setK(K)\n self._peak.setL(L)\n\n self.assertEqual(self._peak.getH(), H)\n self.assertEqual(self._peak.getK(), K)\n self.assertEqual(self._peak.getL(), L)\n\n def test_set_q_lab_frame(self):\n q_lab = V3D(0, 1, 1)\n self._peak.setQLabFrame(q_lab)\n\n npt.assert_allclose(self._peak.getQLabFrame(), q_lab, atol=self._tolerance)\n npt.assert_allclose(self._peak.getQSampleFrame(), q_lab, atol=self._tolerance)\n\n def test_set_q_sample_frame(self):\n q_sample = V3D(0, 1, 1)\n self._peak.setQSampleFrame(q_sample)\n\n npt.assert_allclose(self._peak.getQSampleFrame(), q_sample, atol=self._tolerance)\n npt.assert_allclose(self._peak.getQLabFrame(), q_sample, atol=self._tolerance)\n\n def test_set_goniometer_matrix_with_valid_matrix(self):\n angle = np.pi/4\n rotation = np.array([\n [np.cos(angle), -np.sin(angle), 0],\n [np.sin(angle), np.cos(angle), 0],\n [0, 0, 1]\n ])\n q_sample = V3D(1, 1, 1)\n\n self._peak.setGoniometerMatrix(rotation)\n self._peak.setQSampleFrame(q_sample)\n\n q_lab = np.dot(self._peak.getQLabFrame(), rotation)\n npt.assert_allclose(self._peak.getGoniometerMatrix(), rotation)\n npt.assert_allclose(self._peak.getQSampleFrame(), q_sample, atol=self._tolerance)\n npt.assert_allclose(q_lab, q_sample, atol=self._tolerance)\n\n def test_set_goniometer_matrix_with_singular_matrix(self):\n rotation = np.zeros((3,3))\n self.assertRaises(ValueError, self._peak.setGoniometerMatrix, rotation)\n\n def test_set_wavelength(self):\n wavelength = 1.3\n self._peak.setWavelength(wavelength)\n self.assertAlmostEqual(self._peak.getWavelength(), wavelength)\n\n def test_get_scattering(self):\n det_id = 101\n expected_scattering_angle = 2.878973314094696\n self._peak.setDetectorID(det_id)\n self.assertAlmostEqual(self._peak.getScattering(), expected_scattering_angle)\n\n def test_get_tof(self):\n det_id = 101\n wavelength = 1.9\n expected_tof = 4103.70182610731\n self._peak.setDetectorID(det_id)\n self._peak.setWavelength(wavelength)\n self.assertEqual(self._peak.getTOF(), expected_tof)\n\n def test_get_d_spacing(self):\n det_id = 101\n wavelength = 1.9\n expected_d = 0.958249313959493\n self._peak.setDetectorID(det_id)\n self._peak.setWavelength(wavelength)\n self.assertEqual(self._peak.getDSpacing(), expected_d)\n\n def test_set_initial_energy(self):\n initial_energy = 10.0\n self._peak.setInitialEnergy(initial_energy)\n self.assertAlmostEqual(self._peak.getInitialEnergy(), initial_energy)\n\n def test_set_final_energy(self):\n final_energy = 10.0\n self._peak.setFinalEnergy(final_energy)\n self.assertAlmostEqual(self._peak.getFinalEnergy(), final_energy)\n\n def test_get_energy(self):\n initial_energy = 10.0\n final_energy = 10.0\n self._peak.setFinalEnergy(final_energy)\n self._peak.setInitialEnergy(initial_energy)\n self.assertAlmostEqual(self._peak.getEnergyTransfer(), initial_energy - final_energy)\n\n def test_set_intensity(self):\n intensity = 10.0\n self._peak.setIntensity(intensity)\n self.assertAlmostEqual(self._peak.getIntensity(), intensity)\n\n def test_set_sigma_intensity(self):\n sigma = 10.0\n self._peak.setSigmaIntensity(sigma)\n self.assertAlmostEqual(self._peak.getSigmaIntensity(), sigma)\n\n def test_get_intensity_over_sigma(self):\n intensity = 100.0\n sigma = 10.0\n self._peak.setIntensity(intensity)\n self._peak.setSigmaIntensity(sigma)\n self.assertAlmostEqual(self._peak.getIntensityOverSigma(), intensity / sigma)\n\n def test_set_bin_count(self):\n bin_count = 10.0\n self._peak.setBinCount(bin_count)\n self.assertAlmostEqual(self._peak.getBinCount(), bin_count)\n\n def test_get_row_and_column(self):\n det_id = 101\n row, col = 36, 1\n self._peak.setDetectorID(det_id)\n self.assertEqual(self._peak.getRow(), row)\n self.assertEqual(self._peak.getCol(), col)\n\n def test_get_det_pos(self):\n det_id = 101\n expected_det_pos = np.array([0.061999, 0.0135, -0.236032])\n self._peak.setDetectorID(det_id)\n npt.assert_allclose(self._peak.getDetPos(), expected_det_pos, atol=self._tolerance)\n\n def test_get_l1(self):\n det_id = 101\n expected_l1 = 8.3\n self._peak.setDetectorID(det_id)\n self.assertEqual(self._peak.getL1(), expected_l1)\n\n def test_get_l2(self):\n det_id = 101\n expected_l2 = 0.2444125610784556\n self._peak.setDetectorID(det_id)\n self.assertEqual(self._peak.getL2(), expected_l2)\n\nif __name__ == '__main__':\n unittest.main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements wptrunner.py from simartin/servo (path: tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptrunner.py)."}, {"role": "assistant", "content": "# tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptrunner.py (from simartin/servo, license: mpl-2.0)\n\nfrom __future__ import print_function, unicode_literals\n\nimport json\nimport os\nimport sys\n\nfrom six import iteritems, itervalues\n\nimport wptserve\nfrom wptserve import sslutils\n\nfrom . import environment as env\nfrom . import instruments\nfrom . import mpcontext\nfrom . import products\nfrom . import testloader\nfrom . import wptcommandline\nfrom . import wptlogging\nfrom . import wpttest\nfrom mozlog import capture, handlers\nfrom .font import FontInstaller\nfrom .testrunner import ManagerGroup\nfrom .browsers.base import NullBrowser\n\nhere = os.path.dirname(__file__)\n\nlogger = None\n\n\"\"\"Runner for web-platform-tests\n\nThe runner has several design goals:\n\n* Tests should run with no modification from upstream.\n\n* Tests should be regarded as \"untrusted\" so that errors, timeouts and even\n crashes in the tests can be handled without failing the entire test run.\n\n* For performance tests can be run in multiple browsers in parallel.\n\nThe upstream repository has the facility for creating a test manifest in JSON\nformat. This manifest is used directly to determine which tests exist. Local\nmetadata files are used to store the expected test results.\n\"\"\"\n\ndef setup_logging(*args, **kwargs):\n global logger\n logger = wptlogging.setup(*args, **kwargs)\n return logger\n\ndef get_loader(test_paths, product, debug=None, run_info_extras=None, chunker_kwargs=None,\n test_groups=None, **kwargs):\n if run_info_extras is None:\n run_info_extras = {}\n\n run_info = wpttest.get_run_info(kwargs[\"run_info\"], product,\n browser_version=kwargs.get(\"browser_version\"),\n browser_channel=kwargs.get(\"browser_channel\"),\n verify=kwargs.get(\"verify\"),\n debug=debug,\n extras=run_info_extras,\n enable_webrender=kwargs.get(\"enable_webrender\"))\n\n test_manifests = testloader.ManifestLoader(test_paths, force_manifest_update=kwargs[\"manifest_update\"],\n manifest_download=kwargs[\"manifest_download\"]).load()\n\n manifest_filters = []\n\n include = kwargs[\"include\"]\n if test_groups:\n include = testloader.update_include_for_groups(test_groups, include)\n\n if include or kwargs[\"exclude\"] or kwargs[\"include_manifest\"] or kwargs[\"default_exclude\"]:\n manifest_filters.append(testloader.TestFilter(include=include,\n exclude=kwargs[\"exclude\"],\n manifest_path=kwargs[\"include_manifest\"],\n test_manifests=test_manifests,\n explicit=kwargs[\"default_exclude\"]))\n\n ssl_enabled = sslutils.get_cls(kwargs[\"ssl_type\"]).ssl_enabled\n h2_enabled = wptserve.utils.http2_compatible()\n test_loader = testloader.TestLoader(test_manifests,\n kwargs[\"test_types\"],\n run_info,\n manifest_filters=manifest_filters,\n chunk_type=kwargs[\"chunk_type\"],\n total_chunks=kwargs[\"total_chunks\"],\n chunk_number=kwargs[\"this_chunk\"],\n include_https=ssl_enabled,\n include_h2=h2_enabled,\n include_quic=kwargs[\"enable_quic\"],\n skip_timeout=kwargs[\"skip_timeout\"],\n skip_implementation_status=kwargs[\"skip_implementation_status\"],\n chunker_kwargs=chunker_kwargs)\n return run_info, test_loader\n\ndef list_test_groups(test_paths, product, **kwargs):\n env.do_delayed_imports(logger, test_paths)\n\n run_info_extras = products.load_product(kwargs[\"config\"], product)[-1](**kwargs)\n\n run_info, test_loader = get_loader(test_paths, product,\n run_info_extras=run_info_extras, **kwargs)\n\n for item in sorted(test_loader.groups(kwargs[\"test_types\"])):\n print(item)\n\ndef list_disabled(test_paths, product, **kwargs):\n env.do_delayed_imports(logger, test_paths)\n\n rv = []\n\n run_info_extras = products.load_product(kwargs[\"config\"], product)[-1](**kwargs)\n\n run_info, test_loader = get_loader(test_paths, product,\n run_info_extras=run_info_extras, **kwargs)\n\n for test_type, tests in iteritems(test_loader.disabled_tests):\n for test in tests:\n rv.append({\"test\": test.id, \"reason\": test.disabled()})\n print(json.dumps(rv, indent=2))\n\ndef list_tests(test_paths, product, **kwargs):\n env.do_delayed_imports(logger, test_paths)\n\n run_info_extras = products.load_product(kwargs[\"config\"], product)[-1](**kwargs)\n\n run_info, test_loader = get_loader(test_paths, product,\n run_info_extras=run_info_extras, **kwargs)\n\n for test in test_loader.test_ids:\n print(test)\n\ndef get_pause_after_test(test_loader, **kwargs):\n if kwargs[\"pause_after_test\"] is None:\n if kwargs[\"repeat_until_unexpected\"]:\n return False\n if kwargs[\"headless\"]:\n return False\n if kwargs[\"debug_test\"]:\n return True\n tests = test_loader.tests\n is_single_testharness = (sum(len(item) for item in itervalues(tests)) == 1 and\n len(tests.get(\"testharness\", [])) == 1)\n if kwargs[\"repeat\"] == 1 and kwargs[\"rerun\"] == 1 and is_single_testharness:\n return True\n return False\n return kwargs[\"pause_after_test\"]\n\ndef run_tests(config, test_paths, product, **kwargs):\n \"\"\"Set up the test environment, load the list of tests to be executed, and\n invoke the remainder of the code to execute tests\"\"\"\n mp = mpcontext.get_context()\n if kwargs[\"instrument_to_file\"] is None:\n recorder = instruments.NullInstrument()\n else:\n recorder = instruments.Instrument(kwargs[\"instrument_to_file\"])\n with recorder as recording, capture.CaptureIO(logger,\n not kwargs[\"no_capture_stdio\"],\n mp_context=mp):\n recording.set([\"startup\"])\n env.do_delayed_imports(logger, test_paths)\n\n product = products.load_product(config, product, load_cls=True)\n\n env_extras = product.get_env_extras(**kwargs)\n\n product.check_args(**kwargs)\n\n if kwargs[\"install_fonts\"]:\n env_extras.append(FontInstaller(\n logger,\n font_dir=kwargs[\"font_dir\"],\n ahem=os.path.join(test_paths[\"/\"][\"tests_path\"], \"fonts/Ahem.ttf\")\n ))\n\n recording.set([\"startup\", \"load_tests\"])\n\n test_groups = (testloader.TestGroupsFile(logger, kwargs[\"test_groups_file\"])\n if kwargs[\"test_groups_file\"] else None)\n\n (test_source_cls,\n test_source_kwargs,\n chunker_kwargs) = testloader.get_test_src(logger=logger,\n test_groups=test_groups,\n **kwargs)\n run_info, test_loader = get_loader(test_paths,\n product.name,\n run_info_extras=product.run_info_extras(**kwargs),\n chunker_kwargs=chunker_kwargs,\n test_groups=test_groups,\n **kwargs)\n\n logger.info(\"Using %i client processes\" % kwargs[\"processes\"])\n\n skipped_tests = 0\n test_total = 0\n unexpected_total = 0\n\n if len(test_loader.test_ids) == 0 and kwargs[\"test_list\"]:\n logger.critical(\"Unable to find any tests at the path(s):\")\n for path in kwargs[\"test_list\"]:\n logger.critical(\" %s\" % path)\n logger.critical(\"Please check spelling and make sure there are tests in the specified path(s).\")\n return False\n kwargs[\"pause_after_test\"] = get_pause_after_test(test_loader, **kwargs)\n\n ssl_config = {\"type\": kwargs[\"ssl_type\"],\n \"openssl\": {\"openssl_binary\": kwargs[\"openssl_binary\"]},\n \"pregenerated\": {\"host_key_path\": kwargs[\"host_key_path\"],\n \"host_cert_path\": kwargs[\"host_cert_path\"],\n \"ca_cert_path\": kwargs[\"ca_cert_path\"]}}\n\n testharness_timeout_multipler = product.get_timeout_multiplier(\"testharness\",\n run_info,\n **kwargs)\n\n mojojs_path = kwargs[\"mojojs_path\"] if kwargs[\"enable_mojojs\"] else None\n\n recording.set([\"startup\", \"start_environment\"])\n with env.TestEnvironment(test_paths,\n testharness_timeout_multipler,\n kwargs[\"pause_after_test\"],\n kwargs[\"debug_test\"],\n kwargs[\"debug_info\"],\n product.env_options,\n ssl_config,\n env_extras,\n kwargs[\"enable_quic\"],\n mojojs_path) as test_environment:\n recording.set([\"startup\", \"ensure_environment\"])\n try:\n test_environment.ensure_started()\n except env.TestEnvironmentError as e:\n logger.critical(\"Error starting test environment: %s\" % e.message)\n raise\n\n recording.set([\"startup\"])\n\n repeat = kwargs[\"repeat\"]\n repeat_count = 0\n repeat_until_unexpected = kwargs[\"repeat_until_unexpected\"]\n\n while repeat_count < repeat or repeat_until_unexpected:\n repeat_count += 1\n if repeat_until_unexpected:\n logger.info(\"Repetition %i\" % (repeat_count))\n elif repeat > 1:\n logger.info(\"Repetition %i / %i\" % (repeat_count, repeat))\n\n test_count = 0\n unexpected_count = 0\n\n tests = []\n for test_type in test_loader.test_types:\n tests.extend(test_loader.tests[test_type])\n\n try:\n test_groups = test_source_cls.tests_by_group(tests, **test_source_kwargs)\n except Exception:\n logger.critical(\"Loading tests failed\")\n return False\n\n logger.suite_start(test_groups,\n name='web-platform-test',\n run_info=run_info,\n extra={\"run_by_dir\": kwargs[\"run_by_dir\"]})\n for test_type in kwargs[\"test_types\"]:\n logger.info(\"Running %s tests\" % test_type)\n\n # WebDriver tests may create and destroy multiple browser\n # processes as part of their expected behavior. These\n # processes are managed by a WebDriver server binary. This\n # obviates the need for wptrunner to provide a browser, so\n # the NullBrowser is used in place of the \"target\" browser\n if test_type == \"wdspec\":\n browser_cls = NullBrowser\n else:\n browser_cls = product.browser_cls\n\n browser_kwargs = product.get_browser_kwargs(logger,\n test_type,\n run_info,\n config=test_environment.config,\n num_test_groups=len(test_groups),\n **kwargs)\n\n executor_cls = product.executor_classes.get(test_type)\n executor_kwargs = product.get_executor_kwargs(logger,\n test_type,\n test_environment.config,\n test_environment.cache_manager,\n run_info,\n **kwargs)\n\n if executor_cls is None:\n logger.error(\"Unsupported test type %s for product %s\" %\n (test_type, product.name))\n continue\n\n for test in test_loader.disabled_tests[test_type]:\n logger.test_start(test.id)\n logger.test_end(test.id, status=\"SKIP\")\n skipped_tests += 1\n\n if test_type == \"testharness\":\n run_tests = {\"testharness\": []}\n for test in test_loader.tests[\"testharness\"]:\n if ((test.testdriver and not executor_cls.supports_testdriver) or\n (test.jsshell and not executor_cls.supports_jsshell)):\n logger.test_start(test.id)\n logger.test_end(test.id, status=\"SKIP\")\n skipped_tests += 1\n else:\n run_tests[\"testharness\"].append(test)\n else:\n run_tests = test_loader.tests\n\n recording.pause()\n with ManagerGroup(\"web-platform-tests\",\n kwargs[\"processes\"],\n test_source_cls,\n test_source_kwargs,\n browser_cls,\n browser_kwargs,\n executor_cls,\n executor_kwargs,\n kwargs[\"rerun\"],\n kwargs[\"pause_after_test\"],\n kwargs[\"pause_on_unexpected\"],\n kwargs[\"restart_on_unexpected\"],\n kwargs[\"debug_info\"],\n not kwargs[\"no_capture_stdio\"],\n recording=recording) as manager_group:\n try:\n manager_group.run(test_type, run_tests)\n except KeyboardInterrupt:\n logger.critical(\"Main thread got signal\")\n manager_group.stop()\n raise\n test_count += manager_group.test_count()\n unexpected_count += manager_group.unexpected_count()\n recording.set([\"after-end\"])\n test_total += test_count\n unexpected_total += unexpected_count\n logger.info(\"Got %i unexpected results\" % unexpected_count)\n logger.suite_end()\n if repeat_until_unexpected and unexpected_total > 0:\n break\n if repeat_count == 1 and len(test_loader.test_ids) == skipped_tests:\n break\n\n if test_total == 0:\n if skipped_tests > 0:\n logger.warning(\"All requested tests were skipped\")\n else:\n if kwargs[\"default_exclude\"]:\n logger.info(\"No tests ran\")\n return True\n else:\n logger.critical(\"No tests ran\")\n return False\n\n if unexpected_total and not kwargs[\"fail_on_unexpected\"]:\n logger.info(\"Tolerating %s unexpected results\" % unexpected_total)\n return True\n\n return unexpected_total == 0\n\ndef check_stability(**kwargs):\n from . import stability\n if kwargs[\"stability\"]:\n logger.warning(\"--stability is deprecated; please use --verify instead!\")\n kwargs['verify_max_time'] = None\n kwargs['verify_chaos_mode'] = False\n kwargs['verify_repeat_loop'] = 0\n kwargs['verify_repeat_restart'] = 10 if kwargs['repeat'] == 1 else kwargs['repeat']\n kwargs['verify_output_results'] = True\n\n return stability.check_stability(logger,\n max_time=kwargs['verify_max_time'],\n chaos_mode=kwargs['verify_chaos_mode'],\n repeat_loop=kwargs['verify_repeat_loop'],\n repeat_restart=kwargs['verify_repeat_restart'],\n output_results=kwargs['verify_output_results'],\n **kwargs)\n\ndef start(**kwargs):\n assert logger is not None\n\n logged_critical = wptlogging.LoggedAboveLevelHandler(\"CRITICAL\")\n handler = handlers.LogLevelFilter(logged_critical, \"CRITICAL\")\n logger.add_handler(handler)\n\n rv = False\n try:\n if kwargs[\"list_test_groups\"]:\n list_test_groups(**kwargs)\n elif kwargs[\"list_disabled\"]:\n list_disabled(**kwargs)\n elif kwargs[\"list_tests\"]:\n list_tests(**kwargs)\n elif kwargs[\"verify\"] or kwargs[\"stability\"]:\n rv = check_stability(**kwargs) or logged_critical.has_log\n else:\n rv = not run_tests(**kwargs) or logged_critical.has_log\n finally:\n logger.remove_handler(handler)\n return rv\n\ndef main():\n \"\"\"Main entry point when calling from the command line\"\"\"\n kwargs = wptcommandline.parse_args()\n\n try:\n if kwargs[\"prefs_root\"] is None:\n kwargs[\"prefs_root\"] = os.path.abspath(os.path.join(here, \"prefs\"))\n\n setup_logging(kwargs, {\"raw\": sys.stdout})\n\n return start(**kwargs)\n except Exception:\n if kwargs[\"pdb\"]:\n import pdb\n import traceback\n print(traceback.format_exc())\n pdb.post_mortem()\n else:\n raise"}]} {"messages": [{"role": "user", "content": "Write Python code that implements WhoSampledScraper.py from ScradFTW/WhoSampledMyLib (path: WhoSampledScraper.py)."}, {"role": "assistant", "content": "# WhoSampledScraper.py (from ScradFTW/WhoSampledMyLib, license: gpl-2.0)\n\n\"\"\"\nFile: WhoSampledScraper.py\nAuthor: Brad Jobe\nVersion: 0.0.1\n\nScrapes relevant HTML content from an artist's track page\n\"\"\"\nimport sys\nimport eyed3\nimport urllib2\nfrom lxml import html\nimport httplib\nimport json\n\nclass WhoSampledScraper:\n\n URL_WHOSAMPLED = \"www.whosampled.com\"\n HTTP_PROTO = \"http://\"\n HTTP_REDIRECT = \"3\"\n SONGS_SAMPLED = 0\n WHO_SAMPLED = 2\n SONGS_SAMPLED_CALL = \"songsSampled\"\n WHO_SAMPLED_CALL = \"whoSampled\"\n\n def __init__(self, songLoc):\n \"\"\"\n Parses a songfile for the artist and title ID3 tags and creates the\n theoretical path for the songfile's samplepage.\n\n Param: The directory path to a song file, as a string.\n Throws: MissingTagException if tag(s) could not be found.\n \"\"\"\n songfile = eyed3.load(songLoc)\n\n try:\n self.whoSampledHTML = None\n self.artistName = songfile.tag.artist\n self.songTitle = songfile.tag.title\n self.sampleJSON = {}\n\n if self.artistName == None or self.songTitle == None:\n raise MissingTagException()\n except MissingTagException:\n print \"audiofile at \" + songLoc + \" has missing tag information\"\n\n self.whoSampledPath = (\"/\" + self.artistName + \"/\" + \\\n self.songTitle + \"/\").replace(\" \", \"-\")\n self.sampleJSON[self.whoSampledPath] = { self.SONGS_SAMPLED_CALL:{}, \\\n self.WHO_SAMPLED_CALL: {} }\n\n def getSongsSampled(self):\n \"\"\"\n Returns a list of songs that were sampled in the given track.\n \"\"\"\n jsonSamples = self.sampleScraper(self.SONGS_SAMPLED_CALL)\n return self.convertJsontoList(jsonSamples)\n\n def getWhoSampled(self):\n \"\"\"\n Returns a list of songs that have used the given track as a sample.\n \"\"\"\n jsonSamples = self.sampleScraper(self.WHO_SAMPLED_CALL)\n return self.convertJsontoList(jsonSamples)\n\n def getHTMLFromPath(self):\n \"\"\"\n Returns the html content from the song's sample page.\n\n Throws: RedirectException if the url is redirected away from the\n predicted path of the songs's sample page.\n \"\"\"\n urlCheck = urllib2.urlopen(self.HTTP_PROTO + \\\n self.URL_WHOSAMPLED + \\\n self.whoSampledPath)\n try:\n if urlCheck.geturl().lower() != (self.HTTP_PROTO + \\\n self.URL_WHOSAMPLED + \\\n self.whoSampledPath).lower():\n raise RedirectException()\n except RedirectException:\n print \"The URL of \" + self.songTitle + \" by \" + self.artistName + \\\n \" was redirected.\"\n return None\n\n return urlCheck.read()\n\n def sampleScraper(self, calltype):\n \"\"\"\n Scrapes sample data from the song's sample page.\n\n Params: a string of specifying what type of sample data is to be\n scraped from the sample page.\n Returns: a list of song samples, as strings, or an empty list.\n \"\"\"\n\n self.cachedSamples = self.loadCachedSampleData()\n\n try:\n self.cachedSamples[self.whoSampledPath] == None\n except KeyError:\n self.sampleJson = self.searchForSampleData(calltype)\n else:\n self.sampleJson = self.cachedSamples[self.whoSampledPath][calltype]\n\n return self.sampleJson\n\n def searchForSampleData(self, calltype):\n \"\"\"\n loads html of artist's track page on WhoSampled.com and parses it for\n the relevant sample data.\n\n args: specific type of sample data to parse for\n returns: None if sample data could not be found, returns sample data\n in json format if successful page parse\n \"\"\"\n if self.whoSampledHTML == None:\n self.whoSampledHTML = self.getHTMLFromPath()\n\n if self.whoSampledHTML == None:\n return None\n\n splitHTML = self.whoSampledHTML.split(\" 1:\n whoSampledDoc = html.document_fromstring( \\\n splitHTML[self.WHO_SAMPLED])\n elif len(splitHTML) <= 1:\n return None\n\n artistNamesSamples = whoSampledDoc.find_class(\"trackArtist\")\n songTitlesSamples = whoSampledDoc.find_class(\"trackName\")\n\n if len(artistNamesSamples) != len(songTitlesSamples) \\\n or len(artistNamesSamples) < 1:\n return None\n\n for i in range(0, len(artistNamesSamples)):\n a = artistNamesSamples[i].text_content()\n s = songTitlesSamples[i].text_content()\n self.sampleJSON[self.whoSampledPath][calltype][a] = s\n\n self.cacheSampleData()\n return self.sampleJSON\n\n def loadCachedSampleData(self):\n \"\"\"\n loads stored sample data from previous lookups\n\n returns: json sample data\n \"\"\"\n\n with open(\"samples.json\", \"r\") as inSampleFile:\n jsonData = json.load(inSampleFile)\n\n inSampleFile.close()\n\n return jsonData\n\n def cacheSampleData(self):\n \"\"\"\n stores sample data that has not been previously cached\n \"\"\"\n\n self.cachedSamples[self.whoSampledPath] \\\n = self.sampleJSON[self.whoSampledPath]\n\n with open('samples.json', 'w') as outSampleFile:\n json.dump(self.cachedSamples, outSampleFile)\n\n outSampleFile.close()\n\n def convertJsontoList(self, jsonSampleData):\n \"\"\"\n converts JSON sampled data to a python list\n\n args: json to be converted\n returns: python list of converted data\n \"\"\"\n sampleList = []\n sampleDict = jsonSampleData\n\n if bool(sampleDict) == False:\n return None\n\n for key in sampleDict:\n sampleList.append(str(sampleDict[key]) + \" \" + str(key))\n\n return sampleList\n\nclass RedirectException(Exception):\n pass\n\nclass MissingTagException(Exception):\n pass"}]} {"messages": [{"role": "user", "content": "Write Python code that implements summary.py from SOKP/external_chromium_org (path: tools/telemetry/telemetry/value/summary.py)."}, {"role": "assistant", "content": "# tools/telemetry/telemetry/value/summary.py (from SOKP/external_chromium_org, license: bsd-3-clause)\n\n# Copyright 2014 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nfrom collections import defaultdict\n\nfrom telemetry.value import failure\nfrom telemetry.value import merge_values\nfrom telemetry.value import skip\n\nclass Summary(object):\n \"\"\"Computes summary values from the per-page-run values produced by a test.\n\n Some telemetry benchmark repeat a number of times in order to get a reliable\n measurement. The test does not have to handle merging of these runs:\n summarizer does it for you.\n\n For instance, if two pages run, 3 and 1 time respectively:\n ScalarValue(page1, 'foo', units='ms', 1)\n ScalarValue(page1, 'foo', units='ms', 1)\n ScalarValue(page1, 'foo', units='ms', 1)\n ScalarValue(page2, 'foo', units='ms', 2)\n\n Then summarizer will produce two sets of values. First,\n computed_per_page_values:\n [\n ListOfScalarValues(page1, 'foo', units='ms', [1,1,1])],\n ListOfScalarValues(page2, 'foo', units='ms', [2])]\n ]\n\n In addition, it will produce a summary value:\n [\n ListOfScalarValues(page=None, 'foo', units='ms', [1,1,1,2])]\n ]\n\n \"\"\"\n def __init__(self, all_page_specific_values):\n had_failures = any(isinstance(v, failure.FailureValue) for v in\n all_page_specific_values)\n self.had_failures = had_failures\n self._computed_per_page_values = []\n self._computed_summary_values = []\n self._interleaved_computed_per_page_values_and_summaries = []\n self._ComputePerPageValues(all_page_specific_values)\n\n @property\n def computed_per_page_values(self):\n return self._computed_per_page_values\n\n @property\n def computed_summary_values(self):\n return self._computed_summary_values\n\n @property\n def interleaved_computed_per_page_values_and_summaries(self):\n \"\"\"Returns the computed per page values and summary values interleaved.\n\n All the results for a given name are printed together. First per page\n values, then summary values.\n\n \"\"\"\n return self._interleaved_computed_per_page_values_and_summaries\n\n def _ComputePerPageValues(self, all_page_specific_values):\n all_successful_page_values = [\n v for v in all_page_specific_values if not (isinstance(\n v, failure.FailureValue) or isinstance(v, skip.SkipValue))]\n\n # We will later need to determine how many values were originally created\n # for each value name, to apply a workaround meant to clean up the printf\n # output.\n num_successful_pages_for_value_name = defaultdict(int)\n for v in all_successful_page_values:\n num_successful_pages_for_value_name[v.name] += 1\n\n # By here, due to page repeat options, all_values_from_successful_pages\n # contains values of the same name not only from mulitple pages, but also\n # from the same name. So even if, for instance, only one page ran, it may\n # have run twice, producing two 'x' values.\n #\n # So, get rid of the repeated pages by merging.\n merged_page_values = merge_values.MergeLikeValuesFromSamePage(\n all_successful_page_values)\n\n # Now we have a bunch of values, but there is only one value_name per page.\n # Suppose page1 and page2 ran, producing values x and y. We want to print\n # x for page1\n # x for page2\n # x for page1, page2 combined\n #\n # y for page1\n # y for page2\n # y for page1, page2 combined\n #\n # We already have the x values in the values array. But, we will need\n # them indexable by the value name.\n #\n # The following dict maps value_name -> list of pages that have values of\n # that name.\n per_page_values_by_value_name = defaultdict(list)\n for value in merged_page_values:\n per_page_values_by_value_name[value.name].append(value)\n\n # We already have the x values in the values array. But, we also need\n # the values merged across the pages. And, we will need them indexed by\n # value name so that we can find them when printing out value names in\n # alphabetical order.\n merged_pages_value_by_value_name = {}\n if not self.had_failures:\n for value in merge_values.MergeLikeValuesFromDifferentPages(\n all_successful_page_values):\n assert value.name not in merged_pages_value_by_value_name\n merged_pages_value_by_value_name[value.name] = value\n\n # sorted_value names will govern the order we start printing values.\n value_names = set([v.name for v in merged_page_values])\n sorted_value_names = sorted(value_names)\n\n # Time to walk through the values by name, printing first the page-specific\n # values and then the merged_site value.\n for value_name in sorted_value_names:\n per_page_values = per_page_values_by_value_name.get(value_name, [])\n\n # Sort the values by their url\n sorted_per_page_values = list(per_page_values)\n sorted_per_page_values.sort(\n key=lambda per_page_values: per_page_values.page.display_name)\n\n # Output the page-specific results.\n num_successful_pages_for_this_value_name = (\n num_successful_pages_for_value_name[value_name])\n for per_page_value in sorted_per_page_values:\n self._ComputePerPageValue(per_page_value,\n num_successful_pages_for_this_value_name)\n\n # Output the combined values.\n merged_pages_value = merged_pages_value_by_value_name.get(value_name,\n None)\n if merged_pages_value:\n self._computed_summary_values.append(merged_pages_value)\n self._interleaved_computed_per_page_values_and_summaries.append(\n merged_pages_value)\n\n def _ComputePerPageValue(\n self, value, num_successful_pages_for_this_value_name):\n # If there were any page errors, we typically will print nothing.\n #\n # Note: this branch is structured less-densely to improve legibility.\n if num_successful_pages_for_this_value_name > 1:\n should_print = True\n elif (self.had_failures and\n num_successful_pages_for_this_value_name == 1):\n should_print = True\n else:\n should_print = False\n\n if not should_print:\n return\n\n # Actually save the result.\n self._computed_per_page_values.append(value)\n self._interleaved_computed_per_page_values_and_summaries.append(value)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements tests.py from ayseyo/oclapi (path: django-nonrel/ocl/mappings/tests.py)."}, {"role": "assistant", "content": "# django-nonrel/ocl/mappings/tests.py (from ayseyo/oclapi, license: mpl-2.0)\n\n\"\"\"\nThis file demonstrates writing tests using the unittest module. These will pass\nwhen you run \"manage.py test\".\n\nReplace this with more appropriate tests for your application.\n\"\"\"\nimport os\nfrom unittest import skip\nfrom urlparse import urlparse\n\nfrom django.contrib.auth.models import User\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import ValidationError\nfrom django.db.utils import IntegrityError\nfrom django.test import Client\nfrom django.test.client import MULTIPART_CONTENT, FakePayload\nfrom django.utils.encoding import force_str\n\nfrom collection.models import Collection, CollectionVersion\nfrom concepts.models import Concept, LocalizedText\nfrom mappings.models import Mapping, MappingVersion\nfrom mappings.validation_messages import OPENMRS_SINGLE_MAPPING_BETWEEN_TWO_CONCEPTS\nfrom oclapi.models import ACCESS_TYPE_EDIT, ACCESS_TYPE_VIEW, CUSTOM_VALIDATION_SCHEMA_OPENMRS\nfrom oclapi.utils import add_user_to_org\nfrom orgs.models import Organization\nfrom sources.models import Source, SourceVersion\nfrom test_helper.base import *\nfrom users.models import UserProfile\n\nclass OCLClient(Client):\n\n def put(self, path, data={}, content_type=MULTIPART_CONTENT,\n follow=False, **extra):\n \"\"\"\n Requests a response from the server using POST.\n \"\"\"\n response = self.my_put(path, data=data, content_type=content_type, **extra)\n if follow:\n response = self._handle_redirects(response, **extra)\n return response\n\n def my_put(self, path, data={}, content_type=MULTIPART_CONTENT, **extra):\n \"Construct a PUT request.\"\n\n post_data = self._encode_data(data, content_type)\n\n parsed = urlparse(path)\n r = {\n 'CONTENT_LENGTH': len(post_data),\n 'CONTENT_TYPE': content_type,\n 'PATH_INFO': self._get_path(parsed),\n 'QUERY_STRING': force_str(parsed[4]),\n 'REQUEST_METHOD': str('PUT'),\n 'wsgi.input': FakePayload(post_data),\n }\n r.update(extra)\n return self.request(**r)\n\nclass MappingBaseTest(OclApiBaseTestCase):\n\n def setUp(self):\n super(MappingBaseTest, self).setUp()\n self.user1 = User.objects.create_user(\n username='user1',\n email='user1@test.com',\n password='user1',\n last_name='One',\n first_name='User'\n )\n self.user2 = User.objects.create_user(\n username='user2',\n email='user2@test.com',\n password='user2',\n last_name='Two',\n first_name='User'\n )\n\n self.userprofile1 = UserProfile.objects.create(user=self.user1, mnemonic='user1')\n self.userprofile2 = UserProfile.objects.create(user=self.user2, mnemonic='user2')\n\n self.org1 = Organization.objects.create(name='org1', mnemonic='org1')\n self.org2 = Organization.objects.create(name='org2', mnemonic='org2')\n add_user_to_org(self.userprofile2, self.org2)\n\n self.source1 = Source(\n name='source1',\n mnemonic='source1',\n full_name='Source One',\n source_type='Dictionary',\n public_access=ACCESS_TYPE_EDIT,\n default_locale='en',\n supported_locales=['en'],\n website='www.source1.com',\n description='This is the first test source',\n )\n kwargs = {\n 'parent_resource': self.userprofile1\n }\n Source.persist_new(self.source1, self.user1, **kwargs)\n self.source1 = Source.objects.get(id=self.source1.id)\n\n self.source2 = Source(\n name='source2',\n mnemonic='source2',\n full_name='Source Two',\n source_type='Reference',\n public_access=ACCESS_TYPE_VIEW,\n default_locale='fr',\n supported_locales=['fr'],\n website='www.source2.com',\n description='This is the second test source',\n )\n kwargs = {\n 'parent_resource': self.org2,\n }\n Source.persist_new(self.source2, self.user1, **kwargs)\n self.source2 = Source.objects.get(id=self.source2.id)\n\n self.name = LocalizedText.objects.create(name='Fred', locale='en', type='FULLY_SPECIFIED')\n\n (self.concept1, errors) = create_concept(mnemonic='concept1', user=self.user1, source=self.source1, names=[self.name], descriptions=[self.name])\n (self.concept2, errors) = create_concept(mnemonic='concept2', user=self.user1, source=self.source1, names=[self.name], descriptions=[self.name])\n (self.concept3, errors) = create_concept(mnemonic='concept3', user=self.user1, source=self.source2, names=[self.name], descriptions=[self.name])\n (self.concept4, errors) = create_concept(mnemonic='concept4', user=self.user1, source=self.source2, names=[self.name], descriptions=[self.name])\n\nclass MappingVersionBaseTest(MappingBaseTest):\n def setUp(self):\n super(MappingVersionBaseTest, self).setUp()\n self.mapping1 = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='versionmapping1',\n )\n self.mapping1.full_clean()\n self.mapping1.save()\n\nclass MappingTest(MappingBaseTest):\n\n def test_create_mapping_positive(self):\n mapping = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n mapping.full_clean()\n mapping.save()\n\n self.assertTrue(Mapping.objects.filter(external_id='mapping1').exists())\n mapping = Mapping.objects.get(external_id='mapping1')\n self.assertEquals(ACCESS_TYPE_VIEW, mapping.public_access)\n self.assertEquals('user1', mapping.created_by)\n self.assertEquals('user1', mapping.updated_by)\n self.assertEquals(self.source1, mapping.parent)\n self.assertEquals('Same As', mapping.map_type)\n self.assertEquals(self.concept1, mapping.from_concept)\n self.assertEquals(self.concept2, mapping.to_concept)\n self.assertEquals(self.source1, mapping.from_source)\n self.assertEquals(self.source1.owner_name, mapping.from_source_owner)\n self.assertEquals(self.source1.mnemonic, mapping.from_source_name)\n self.assertEquals(self.source1, mapping.get_to_source())\n self.assertEquals(self.source1.owner_name, mapping.to_source_owner)\n self.assertEquals(self.concept2.mnemonic, mapping.get_to_concept_code())\n self.assertEquals(self.concept2.display_name, mapping.get_to_concept_name())\n\n def test_create_mapping_negative__no_created_by(self):\n with self.assertRaises(ValidationError):\n mapping = Mapping(\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n mapping.full_clean()\n mapping.save()\n\n def test_create_mapping_negative__no_updated_by(self):\n with self.assertRaises(ValidationError):\n mapping = Mapping(\n created_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n mapping.full_clean()\n mapping.save()\n\n def test_create_mapping_negative__no_parent(self):\n mapping = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n\n errors = Mapping.persist_new(mapping, self.user1)\n self.assertTrue(errors)\n\n def test_create_mapping_negative__no_map_type(self):\n with self.assertRaises(ValidationError):\n mapping = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n mapping.full_clean()\n mapping.save()\n\n def test_create_mapping_negative__no_from_concept(self):\n with self.assertRaises(ValidationError):\n mapping = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n to_concept=self.concept2,\n external_id='mapping1',\n )\n mapping.full_clean()\n mapping.save()\n\n def test_create_mapping_negative__no_to_concept(self):\n with self.assertRaises(ValidationError):\n mapping = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept2,\n external_id='mapping1',\n )\n mapping.full_clean()\n mapping.save()\n\n def test_create_mapping_negative__two_to_concepts(self):\n with self.assertRaises(ValidationError):\n mapping = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n to_concept_code='code',\n external_id='mapping1',\n )\n mapping.full_clean()\n mapping.save()\n\n def test_create_mapping_negative__self_mapping(self):\n with self.assertRaises(ValidationError):\n mapping = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept1,\n external_id='mapping1',\n )\n mapping.full_clean()\n mapping.save()\n\n def test_create_mapping_negative__same_mapping_type1(self):\n mapping = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n mapping.full_clean()\n mapping.save()\n\n self.assertTrue(Mapping.objects.filter(external_id='mapping1').exists())\n\n with self.assertRaises(ValidationError):\n mapping = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n mapping.full_clean()\n mapping.save()\n\n def test_create_mapping_negative__same_mapping_type2(self):\n mapping = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_source=self.source1,\n to_concept_code='code',\n to_concept_name='name',\n external_id='mapping1',\n )\n mapping.full_clean()\n mapping.save()\n\n self.assertTrue(Mapping.objects.filter(external_id='mapping1').exists())\n mapping = Mapping.objects.get(external_id='mapping1')\n self.assertEquals(ACCESS_TYPE_VIEW, mapping.public_access)\n self.assertEquals('user1', mapping.created_by)\n self.assertEquals('user1', mapping.updated_by)\n self.assertEquals(self.source1, mapping.parent)\n self.assertEquals('Same As', mapping.map_type)\n self.assertEquals(self.concept1, mapping.from_concept)\n self.assertIsNone(mapping.to_concept)\n self.assertEquals(self.source1, mapping.from_source)\n self.assertEquals(self.source1.owner_name, mapping.from_source_owner)\n self.assertEquals(self.source1.mnemonic, mapping.from_source_name)\n self.assertEquals(self.source1, mapping.get_to_source())\n self.assertEquals(self.source1.owner_name, mapping.to_source_owner)\n self.assertEquals('code', mapping.get_to_concept_code())\n self.assertEquals('name', mapping.get_to_concept_name())\n\n self.assertTrue(Mapping.objects.filter(external_id='mapping1').exists())\n\n with self.assertRaises(IntegrityError):\n mapping = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_source=self.source1,\n to_concept_code='code',\n to_concept_name='name',\n external_id='mapping1',\n )\n\n mapping.full_clean()\n mapping.save()\n\n def test_mapping_access_changes_with_source(self):\n public_access = self.source1.public_access\n mapping = Mapping(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n public_access=public_access,\n external_id='mapping1',\n )\n mapping.full_clean()\n mapping.save()\n\n self.assertEquals(self.source1.public_access, mapping.public_access)\n self.source1.public_access = ACCESS_TYPE_VIEW\n self.source1.save()\n\n mapping = Mapping.objects.get(id=mapping.id)\n self.assertNotEquals(public_access, self.source1.public_access)\n self.assertEquals(self.source1.public_access, mapping.public_access)\n\n @skip('Skip this test until development of map type validation feature is complete.')\n def test_create_mapping_negative__invalid_mapping_type(self):\n maptypes_source = Source.objects.get(name=\"MapTypes\")\n create_concept(self.user1, maptypes_source, concept_class=\"MapType\",names=[create_localized_text(\"SAME-AS\")])\n create_concept(self.user1, maptypes_source, concept_class=\"MapType\",names=[create_localized_text(\"NARROWER-THAN\")])\n\n user = create_user()\n\n source = create_source(user)\n (concept1, _) = create_concept(user, source)\n (concept2, _) = create_concept(user, source)\n\n mapping = Mapping(\n created_by=user,\n updated_by=user,\n parent=source,\n map_type='XYZQWERT',\n from_concept=concept1,\n to_concept=concept2,\n public_access=ACCESS_TYPE_VIEW,\n )\n\n kwargs = {\n 'parent_resource': source,\n }\n\n errors = Mapping.persist_new(mapping, user, **kwargs)\n self.assertEquals(1, len(errors))\n self.assertEquals(errors['names'][0], 'Mapping type should be valid attribute')\n\n @skip('Skip this test until development of map type validation feature is complete.')\n def test_create_mapping_positive__valid_mapping_type(self):\n maptypes_source = Source.objects.get(name=\"MapTypes\")\n create_concept(self.user1, maptypes_source, concept_class=\"MapType\", names=[create_localized_text(\"SAME-AS\")])\n create_concept(self.user1, maptypes_source, concept_class=\"MapType\", names=[create_localized_text(\"NARROWER-THAN\")])\n\n user = create_user()\n\n source = create_source(user)\n (concept1, _) = create_concept(user, source)\n (concept2, _) = create_concept(user, source)\n\n mapping = Mapping(\n created_by=user,\n updated_by=user,\n parent=source,\n map_type='SAME-AS',\n from_concept=concept1,\n to_concept=concept2,\n public_access=ACCESS_TYPE_VIEW,\n )\n\n kwargs = {\n 'parent_resource': source,\n }\n\n errors = Mapping.persist_new(mapping, user, **kwargs)\n self.assertEquals(0, len(errors))\n\nclass MappingVersionTest(MappingVersionBaseTest):\n\n def test_create_mapping_positive(self):\n mapping_version = MappingVersion(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mappingversion1',\n versioned_object_id=self.mapping1.id,\n mnemonic='tempid',\n versioned_object_type=ContentType.objects.get_for_model(Mapping),\n )\n mapping_version.full_clean()\n mapping_version.save()\n\n self.assertTrue(MappingVersion.objects.filter(versioned_object_id = self.mapping1.id).exists())\n mapping_version = MappingVersion.objects.get(versioned_object_id = self.mapping1.id)\n self.assertEquals(ACCESS_TYPE_VIEW, mapping_version.public_access)\n self.assertEquals('user1', mapping_version.created_by)\n self.assertEquals('user1', mapping_version.updated_by)\n self.assertEquals(self.source1, mapping_version.parent)\n self.assertEquals('Same As', mapping_version.map_type)\n self.assertEquals(self.concept1, mapping_version.from_concept)\n self.assertEquals(self.concept2, mapping_version.to_concept)\n self.assertEquals(self.source1, mapping_version.from_source)\n self.assertEquals(self.source1.owner_name, mapping_version.from_source_owner)\n self.assertEquals(self.source1.mnemonic, mapping_version.from_source_name)\n self.assertEquals(self.source1, mapping_version.get_to_source())\n self.assertEquals(self.source1.owner_name, mapping_version.to_source_owner)\n self.assertEquals(self.concept2.mnemonic, mapping_version.get_to_concept_code())\n self.assertEquals(self.concept2.display_name, mapping_version.get_to_concept_name())\n\n def test_create_mapping_negative__no_created_by(self):\n with self.assertRaises(ValidationError):\n mapping_version = MappingVersion(\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping111',\n versioned_object_id=self.mapping1.id,\n versioned_object_type=ContentType.objects.get_for_model(Mapping),\n mnemonic='tempid'\n )\n mapping_version.full_clean()\n mapping_version.save()\n\n def test_create_mapping_negative__no_updated_by(self):\n with self.assertRaises(ValidationError):\n mapping_version = MappingVersion(\n created_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n versioned_object_id=self.mapping1.id,\n versioned_object_type=ContentType.objects.get_for_model(Mapping),\n mnemonic='tempid'\n )\n mapping_version.full_clean()\n mapping_version.save()\n\n def test_create_mapping_negative__no_parent(self):\n with self.assertRaises(ValidationError):\n mapping_version = MappingVersion(\n created_by=self.user1,\n updated_by=self.user1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n versioned_object_id=self.mapping1.id,\n versioned_object_type=ContentType.objects.get_for_model(Mapping),\n mnemonic='tempid'\n )\n mapping_version.full_clean()\n mapping_version.save()\n\n def test_create_mapping_negative__no_map_type(self):\n with self.assertRaises(ValidationError):\n mapping_version = MappingVersion(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n versioned_object_id=self.mapping1.id,\n versioned_object_type=ContentType.objects.get_for_model(Mapping),\n mnemonic='tempid'\n )\n mapping_version.full_clean()\n mapping_version.save()\n\n def test_create_mapping_negative__no_from_concept(self):\n with self.assertRaises(ValidationError):\n mapping_version = MappingVersion(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n to_concept=self.concept2,\n external_id='mapping1',\n versioned_object_id=self.mapping1.id,\n versioned_object_type=ContentType.objects.get_for_model(Mapping),\n mnemonic='tempid'\n )\n mapping_version.full_clean()\n mapping_version.save()\n\n def test_create_mapping_negative__no_version_object(self):\n with self.assertRaises(ValidationError):\n mapping_version = MappingVersion(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n versioned_object_type=ContentType.objects.get_for_model(Mapping),\n mnemonic='tempid'\n )\n mapping_version.full_clean()\n mapping_version.save()\n\n def test_mapping_access_changes_with_source(self):\n public_access = self.source1.public_access\n mapping_version = MappingVersion(\n created_by=self.user1,\n updated_by=self.user1,\n parent=self.source1,\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n public_access=public_access,\n external_id='mapping1',\n versioned_object_id=self.mapping1.id,\n versioned_object_type=ContentType.objects.get_for_model(Mapping),\n mnemonic='tempid'\n )\n mapping_version.full_clean()\n mapping_version.save()\n\n self.assertEquals(self.source1.public_access, mapping_version.public_access)\n self.source1.public_access = ACCESS_TYPE_VIEW\n self.source1.save()\n\n def test_collections_ids(self):\n kwargs = {\n 'parent_resource': self.userprofile1\n }\n\n collection = Collection(\n name='collection2',\n mnemonic='collection2',\n full_name='Collection Two',\n collection_type='Dictionary',\n public_access=ACCESS_TYPE_EDIT,\n default_locale='en',\n supported_locales=['en'],\n website='www.collection2.com',\n description='This is the second test collection'\n )\n Collection.persist_new(collection, self.user1, **kwargs)\n\n source = Source(\n name='source',\n mnemonic='source',\n full_name='Source One',\n source_type='Dictionary',\n public_access=ACCESS_TYPE_EDIT,\n default_locale='en',\n supported_locales=['en'],\n website='www.source1.com',\n description='This is the first test source'\n )\n kwargs = {\n 'parent_resource': self.org1\n }\n Source.persist_new(source, self.user1, **kwargs)\n\n (concept1, errors) = create_concept(mnemonic='concept12', user=self.user1, source=source)\n (from_concept, errors) = create_concept(mnemonic='fromConcept', user=self.user1, source=source)\n (to_concept, errors) = create_concept(mnemonic='toConcept', user=self.user1, source=source)\n\n mapping = Mapping(\n map_type='Same As',\n from_concept=from_concept,\n to_concept=to_concept,\n external_id='mapping',\n )\n kwargs = {\n 'parent_resource': source,\n }\n\n Mapping.persist_new(mapping, self.user1, **kwargs)\n initial_mapping_version = MappingVersion.objects.get(versioned_object_id=mapping.id)\n new_mapping_version = MappingVersion.for_mapping(mapping)\n new_mapping_version.mnemonic = 98\n new_mapping_version.save()\n\n from_concept_reference = '/orgs/org1/sources/source/concepts/' + Concept.objects.get(mnemonic=from_concept.mnemonic).mnemonic + '/'\n concept1_reference = '/orgs/org1/sources/source/concepts/' + Concept.objects.get(mnemonic=concept1.mnemonic).mnemonic + '/'\n mapping = Mapping.objects.filter()[1]\n references = [concept1_reference, from_concept_reference, mapping.uri, initial_mapping_version.uri]\n\n collection.expressions = references\n collection.full_clean()\n collection.save()\n self.assertEquals(initial_mapping_version.collection_ids, [collection.id])\n self.assertEquals(new_mapping_version.collection_ids, [collection.id])\n\n def test_collections_version_ids(self):\n kwargs = {\n 'parent_resource': self.userprofile1\n }\n\n collection = Collection(\n name='collection2',\n mnemonic='collection2',\n full_name='Collection Two',\n collection_type='Dictionary',\n public_access=ACCESS_TYPE_EDIT,\n default_locale='en',\n supported_locales=['en'],\n website='www.collection2.com',\n description='This is the second test collection'\n )\n Collection.persist_new(collection, self.user1, **kwargs)\n\n source = Source(\n name='source',\n mnemonic='source',\n full_name='Source One',\n source_type='Dictionary',\n public_access=ACCESS_TYPE_EDIT,\n default_locale='en',\n supported_locales=['en'],\n website='www.source1.com',\n description='This is the first test source'\n )\n kwargs = {\n 'parent_resource': self.org1\n }\n Source.persist_new(source, self.user1, **kwargs)\n\n (concept1, errors) = create_concept(mnemonic='concept12', user=self.user1, source=source)\n (from_concept, errors) = create_concept(mnemonic='fromConcept', user=self.user1, source=source)\n (to_concept, errors) = create_concept(mnemonic='toConcept', user=self.user1, source=source)\n\n mapping = Mapping(\n map_type='Same As',\n from_concept=from_concept,\n to_concept=to_concept,\n external_id='mapping',\n )\n kwargs = {\n 'parent_resource': source,\n }\n\n Mapping.persist_new(mapping, self.user1, **kwargs)\n\n mapping = Mapping.objects.filter()[1]\n mapping_reference = '/orgs/org1/sources/source/mappings/' + mapping.id + '/'\n\n references = [mapping_reference]\n\n collection.expressions = references\n collection.full_clean()\n collection.save()\n\n mapping_version = MappingVersion.objects.filter()[0]\n collection_version = CollectionVersion(\n name='version1',\n mnemonic='version1',\n versioned_object=collection,\n released=True,\n created_by=self.user1,\n updated_by=self.user1,\n mappings=[mapping_version.id]\n )\n collection_version.full_clean()\n collection_version.save()\n\n self.assertEquals(mapping_version.collection_version_ids, [collection_version.id])\n\nclass MappingClassMethodsTest(MappingBaseTest):\n\n def test_persist_new_positive(self):\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n source_version = SourceVersion.get_latest_version_of(self.source1)\n self.assertEquals(0, len(source_version.mappings))\n kwargs = {\n 'parent_resource': self.source1,\n }\n errors = Mapping.persist_new(mapping, self.user1, **kwargs)\n self.assertEquals(0, len(errors))\n\n self.assertTrue(Mapping.objects.filter(external_id='mapping1').exists())\n mapping = Mapping.objects.get(external_id='mapping1')\n self.assertEquals(self.source1.public_access, mapping.public_access)\n self.assertEquals('user1', mapping.created_by)\n self.assertEquals('user1', mapping.updated_by)\n self.assertEquals(self.source1, mapping.parent)\n self.assertEquals('Same As', mapping.map_type)\n self.assertEquals(self.concept1, mapping.from_concept)\n self.assertEquals(self.concept2, mapping.to_concept)\n self.assertEquals(self.source1, mapping.from_source)\n self.assertEquals(self.source1.owner_name, mapping.from_source_owner)\n self.assertEquals(self.source1.mnemonic, mapping.from_source_name)\n self.assertEquals(self.source1, mapping.get_to_source())\n self.assertEquals(self.source1.owner_name, mapping.to_source_owner)\n self.assertEquals(self.concept2.mnemonic, mapping.get_to_concept_code())\n self.assertEquals(self.concept2.display_name, mapping.get_to_concept_name())\n\n source_version = SourceVersion.objects.get(id=source_version.id)\n self.assertEquals(1, len(source_version.mappings))\n self.assertTrue(MappingVersion.objects.get(versioned_object_id=mapping.id).id in source_version.mappings)\n\n def test_persist_new_version_created_positive(self):\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n source_version = SourceVersion.get_latest_version_of(self.source1)\n self.assertEquals(0, len(source_version.mappings))\n kwargs = {\n 'parent_resource': self.source1,\n }\n errors = Mapping.persist_new(mapping, self.user1, **kwargs)\n self.assertEquals(0, len(errors))\n\n self.assertTrue(Mapping.objects.filter(external_id='mapping1').exists())\n mapping = Mapping.objects.get(external_id='mapping1')\n self.assertTrue(MappingVersion.objects.filter(versioned_object_id=mapping.id, is_latest_version=True).exists())\n mapping_version = MappingVersion.objects.get(versioned_object_id=mapping.id, is_latest_version=True)\n self.assertEquals(self.source1.public_access, mapping_version.public_access)\n self.assertEquals('user1', mapping_version.created_by)\n self.assertEquals('user1', mapping_version.updated_by)\n self.assertEquals(self.source1, mapping_version.parent)\n self.assertEquals('Same As', mapping_version.map_type)\n self.assertEquals(self.concept1, mapping_version.from_concept)\n self.assertEquals(self.concept2, mapping_version.to_concept)\n self.assertEquals(self.source1, mapping_version.from_source)\n self.assertEquals(self.source1.owner_name, mapping_version.from_source_owner)\n self.assertEquals(self.source1.mnemonic, mapping_version.from_source_name)\n self.assertEquals(self.source1, mapping_version.get_to_source())\n self.assertEquals(self.source1.owner_name, mapping_version.to_source_owner)\n self.assertEquals(self.concept2.mnemonic, mapping_version.get_to_concept_code())\n self.assertEquals(self.concept2.display_name, mapping_version.get_to_concept_name())\n\n source_version = SourceVersion.objects.get(id=source_version.id)\n self.assertEquals(1, len(source_version.mappings))\n self.assertTrue(MappingVersion.objects.get(versioned_object_id=mapping.id).id in source_version.mappings)\n\n def test_persist_new_negative__no_creator(self):\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n source_version = SourceVersion.get_latest_version_of(self.source1)\n self.assertEquals(0, len(source_version.mappings))\n kwargs = {\n 'parent_resource': self.source1,\n }\n errors = Mapping.persist_new(mapping, None, **kwargs)\n self.assertEquals(1, len(errors))\n self.assertTrue('non_field_errors' in errors)\n non_field_errors = errors['non_field_errors']\n self.assertEquals(1, len(non_field_errors))\n self.assertTrue('creator' in non_field_errors[0])\n\n self.assertFalse(Mapping.objects.filter(external_id='mapping1').exists())\n source_version = SourceVersion.objects.get(id=source_version.id)\n self.assertEquals(0, len(source_version.mappings))\n\n def test_persist_new_negative__no_parent(self):\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n source_version = SourceVersion.get_latest_version_of(self.source1)\n self.assertEquals(0, len(source_version.mappings))\n kwargs = {}\n errors = Mapping.persist_new(mapping, self.user1, **kwargs)\n self.assertEquals(1, len(errors))\n self.assertTrue('non_field_errors' in errors)\n non_field_errors = errors['non_field_errors']\n self.assertEquals(1, len(non_field_errors))\n self.assertTrue('parent' in non_field_errors[0])\n\n self.assertFalse(Mapping.objects.filter(external_id='mapping1').exists())\n source_version = SourceVersion.objects.get(id=source_version.id)\n self.assertEquals(0, len(source_version.mappings))\n\n def test_persist_new_negative__same_mapping(self):\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n source_version = SourceVersion.get_latest_version_of(self.source1)\n self.assertEquals(0, len(source_version.mappings))\n kwargs = {\n 'parent_resource': self.source1,\n }\n errors = Mapping.persist_new(mapping, self.user1, **kwargs)\n self.assertEquals(0, len(errors))\n\n self.assertTrue(Mapping.objects.filter(external_id='mapping1').exists())\n mapping = Mapping.objects.get(external_id='mapping1')\n source_version = SourceVersion.objects.get(id=source_version.id)\n self.assertEquals(1, len(source_version.mappings))\n mv = MappingVersion.objects.get(versioned_object_id=mapping.id)\n self.assertTrue(mv.id in source_version.mappings)\n\n # Repeat with same concepts\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping2',\n )\n kwargs = {\n 'parent_resource': self.source1,\n }\n errors = Mapping.persist_new(mapping, self.user1, **kwargs)\n self.assertEquals(1, len(errors))\n self.assertEquals(1, len(errors))\n self.assertTrue('__all__' in errors)\n non_field_errors = errors['__all__']\n self.assertEquals(1, len(non_field_errors))\n self.assertTrue('already exists' in non_field_errors[0])\n self.assertEquals(1, len(source_version.mappings))\n\n def test_persist_new_positive__same_mapping_different_source(self):\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n source_version = SourceVersion.get_latest_version_of(self.source1)\n self.assertEquals(0, len(source_version.mappings))\n kwargs = {\n 'parent_resource': self.source1,\n }\n errors = Mapping.persist_new(mapping, self.user1, **kwargs)\n self.assertEquals(0, len(errors))\n\n self.assertTrue(Mapping.objects.filter(external_id='mapping1').exists())\n mapping = Mapping.objects.get(external_id='mapping1')\n\n source_version = SourceVersion.objects.get(id=source_version.id)\n self.assertEquals(1, len(source_version.mappings))\n self.assertTrue(MappingVersion.objects.get(versioned_object_id=mapping.id).id in source_version.mappings)\n\n # Repeat with same concepts\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping2',\n )\n kwargs = {\n 'parent_resource': self.source2,\n }\n source_version = SourceVersion.get_latest_version_of(self.source2)\n self.assertEquals(0, len(source_version.mappings))\n errors = Mapping.persist_new(mapping, self.user1, **kwargs)\n self.assertEquals(0, len(errors))\n\n self.assertTrue(Mapping.objects.filter(external_id='mapping2').exists())\n mapping = Mapping.objects.get(external_id='mapping2')\n\n source_version = SourceVersion.objects.get(id=source_version.id)\n self.assertEquals(1, len(source_version.mappings))\n self.assertTrue(MappingVersion.objects.get(versioned_object_id=mapping.id).id in source_version.mappings)\n\n def test_persist_new_positive__earlier_source_version(self):\n version1 = SourceVersion.get_latest_version_of(self.source1)\n self.assertEquals(0, len(version1.mappings))\n\n version2 = SourceVersion.for_base_object(self.source1, label='version2')\n version2.save()\n self.assertEquals(0, len(version2.mappings))\n\n source_version = SourceVersion.get_latest_version_of(self.source1)\n self.assertEquals(0, len(source_version.mappings))\n\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n kwargs = {\n 'parent_resource': self.source1,\n 'parent_resource_version': version1,\n }\n\n errors = Mapping.persist_new(mapping, self.user1, **kwargs)\n self.assertEquals(0, len(errors))\n self.assertTrue(Mapping.objects.filter(external_id='mapping1').exists())\n mapping = Mapping.objects.get(external_id='mapping1')\n\n version1 = SourceVersion.objects.get(id=version1.id)\n self.assertEquals(1, len(version1.mappings))\n self.assertTrue(MappingVersion.objects.get(versioned_object_id=mapping.id).id in version1.mappings)\n\n version2 = SourceVersion.objects.get(id=version2.id)\n self.assertEquals(0, len(version2.mappings))\n latest_version = SourceVersion.get_latest_version_of(self.source1)\n self.assertEquals(0, len(latest_version.mappings))\n\n def test_persist_persist_changes_positive(self):\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n source_version = SourceVersion.get_latest_version_of(self.source1)\n self.assertEquals(0, len(source_version.mappings))\n kwargs = {\n 'parent_resource': self.source1,\n }\n Mapping.persist_new(mapping, self.user1, **kwargs)\n mapping = Mapping.objects.get(external_id='mapping1')\n to_concept = mapping.to_concept\n\n source_version = SourceVersion.objects.get(id=source_version.id)\n self.assertEquals(1, len(source_version.mappings))\n self.assertTrue(MappingVersion.objects.get(versioned_object_id=mapping.id).id in source_version.mappings)\n\n mapping.to_concept = self.concept3\n errors = Mapping.persist_changes(mapping, self.user1)\n self.assertEquals(0, len(errors))\n mapping = Mapping.objects.get(external_id='mapping1')\n\n self.assertEquals(self.concept3, mapping.to_concept)\n self.assertNotEquals(to_concept, mapping.to_concept)\n\n source_version = SourceVersion.objects.get(id=source_version.id)\n self.assertEquals(1, len(source_version.mappings))\n mv = MappingVersion.objects.filter(versioned_object_id=mapping.id)\n self.assertTrue(mv[1].id in source_version.mappings)\n\n def test_persist_persist_changes_negative__no_updated_by(self):\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n source_version = SourceVersion.get_latest_version_of(self.source1)\n self.assertEquals(0, len(source_version.mappings))\n kwargs = {\n 'parent_resource': self.source1,\n }\n Mapping.persist_new(mapping, self.user1, **kwargs)\n mapping = Mapping.objects.get(external_id='mapping1')\n\n source_version = SourceVersion.objects.get(id=source_version.id)\n self.assertEquals(1, len(source_version.mappings))\n self.assertTrue(MappingVersion.objects.get(versioned_object_id=mapping.id).id in source_version.mappings)\n\n mapping.to_concept = self.concept3\n errors = Mapping.persist_changes(mapping, None)\n self.assertEquals(1, len(errors))\n self.assertTrue('updated_by' in errors)\n\n source_version = SourceVersion.objects.get(id=source_version.id)\n self.assertEquals(1, len(source_version.mappings))\n self.assertTrue(MappingVersion.objects.get(versioned_object_id=mapping.id).id in source_version.mappings)\n\n def test_retire_positive(self):\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n kwargs = {\n 'parent_resource': self.source1,\n }\n Mapping.persist_new(mapping, self.user1, **kwargs)\n mapping = Mapping.objects.get(external_id='mapping1')\n self.assertFalse(mapping.retired)\n\n Mapping.retire(mapping, self.user1)\n self.assertTrue(mapping.retired)\n mapping = Mapping.objects.get(external_id='mapping1')\n self.assertTrue(mapping.retired)\n mappingVersion=MappingVersion.objects.get(versioned_object_id=mapping.mnemonic, mnemonic=2)\n self.assertTrue(mappingVersion.retired)\n\n def test_retire_negative(self):\n mapping = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n retired=True,\n )\n kwargs = {\n 'parent_resource': self.source1,\n }\n Mapping.persist_new(mapping, self.user1, **kwargs)\n mapping = Mapping.objects.get(external_id='mapping1')\n self.assertTrue(mapping.retired)\n\n result=Mapping.retire(mapping, self.user1)\n self.assertFalse(result)\n mapping = Mapping.objects.get(external_id='mapping1')\n self.assertTrue(mapping.retired)\n\n def test_edit_mapping_make_new_version_positive(self):\n mapping1 = Mapping(\n map_type='Same As',\n from_concept=self.concept1,\n to_concept=self.concept2,\n external_id='mapping1',\n )\n source_version = SourceVersion.get_latest_version_of(self.source1)\n self.assertEquals(0, len(source_version.mappings))\n kwargs = {\n 'parent_resource': self.source1,\n }\n errors = Mapping.persist_new(mapping1, self.user1, **kwargs)\n self.assertEquals(0, len(errors))\n\n self.assertEquals(1,len(MappingVersion.objects.filter(versioned_object_id=mapping1.id)))\n\n mapping1.map_type='BROADER_THAN'\n Mapping.persist_changes(mapping1, self.user1)\n\n self.assertEquals(2, len(MappingVersion.objects.filter(versioned_object_id=mapping1.id)))\n\n old_version = MappingVersion.objects.get(versioned_object_id=mapping1.id, is_latest_version=False)\n\n new_version= MappingVersion.objects.get(versioned_object_id=mapping1.id, is_latest_version=True)\n\n self.assertFalse(old_version.is_latest_version)\n self.assertTrue(new_version.is_latest_version)\n self.assertEquals(new_version.map_type,'BROADER_THAN')\n self.assertEquals(old_version.map_type,'Same As')\n\nclass OpenMRSMappingValidationTest(MappingBaseTest):\n\n def test_create_same_from_and_to_pair_with_different_map_types_should_throw_validation_error(self):\n user = create_user()\n\n source = create_source(user, validation_schema=CUSTOM_VALIDATION_SCHEMA_OPENMRS)\n (concept1, _) = create_concept(user, source)\n (concept2, _) = create_concept(user, source)\n\n create_mapping(user, source, concept1, concept2, \"Same As\")\n\n mapping = Mapping(\n created_by=user,\n updated_by=user,\n parent=source,\n map_type='Is Subset of',\n from_concept=concept1,\n to_concept=concept2,\n public_access=ACCESS_TYPE_VIEW,\n )\n\n kwargs = {\n 'parent_resource': source,\n }\n\n errors = Mapping.persist_new(mapping, user, **kwargs)\n self.assertTrue(OPENMRS_SINGLE_MAPPING_BETWEEN_TWO_CONCEPTS in errors[\"__all__\"])\n\n def test_update_different_from_and_to_pairs_to_same_from_and_to_pairs_should_throw_validation_error(self):\n user = create_user()\n\n source1 = create_source(user, validation_schema=CUSTOM_VALIDATION_SCHEMA_OPENMRS)\n source2 = create_source(user, validation_schema=CUSTOM_VALIDATION_SCHEMA_OPENMRS)\n\n (concept1, _) = create_concept(user, source1)\n (concept2, _) = create_concept(user, source2)\n (concept3, _) = create_concept(user, source2)\n\n create_mapping(user, source1, concept1, concept2, \"Same As\")\n mapping = create_mapping(user, source1, concept2, concept3, \"Same As\")\n\n mapping.from_concept = concept1\n mapping.to_concept = concept2\n mapping.map_type = \"Different\"\n\n errors = Mapping.persist_changes(mapping, user)\n\n self.assertTrue(\n OPENMRS_SINGLE_MAPPING_BETWEEN_TWO_CONCEPTS in errors[\"__all__\"])"}]} {"messages": [{"role": "user", "content": "Write Python code that implements profile.py from PyGotham/pygotham (path: pygotham/frontend/profile.py)."}, {"role": "assistant", "content": "# pygotham/frontend/profile.py (from PyGotham/pygotham, license: bsd-3-clause)\n\n\"\"\"PyGotham user profiles.\"\"\"\n\nfrom flask import (\n Blueprint, flash, g, redirect, render_template, request, url_for\n)\nfrom flask_login import current_user\nfrom flask_security import login_required\n\nfrom pygotham.core import db\nfrom pygotham.frontend import route\nfrom pygotham.models import Talk, Volunteer\n\n__all__ = ('blueprint',)\n\nblueprint = Blueprint(\n 'profile',\n __name__,\n subdomain='',\n url_prefix='/profile',\n)\n\n@route(blueprint, '/dashboard/')\n@login_required\ndef dashboard():\n \"\"\"Return the user's dashboard.\"\"\"\n # TODO: Optionally, old proposals should be shown in a read-only mode.\n talks = Talk.query.current.filter(Talk.user == current_user)\n return render_template(\n 'profile/dashboard.html', talks=talks)\n\n@route(blueprint, '/settings/', methods=('GET', 'POST'))\n@login_required\ndef settings():\n \"\"\"Return the user's settings.\"\"\"\n # TODO: How should this be handled? Should a speaker's bio be stored\n # as a snapshot from event to event? It could be stored as part of a\n # talks.models.Presentation.\n from pygotham.forms import ProfileForm\n\n form = ProfileForm(request.form, obj=current_user)\n if form.validate_on_submit():\n form.populate_obj(current_user)\n db.session.commit()\n\n flash('Your profile has been updated.', 'success')\n\n return redirect(url_for('profile.settings'))\n\n return render_template('profile/settings.html', form=form)\n\n@route(blueprint, '/unvolunteer/')\n@login_required\ndef unvolunteer():\n \"\"\"Remove a user from being a volunteer.\"\"\"\n if current_user.is_volunteer:\n volunteer = Volunteer.query.current.filter(\n Volunteer.user == current_user).first()\n db.session.delete(volunteer)\n db.session.commit()\n flash(\"We're sorry to see you change your mind!\")\n return redirect(url_for('profile.dashboard'))\n\n@route(blueprint, '/volunteer/')\n@login_required\ndef volunteer():\n \"\"\"Sign up a user as a volunteer.\"\"\"\n if not current_user.is_volunteer:\n volunteer = Volunteer(user=current_user, event=g.current_event)\n db.session.add(volunteer)\n db.session.commit()\n flash('Thanks for volunteering!')\n return redirect(url_for('profile.dashboard'))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements extension.py from f-guichard/cf-sample-php-buildpack-custo (path: extensions/composer/extension.py)."}, {"role": "assistant", "content": "# extensions/composer/extension.py (from f-guichard/cf-sample-php-buildpack-custo, license: apache-2.0)\n\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Composer Extension\n\nDownloads, installs and runs Composer.\n\"\"\"\nimport os\nimport os.path\nimport sys\nimport logging\nimport re\nimport json\nimport StringIO\nfrom build_pack_utils import utils\nfrom build_pack_utils import stream_output\nfrom extension_helpers import ExtensionHelper\n\n_log = logging.getLogger('composer')\n\ndef find_composer_paths(ctx):\n build_dir = ctx['BUILD_DIR']\n webdir = ctx['WEBDIR']\n\n json_path = None\n lock_path = None\n json_paths = [\n os.path.join(build_dir, 'composer.json'),\n os.path.join(build_dir, webdir, 'composer.json')\n ]\n\n lock_paths = [\n os.path.join(build_dir, 'composer.lock'),\n os.path.join(build_dir, webdir, 'composer.lock')\n ]\n\n env_path = os.getenv('COMPOSER_PATH')\n if env_path is not None:\n json_paths = json_paths + [\n os.path.join(build_dir, env_path, 'composer.json'),\n os.path.join(build_dir, webdir, env_path, 'composer.json')\n ]\n\n lock_paths = lock_paths + [\n os.path.join(build_dir, env_path, 'composer.lock'),\n os.path.join(build_dir, webdir, env_path, 'composer.lock')\n ]\n\n for path in json_paths:\n if os.path.exists(path):\n json_path = path\n for path in lock_paths:\n if os.path.exists(path):\n lock_path = path\n\n return (json_path, lock_path)\n\nclass ComposerConfiguration(object):\n def __init__(self, ctx):\n self._ctx = ctx\n self._log = _log\n self._init_composer_paths()\n\n def _init_composer_paths(self):\n (self.json_path, self.lock_path) = \\\n find_composer_paths(self._ctx)\n\n def read_exts_from_path(self, path):\n exts = []\n if path:\n req_pat = re.compile(r'\"require\"\\s?\\:\\s?\\{(.*?)\\}', re.DOTALL)\n ext_pat = re.compile(r'\"ext-(.*?)\"')\n with open(path, 'rt') as fp:\n data = fp.read()\n for req_match in req_pat.finditer(data):\n for ext_match in ext_pat.finditer(req_match.group(1)):\n exts.append(ext_match.group(1))\n return exts\n\n def pick_php_version(self, requested):\n selected = None\n if requested is None:\n selected = self._ctx['PHP_VERSION']\n elif requested == '5.5.*' or requested == '>=5.5':\n selected = self._ctx['PHP_55_LATEST']\n elif requested == '5.6.*' or requested == '>=5.6':\n selected = self._ctx['PHP_56_LATEST']\n elif requested.startswith('5.5.'):\n selected = requested\n elif requested.startswith('5.6.'):\n selected = requested\n else:\n selected = self._ctx['PHP_VERSION']\n return selected\n\n def read_version_from_composer(self, key):\n (json_path, lock_path) = find_composer_paths(self._ctx)\n if json_path is not None:\n composer = json.load(open(json_path, 'r'))\n require = composer.get('require', {})\n return require.get(key, None)\n if lock_path is not None:\n composer = json.load(open(lock_path, 'r'))\n platform = composer.get('platform', {})\n return platform.get(key, None)\n return None\n\n def configure(self):\n if self.json_path or self.lock_path:\n exts = []\n # include any existing extensions\n exts.extend(self._ctx.get('PHP_EXTENSIONS', []))\n # add 'openssl' extension\n exts.append('openssl')\n # add platform extensions from composer.json & composer.lock\n exts.extend(self.read_exts_from_path(self.json_path))\n exts.extend(self.read_exts_from_path(self.lock_path))\n hhvm_version = self.read_version_from_composer('hhvm')\n if hhvm_version:\n self._ctx['PHP_VM'] = 'hhvm'\n self._log.debug('Composer picked HHVM Version [%s]',\n hhvm_version)\n else:\n # update context with new list of extensions,\n # if composer.json exists\n php_version = self.read_version_from_composer('php')\n self._log.debug('Composer picked PHP Version [%s]',\n php_version)\n self._ctx['PHP_VERSION'] = self.pick_php_version(php_version)\n self._ctx['PHP_EXTENSIONS'] = utils.unique(exts)\n self._ctx['PHP_VM'] = 'php'\n\nclass ComposerExtension(ExtensionHelper):\n def __init__(self, ctx):\n ExtensionHelper.__init__(self, ctx)\n self._log = _log\n\n def _defaults(self):\n return {\n 'COMPOSER_VERSION': '1.0.0-alpha10',\n 'COMPOSER_PACKAGE': 'composer.phar',\n 'COMPOSER_DOWNLOAD_URL': '/composer/'\n '{COMPOSER_VERSION}/{COMPOSER_PACKAGE}',\n 'COMPOSER_INSTALL_OPTIONS': ['--no-interaction', '--no-dev'],\n 'COMPOSER_VENDOR_DIR': '{BUILD_DIR}/{LIBDIR}/vendor',\n 'COMPOSER_BIN_DIR': '{BUILD_DIR}/php/bin',\n 'COMPOSER_CACHE_DIR': '{CACHE_DIR}/composer'\n }\n\n def _should_compile(self):\n (json_path, lock_path) = \\\n find_composer_paths(self._ctx)\n return (json_path is not None or lock_path is not None)\n\n def _compile(self, install):\n self._builder = install.builder\n self.composer_runner = ComposerCommandRunner(self._ctx, self._builder)\n self.move_local_vendor_folder()\n self.install()\n self.run()\n\n def move_local_vendor_folder(self):\n vendor_path = os.path.join(self._ctx['BUILD_DIR'],\n self._ctx['WEBDIR'],\n 'vendor')\n if os.path.exists(vendor_path):\n self._log.debug(\"Vendor [%s] exists, moving to LIBDIR\",\n vendor_path)\n (self._builder.move()\n .under('{BUILD_DIR}/{WEBDIR}')\n .into('{BUILD_DIR}/{LIBDIR}')\n .where_name_matches('^%s/.*$' % vendor_path)\n .done())\n\n def install(self):\n self._builder.install().package('PHP').done()\n if self._ctx['COMPOSER_VERSION'] == 'latest':\n dependencies_path = os.path.join(self._ctx['BP_DIR'],\n 'dependencies')\n if os.path.exists(dependencies_path):\n raise RuntimeError('\"COMPOSER_VERSION\": \"latest\" ' \\\n 'is not supported in the cached buildpack. Please vendor your preferred version of composer with your app, or use the provided default composer version.')\n\n self._ctx['COMPOSER_DOWNLOAD_URL'] = \\\n 'https://getcomposer.org/composer.phar'\n self._builder.install()._installer.install_binary_direct(\n self._ctx['COMPOSER_DOWNLOAD_URL'], None,\n os.path.join(self._ctx['BUILD_DIR'], 'php', 'bin'),\n extract=False)\n else:\n self._builder.install()._installer._install_binary_from_manifest(\n self._ctx['COMPOSER_DOWNLOAD_URL'],\n os.path.join(self._ctx['BUILD_DIR'], 'php', 'bin'),\n extract=False)\n\n def _github_oauth_token_is_valid(self, candidate_oauth_token):\n stringio_writer = StringIO.StringIO()\n\n curl_command = 'curl -H \"Authorization: token %s\" ' \\\n 'https://api.github.com/rate_limit' % candidate_oauth_token\n\n stream_output(stringio_writer,\n curl_command,\n env=os.environ,\n cwd=self._ctx['BUILD_DIR'],\n shell=True)\n\n github_response = stringio_writer.getvalue()\n\n github_response_json = json.loads(github_response)\n return 'resources' in github_response_json\n\n def _github_rate_exceeded(self, token_is_valid):\n stringio_writer = StringIO.StringIO()\n if token_is_valid:\n candidate_oauth_token = os.getenv('COMPOSER_GITHUB_OAUTH_TOKEN')\n curl_command = 'curl -H \"Authorization: token %s\" ' \\\n 'https://api.github.com/rate_limit' % candidate_oauth_token\n else:\n curl_command = 'curl https://api.github.com/rate_limit'\n\n stream_output(stringio_writer,\n curl_command,\n env=os.environ,\n cwd=self._ctx['BUILD_DIR'],\n shell=True)\n\n github_response = stringio_writer.getvalue()\n github_response_json = json.loads(github_response)\n\n rate = github_response_json['rate']\n num_remaining = rate['remaining']\n\n return num_remaining <= 0\n\n def setup_composer_github_token(self):\n github_oauth_token = os.getenv('COMPOSER_GITHUB_OAUTH_TOKEN')\n if self._github_oauth_token_is_valid(github_oauth_token):\n print('-----> Using custom GitHub OAuth token in'\n ' $COMPOSER_GITHUB_OAUTH_TOKEN')\n self.composer_runner.run('config', '-g',\n 'github-oauth.github.com',\n '\"%s\"' % github_oauth_token)\n return True\n else:\n print('-----> The GitHub OAuth token supplied from '\n '$COMPOSER_GITHUB_OAUTH_TOKEN is invalid')\n return False\n\n def check_github_rate_exceeded(self, token_is_valid):\n if self._github_rate_exceeded(token_is_valid):\n print('-----> The GitHub api rate limit has been exceeded. '\n 'Composer will continue by downloading from source, which might result in slower downloads. '\n 'You can increase your rate limit with a GitHub OAuth token. '\n 'Please obtain a GitHub OAuth token by registering your application at '\n 'https://github.com/settings/applications/new. '\n 'Then set COMPOSER_GITHUB_OAUTH_TOKEN in your environment to the value of this token.')\n\n def run(self):\n # Move composer files into root directory\n (json_path, lock_path) = find_composer_paths(self._ctx)\n if json_path is not None and os.path.dirname(json_path) != self._ctx['BUILD_DIR']:\n (self._builder.move()\n .under(os.path.dirname(json_path))\n .where_name_is('composer.json')\n .into('BUILD_DIR')\n .done())\n if lock_path is not None and os.path.dirname(lock_path) != self._ctx['BUILD_DIR']:\n (self._builder.move()\n .under(os.path.dirname(lock_path))\n .where_name_is('composer.lock')\n .into('BUILD_DIR')\n .done())\n # Sanity Checks\n if not os.path.exists(os.path.join(self._ctx['BUILD_DIR'],\n 'composer.lock')):\n msg = (\n 'PROTIP: Include a `composer.lock` file with your '\n 'application! This will make sure the exact same version '\n 'of dependencies are used when you deploy to CloudFoundry.')\n self._log.warning(msg)\n print msg\n # dump composer version, if in debug mode\n if self._ctx.get('BP_DEBUG', False):\n self.composer_runner.run('-V')\n if not os.path.exists(os.path.join(self._ctx['BP_DIR'], 'dependencies')):\n token_is_valid = False\n # config composer to use github token, if provided\n if os.getenv('COMPOSER_GITHUB_OAUTH_TOKEN', False):\n token_is_valid = self.setup_composer_github_token()\n # check that the api rate limit has not been exceeded, otherwise exit\n self.check_github_rate_exceeded(token_is_valid)\n # install dependencies w/Composer\n self.composer_runner.run('install', '--no-progress',\n *self._ctx['COMPOSER_INSTALL_OPTIONS'])\n\nclass ComposerCommandRunner(object):\n def __init__(self, ctx, builder):\n self._log = _log\n self._ctx = ctx\n self._strategy = HHVMComposerStrategy(ctx) \\\n if ctx['PHP_VM'] == 'hhvm' else PHPComposerStrategy(ctx)\n self._php_path = self._strategy.binary_path()\n self._composer_path = os.path.join(ctx['BUILD_DIR'], 'php',\n 'bin', 'composer.phar')\n self._strategy.write_config(builder)\n\n def _build_composer_environment(self):\n env = {}\n for key in os.environ.keys():\n val = self._ctx.get(key, '')\n env[key] = val if type(val) == str else json.dumps(val)\n\n # add basic composer vars\n env['COMPOSER_VENDOR_DIR'] = self._ctx['COMPOSER_VENDOR_DIR']\n env['COMPOSER_BIN_DIR'] = self._ctx['COMPOSER_BIN_DIR']\n env['COMPOSER_CACHE_DIR'] = self._ctx['COMPOSER_CACHE_DIR']\n\n # prevent key system variables from being overridden\n env['LD_LIBRARY_PATH'] = self._strategy.ld_library_path()\n env['PHPRC'] = self._ctx['TMPDIR']\n env['PATH'] = ':'.join(filter(None,\n [env.get('PATH', ''),\n os.path.dirname(self._php_path)]))\n self._log.debug(\"ENV IS: %s\",\n '\\n'.join([\"%s=%s (%s)\" % (key, val, type(val))\n for (key, val) in env.iteritems()]))\n return env\n\n def run(self, *args):\n try:\n cmd = [self._php_path, self._composer_path]\n cmd.extend(args)\n self._log.debug(\"Running command [%s]\", ' '.join(cmd))\n stream_output(sys.stdout,\n ' '.join(cmd),\n env=self._build_composer_environment(),\n cwd=self._ctx['BUILD_DIR'],\n shell=True)\n except:\n print \"-----> Composer command failed\"\n raise\n\nclass HHVMComposerStrategy(object):\n def __init__(self, ctx):\n self._ctx = ctx\n\n def binary_path(self):\n return os.path.join(\n self._ctx['BUILD_DIR'], 'hhvm', 'usr', 'bin', 'hhvm')\n\n def write_config(self, builder):\n pass\n\n def ld_library_path(self):\n return os.path.join(\n self._ctx['BUILD_DIR'], 'hhvm', 'usr', 'lib', 'hhvm')\n\nclass PHPComposerStrategy(object):\n def __init__(self, ctx):\n self._ctx = ctx\n\n def binary_path(self):\n return os.path.join(\n self._ctx['BUILD_DIR'], 'php', 'bin', 'php')\n\n def write_config(self, builder):\n # rewrite a temp copy of php.ini for use by composer\n (builder.copy()\n .under('{BUILD_DIR}/php/etc')\n .where_name_is('php.ini')\n .into('TMPDIR')\n .done())\n utils.rewrite_cfgs(os.path.join(self._ctx['TMPDIR'], 'php.ini'),\n {'TMPDIR': self._ctx['TMPDIR'],\n 'HOME': self._ctx['BUILD_DIR']},\n delim='@')\n\n def ld_library_path(self):\n return os.path.join(\n self._ctx['BUILD_DIR'], 'php', 'lib')\n\n# Extension Methods\ndef configure(ctx):\n config = ComposerConfiguration(ctx)\n config.configure()\n\ndef preprocess_commands(ctx):\n composer = ComposerExtension(ctx)\n return composer.preprocess_commands()\n\ndef service_commands(ctx):\n composer = ComposerExtension(ctx)\n return composer.service_commands()\n\ndef service_environment(ctx):\n composer = ComposerExtension(ctx)\n return composer.service_environment()\n\ndef compile(install):\n composer = ComposerExtension(install.builder._ctx)\n return composer.compile(install)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_admin.py from brayan15/Events (path: events/users/tests/test_admin.py)."}, {"role": "assistant", "content": "# events/users/tests/test_admin.py (from brayan15/Events, license: mit)\n\nfrom test_plus.test import TestCase\n\nfrom ..admin import MyUserCreationForm\n\nclass TestMyUserCreationForm(TestCase):\n\n def setUp(self):\n self.user = self.make_user('notalamode', 'notalamodespassword')\n\n def test_clean_username_success(self):\n # Instantiate the form with a new username\n form = MyUserCreationForm({\n 'username': 'alamode',\n 'password1': '7jefB#f@Cc7YJB]2v',\n 'password2': '7jefB#f@Cc7YJB]2v',\n })\n # Run is_valid() to trigger the validation\n valid = form.is_valid()\n self.assertTrue(valid)\n\n # Run the actual clean_username method\n username = form.clean_username()\n self.assertEqual('alamode', username)\n\n def test_clean_username_false(self):\n # Instantiate the form with the same username as self.user\n form = MyUserCreationForm({\n 'username': self.user.username,\n 'password1': 'notalamodespassword',\n 'password2': 'notalamodespassword',\n })\n # Run is_valid() to trigger the validation, which is going to fail\n # because the username is already taken\n valid = form.is_valid()\n self.assertFalse(valid)\n\n # The form.errors dict should contain a single error called 'username'\n self.assertTrue(len(form.errors) == 1)\n self.assertTrue('username' in form.errors)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements urls.py from ofcourseican/django-openid-auth (path: example_consumer/urls.py)."}, {"role": "assistant", "content": "# example_consumer/urls.py (from ofcourseican/django-openid-auth, license: bsd-2-clause)\n\n# django-openid-auth - OpenID integration for django.contrib.auth\n#\n# Copyright (C) 2007 Simon Willison\n# Copyright (C) 2008-2010 Canonical Ltd.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nfrom django.conf.urls.defaults import *\nfrom django.contrib import admin\n\nimport views\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n (r'^$', views.index),\n (r'^openid/', include('django_openid_auth.urls')),\n (r'^logout/$', 'django.contrib.auth.views.logout'),\n (r'^private/$', views.require_authentication),\n\n (r'^admin/(.*)', admin.site.root),\n)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements email_scribd.py from upgoingstar/datasploit (path: emails/email_scribd.py)."}, {"role": "assistant", "content": "# emails/email_scribd.py (from upgoingstar/datasploit, license: gpl-3.0)\n\n#!/usr/bin/env python\n\nimport base\nimport re\nimport sys\nimport requests\nfrom termcolor import colored\n\n# Control whether the module is enabled or not\nENABLED = True\n\nclass style:\n BOLD = '\\033[1m'\n END = '\\033[0m'\n\ndef banner():\n print colored(style.BOLD + '\\n---> Searching Scribd Docs\\n' + style.END, 'blue')\n\ndef main(email):\n req = requests.get('https://www.scribd.com/search?page=1&content_type=documents&query=%s' % (email))\n m = re.findall('(?<=https://www.scribd.com/doc/)\\w+', req.text.encode('UTF-8'))\n m = set(m)\n m = list(m)\n links = []\n length = len(m)\n for lt in range(0, length - 1):\n links.append(\"https://www.scribd.com/doc/\" + m[lt])\n return links\n\ndef output(data, email=\"\"):\n if data:\n print \"Found %s associated SCRIBD documents:\\n\" % len(data)\n for link in data:\n print link\n print \"\"\n print colored(style.BOLD + 'More results might be available, please follow this link:' + style.END)\n print \"https://www.scribd.com/search?page=1&content_type=documents&query=\" + email\n else:\n print colored('[-] No Associated Scribd Documents found.', 'red')\n\nif __name__ == \"__main__\":\n try:\n email = sys.argv[1]\n banner()\n result = main(email)\n output(result, email)\n except Exception as e:\n print e\n print \"Please provide an email as argument\""}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_query.py from dstufft/sqlalchemy (path: test/dialect/mysql/test_query.py)."}, {"role": "assistant", "content": "# test/dialect/mysql/test_query.py (from dstufft/sqlalchemy, license: mit)\n\n# coding: utf-8\n\nfrom sqlalchemy.testing import eq_, is_\nfrom sqlalchemy import *\nfrom sqlalchemy.testing import fixtures, AssertsCompiledSQL\nfrom sqlalchemy import testing\n\nclass IdiosyncrasyTest(fixtures.TestBase, AssertsCompiledSQL):\n __only_on__ = 'mysql'\n __backend__ = True\n\n @testing.emits_warning()\n def test_is_boolean_symbols_despite_no_native(self):\n is_(\n testing.db.scalar(select([cast(true().is_(true()), Boolean)])),\n True\n )\n\n is_(\n testing.db.scalar(select([cast(true().isnot(true()), Boolean)])),\n False\n )\n\n is_(\n testing.db.scalar(select([cast(false().is_(false()), Boolean)])),\n True\n )\n\nclass MatchTest(fixtures.TestBase, AssertsCompiledSQL):\n __only_on__ = 'mysql'\n __backend__ = True\n\n @classmethod\n def setup_class(cls):\n global metadata, cattable, matchtable\n metadata = MetaData(testing.db)\n\n cattable = Table('cattable', metadata,\n Column('id', Integer, primary_key=True),\n Column('description', String(50)),\n mysql_engine='MyISAM'\n )\n matchtable = Table('matchtable', metadata,\n Column('id', Integer, primary_key=True),\n Column('title', String(200)),\n Column('category_id', Integer, ForeignKey('cattable.id')),\n mysql_engine='MyISAM'\n )\n metadata.create_all()\n\n cattable.insert().execute([\n {'id': 1, 'description': 'Python'},\n {'id': 2, 'description': 'Ruby'},\n ])\n matchtable.insert().execute([\n {'id': 1,\n 'title': 'Agile Web Development with Ruby On Rails',\n 'category_id': 2},\n {'id': 2,\n 'title': 'Dive Into Python',\n 'category_id': 1},\n {'id': 3,\n 'title': \"Programming Matz's Ruby\",\n 'category_id': 2},\n {'id': 4,\n 'title': 'The Definitive Guide to Django',\n 'category_id': 1},\n {'id': 5,\n 'title': 'Python in a Nutshell',\n 'category_id': 1}\n ])\n\n @classmethod\n def teardown_class(cls):\n metadata.drop_all()\n\n @testing.fails_on('mysql+mysqlconnector', 'uses pyformat')\n def test_expression_format(self):\n format = testing.db.dialect.paramstyle == 'format' and '%s' or '?'\n self.assert_compile(\n matchtable.c.title.match('somstr'),\n \"MATCH (matchtable.title) AGAINST (%s IN BOOLEAN MODE)\" % format)\n\n @testing.fails_on('mysql+mysqldb', 'uses format')\n @testing.fails_on('mysql+pymysql', 'uses format')\n @testing.fails_on('mysql+cymysql', 'uses format')\n @testing.fails_on('mysql+oursql', 'uses format')\n @testing.fails_on('mysql+pyodbc', 'uses format')\n @testing.fails_on('mysql+zxjdbc', 'uses format')\n def test_expression_pyformat(self):\n format = '%(title_1)s'\n self.assert_compile(\n matchtable.c.title.match('somstr'),\n \"MATCH (matchtable.title) AGAINST (%s IN BOOLEAN MODE)\" % format)\n\n def test_simple_match(self):\n results = (matchtable.select().\n where(matchtable.c.title.match('python')).\n order_by(matchtable.c.id).\n execute().\n fetchall())\n eq_([2, 5], [r.id for r in results])\n\n def test_not_match(self):\n results = (matchtable.select().\n where(~matchtable.c.title.match('python')).\n order_by(matchtable.c.id).\n execute().\n fetchall())\n eq_([1, 3, 4], [r.id for r in results])\n\n def test_simple_match_with_apostrophe(self):\n results = (matchtable.select().\n where(matchtable.c.title.match(\"Matz's\")).\n execute().\n fetchall())\n eq_([3], [r.id for r in results])\n\n def test_return_value(self):\n # test [ticket:3263]\n result = testing.db.execute(\n select([\n matchtable.c.title.match('Agile Ruby Programming').label('ruby'),\n matchtable.c.title.match('Dive Python').label('python'),\n matchtable.c.title\n ]).order_by(matchtable.c.id)\n ).fetchall()\n eq_(\n result,\n [\n (2.0, 0.0, 'Agile Web Development with Ruby On Rails'),\n (0.0, 2.0, 'Dive Into Python'),\n (2.0, 0.0, \"Programming Matz's Ruby\"),\n (0.0, 0.0, 'The Definitive Guide to Django'),\n (0.0, 1.0, 'Python in a Nutshell')\n ]\n )\n\n def test_or_match(self):\n results1 = (matchtable.select().\n where(or_(matchtable.c.title.match('nutshell'),\n matchtable.c.title.match('ruby'))).\n order_by(matchtable.c.id).\n execute().\n fetchall())\n eq_([1, 3, 5], [r.id for r in results1])\n results2 = (matchtable.select().\n where(matchtable.c.title.match('nutshell ruby')).\n order_by(matchtable.c.id).\n execute().\n fetchall())\n eq_([1, 3, 5], [r.id for r in results2])\n\n def test_and_match(self):\n results1 = (matchtable.select().\n where(and_(matchtable.c.title.match('python'),\n matchtable.c.title.match('nutshell'))).\n execute().\n fetchall())\n eq_([5], [r.id for r in results1])\n results2 = (matchtable.select().\n where(matchtable.c.title.match('+python +nutshell')).\n execute().\n fetchall())\n eq_([5], [r.id for r in results2])\n\n def test_match_across_joins(self):\n results = (matchtable.select().\n where(and_(cattable.c.id==matchtable.c.category_id,\n or_(cattable.c.description.match('Ruby'),\n matchtable.c.title.match('nutshell')))).\n order_by(matchtable.c.id).\n execute().\n fetchall())\n eq_([1, 3, 5], [r.id for r in results])"}]} {"messages": [{"role": "user", "content": "Write Python code that implements host.py from madj4ck/ansible (path: lib/ansible/new_inventory/host.py)."}, {"role": "assistant", "content": "# lib/ansible/new_inventory/host.py (from madj4ck/ansible, license: gpl-3.0)\n\n# (c) 2012-2014, Michael DeHaan \n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\n# Make coding more python3-ish\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nclass Host:\n def __init__(self, name):\n self._name = name\n self._connection = None\n self._ipv4_address = ''\n self._ipv6_address = ''\n self._port = 22\n self._vars = dict()\n\n def __repr__(self):\n return self.get_name()\n\n def get_name(self):\n return self._name\n\n def get_groups(self):\n return []\n\n def set_variable(self, name, value):\n ''' sets a variable for this host '''\n\n self._vars[name] = value\n\n def get_vars(self):\n ''' returns all variables for this host '''\n\n all_vars = self._vars.copy()\n all_vars.update(dict(inventory_hostname=self._name))\n return all_vars"}]} {"messages": [{"role": "user", "content": "Write Python code that implements ServicePosition.py from philotas/enigma2 (path: lib/python/Components/Converter/ServicePosition.py)."}, {"role": "assistant", "content": "# lib/python/Components/Converter/ServicePosition.py (from philotas/enigma2, license: gpl-2.0)\n\nfrom Converter import Converter\nfrom Poll import Poll\nfrom enigma import iPlayableService\nfrom Components.Element import cached, ElementError\nfrom Components.config import config\n\nclass ServicePosition(Poll, Converter, object):\n\tTYPE_LENGTH = 0\n\tTYPE_POSITION = 1\n\tTYPE_REMAINING = 2\n\tTYPE_GAUGE = 3\n\tTYPE_SUMMARY = 4\n\tTYPE_VFD_LENGTH = 5\n\tTYPE_VFD_POSITION = 6\n\tTYPE_VFD_REMAINING = 7\n\tTYPE_VFD_GAUGE = 8\n\tTYPE_VFD_SUMMARY = 9\n\n\tdef __init__(self, type):\n\t\tPoll.__init__(self)\n\t\tConverter.__init__(self, type)\n\n\t\targs = type.split(',')\n\t\ttype = args.pop(0)\n\n\t\tself.negate = 'Negate' in args\n\t\tself.detailed = 'Detailed' in args\n\t\tself.showHours = 'ShowHours' in args\n\t\tself.showNoSeconds = 'ShowNoSeconds' in args\n\t\tself.OnlyMinute = 'OnlyMinute' in args\n\n\t\tif type == \"Length\":\n\t\t\tself.type = self.TYPE_LENGTH\n\t\telif type == \"Position\":\n\t\t\tself.type = self.TYPE_POSITION\n\t\telif type == \"Remaining\":\n\t\t\tself.type = self.TYPE_REMAINING\n\t\telif type == \"Gauge\":\n\t\t\tself.type = self.TYPE_GAUGE\n\t\telif type == \"Summary\":\n\t\t\tself.type = self.TYPE_SUMMARY\n\t\telif type == \"VFDLength\":\n\t\t\tself.type = self.TYPE_VFD_LENGTH\n\t\telif type == \"VFDPosition\":\n\t\t\tself.type = self.TYPE_VFD_POSITION\n\t\telif type == \"VFDRemaining\":\n\t\t\tself.type = self.TYPE_VFD_REMAINING\n\t\telif type == \"VFDGauge\":\n\t\t\tself.type = self.TYPE_VFD_GAUGE\n\t\telif type == \"VFDSummary\":\n\t\t\tself.type = self.TYPE_VFD_SUMMARY\n\t\telse:\n\t\t\traise ElementError(\"type must be {Length|Position|Remaining|Gauge|Summary} with optional arguments {Negate|Detailed|ShowHours|ShowNoSeconds} for ServicePosition converter\")\n\n\t\tif self.detailed:\n\t\t\tself.poll_interval = 100\n\t\telif self.type == self.TYPE_LENGTH or self.type == self.TYPE_VFD_LENGTH:\n\t\t\tself.poll_interval = 2000\n\t\telse:\n\t\t\tself.poll_interval = 500\n\n\t\tself.poll_enabled = True\n\n\tdef getSeek(self):\n\t\ts = self.source.service\n\t\treturn s and s.seek()\n\n\t@cached\n\tdef getPosition(self):\n\t\tseek = self.getSeek()\n\t\tif seek is None:\n\t\t\treturn None\n\t\tpos = seek.getPlayPosition()\n\t\tif pos[0]:\n\t\t\treturn 0\n\t\treturn pos[1]\n\n\t@cached\n\tdef getLength(self):\n\t\tseek = self.getSeek()\n\t\tif seek is None:\n\t\t\treturn None\n\t\tlength = seek.getLength()\n\t\tif length[0]:\n\t\t\treturn 0\n\t\treturn length[1]\n\n\t@cached\n\tdef getCutlist(self):\n\t\tservice = self.source.service\n\t\tcue = service and service.cueSheet()\n\t\treturn cue and cue.getCutList()\n\n\t@cached\n\tdef getText(self):\n\t\tseek = self.getSeek()\n\t\tif seek is None:\n\t\t\treturn \"\"\n\n\t\tif self.type == self.TYPE_SUMMARY or self.type == self.TYPE_SUMMARY:\n\t\t\ts = self.position / 90000\n\t\t\te = (self.length / 90000) - s\n\t\t\treturn \"%02d:%02d +%2dm\" % (s/60, s%60, e/60)\n\n\t\tl = self.length\n\t\tp = self.position\n\t\tr = self.length - self.position # Remaining\n\n\t\tif l < 0:\n\t\t\treturn \"\"\n\n\t\tif not self.detailed:\n\t\t\tl /= 90000\n\t\t\tp /= 90000\n\t\t\tr /= 90000\n\n\t\tif self.negate: l = -l\n\t\tif self.negate: p = -p\n\t\tif self.negate: r = -r\n\n\t\tif l >= 0:\n\t\t\tsign_l = \"\"\n\t\telse:\n\t\t\tl = -l\n\t\t\tsign_l = \"-\"\n\n\t\tif p >= 0:\n\t\t\tsign_p = \"\"\n\t\telse:\n\t\t\tp = -p\n\t\t\tsign_p = \"-\"\n\n\t\tif r >= 0:\n\t\t\tsign_r = \"\"\n\t\telse:\n\t\t\tr = -r\n\t\t\tsign_r = \"-\"\n\n\t\tif self.type < 5:\n\t\t\tif config.usage.elapsed_time_positive_osd.value:\n\t\t\t\tsign_p = \"+\"\n\t\t\t\tsign_r = \"-\"\n\t\t\t\tsign_l = \"\"\n\t\t\telse:\n\t\t\t\tsign_p = \"-\"\n\t\t\t\tsign_r = \"+\"\n\t\t\t\tsign_l = \"\"\n\n\t\t\tif config.usage.swap_media_time_display_on_osd.value == \"1\": # Mins\n\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\treturn ngettext(\"%d Min\", \"%d Mins\", (l/60)) % (l/60)\n\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (p/60)) % (p/60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d \" % (p/60) + sign_r + ngettext(\"%d Min\", \"%d Mins\", (r/60)) % (r/60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d \" % (r/60) + sign_p + ngettext(\"%d Min\", \"%d Mins\", (p/60)) % (p/60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (r/60)) % (r/60)\n\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (p/60)) % (p/60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\" or config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (r/60)) % (r/60)\n\t\t\telif config.usage.swap_media_time_display_on_osd.value == \"2\": # Mins Secs\n\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\treturn sign_l + \"%d:%02d\" % (l/60, l%60)\n\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (p/60, p%60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d:%02d \" % (p/60, p%60) + sign_r + \"%d:%02d\" % (r/60, r%60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d:%02d \" % (r/60, r%60) + sign_p + \"%d:%02d\" % (p/60, p%60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (r/60, r%60)\n\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (p/60, p%60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\" or config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (r/60, r%60)\n\t\t\telif config.usage.swap_media_time_display_on_osd.value == \"3\": # Hours Mins\n\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d\" % (l/3600, l%3600/60)\n\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (p/3600, p%3600/60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d:%02d \" % (p/3600, p%3600/60) + sign_r + \"%d:%02d\" % (r/3600, r%3600/60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d:%02d \" % (r/3600, r%3600/60) + sign_p + \"%d:%02d\" % (p/3600, p%3600/60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (r/3600, r%3600/60)\n\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (p/3600, p%3600/60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\" or config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (r/3600, r%3600/60)\n\t\t\telif config.usage.swap_media_time_display_on_osd.value == \"4\": # Hours Mins Secs\n\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d:%02d\" % (l/3600, l%3600/60, l%60)\n\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d\" % (p/3600, p%3600/60, p%60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d \" % (p/3600, p%3600/60, p%60) + sign_r + \"%d:%02d:%02d\" % (r/3600, r%3600/60, r%60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d \" % (r/3600, r%3600/60, r%60) + sign_p + \"%d:%02d:%02d\" % (p/3600, p%3600/60, p%60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d\" % (r/3600, r%3600/60, r%60)\n\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d\" % (p/3600, p%3600/60, p%60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\" or config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d\" % (r/3600, r%3600/60, r%60)\n\t\t\telif config.usage.swap_media_time_display_on_osd.value == \"5\": # Percentage\n\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d\" % (l/3600, l%3600/60)\n\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_p + \"%d%%\" % ((float(p + 0.0) / float(l + 0.0)) * 100)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_p + \"%d%% \" % ((float(p + 0.0) / float(l + 0.0)) * 100) + sign_r + \"%d%%\" % ((float(r + 0.0) / float(l + 0.0)) * 100 + 1)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_r + \"%d%% \" % ((float(r + 0.0) / float(l + 0.0)) * 100 +1 ) + sign_p + \"%d%%\" % ((float(p + 0.0) / float(l + 0.0)) * 100)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_r + \"%d%%\" % ((float(p + 0.0) / float(l + 0.0)) * 100)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\ttest = 0\n\t\t\t\t\tif config.usage.swap_time_remaining_on_osd.value == \"1\": # Elapsed\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_p + \"%d%%\" % ((float(p + 0.0) / float(l + 0.0)) * 100)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telif config.usage.swap_time_remaining_on_osd.value == \"2\" or config.usage.swap_time_remaining_on_osd.value == \"3\": # Elapsed & Remaining\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_r + \"%d%%\" % ((float(p + 0.0) / float(l + 0.0)) * 100)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\treturn \"\"\n\n\t\t\telse: # Skin Setting\n\t\t\t\tif not self.detailed:\n\t\t\t\t\tif self.showHours:\n\t\t\t\t\t\tif self.showNoSeconds:\n\t\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\t\treturn sign_l + \"%d:%02d\" % (l/3600, l%3600/60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (p/3600, p%3600/60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (r/3600, r%3600/60)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\t\treturn sign_l + \"%d:%02d:%02d\" % (l/3600, l%3600/60, l%60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d\" % (p/3600, p%3600/60, p%60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d\" % (r/3600, r%3600/60, r%60)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif self.showNoSeconds:\n\t\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\t\treturn ngettext(\"%d Min\", \"%d Mins\", (l/60)) % (l/60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (p/60)) % (p/60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING and self.OnlyMinute:\n\t\t\t\t\t\t\t\treturn ngettext(\"%d\", \"%d\", (r/60)) % (r/60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (r/60)) % (r/60)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\t\treturn sign_l + \"%d:%02d\" % (l/60, l%60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (p/60, p%60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (r/60, r%60)\n\t\t\t\telse:\n\t\t\t\t\tif self.showHours:\n\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\treturn sign_l + \"%d:%02d:%02d:%03d\" % ((l/3600/90000), (l/90000)%3600/60, (l/90000)%60, (l%90000)/90)\n\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d:%03d\" % ((r/3600/90000), (r/90000)%3600/60, (r/90000)%60, (r%90000)/90)\n\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d:%03d\" % ((p/3600/90000), (p/90000)%3600/60, (p/90000)%60, (p%90000)/90)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif self.type == self.TYPE_LENGTH:\n\t\t\t\t\t\t\treturn sign_l + \"%d:%02d:%03d\" % ((l/60/90000), (l/90000)%60, (l%90000)/90)\n\t\t\t\t\t\telif self.type == self.TYPE_POSITION:\n\t\t\t\t\t\t\treturn sign_p + \"%d:%02d:%03d\" % ((p/60/90000), (p/90000)%60, (p%90000)/90)\n\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\treturn sign_r + \"%d:%02d:%03d\" % ((r/60/90000), (r/90000)%60, (r%90000)/90)\n\n\t\telse:\n\t\t\tif config.usage.elapsed_time_positive_vfd.value:\n\t\t\t\tsign_p = \"+\"\n\t\t\t\tsign_r = \"-\"\n\t\t\telse:\n\t\t\t\tsign_p = \"-\"\n\t\t\t\tsign_r = \"+\"\n\t\t\tif config.usage.swap_media_time_display_on_vfd.value == \"1\": # Mins\n\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\treturn ngettext(\"%d Min\", \"%d Mins\", (l/60)) % (l/60)\n\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (p/60)) % (p/60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d \" % (p/60) + sign_r + ngettext(\"%d Min\", \"%d Mins\", (r/60)) % (r/60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d \" % (r/60) + sign_p + ngettext(\"%d Min\", \"%d Mins\", (p/60)) % (p/60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (r/60)) % (r/60)\n\t\t\t\telif self.type == self.TYPE_VFD_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (p/60)) % (p/60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\" or config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (r/60)) % (r/60)\n\t\t\telif config.usage.swap_media_time_display_on_vfd.value == \"2\": # Mins Secs\n\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\treturn sign_l + \"%d:%02d\" % (l/60, l%60)\n\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (p/60, p%60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d:%02d \" % (p/60, p%60) + sign_r + \"%d:%02d\" % (r/60, r%60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d:%02d \" % (r/60, r%60) + sign_p + \"%d:%02d\" % (p/60, p%60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (r/60, r%60)\n\t\t\t\telif self.type == self.TYPE_VFD_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (p/60, p%60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\" or config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (r/60, r%60)\n\t\t\telif config.usage.swap_media_time_display_on_vfd.value == \"3\": # Hours Mins\n\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d\" % (l/3600, l%3600/60)\n\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (p/3600, p%3600/60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d:%02d \" % (p/3600, p%3600/60) + sign_r + \"%d:%02d\" % (r/3600, r%3600/60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d:%02d \" % (r/3600, r%3600/60) + sign_p + \"%d:%02d\" % (p/3600, p%3600/60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (r/3600, r%3600/60)\n\t\t\t\telif self.type == self.TYPE_VFD_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (p/3600, p%3600/60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\" or config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (r/3600, r%3600/60)\n\t\t\telif config.usage.swap_media_time_display_on_vfd.value == \"4\": # Hours Mins Secs\n\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d:%02d\" % (l/3600, l%3600/60, l%60)\n\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d\" % (p/3600, p%3600/60, p%60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d \" % (p/3600, p%3600/60, p%60) + sign_r + \"%d:%02d:%02d\" % (r/3600, r%3600/60, r%60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d \" % (r/3600, r%3600/60, r%60) + sign_p + \"%d:%02d:%02d\" % (p/3600, p%3600/60, p%60)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d\" % (r/3600, r%3600/60, r%60)\n\t\t\t\telif self.type == self.TYPE_VFD_REMAINING:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d\" % (p/3600, p%3600/60, p%60)\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\" or config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d\" % (r/3600, r%3600/60, r%60)\n\t\t\telif config.usage.swap_media_time_display_on_vfd.value == \"5\": # Percentage\n\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\treturn sign_l + \"%d:%02d\" % (l/3600, l%3600/60)\n\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_p + \"%d%%\" % ((float(p + 0.0) / float(l + 0.0)) * 100)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\": # Elapsed & Remaining\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_p + \"%d%% \" % ((float(p + 0.0) / float(l + 0.0)) * 100) + sign_r + \"%d%%\" % ((float(r + 0.0) / float(l + 0.0)) * 100 + 1)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"3\": # Remaining & Elapsed\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_r + \"%d%% \" % ((float(r + 0.0) / float(l + 0.0)) * 100 +1 ) + sign_p + \"%d%%\" % ((float(p + 0.0) / float(l + 0.0)) * 100)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_r + \"%d%%\" % ((float(p + 0.0) / float(l + 0.0)) * 100)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\telif self.type == self.TYPE_VFD_REMAINING:\n\t\t\t\t\ttest = 0\n\t\t\t\t\tif config.usage.swap_time_remaining_on_vfd.value == \"1\": # Elapsed\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_p + \"%d%%\" % ((float(p + 0.0) / float(l + 0.0)) * 100)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telif config.usage.swap_time_remaining_on_vfd.value == \"2\" or config.usage.swap_time_remaining_on_vfd.value == \"3\": # Elapsed & Remaining\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\treturn sign_r + \"%d%%\" % ((float(p + 0.0) / float(l + 0.0)) * 100)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\treturn \"\"\n\n\t\t\telse: # Skin Setting\n\t\t\t\tif not self.detailed:\n\t\t\t\t\tif self.showHours:\n\t\t\t\t\t\tif self.showNoSeconds:\n\t\t\t\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\t\t\treturn sign_l + \"%d:%02d\" % (l/3600, l%3600/60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (p/3600, p%3600/60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (r/3600, r%3600/60)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\t\t\treturn sign_l + \"%d:%02d:%02d\" % (l/3600, l%3600/60, l%60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d\" % (p/3600, p%3600/60, p%60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d\" % (r/3600, r%3600/60, r%60)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif self.showNoSeconds:\n\t\t\t\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\t\t\treturn ngettext(\"%d Min\", \"%d Mins\", (l/60)) % (l/60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\t\t\t\treturn sign_p + ngettext(\"%d Min\", \"%d Mins\", (p/60)) % (p/60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_VFD_REMAINING:\n\t\t\t\t\t\t\t\treturn sign_r + ngettext(\"%d Min\", \"%d Mins\", (r/60)) % (r/60)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\t\t\treturn sign_l + \"%d:%02d\" % (l/60, l%60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\t\t\t\treturn sign_p + \"%d:%02d\" % (p/60, p%60)\n\t\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\t\treturn sign_r + \"%d:%02d\" % (r/60, r%60)\n\t\t\t\telse:\n\t\t\t\t\tif self.showHours:\n\t\t\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\t\treturn sign_l + \"%d:%02d:%02d:%03d\" % ((l/3600/90000), (l/90000)%3600/60, (l/90000)%60, (l%90000)/90)\n\t\t\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\t\t\treturn sign_r + \"%d:%02d:%02d:%03d\" % ((r/3600/90000), (r/90000)%3600/60, (r/90000)%60, (r%90000)/90)\n\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\treturn sign_p + \"%d:%02d:%02d:%03d\" % ((p/3600/90000), (p/90000)%3600/60, (p/90000)%60, (p%90000)/90)\n\t\t\t\t\telse:\n\t\t\t\t\t\tif self.type == self.TYPE_VFD_LENGTH:\n\t\t\t\t\t\t\treturn sign_l + \"%d:%02d:%03d\" % ((l/60/90000), (l/90000)%60, (l%90000)/90)\n\t\t\t\t\t\telif self.type == self.TYPE_VFD_POSITION:\n\t\t\t\t\t\t\treturn sign_p + \"%d:%02d:%03d\" % ((p/60/90000), (p/90000)%60, (p%90000)/90)\n\t\t\t\t\t\telif self.type == self.TYPE_REMAINING:\n\t\t\t\t\t\t\treturn sign_r + \"%d:%02d:%03d\" % ((r/60/90000), (r/90000)%60, (r%90000)/90)\n\n\t# range/value are for the Progress renderer\n\trange = 10000\n\n\t@cached\n\tdef getValue(self):\n\t\tpos = self.position\n\t\tlen = self.length\n\t\tif pos is None or len is None or len <= 0:\n\t\t\treturn None\n\t\treturn pos * 10000 / len\n\n\tposition = property(getPosition)\n\tlength = property(getLength)\n\tcutlist = property(getCutlist)\n\ttext = property(getText)\n\tvalue = property(getValue)\n\n\tdef changed(self, what):\n\t\tcutlist_refresh = what[0] != self.CHANGED_SPECIFIC or what[1] in (iPlayableService.evCuesheetChanged,)\n\t\ttime_refresh = what[0] == self.CHANGED_POLL or what[0] == self.CHANGED_SPECIFIC and what[1] in (iPlayableService.evCuesheetChanged,)\n\n\t\tif cutlist_refresh:\n\t\t\tif self.type == self.TYPE_GAUGE:\n\t\t\t\tself.downstream_elements.cutlist_changed()\n\n\t\tif time_refresh:\n\t\t\tself.downstream_elements.changed(what)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements fastqc.py from MikkelSchubert/paleomix (path: paleomix/nodes/fastqc.py)."}, {"role": "assistant", "content": "# paleomix/nodes/fastqc.py (from MikkelSchubert/paleomix, license: mit)\n\n#!/usr/bin/env python3\n\"\"\"\nFastQC - A quality control analysis tool for high throughput sequencing data\n\nhttps://github.com/s-andrews/FastQC\n\"\"\"\nimport os\nimport re\n\nfrom paleomix.common.command import AtomicCmd, InputFile, OutputFile\nfrom paleomix.common.versions import Requirement\nfrom paleomix.node import CommandNode\n\n# File extensions striped by FASTQ for output filenames\n_FASTQC_EXCLUDED_EXTENSIONS = re.compile(\n r\"(\\.gz|\\.bz2|\\.txt|\\.fastq|\\.fq|\\.csfastq|\\.sam|\\.bam)+$\"\n)\n\nclass FastQCNode(CommandNode):\n def __init__(self, in_file, out_folder, options={}, dependencies=()):\n out_prefix = _FASTQC_EXCLUDED_EXTENSIONS.sub(\"\", os.path.basename(in_file))\n\n command = AtomicCmd(\n [\"fastqc\", InputFile(in_file)],\n extra_files=[\n OutputFile(os.path.join(out_folder, out_prefix + \"_fastqc.html\")),\n OutputFile(os.path.join(out_folder, out_prefix + \"_fastqc.zip\")),\n ],\n requirements=[\n Requirement(\n name=\"FastQC\",\n call=[\"fastqc\", \"--version\"],\n search=r\"FastQC v(\\d+).(\\d+).(\\d+)\",\n ),\n ],\n )\n\n command.merge_options(\n user_options=options,\n fixed_options={\n \"--outdir\": \"%(TEMP_DIR)s\",\n \"--dir\": \"%(TEMP_DIR)s\",\n },\n )\n\n CommandNode.__init__(\n self,\n command=command,\n description=\"fastQC of {}\".format(in_file),\n dependencies=dependencies,\n )"}]} {"messages": [{"role": "user", "content": "Write Python code that implements parser.py from duramato/CouchPotatoServer (path: libs/dateutil/parser.py)."}, {"role": "assistant", "content": "# libs/dateutil/parser.py (from duramato/CouchPotatoServer, license: gpl-3.0)\n\n# -*- coding:iso-8859-1 -*-\n\"\"\"\nCopyright (c) 2003-2007 Gustavo Niemeyer \n\nThis module offers extensions to the standard Python\ndatetime module.\n\"\"\"\nfrom __future__ import unicode_literals\n__license__ = \"Simplified BSD\"\n\nimport datetime\nimport string\nimport time\nimport collections\n\ntry:\n from io import StringIO\nexcept ImportError:\n from io import StringIO\n\nfrom six import text_type, binary_type, integer_types\n\nfrom . import relativedelta\nfrom . import tz\n\n__all__ = [\"parse\", \"parserinfo\"]\n\n# Some pointers:\n#\n# http://www.cl.cam.ac.uk/~mgk25/iso-time.html\n# http://www.iso.ch/iso/en/prods-services/popstds/datesandtime.html\n# http://www.w3.org/TR/NOTE-datetime\n# http://ringmaster.arc.nasa.gov/tools/time_formats.html\n# http://search.cpan.org/author/MUIR/Time-modules-2003.0211/lib/Time/ParseDate.pm\n# http://stein.cshl.org/jade/distrib/docs/java.text.SimpleDateFormat.html\n\nclass _timelex(object):\n\n def __init__(self, instream):\n if isinstance(instream, text_type):\n instream = StringIO(instream)\n self.instream = instream\n self.wordchars = ('abcdfeghijklmnopqrstuvwxyz'\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_'\n 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'\n 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ')\n self.numchars = '0123456789'\n self.whitespace = ' \\t\\r\\n'\n self.charstack = []\n self.tokenstack = []\n self.eof = False\n\n def get_token(self):\n if self.tokenstack:\n return self.tokenstack.pop(0)\n seenletters = False\n token = None\n state = None\n wordchars = self.wordchars\n numchars = self.numchars\n whitespace = self.whitespace\n while not self.eof:\n if self.charstack:\n nextchar = self.charstack.pop(0)\n else:\n nextchar = self.instream.read(1)\n while nextchar == '\\x00':\n nextchar = self.instream.read(1)\n if not nextchar:\n self.eof = True\n break\n elif not state:\n token = nextchar\n if nextchar in wordchars:\n state = 'a'\n elif nextchar in numchars:\n state = '0'\n elif nextchar in whitespace:\n token = ' '\n break # emit token\n else:\n break # emit token\n elif state == 'a':\n seenletters = True\n if nextchar in wordchars:\n token += nextchar\n elif nextchar == '.':\n token += nextchar\n state = 'a.'\n else:\n self.charstack.append(nextchar)\n break # emit token\n elif state == '0':\n if nextchar in numchars:\n token += nextchar\n elif nextchar == '.':\n token += nextchar\n state = '0.'\n else:\n self.charstack.append(nextchar)\n break # emit token\n elif state == 'a.':\n seenletters = True\n if nextchar == '.' or nextchar in wordchars:\n token += nextchar\n elif nextchar in numchars and token[-1] == '.':\n token += nextchar\n state = '0.'\n else:\n self.charstack.append(nextchar)\n break # emit token\n elif state == '0.':\n if nextchar == '.' or nextchar in numchars:\n token += nextchar\n elif nextchar in wordchars and token[-1] == '.':\n token += nextchar\n state = 'a.'\n else:\n self.charstack.append(nextchar)\n break # emit token\n if (state in ('a.', '0.') and\n (seenletters or token.count('.') > 1 or token[-1] == '.')):\n l = token.split('.')\n token = l[0]\n for tok in l[1:]:\n self.tokenstack.append('.')\n if tok:\n self.tokenstack.append(tok)\n return token\n\n def __iter__(self):\n return self\n\n def __next__(self):\n token = self.get_token()\n if token is None:\n raise StopIteration\n return token\n\n def next(self):\n return self.__next__() # Python 2.x support\n\n def split(cls, s):\n return list(cls(s))\n split = classmethod(split)\n\nclass _resultbase(object):\n\n def __init__(self):\n for attr in self.__slots__:\n setattr(self, attr, None)\n\n def _repr(self, classname):\n l = []\n for attr in self.__slots__:\n value = getattr(self, attr)\n if value is not None:\n l.append(\"%s=%s\" % (attr, repr(value)))\n return \"%s(%s)\" % (classname, \", \".join(l))\n\n def __repr__(self):\n return self._repr(self.__class__.__name__)\n\nclass parserinfo(object):\n\n # m from a.m/p.m, t from ISO T separator\n JUMP = [\" \", \".\", \",\", \";\", \"-\", \"/\", \"'\",\n \"at\", \"on\", \"and\", \"ad\", \"m\", \"t\", \"of\",\n \"st\", \"nd\", \"rd\", \"th\"]\n\n WEEKDAYS = [(\"Mon\", \"Monday\"),\n (\"Tue\", \"Tuesday\"),\n (\"Wed\", \"Wednesday\"),\n (\"Thu\", \"Thursday\"),\n (\"Fri\", \"Friday\"),\n (\"Sat\", \"Saturday\"),\n (\"Sun\", \"Sunday\")]\n MONTHS = [(\"Jan\", \"January\"),\n (\"Feb\", \"February\"),\n (\"Mar\", \"March\"),\n (\"Apr\", \"April\"),\n (\"May\", \"May\"),\n (\"Jun\", \"June\"),\n (\"Jul\", \"July\"),\n (\"Aug\", \"August\"),\n (\"Sep\", \"Sept\", \"September\"),\n (\"Oct\", \"October\"),\n (\"Nov\", \"November\"),\n (\"Dec\", \"December\")]\n HMS = [(\"h\", \"hour\", \"hours\"),\n (\"m\", \"minute\", \"minutes\"),\n (\"s\", \"second\", \"seconds\")]\n AMPM = [(\"am\", \"a\"),\n (\"pm\", \"p\")]\n UTCZONE = [\"UTC\", \"GMT\", \"Z\"]\n PERTAIN = [\"of\"]\n TZOFFSET = {}\n\n def __init__(self, dayfirst = False, yearfirst = False):\n self._jump = self._convert(self.JUMP)\n self._weekdays = self._convert(self.WEEKDAYS)\n self._months = self._convert(self.MONTHS)\n self._hms = self._convert(self.HMS)\n self._ampm = self._convert(self.AMPM)\n self._utczone = self._convert(self.UTCZONE)\n self._pertain = self._convert(self.PERTAIN)\n\n self.dayfirst = dayfirst\n self.yearfirst = yearfirst\n\n self._year = time.localtime().tm_year\n self._century = self._year // 100 * 100\n\n def _convert(self, lst):\n dct = {}\n for i in range(len(lst)):\n v = lst[i]\n if isinstance(v, tuple):\n for v in v:\n dct[v.lower()] = i\n else:\n dct[v.lower()] = i\n return dct\n\n def jump(self, name):\n return name.lower() in self._jump\n\n def weekday(self, name):\n if len(name) >= 3:\n try:\n return self._weekdays[name.lower()]\n except KeyError:\n pass\n return None\n\n def month(self, name):\n if len(name) >= 3:\n try:\n return self._months[name.lower()] + 1\n except KeyError:\n pass\n return None\n\n def hms(self, name):\n try:\n return self._hms[name.lower()]\n except KeyError:\n return None\n\n def ampm(self, name):\n try:\n return self._ampm[name.lower()]\n except KeyError:\n return None\n\n def pertain(self, name):\n return name.lower() in self._pertain\n\n def utczone(self, name):\n return name.lower() in self._utczone\n\n def tzoffset(self, name):\n if name in self._utczone:\n return 0\n return self.TZOFFSET.get(name)\n\n def convertyear(self, year):\n if year < 100:\n year += self._century\n if abs(year - self._year) >= 50:\n if year < self._year:\n year += 100\n else:\n year -= 100\n return year\n\n def validate(self, res):\n # move to info\n if res.year is not None:\n res.year = self.convertyear(res.year)\n if res.tzoffset == 0 and not res.tzname or res.tzname == 'Z':\n res.tzname = \"UTC\"\n res.tzoffset = 0\n elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname):\n res.tzoffset = 0\n return True\n\nclass parser(object):\n\n def __init__(self, info = None):\n self.info = info or parserinfo()\n\n def parse(self, timestr, default = None,\n ignoretz = False, tzinfos = None,\n **kwargs):\n if not default:\n default = datetime.datetime.now().replace(hour = 0, minute = 0,\n second = 0, microsecond = 0)\n res = self._parse(timestr, **kwargs)\n if res is None:\n raise ValueError(\"unknown string format\")\n repl = {}\n for attr in [\"year\", \"month\", \"day\", \"hour\",\n \"minute\", \"second\", \"microsecond\"]:\n value = getattr(res, attr)\n if value is not None:\n repl[attr] = value\n ret = default.replace(**repl)\n if res.weekday is not None and not res.day:\n ret = ret + relativedelta.relativedelta(weekday = res.weekday)\n if not ignoretz:\n if isinstance(tzinfos, collections.Callable) or tzinfos and res.tzname in tzinfos:\n if isinstance(tzinfos, collections.Callable):\n tzdata = tzinfos(res.tzname, res.tzoffset)\n else:\n tzdata = tzinfos.get(res.tzname)\n if isinstance(tzdata, datetime.tzinfo):\n tzinfo = tzdata\n elif isinstance(tzdata, text_type):\n tzinfo = tz.tzstr(tzdata)\n elif isinstance(tzdata, integer_types):\n tzinfo = tz.tzoffset(res.tzname, tzdata)\n else:\n raise ValueError(\"offset must be tzinfo subclass, \" \\\n \"tz string, or int offset\")\n ret = ret.replace(tzinfo = tzinfo)\n elif res.tzname and res.tzname in time.tzname:\n ret = ret.replace(tzinfo = tz.tzlocal())\n elif res.tzoffset == 0:\n ret = ret.replace(tzinfo = tz.tzutc())\n elif res.tzoffset:\n ret = ret.replace(tzinfo = tz.tzoffset(res.tzname, res.tzoffset))\n return ret\n\n class _result(_resultbase):\n __slots__ = [\"year\", \"month\", \"day\", \"weekday\",\n \"hour\", \"minute\", \"second\", \"microsecond\",\n \"tzname\", \"tzoffset\"]\n\n def _parse(self, timestr, dayfirst = None, yearfirst = None, fuzzy = False):\n info = self.info\n if dayfirst is None:\n dayfirst = info.dayfirst\n if yearfirst is None:\n yearfirst = info.yearfirst\n res = self._result()\n l = _timelex.split(timestr)\n try:\n\n # year/month/day list\n ymd = []\n\n # Index of the month string in ymd\n mstridx = -1\n\n len_l = len(l)\n i = 0\n while i < len_l:\n\n # Check if it's a number\n try:\n value_repr = l[i]\n value = float(value_repr)\n except ValueError:\n value = None\n\n if value is not None:\n # Token is a number\n len_li = len(l[i])\n i += 1\n if (len(ymd) == 3 and len_li in (2, 4)\n and (i >= len_l or (l[i] != ':' and\n info.hms(l[i]) is None))):\n # 19990101T23[59]\n s = l[i - 1]\n res.hour = int(s[:2])\n if len_li == 4:\n res.minute = int(s[2:])\n elif len_li == 6 or (len_li > 6 and l[i - 1].find('.') == 6):\n # YYMMDD or HHMMSS[.ss]\n s = l[i - 1]\n if not ymd and l[i - 1].find('.') == -1:\n ymd.append(info.convertyear(int(s[:2])))\n ymd.append(int(s[2:4]))\n ymd.append(int(s[4:]))\n else:\n # 19990101T235959[.59]\n res.hour = int(s[:2])\n res.minute = int(s[2:4])\n res.second, res.microsecond = _parsems(s[4:])\n elif len_li == 8:\n # YYYYMMDD\n s = l[i - 1]\n ymd.append(int(s[:4]))\n ymd.append(int(s[4:6]))\n ymd.append(int(s[6:]))\n elif len_li in (12, 14):\n # YYYYMMDDhhmm[ss]\n s = l[i - 1]\n ymd.append(int(s[:4]))\n ymd.append(int(s[4:6]))\n ymd.append(int(s[6:8]))\n res.hour = int(s[8:10])\n res.minute = int(s[10:12])\n if len_li == 14:\n res.second = int(s[12:])\n elif ((i < len_l and info.hms(l[i]) is not None) or\n (i + 1 < len_l and l[i] == ' ' and\n info.hms(l[i + 1]) is not None)):\n # HH[ ]h or MM[ ]m or SS[.ss][ ]s\n if l[i] == ' ':\n i += 1\n idx = info.hms(l[i])\n while True:\n if idx == 0:\n res.hour = int(value)\n if value % 1:\n res.minute = int(60 * (value % 1))\n elif idx == 1:\n res.minute = int(value)\n if value % 1:\n res.second = int(60 * (value % 1))\n elif idx == 2:\n res.second, res.microsecond = \\\n _parsems(value_repr)\n i += 1\n if i >= len_l or idx == 2:\n break\n # 12h00\n try:\n value_repr = l[i]\n value = float(value_repr)\n except ValueError:\n break\n else:\n i += 1\n idx += 1\n if i < len_l:\n newidx = info.hms(l[i])\n if newidx is not None:\n idx = newidx\n elif i == len_l and l[i - 2] == ' ' and info.hms(l[i - 3]) is not None:\n # X h MM or X m SS\n idx = info.hms(l[i - 3]) + 1\n if idx == 1:\n res.minute = int(value)\n if value % 1:\n res.second = int(60 * (value % 1))\n elif idx == 2:\n res.second, res.microsecond = \\\n _parsems(value_repr)\n i += 1\n elif i + 1 < len_l and l[i] == ':':\n # HH:MM[:SS[.ss]]\n res.hour = int(value)\n i += 1\n value = float(l[i])\n res.minute = int(value)\n if value % 1:\n res.second = int(60 * (value % 1))\n i += 1\n if i < len_l and l[i] == ':':\n res.second, res.microsecond = _parsems(l[i + 1])\n i += 2\n elif i < len_l and l[i] in ('-', '/', '.'):\n sep = l[i]\n ymd.append(int(value))\n i += 1\n if i < len_l and not info.jump(l[i]):\n try:\n # 01-01[-01]\n ymd.append(int(l[i]))\n except ValueError:\n # 01-Jan[-01]\n value = info.month(l[i])\n if value is not None:\n ymd.append(value)\n assert mstridx == -1\n mstridx = len(ymd) - 1\n else:\n return None\n i += 1\n if i < len_l and l[i] == sep:\n # We have three members\n i += 1\n value = info.month(l[i])\n if value is not None:\n ymd.append(value)\n mstridx = len(ymd) - 1\n assert mstridx == -1\n else:\n ymd.append(int(l[i]))\n i += 1\n elif i >= len_l or info.jump(l[i]):\n if i + 1 < len_l and info.ampm(l[i + 1]) is not None:\n # 12 am\n res.hour = int(value)\n if res.hour < 12 and info.ampm(l[i + 1]) == 1:\n res.hour += 12\n elif res.hour == 12 and info.ampm(l[i + 1]) == 0:\n res.hour = 0\n i += 1\n else:\n # Year, month or day\n ymd.append(int(value))\n i += 1\n elif info.ampm(l[i]) is not None:\n # 12am\n res.hour = int(value)\n if res.hour < 12 and info.ampm(l[i]) == 1:\n res.hour += 12\n elif res.hour == 12 and info.ampm(l[i]) == 0:\n res.hour = 0\n i += 1\n elif not fuzzy:\n return None\n else:\n i += 1\n continue\n\n # Check weekday\n value = info.weekday(l[i])\n if value is not None:\n res.weekday = value\n i += 1\n continue\n\n # Check month name\n value = info.month(l[i])\n if value is not None:\n ymd.append(value)\n assert mstridx == -1\n mstridx = len(ymd) - 1\n i += 1\n if i < len_l:\n if l[i] in ('-', '/'):\n # Jan-01[-99]\n sep = l[i]\n i += 1\n ymd.append(int(l[i]))\n i += 1\n if i < len_l and l[i] == sep:\n # Jan-01-99\n i += 1\n ymd.append(int(l[i]))\n i += 1\n elif (i + 3 < len_l and l[i] == l[i + 2] == ' '\n and info.pertain(l[i + 1])):\n # Jan of 01\n # In this case, 01 is clearly year\n try:\n value = int(l[i + 3])\n except ValueError:\n # Wrong guess\n pass\n else:\n # Convert it here to become unambiguous\n ymd.append(info.convertyear(value))\n i += 4\n continue\n\n # Check am/pm\n value = info.ampm(l[i])\n if value is not None:\n if value == 1 and res.hour < 12:\n res.hour += 12\n elif value == 0 and res.hour == 12:\n res.hour = 0\n i += 1\n continue\n\n # Check for a timezone name\n if (res.hour is not None and len(l[i]) <= 5 and\n res.tzname is None and res.tzoffset is None and\n not [x for x in l[i] if x not in string.ascii_uppercase]):\n res.tzname = l[i]\n res.tzoffset = info.tzoffset(res.tzname)\n i += 1\n\n # Check for something like GMT+3, or BRST+3. Notice\n # that it doesn't mean \"I am 3 hours after GMT\", but\n # \"my time +3 is GMT\". If found, we reverse the\n # logic so that timezone parsing code will get it\n # right.\n if i < len_l and l[i] in ('+', '-'):\n l[i] = ('+', '-')[l[i] == '+']\n res.tzoffset = None\n if info.utczone(res.tzname):\n # With something like GMT+3, the timezone\n # is *not* GMT.\n res.tzname = None\n\n continue\n\n # Check for a numbered timezone\n if res.hour is not None and l[i] in ('+', '-'):\n signal = (-1, 1)[l[i] == '+']\n i += 1\n len_li = len(l[i])\n if len_li == 4:\n # -0300\n res.tzoffset = int(l[i][:2]) * 3600 + int(l[i][2:]) * 60\n elif i + 1 < len_l and l[i + 1] == ':':\n # -03:00\n res.tzoffset = int(l[i]) * 3600 + int(l[i + 2]) * 60\n i += 2\n elif len_li <= 2:\n # -[0]3\n res.tzoffset = int(l[i][:2]) * 3600\n else:\n return None\n i += 1\n res.tzoffset *= signal\n\n # Look for a timezone name between parenthesis\n if (i + 3 < len_l and\n info.jump(l[i]) and l[i + 1] == '(' and l[i + 3] == ')' and\n 3 <= len(l[i + 2]) <= 5 and\n not [x for x in l[i + 2]\n if x not in string.ascii_uppercase]):\n # -0300 (BRST)\n res.tzname = l[i + 2]\n i += 4\n continue\n\n # Check jumps\n if not (info.jump(l[i]) or fuzzy):\n return None\n\n i += 1\n\n # Process year/month/day\n len_ymd = len(ymd)\n if len_ymd > 3:\n # More than three members!?\n return None\n elif len_ymd == 1 or (mstridx != -1 and len_ymd == 2):\n # One member, or two members with a month string\n if mstridx != -1:\n res.month = ymd[mstridx]\n del ymd[mstridx]\n if len_ymd > 1 or mstridx == -1:\n if ymd[0] > 31:\n res.year = ymd[0]\n else:\n res.day = ymd[0]\n elif len_ymd == 2:\n # Two members with numbers\n if ymd[0] > 31:\n # 99-01\n res.year, res.month = ymd\n elif ymd[1] > 31:\n # 01-99\n res.month, res.year = ymd\n elif dayfirst and ymd[1] <= 12:\n # 13-01\n res.day, res.month = ymd\n else:\n # 01-13\n res.month, res.day = ymd\n if len_ymd == 3:\n # Three members\n if mstridx == 0:\n res.month, res.day, res.year = ymd\n elif mstridx == 1:\n if ymd[0] > 31 or (yearfirst and ymd[2] <= 31):\n # 99-Jan-01\n res.year, res.month, res.day = ymd\n else:\n # 01-Jan-01\n # Give precendence to day-first, since\n # two-digit years is usually hand-written.\n res.day, res.month, res.year = ymd\n elif mstridx == 2:\n # WTF!?\n if ymd[1] > 31:\n # 01-99-Jan\n res.day, res.year, res.month = ymd\n else:\n # 99-01-Jan\n res.year, res.day, res.month = ymd\n else:\n if ymd[0] > 31 or \\\n (yearfirst and ymd[1] <= 12 and ymd[2] <= 31):\n # 99-01-01\n res.year, res.month, res.day = ymd\n elif ymd[0] > 12 or (dayfirst and ymd[1] <= 12):\n # 13-01-01\n res.day, res.month, res.year = ymd\n else:\n # 01-13-01\n res.month, res.day, res.year = ymd\n\n except (IndexError, ValueError, AssertionError):\n return None\n\n if not info.validate(res):\n return None\n return res\n\nDEFAULTPARSER = parser()\ndef parse(timestr, parserinfo = None, **kwargs):\n # Python 2.x support: datetimes return their string presentation as\n # bytes in 2.x and unicode in 3.x, so it's reasonable to expect that\n # the parser will get both kinds. Internally we use unicode only.\n if isinstance(timestr, binary_type):\n timestr = timestr.decode()\n if parserinfo:\n return parser(parserinfo).parse(timestr, **kwargs)\n else:\n return DEFAULTPARSER.parse(timestr, **kwargs)\n\nclass _tzparser(object):\n\n class _result(_resultbase):\n\n __slots__ = [\"stdabbr\", \"stdoffset\", \"dstabbr\", \"dstoffset\",\n \"start\", \"end\"]\n\n class _attr(_resultbase):\n __slots__ = [\"month\", \"week\", \"weekday\",\n \"yday\", \"jyday\", \"day\", \"time\"]\n\n def __repr__(self):\n return self._repr(\"\")\n\n def __init__(self):\n _resultbase.__init__(self)\n self.start = self._attr()\n self.end = self._attr()\n\n def parse(self, tzstr):\n res = self._result()\n l = _timelex.split(tzstr)\n try:\n\n len_l = len(l)\n\n i = 0\n while i < len_l:\n # BRST+3[BRDT[+2]]\n j = i\n while j < len_l and not [x for x in l[j]\n if x in \"0123456789:,-+\"]:\n j += 1\n if j != i:\n if not res.stdabbr:\n offattr = \"stdoffset\"\n res.stdabbr = \"\".join(l[i:j])\n else:\n offattr = \"dstoffset\"\n res.dstabbr = \"\".join(l[i:j])\n i = j\n if (i < len_l and\n (l[i] in ('+', '-') or l[i][0] in \"0123456789\")):\n if l[i] in ('+', '-'):\n # Yes, that's right. See the TZ variable\n # documentation.\n signal = (1, -1)[l[i] == '+']\n i += 1\n else:\n signal = -1\n len_li = len(l[i])\n if len_li == 4:\n # -0300\n setattr(res, offattr,\n (int(l[i][:2]) * 3600 + int(l[i][2:]) * 60) * signal)\n elif i + 1 < len_l and l[i + 1] == ':':\n # -03:00\n setattr(res, offattr,\n (int(l[i]) * 3600 + int(l[i + 2]) * 60) * signal)\n i += 2\n elif len_li <= 2:\n # -[0]3\n setattr(res, offattr,\n int(l[i][:2]) * 3600 * signal)\n else:\n return None\n i += 1\n if res.dstabbr:\n break\n else:\n break\n\n if i < len_l:\n for j in range(i, len_l):\n if l[j] == ';': l[j] = ','\n\n assert l[i] == ','\n\n i += 1\n\n if i >= len_l:\n pass\n elif (8 <= l.count(',') <= 9 and\n not [y for x in l[i:] if x != ','\n for y in x if y not in \"0123456789\"]):\n # GMT0BST,3,0,30,3600,10,0,26,7200[,3600]\n for x in (res.start, res.end):\n x.month = int(l[i])\n i += 2\n if l[i] == '-':\n value = int(l[i + 1]) * -1\n i += 1\n else:\n value = int(l[i])\n i += 2\n if value:\n x.week = value\n x.weekday = (int(l[i]) - 1) % 7\n else:\n x.day = int(l[i])\n i += 2\n x.time = int(l[i])\n i += 2\n if i < len_l:\n if l[i] in ('-', '+'):\n signal = (-1, 1)[l[i] == \"+\"]\n i += 1\n else:\n signal = 1\n res.dstoffset = (res.stdoffset + int(l[i])) * signal\n elif (l.count(',') == 2 and l[i:].count('/') <= 2 and\n not [y for x in l[i:] if x not in (',', '/', 'J', 'M',\n '.', '-', ':')\n for y in x if y not in \"0123456789\"]):\n for x in (res.start, res.end):\n if l[i] == 'J':\n # non-leap year day (1 based)\n i += 1\n x.jyday = int(l[i])\n elif l[i] == 'M':\n # month[-.]week[-.]weekday\n i += 1\n x.month = int(l[i])\n i += 1\n assert l[i] in ('-', '.')\n i += 1\n x.week = int(l[i])\n if x.week == 5:\n x.week = -1\n i += 1\n assert l[i] in ('-', '.')\n i += 1\n x.weekday = (int(l[i]) - 1) % 7\n else:\n # year day (zero based)\n x.yday = int(l[i]) + 1\n\n i += 1\n\n if i < len_l and l[i] == '/':\n i += 1\n # start time\n len_li = len(l[i])\n if len_li == 4:\n # -0300\n x.time = (int(l[i][:2]) * 3600 + int(l[i][2:]) * 60)\n elif i + 1 < len_l and l[i + 1] == ':':\n # -03:00\n x.time = int(l[i]) * 3600 + int(l[i + 2]) * 60\n i += 2\n if i + 1 < len_l and l[i + 1] == ':':\n i += 2\n x.time += int(l[i])\n elif len_li <= 2:\n # -[0]3\n x.time = (int(l[i][:2]) * 3600)\n else:\n return None\n i += 1\n\n assert i == len_l or l[i] == ','\n\n i += 1\n\n assert i >= len_l\n\n except (IndexError, ValueError, AssertionError):\n return None\n\n return res\n\nDEFAULTTZPARSER = _tzparser()\ndef _parsetz(tzstr):\n return DEFAULTTZPARSER.parse(tzstr)\n\ndef _parsems(value):\n \"\"\"Parse a I[.F] seconds value into (seconds, microseconds).\"\"\"\n if \".\" not in value:\n return int(value), 0\n else:\n i, f = value.split(\".\")\n return int(i), int(f.ljust(6, \"0\")[:6])\n\n# vim:ts=4:sw=4:et"}]} {"messages": [{"role": "user", "content": "Write Python code that implements cc_write_flash.py from wavesoft/CCLib (path: Python/cc_write_flash.py)."}, {"role": "assistant", "content": "# Python/cc_write_flash.py (from wavesoft/CCLib, license: gpl-3.0)\n\n#!/usr/bin/python\n#\n# CCLib_proxy Utilities\n# Copyright (c) 2014 Ioannis Charalampidis\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\nfrom __future__ import print_function\nfrom cclib import CCHEXFile, getOptions, openCCDebugger\nimport sys\n\n# Get serial port either form environment or from arguments\nopts = getOptions(\"Generic CCDebugger Flash Writer Tool\", hexIn=True,\n\terase=\"Full chip erase before write\", offset=\":Offset the addresses in the .hex file by this value\")\n\n# Open debugger\ntry:\n\tdbg = openCCDebugger(opts['port'], enterDebug=opts['enter'])\nexcept Exception as e:\n\tprint(\"ERROR: %s\" % str(e))\n\tsys.exit(1)\n\n# Get offset\noffset = 0\nif opts['offset']:\n\tif opts['offset'][0:2] == \"0x\":\n\t\toffset = int(opts['offset'], 16)\n\telse:\n\t\toffset = int(opts['offset'])\n\tprint(\"NOTE: The memory addresses are offset by %i bytes!\" % offset)\n\n# Get bluegiga-specific info\nserial = dbg.getSerial()\n\n# Parse the HEX file\nhexFile = CCHEXFile( opts['in'] )\nhexFile.load()\n\n# Display sections & calculate max memory usage\nmaxMem = 0\nprint(\"Sections in %s:\\n\" % opts['in'])\nprint(\" Addr. Size\")\nprint(\"-------- -------------\")\nfor mb in hexFile.memBlocks:\n\n\t# Calculate top position\n\tmemTop = mb.addr + mb.size\n\tif memTop > maxMem:\n\t\tmaxMem = memTop\n\n\t# Print portion\n\tprint(\" 0x%04x %i B \" % (mb.addr + offset, mb.size))\nprint(\"\")\n\n# Check for oversize data\nif maxMem > (dbg.chipInfo['flash'] * 1024):\n\tprint(\"ERROR: Data too bit to fit in chip's memory!\")\n\tsys.exit(4)\n\n# Confirm\nerasePrompt = \"OVERWRITE\"\nif opts['erase']:\n\terasePrompt = \"ERASE and REPROGRAM\"\nprint(\"This is going to %s the chip. Are you sure? : \" % erasePrompt, end=' ')\nans = sys.stdin.readline()[0:-1]\nif (ans != \"y\") and (ans != \"Y\"):\n\tprint(\"Aborted\")\n\tsys.exit(2)\n\n# Flashing messages\nprint(\"\\nFlashing:\")\n\n# Send chip erase\nif opts['erase']:\n\tprint(\" - Chip erase...\")\n\ttry:\n\t\tdbg.chipErase()\n\texcept Exception as e:\n\t \tprint(\"ERROR: %s\" % str(e))\n\t \tsys.exit(3)\n\n# Flash memory\ndbg.pauseDMA(False)\nprint(\" - Flashing %i memory blocks...\" % len(hexFile.memBlocks))\nfor mb in hexFile.memBlocks:\n\n\t# Flash memory block\n\tprint(\" -> 0x%04x : %i bytes \" % (mb.addr + offset, mb.size))\n\ttry:\n\t\tdbg.writeCODE( mb.addr + offset, mb.bytes, verify=True, showProgress=True )\n\texcept Exception as e:\n\t\tprint(\"ERROR: %s\" % str(e))\n\t\tsys.exit(3)\n\n# Done\nprint(\"\\nCompleted\")\nprint(\"\")"}]} {"messages": [{"role": "user", "content": "Write Python code that implements float.py from dav94/plastex (path: plasTeX/Packages/float.py)."}, {"role": "assistant", "content": "# plasTeX/Packages/float.py (from dav94/plastex, license: mit)\n\n#!/usr/bin/env python\n\nimport new\nfrom plasTeX import Command, Environment\nfrom plasTeX.Base.LaTeX.Floats import Float, Caption\n\nclass newfloat(Command):\n args = 'name:str pos:str capfile:str [ reset:str ]'\n def invoke(self, tex):\n Command.invoke(self, tex)\n name = str(self.attributes['name'])\n\n # Create the float class and the caption class\n floatcls = new.classobj(name, (Float,), {})\n captioncls = new.classobj('caption', (Caption,), \n {'macroName':'caption', 'counter':name})\n floatcls.caption = captioncls\n c = self.ownerDocument.context\n c.addGlobal(name, floatcls)\n\n # Create a counter\n resetby = self.attributes['reset'] or 'chapter'\n c.newcounter(name, resetby, 0, format='${the%s}.${%s}' % (resetby,name))\n\n # Create the float name macro\n c.newcommand(name+'name', 0, name)\n\nclass floatstyle(Command):\n args = 'style:str' \n\nclass restylefloat(Command):\n args = 'float:str'\n\nclass floatname(Command):\n args = 'float:str name:str'\n def invoke(self, tex):\n Command.invoke(self, tex)\n float = str(self.attributes['float'])\n name = self.attributes['name']\n c = self.ownerDocument.context\n c.newcommand(float+'name', 0, name)\n\nclass floatplacement(Command):\n args = 'float:str pos:str'\n\nclass listof(Command):\n args = 'float:str title'"}]} {"messages": [{"role": "user", "content": "Write Python code that implements tests.py from justinslee/Wai-Not-Makahiki (path: makahiki/apps/widgets/notifications/tests.py)."}, {"role": "assistant", "content": "# makahiki/apps/widgets/notifications/tests.py (from justinslee/Wai-Not-Makahiki, license: mit)\n\n\"\"\"Notification testing.\"\"\"\n\nfrom django.test import TransactionTestCase\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.models import User\nfrom apps.managers.challenge_mgr import challenge_mgr\nfrom apps.utils import test_utils\n\nfrom apps.widgets.notifications import get_unread_notifications\nfrom apps.widgets.notifications.models import UserNotification\n\nclass NotificationUnitTests(TransactionTestCase):\n \"\"\"Notification Test.\"\"\"\n def testGetUnread(self):\n \"\"\"Test that we can get the user's unread notifications.\"\"\"\n user = User.objects.create_user(\"test\", \"test@test.com\")\n for i in range(0, 3):\n notification = UserNotification(recipient=user, contents=\"Test notification %i\" % i)\n notification.save()\n\n notifications = get_unread_notifications(user)\n self.assertEqual(notifications[\"alerts\"].count(), 0,\n \"There should not be any alert notifications.\")\n unread = notifications[\"unread\"]\n self.assertEqual(unread.count(), 3, \"There should be three unread notifications.\")\n alert = UserNotification(recipient=user, contents=\"Alert notification\", display_alert=True)\n alert.save()\n\n notifications = get_unread_notifications(user)\n self.assertEqual(notifications[\"alerts\"][0], alert,\n \"Alert notification should have been returned.\")\n unread = notifications[\"unread\"]\n self.assertEqual(unread.count(), 4, \"There should be four unread notifications.\")\n\nclass NotificationFunctionalTests(TransactionTestCase):\n \"\"\"View Test.\"\"\"\n\n def setUp(self):\n self.user = test_utils.setup_user(username=\"user\", password=\"test\")\n self.team = self.user.get_profile().team\n\n challenge_mgr.register_page_widget(\"help\", \"help.faq\")\n challenge_mgr.register_page_widget(\"home\", \"home\")\n\n from apps.managers.cache_mgr import cache_mgr\n cache_mgr.clear()\n\n self.client.login(username=\"user\", password=\"test\")\n\n def testShowNotifications(self):\n \"\"\"\n Test that we can show notifications to the user.\n \"\"\"\n for i in range(0, 3):\n notification = UserNotification(recipient=self.user,\n contents=\"Test notification %i\" % i)\n notification.save()\n\n response = self.client.get(reverse(\"home_index\"))\n self.assertNotContains(response, \"The following item(s) need your attention\",\n msg_prefix=\"Alert should not be shown\"\n )\n for i in range(0, 3):\n self.assertContains(response, \"Test notification %i\" % i,\n msg_prefix=\"Notification %i is not shown\" % i\n )\n\n def testAlertNotifications(self):\n \"\"\"Test alert.\"\"\"\n alert = UserNotification(recipient=self.user, contents=\"Alert notification\",\n display_alert=True)\n alert.save()\n response = self.client.get(reverse(\"home_index\"))\n self.assertContains(response, \"notification-dialog\", msg_prefix=\"Alert should be shown\")\n\n response = self.client.get(reverse(\"help_index\"))\n self.assertNotContains(response, \"notification-dialog\",\n msg_prefix=\"Dialog should not be displayed\")\n\n def testAjaxReadNotifications(self):\n \"\"\"Test that notifications can be marked as read via AJAX.\"\"\"\n notification = UserNotification(recipient=self.user, contents=\"Test notification\")\n notification.save()\n\n response = self.client.post(reverse(\"notifications_read\", args=(notification.pk,)), {},\n HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.failUnlessEqual(response.status_code, 200)\n\n response = self.client.get(reverse(\"home_index\"))\n self.assertNotContains(response, \"Test notification\",\n msg_prefix=\"Notification should be read\")\n\n def testReadNotifications(self):\n \"\"\"Test that notifications can be marked as read without AJAX.\"\"\"\n notification = UserNotification(recipient=self.user, contents=\"Test notification\")\n notification.save()\n\n response = self.client.post(reverse(\"notifications_read\", args=(notification.pk,)), {})\n self.assertRedirects(response, reverse(\"home_index\"),\n msg_prefix=\"Marking as read should redirect.\")\n\n response = self.client.get(reverse(\"home_index\"))\n self.assertNotContains(response, \"Test notification\",\n msg_prefix=\"Notification should be read\")\n\n # Test with a referring page.\n notification = UserNotification(recipient=self.user, contents=\"Test notification 2\")\n notification.save()\n\n response = self.client.post(reverse(\"notifications_read\", args=(notification.pk,)), {},\n HTTP_REFERER=reverse(\"help_index\"))\n self.assertRedirects(response, reverse(\"help_index\"),\n msg_prefix=\"Marking as read should redirect.\")\n\n response = self.client.get(reverse(\"home_index\"))\n self.assertNotContains(response, \"Test notification 2\",\n msg_prefix=\"Notification should be read\")"}]} {"messages": [{"role": "user", "content": "Write Python code that implements checkrom.py from ntddk/pemu (path: roms/seabios/scripts/checkrom.py)."}, {"role": "assistant", "content": "# roms/seabios/scripts/checkrom.py (from ntddk/pemu, license: gpl-2.0)\n\n#!/usr/bin/env python\n# Script to check a bios image and report info on it.\n#\n# Copyright (C) 2008 Kevin O'Connor \n#\n# This file may be distributed under the terms of the GNU GPLv3 license.\n\nimport sys, struct\nimport layoutrom, buildrom\n\nfrom python23compat import as_bytes\n\ndef subst(data, offset, new):\n return data[:offset] + new + data[offset + len(new):]\n\ndef checksum(data, start, size, csum):\n sumbyte = buildrom.checksum(data[start:start+size])\n return subst(data, start+csum, sumbyte)\n\ndef main():\n # Get args\n objinfo, finalsize, rawfile, outfile = sys.argv[1:]\n\n # Read in symbols\n objinfofile = open(objinfo, 'r')\n symbols = layoutrom.parseObjDump(objinfofile, 'in')[1]\n\n # Read in raw file\n f = open(rawfile, 'rb')\n rawdata = f.read()\n f.close()\n datasize = len(rawdata)\n finalsize = int(finalsize) * 1024\n if finalsize == 0:\n finalsize = 64*1024\n if datasize > 64*1024:\n finalsize = 128*1024\n if datasize > 128*1024:\n finalsize = 256*1024\n if datasize > finalsize:\n print(\"Error! ROM doesn't fit (%d > %d)\" % (datasize, finalsize))\n print(\" You have to either increate the size (CONFIG_ROM_SIZE)\")\n print(\" or turn off some features (such as hardware support not\")\n print(\" needed) to make it fit. Trying a more recent gcc version\")\n print(\" might work too.\")\n sys.exit(1)\n\n # Sanity checks\n start = symbols['code32flat_start'].offset\n end = symbols['code32flat_end'].offset\n expend = layoutrom.BUILD_BIOS_ADDR + layoutrom.BUILD_BIOS_SIZE\n if end != expend:\n print(\"Error! Code does not end at 0x%x (got 0x%x)\" % (\n expend, end))\n sys.exit(1)\n if datasize > finalsize:\n print(\"Error! Code is too big (0x%x vs 0x%x)\" % (\n datasize, finalsize))\n sys.exit(1)\n expdatasize = end - start\n if datasize != expdatasize:\n print(\"Error! Unknown extra data (0x%x vs 0x%x)\" % (\n datasize, expdatasize))\n sys.exit(1)\n\n # Fix up CSM Compatibility16 table\n if 'csm_compat_table' in symbols and 'entry_csm' in symbols:\n # Field offsets within EFI_COMPATIBILITY16_TABLE\n ENTRY_FIELD_OFS = 14 # Compatibility16CallOffset (UINT16)\n SIZE_FIELD_OFS = 5 # TableLength (UINT8)\n CSUM_FIELD_OFS = 4 # TableChecksum (UINT8)\n\n tableofs = symbols['csm_compat_table'].offset - symbols['code32flat_start'].offset\n entry_addr = symbols['entry_csm'].offset - layoutrom.BUILD_BIOS_ADDR\n entry_addr = struct.pack('\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n###############################################################################\n\nfrom __future__ import division, absolute_import, print_function\nfrom collections import defaultdict\nimport datetime\nimport sys\nimport atexit\nimport platform\n\nimport sip\nimport numpy as N\nfrom .. import qtall as qt\n\nfrom .utilfuncs import rrepr\nfrom .version import version\nfrom ..compat import citems, curlrequest, curlencode\n\n\"\"\"Feedback module for providing information about usage.\n\nNote: careful not to send a unique identifier and to reset counts to\nensure lack of traceability.\n\"\"\"\n\n# patch this to disable any feedback\ndisableFeedback=False\n\n# for QSettings\n_org='veusz.org'\n_app='veusz-feedback'\n_url='https://barmag.net/veusz-feedback/'\n\n# min send interval in days\n_mininterval = 7\n# min interval to try sending in days\n_minattemptinterval = 1\n\nclass Feedback:\n \"\"\"Keep track of number of activities.\"\"\"\n\n def __init__(self):\n # counts of widget creation\n self.widgetcts = defaultdict(int)\n # counts of data import\n self.importcts = defaultdict(int)\n # counts of data export\n self.exportcts = defaultdict(int)\n\n# singleton\nfeedback = Feedback()\n\n@atexit.register\ndef updatects():\n \"\"\"Add saved counts with values from app.\"\"\"\n #print(\"running updates\")\n setn = qt.QSettings(_org, _app)\n\n # get statistics and reset in config file\n widgetcts = eval(setn.value('counts/widget', '{}'))\n importcts = eval(setn.value('counts/import', '{}'))\n exportcts = eval(setn.value('counts/export', '{}'))\n\n # add existing counts\n for k, v in citems(feedback.widgetcts):\n widgetcts[k] = widgetcts.get(k, 0) + v\n for k, v in citems(feedback.importcts):\n importcts[k] = importcts.get(k, 0) + v\n for k, v in citems(feedback.exportcts):\n exportcts[k] = exportcts.get(k, 0) + v\n\n setn.setValue('counts/widget', rrepr(widgetcts))\n setn.setValue('counts/import', rrepr(importcts))\n setn.setValue('counts/export', rrepr(exportcts))\n\nclass FeedbackCheckThread(qt.QThread):\n \"\"\"Async thread to send feedback.\"\"\"\n\n def run(self):\n from ..setting import settingdb\n\n # exit if disabled\n if (settingdb['feedback_disabled'] or\n disableFeedback or\n not settingdb['feedback_asked_user']):\n #print('disabled')\n return\n\n setn = qt.QSettings(_org, _app)\n\n # keep track of when we successfully sent the data (lastsent)\n # and when we last tried (lastattempt), so we don't send too\n # often\n\n today = datetime.date.today()\n today_tpl = (today.year, today.month, today.day)\n\n # don't try to send too often\n lastattempt = setn.value('last-attempt', '(2000,1,1)')\n lastattempt = datetime.date(*eval(lastattempt))\n delta_attempt = (today-lastattempt).days\n if delta_attempt<_minattemptinterval:\n #print(\"too soon 1\")\n return\n\n lastsent = setn.value('last-sent')\n if not lastsent:\n delta_sent = -1\n else:\n lastsent = datetime.date(*eval(lastsent))\n delta_sent = (today-lastsent).days\n\n # are we within the send period\n if delta_sent<_mininterval:\n #print(\"too soon 2\")\n return\n\n # avoid accessing url too often by updating date first\n setn.setValue('last-attempt', repr(today_tpl))\n\n # get statistics and reset in config file\n widgetcts = setn.value('counts/widget', '{}')\n importcts = setn.value('counts/import', '{}')\n exportcts = setn.value('counts/export', '{}')\n\n try:\n winver = str(sys.getwindowsversion())\n except Exception:\n winver = 'N/A'\n\n # construct post message - these are the data sent to the\n # remote server\n args = {\n 'interval': str(delta_sent),\n 'veusz-version': version(),\n 'python-version': sys.version,\n 'python-version_info': repr(tuple(sys.version_info)),\n 'python-platform': sys.platform,\n 'platform-machine': platform.machine(),\n 'windows-version': winver,\n 'numpy-version': N.__version__,\n 'qt-version': qt.qVersion(),\n 'pyqt-version': qt.PYQT_VERSION_STR,\n 'sip-version': sip.SIP_VERSION_STR,\n 'locale': qt.QLocale().name(),\n 'widgetcts': widgetcts,\n 'importcts': importcts,\n 'exportcts': exportcts,\n }\n postdata = curlencode(args).encode('utf8')\n\n # now post the data\n try:\n f = curlrequest.urlopen(_url, postdata)\n retn = f.readline().decode('utf8').strip()\n f.close()\n\n if retn == 'ok':\n #print(\"success\")\n # reset in stats file and set date last done\n setn.setValue('counts/widget', '{}')\n setn.setValue('counts/import', '{}')\n setn.setValue('counts/export', '{}')\n setn.setValue('last-sent', repr(today_tpl))\n\n except Exception as e:\n #print(\"failure\",e)\n pass"}]} {"messages": [{"role": "user", "content": "Write Python code that implements iostream.py from multikatt/CouchPotatoServer (path: libs/tornado/iostream.py)."}, {"role": "assistant", "content": "# libs/tornado/iostream.py (from multikatt/CouchPotatoServer, license: gpl-3.0)\n\n#!/usr/bin/env python\n#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Utility classes to write to and read from non-blocking files and sockets.\n\nContents:\n\n* `BaseIOStream`: Generic interface for reading and writing.\n* `IOStream`: Implementation of BaseIOStream using non-blocking sockets.\n* `SSLIOStream`: SSL-aware version of IOStream.\n* `PipeIOStream`: Pipe-based IOStream implementation.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport collections\nimport errno\nimport numbers\nimport os\nimport socket\nimport sys\nimport re\n\nfrom tornado.concurrent import TracebackFuture\nfrom tornado import ioloop\nfrom tornado.log import gen_log, app_log\nfrom tornado.netutil import ssl_wrap_socket, ssl_match_hostname, SSLCertificateError\nfrom tornado import stack_context\nfrom tornado.util import errno_from_exception\n\ntry:\n from tornado.platform.posix import _set_nonblocking\nexcept ImportError:\n _set_nonblocking = None\n\ntry:\n import ssl\nexcept ImportError:\n # ssl is not available on Google App Engine\n ssl = None\n\n# These errnos indicate that a non-blocking operation must be retried\n# at a later time. On most platforms they're the same value, but on\n# some they differ.\n_ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN)\n\nif hasattr(errno, \"WSAEWOULDBLOCK\"):\n _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,)\n\n# These errnos indicate that a connection has been abruptly terminated.\n# They should be caught and handled less noisily than other errors.\n_ERRNO_CONNRESET = (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE,\n errno.ETIMEDOUT)\n\nif hasattr(errno, \"WSAECONNRESET\"):\n _ERRNO_CONNRESET += (errno.WSAECONNRESET, errno.WSAECONNABORTED, errno.WSAETIMEDOUT)\n\nif sys.platform == 'darwin':\n # OSX appears to have a race condition that causes send(2) to return\n # EPROTOTYPE if called while a socket is being torn down:\n # http://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/\n # Since the socket is being closed anyway, treat this as an ECONNRESET\n # instead of an unexpected error.\n _ERRNO_CONNRESET += (errno.EPROTOTYPE,)\n\n# More non-portable errnos:\n_ERRNO_INPROGRESS = (errno.EINPROGRESS,)\n\nif hasattr(errno, \"WSAEINPROGRESS\"):\n _ERRNO_INPROGRESS += (errno.WSAEINPROGRESS,)\n\n#######################################################\nclass StreamClosedError(IOError):\n \"\"\"Exception raised by `IOStream` methods when the stream is closed.\n\n Note that the close callback is scheduled to run *after* other\n callbacks on the stream (to allow for buffered data to be processed),\n so you may see this error before you see the close callback.\n \"\"\"\n pass\n\nclass UnsatisfiableReadError(Exception):\n \"\"\"Exception raised when a read cannot be satisfied.\n\n Raised by ``read_until`` and ``read_until_regex`` with a ``max_bytes``\n argument.\n \"\"\"\n pass\n\nclass StreamBufferFullError(Exception):\n \"\"\"Exception raised by `IOStream` methods when the buffer is full.\n \"\"\"\n\nclass BaseIOStream(object):\n \"\"\"A utility class to write to and read from a non-blocking file or socket.\n\n We support a non-blocking ``write()`` and a family of ``read_*()`` methods.\n All of the methods take an optional ``callback`` argument and return a\n `.Future` only if no callback is given. When the operation completes,\n the callback will be run or the `.Future` will resolve with the data\n read (or ``None`` for ``write()``). All outstanding ``Futures`` will\n resolve with a `StreamClosedError` when the stream is closed; users\n of the callback interface will be notified via\n `.BaseIOStream.set_close_callback` instead.\n\n When a stream is closed due to an error, the IOStream's ``error``\n attribute contains the exception object.\n\n Subclasses must implement `fileno`, `close_fd`, `write_to_fd`,\n `read_from_fd`, and optionally `get_fd_error`.\n \"\"\"\n def __init__(self, io_loop=None, max_buffer_size=None,\n read_chunk_size=None, max_write_buffer_size=None):\n \"\"\"`BaseIOStream` constructor.\n\n :arg io_loop: The `.IOLoop` to use; defaults to `.IOLoop.current`.\n Deprecated since Tornado 4.1.\n :arg max_buffer_size: Maximum amount of incoming data to buffer;\n defaults to 100MB.\n :arg read_chunk_size: Amount of data to read at one time from the\n underlying transport; defaults to 64KB.\n :arg max_write_buffer_size: Amount of outgoing data to buffer;\n defaults to unlimited.\n\n .. versionchanged:: 4.0\n Add the ``max_write_buffer_size`` parameter. Changed default\n ``read_chunk_size`` to 64KB.\n \"\"\"\n self.io_loop = io_loop or ioloop.IOLoop.current()\n self.max_buffer_size = max_buffer_size or 104857600\n # A chunk size that is too close to max_buffer_size can cause\n # spurious failures.\n self.read_chunk_size = min(read_chunk_size or 65536,\n self.max_buffer_size // 2)\n self.max_write_buffer_size = max_write_buffer_size\n self.error = None\n self._read_buffer = collections.deque()\n self._write_buffer = collections.deque()\n self._read_buffer_size = 0\n self._write_buffer_size = 0\n self._write_buffer_frozen = False\n self._read_delimiter = None\n self._read_regex = None\n self._read_max_bytes = None\n self._read_bytes = None\n self._read_partial = False\n self._read_until_close = False\n self._read_callback = None\n self._read_future = None\n self._streaming_callback = None\n self._write_callback = None\n self._write_future = None\n self._close_callback = None\n self._connect_callback = None\n self._connect_future = None\n self._connecting = False\n self._state = None\n self._pending_callbacks = 0\n self._closed = False\n\n def fileno(self):\n \"\"\"Returns the file descriptor for this stream.\"\"\"\n raise NotImplementedError()\n\n def close_fd(self):\n \"\"\"Closes the file underlying this stream.\n\n ``close_fd`` is called by `BaseIOStream` and should not be called\n elsewhere; other users should call `close` instead.\n \"\"\"\n raise NotImplementedError()\n\n def write_to_fd(self, data):\n \"\"\"Attempts to write ``data`` to the underlying file.\n\n Returns the number of bytes written.\n \"\"\"\n raise NotImplementedError()\n\n def read_from_fd(self):\n \"\"\"Attempts to read from the underlying file.\n\n Returns ``None`` if there was nothing to read (the socket\n returned `~errno.EWOULDBLOCK` or equivalent), otherwise\n returns the data. When possible, should return no more than\n ``self.read_chunk_size`` bytes at a time.\n \"\"\"\n raise NotImplementedError()\n\n def get_fd_error(self):\n \"\"\"Returns information about any error on the underlying file.\n\n This method is called after the `.IOLoop` has signaled an error on the\n file descriptor, and should return an Exception (such as `socket.error`\n with additional information, or None if no such information is\n available.\n \"\"\"\n return None\n\n def read_until_regex(self, regex, callback=None, max_bytes=None):\n \"\"\"Asynchronously read until we have matched the given regex.\n\n The result includes the data that matches the regex and anything\n that came before it. If a callback is given, it will be run\n with the data as an argument; if not, this method returns a\n `.Future`.\n\n If ``max_bytes`` is not None, the connection will be closed\n if more than ``max_bytes`` bytes have been read and the regex is\n not satisfied.\n\n .. versionchanged:: 4.0\n Added the ``max_bytes`` argument. The ``callback`` argument is\n now optional and a `.Future` will be returned if it is omitted.\n \"\"\"\n future = self._set_read_callback(callback)\n self._read_regex = re.compile(regex)\n self._read_max_bytes = max_bytes\n try:\n self._try_inline_read()\n except UnsatisfiableReadError as e:\n # Handle this the same way as in _handle_events.\n gen_log.info(\"Unsatisfiable read, closing connection: %s\" % e)\n self.close(exc_info=True)\n return future\n except:\n if future is not None:\n # Ensure that the future doesn't log an error because its\n # failure was never examined.\n future.add_done_callback(lambda f: f.exception())\n raise\n return future\n\n def read_until(self, delimiter, callback=None, max_bytes=None):\n \"\"\"Asynchronously read until we have found the given delimiter.\n\n The result includes all the data read including the delimiter.\n If a callback is given, it will be run with the data as an argument;\n if not, this method returns a `.Future`.\n\n If ``max_bytes`` is not None, the connection will be closed\n if more than ``max_bytes`` bytes have been read and the delimiter\n is not found.\n\n .. versionchanged:: 4.0\n Added the ``max_bytes`` argument. The ``callback`` argument is\n now optional and a `.Future` will be returned if it is omitted.\n \"\"\"\n future = self._set_read_callback(callback)\n self._read_delimiter = delimiter\n self._read_max_bytes = max_bytes\n try:\n self._try_inline_read()\n except UnsatisfiableReadError as e:\n # Handle this the same way as in _handle_events.\n gen_log.info(\"Unsatisfiable read, closing connection: %s\" % e)\n self.close(exc_info=True)\n return future\n except:\n if future is not None:\n future.add_done_callback(lambda f: f.exception())\n raise\n return future\n\n def read_bytes(self, num_bytes, callback=None, streaming_callback=None,\n partial=False):\n \"\"\"Asynchronously read a number of bytes.\n\n If a ``streaming_callback`` is given, it will be called with chunks\n of data as they become available, and the final result will be empty.\n Otherwise, the result is all the data that was read.\n If a callback is given, it will be run with the data as an argument;\n if not, this method returns a `.Future`.\n\n If ``partial`` is true, the callback is run as soon as we have\n any bytes to return (but never more than ``num_bytes``)\n\n .. versionchanged:: 4.0\n Added the ``partial`` argument. The callback argument is now\n optional and a `.Future` will be returned if it is omitted.\n \"\"\"\n future = self._set_read_callback(callback)\n assert isinstance(num_bytes, numbers.Integral)\n self._read_bytes = num_bytes\n self._read_partial = partial\n self._streaming_callback = stack_context.wrap(streaming_callback)\n try:\n self._try_inline_read()\n except:\n if future is not None:\n future.add_done_callback(lambda f: f.exception())\n raise\n return future\n\n def read_until_close(self, callback=None, streaming_callback=None):\n \"\"\"Asynchronously reads all data from the socket until it is closed.\n\n If a ``streaming_callback`` is given, it will be called with chunks\n of data as they become available, and the final result will be empty.\n Otherwise, the result is all the data that was read.\n If a callback is given, it will be run with the data as an argument;\n if not, this method returns a `.Future`.\n\n .. versionchanged:: 4.0\n The callback argument is now optional and a `.Future` will\n be returned if it is omitted.\n \"\"\"\n future = self._set_read_callback(callback)\n self._streaming_callback = stack_context.wrap(streaming_callback)\n if self.closed():\n if self._streaming_callback is not None:\n self._run_read_callback(self._read_buffer_size, True)\n self._run_read_callback(self._read_buffer_size, False)\n return future\n self._read_until_close = True\n try:\n self._try_inline_read()\n except:\n future.add_done_callback(lambda f: f.exception())\n raise\n return future\n\n def write(self, data, callback=None):\n \"\"\"Asynchronously write the given data to this stream.\n\n If ``callback`` is given, we call it when all of the buffered write\n data has been successfully written to the stream. If there was\n previously buffered write data and an old write callback, that\n callback is simply overwritten with this new callback.\n\n If no ``callback`` is given, this method returns a `.Future` that\n resolves (with a result of ``None``) when the write has been\n completed. If `write` is called again before that `.Future` has\n resolved, the previous future will be orphaned and will never resolve.\n\n .. versionchanged:: 4.0\n Now returns a `.Future` if no callback is given.\n \"\"\"\n assert isinstance(data, bytes)\n self._check_closed()\n # We use bool(_write_buffer) as a proxy for write_buffer_size>0,\n # so never put empty strings in the buffer.\n if data:\n if (self.max_write_buffer_size is not None and\n self._write_buffer_size + len(data) > self.max_write_buffer_size):\n raise StreamBufferFullError(\"Reached maximum write buffer size\")\n # Break up large contiguous strings before inserting them in the\n # write buffer, so we don't have to recopy the entire thing\n # as we slice off pieces to send to the socket.\n WRITE_BUFFER_CHUNK_SIZE = 128 * 1024\n for i in range(0, len(data), WRITE_BUFFER_CHUNK_SIZE):\n self._write_buffer.append(data[i:i + WRITE_BUFFER_CHUNK_SIZE])\n self._write_buffer_size += len(data)\n if callback is not None:\n self._write_callback = stack_context.wrap(callback)\n future = None\n else:\n future = self._write_future = TracebackFuture()\n future.add_done_callback(lambda f: f.exception())\n if not self._connecting:\n self._handle_write()\n if self._write_buffer:\n self._add_io_state(self.io_loop.WRITE)\n self._maybe_add_error_listener()\n return future\n\n def set_close_callback(self, callback):\n \"\"\"Call the given callback when the stream is closed.\n\n This is not necessary for applications that use the `.Future`\n interface; all outstanding ``Futures`` will resolve with a\n `StreamClosedError` when the stream is closed.\n \"\"\"\n self._close_callback = stack_context.wrap(callback)\n self._maybe_add_error_listener()\n\n def close(self, exc_info=False):\n \"\"\"Close this stream.\n\n If ``exc_info`` is true, set the ``error`` attribute to the current\n exception from `sys.exc_info` (or if ``exc_info`` is a tuple,\n use that instead of `sys.exc_info`).\n \"\"\"\n if not self.closed():\n if exc_info:\n if not isinstance(exc_info, tuple):\n exc_info = sys.exc_info()\n if any(exc_info):\n self.error = exc_info[1]\n if self._read_until_close:\n if (self._streaming_callback is not None and\n self._read_buffer_size):\n self._run_read_callback(self._read_buffer_size, True)\n self._read_until_close = False\n self._run_read_callback(self._read_buffer_size, False)\n if self._state is not None:\n self.io_loop.remove_handler(self.fileno())\n self._state = None\n self.close_fd()\n self._closed = True\n self._maybe_run_close_callback()\n\n def _maybe_run_close_callback(self):\n # If there are pending callbacks, don't run the close callback\n # until they're done (see _maybe_add_error_handler)\n if self.closed() and self._pending_callbacks == 0:\n futures = []\n if self._read_future is not None:\n futures.append(self._read_future)\n self._read_future = None\n if self._write_future is not None:\n futures.append(self._write_future)\n self._write_future = None\n if self._connect_future is not None:\n futures.append(self._connect_future)\n self._connect_future = None\n for future in futures:\n if (isinstance(self.error, (socket.error, IOError)) and\n errno_from_exception(self.error) in _ERRNO_CONNRESET):\n # Treat connection resets as closed connections so\n # clients only have to catch one kind of exception\n # to avoid logging.\n future.set_exception(StreamClosedError())\n else:\n future.set_exception(self.error or StreamClosedError())\n if self._close_callback is not None:\n cb = self._close_callback\n self._close_callback = None\n self._run_callback(cb)\n # Delete any unfinished callbacks to break up reference cycles.\n self._read_callback = self._write_callback = None\n # Clear the buffers so they can be cleared immediately even\n # if the IOStream object is kept alive by a reference cycle.\n # TODO: Clear the read buffer too; it currently breaks some tests.\n self._write_buffer = None\n\n def reading(self):\n \"\"\"Returns true if we are currently reading from the stream.\"\"\"\n return self._read_callback is not None or self._read_future is not None\n\n def writing(self):\n \"\"\"Returns true if we are currently writing to the stream.\"\"\"\n return bool(self._write_buffer)\n\n def closed(self):\n \"\"\"Returns true if the stream has been closed.\"\"\"\n return self._closed\n\n def set_nodelay(self, value):\n \"\"\"Sets the no-delay flag for this stream.\n\n By default, data written to TCP streams may be held for a time\n to make the most efficient use of bandwidth (according to\n Nagle's algorithm). The no-delay flag requests that data be\n written as soon as possible, even if doing so would consume\n additional bandwidth.\n\n This flag is currently defined only for TCP-based ``IOStreams``.\n\n .. versionadded:: 3.1\n \"\"\"\n pass\n\n def _handle_events(self, fd, events):\n if self.closed():\n gen_log.warning(\"Got events for closed stream %s\", fd)\n return\n try:\n if self._connecting:\n # Most IOLoops will report a write failed connect\n # with the WRITE event, but SelectIOLoop reports a\n # READ as well so we must check for connecting before\n # either.\n self._handle_connect()\n if self.closed():\n return\n if events & self.io_loop.READ:\n self._handle_read()\n if self.closed():\n return\n if events & self.io_loop.WRITE:\n self._handle_write()\n if self.closed():\n return\n if events & self.io_loop.ERROR:\n self.error = self.get_fd_error()\n # We may have queued up a user callback in _handle_read or\n # _handle_write, so don't close the IOStream until those\n # callbacks have had a chance to run.\n self.io_loop.add_callback(self.close)\n return\n state = self.io_loop.ERROR\n if self.reading():\n state |= self.io_loop.READ\n if self.writing():\n state |= self.io_loop.WRITE\n if state == self.io_loop.ERROR and self._read_buffer_size == 0:\n # If the connection is idle, listen for reads too so\n # we can tell if the connection is closed. If there is\n # data in the read buffer we won't run the close callback\n # yet anyway, so we don't need to listen in this case.\n state |= self.io_loop.READ\n if state != self._state:\n assert self._state is not None, \\\n \"shouldn't happen: _handle_events without self._state\"\n self._state = state\n self.io_loop.update_handler(self.fileno(), self._state)\n except UnsatisfiableReadError as e:\n gen_log.info(\"Unsatisfiable read, closing connection: %s\" % e)\n self.close(exc_info=True)\n except Exception:\n gen_log.error(\"Uncaught exception, closing connection.\",\n exc_info=True)\n self.close(exc_info=True)\n raise\n\n def _run_callback(self, callback, *args):\n def wrapper():\n self._pending_callbacks -= 1\n try:\n return callback(*args)\n except Exception:\n app_log.error(\"Uncaught exception, closing connection.\",\n exc_info=True)\n # Close the socket on an uncaught exception from a user callback\n # (It would eventually get closed when the socket object is\n # gc'd, but we don't want to rely on gc happening before we\n # run out of file descriptors)\n self.close(exc_info=True)\n # Re-raise the exception so that IOLoop.handle_callback_exception\n # can see it and log the error\n raise\n finally:\n self._maybe_add_error_listener()\n # We schedule callbacks to be run on the next IOLoop iteration\n # rather than running them directly for several reasons:\n # * Prevents unbounded stack growth when a callback calls an\n # IOLoop operation that immediately runs another callback\n # * Provides a predictable execution context for e.g.\n # non-reentrant mutexes\n # * Ensures that the try/except in wrapper() is run outside\n # of the application's StackContexts\n with stack_context.NullContext():\n # stack_context was already captured in callback, we don't need to\n # capture it again for IOStream's wrapper. This is especially\n # important if the callback was pre-wrapped before entry to\n # IOStream (as in HTTPConnection._header_callback), as we could\n # capture and leak the wrong context here.\n self._pending_callbacks += 1\n self.io_loop.add_callback(wrapper)\n\n def _read_to_buffer_loop(self):\n # This method is called from _handle_read and _try_inline_read.\n try:\n if self._read_bytes is not None:\n target_bytes = self._read_bytes\n elif self._read_max_bytes is not None:\n target_bytes = self._read_max_bytes\n elif self.reading():\n # For read_until without max_bytes, or\n # read_until_close, read as much as we can before\n # scanning for the delimiter.\n target_bytes = None\n else:\n target_bytes = 0\n next_find_pos = 0\n # Pretend to have a pending callback so that an EOF in\n # _read_to_buffer doesn't trigger an immediate close\n # callback. At the end of this method we'll either\n # establish a real pending callback via\n # _read_from_buffer or run the close callback.\n #\n # We need two try statements here so that\n # pending_callbacks is decremented before the `except`\n # clause below (which calls `close` and does need to\n # trigger the callback)\n self._pending_callbacks += 1\n while not self.closed():\n # Read from the socket until we get EWOULDBLOCK or equivalent.\n # SSL sockets do some internal buffering, and if the data is\n # sitting in the SSL object's buffer select() and friends\n # can't see it; the only way to find out if it's there is to\n # try to read it.\n if self._read_to_buffer() == 0:\n break\n\n self._run_streaming_callback()\n\n # If we've read all the bytes we can use, break out of\n # this loop. We can't just call read_from_buffer here\n # because of subtle interactions with the\n # pending_callback and error_listener mechanisms.\n #\n # If we've reached target_bytes, we know we're done.\n if (target_bytes is not None and\n self._read_buffer_size >= target_bytes):\n break\n\n # Otherwise, we need to call the more expensive find_read_pos.\n # It's inefficient to do this on every read, so instead\n # do it on the first read and whenever the read buffer\n # size has doubled.\n if self._read_buffer_size >= next_find_pos:\n pos = self._find_read_pos()\n if pos is not None:\n return pos\n next_find_pos = self._read_buffer_size * 2\n return self._find_read_pos()\n finally:\n self._pending_callbacks -= 1\n\n def _handle_read(self):\n try:\n pos = self._read_to_buffer_loop()\n except UnsatisfiableReadError:\n raise\n except Exception:\n gen_log.warning(\"error on read\", exc_info=True)\n self.close(exc_info=True)\n return\n if pos is not None:\n self._read_from_buffer(pos)\n return\n else:\n self._maybe_run_close_callback()\n\n def _set_read_callback(self, callback):\n assert self._read_callback is None, \"Already reading\"\n assert self._read_future is None, \"Already reading\"\n if callback is not None:\n self._read_callback = stack_context.wrap(callback)\n else:\n self._read_future = TracebackFuture()\n return self._read_future\n\n def _run_read_callback(self, size, streaming):\n if streaming:\n callback = self._streaming_callback\n else:\n callback = self._read_callback\n self._read_callback = self._streaming_callback = None\n if self._read_future is not None:\n assert callback is None\n future = self._read_future\n self._read_future = None\n future.set_result(self._consume(size))\n if callback is not None:\n assert self._read_future is None\n self._run_callback(callback, self._consume(size))\n else:\n # If we scheduled a callback, we will add the error listener\n # afterwards. If we didn't, we have to do it now.\n self._maybe_add_error_listener()\n\n def _try_inline_read(self):\n \"\"\"Attempt to complete the current read operation from buffered data.\n\n If the read can be completed without blocking, schedules the\n read callback on the next IOLoop iteration; otherwise starts\n listening for reads on the socket.\n \"\"\"\n # See if we've already got the data from a previous read\n self._run_streaming_callback()\n pos = self._find_read_pos()\n if pos is not None:\n self._read_from_buffer(pos)\n return\n self._check_closed()\n try:\n pos = self._read_to_buffer_loop()\n except Exception:\n # If there was an in _read_to_buffer, we called close() already,\n # but couldn't run the close callback because of _pending_callbacks.\n # Before we escape from this function, run the close callback if\n # applicable.\n self._maybe_run_close_callback()\n raise\n if pos is not None:\n self._read_from_buffer(pos)\n return\n # We couldn't satisfy the read inline, so either close the stream\n # or listen for new data.\n if self.closed():\n self._maybe_run_close_callback()\n else:\n self._add_io_state(ioloop.IOLoop.READ)\n\n def _read_to_buffer(self):\n \"\"\"Reads from the socket and appends the result to the read buffer.\n\n Returns the number of bytes read. Returns 0 if there is nothing\n to read (i.e. the read returns EWOULDBLOCK or equivalent). On\n error closes the socket and raises an exception.\n \"\"\"\n try:\n chunk = self.read_from_fd()\n except (socket.error, IOError, OSError) as e:\n # ssl.SSLError is a subclass of socket.error\n if e.args[0] in _ERRNO_CONNRESET:\n # Treat ECONNRESET as a connection close rather than\n # an error to minimize log spam (the exception will\n # be available on self.error for apps that care).\n self.close(exc_info=True)\n return\n self.close(exc_info=True)\n raise\n if chunk is None:\n return 0\n self._read_buffer.append(chunk)\n self._read_buffer_size += len(chunk)\n if self._read_buffer_size > self.max_buffer_size:\n gen_log.error(\"Reached maximum read buffer size\")\n self.close()\n raise StreamBufferFullError(\"Reached maximum read buffer size\")\n return len(chunk)\n\n def _run_streaming_callback(self):\n if self._streaming_callback is not None and self._read_buffer_size:\n bytes_to_consume = self._read_buffer_size\n if self._read_bytes is not None:\n bytes_to_consume = min(self._read_bytes, bytes_to_consume)\n self._read_bytes -= bytes_to_consume\n self._run_read_callback(bytes_to_consume, True)\n\n def _read_from_buffer(self, pos):\n \"\"\"Attempts to complete the currently-pending read from the buffer.\n\n The argument is either a position in the read buffer or None,\n as returned by _find_read_pos.\n \"\"\"\n self._read_bytes = self._read_delimiter = self._read_regex = None\n self._read_partial = False\n self._run_read_callback(pos, False)\n\n def _find_read_pos(self):\n \"\"\"Attempts to find a position in the read buffer that satisfies\n the currently-pending read.\n\n Returns a position in the buffer if the current read can be satisfied,\n or None if it cannot.\n \"\"\"\n if (self._read_bytes is not None and\n (self._read_buffer_size >= self._read_bytes or\n (self._read_partial and self._read_buffer_size > 0))):\n num_bytes = min(self._read_bytes, self._read_buffer_size)\n return num_bytes\n elif self._read_delimiter is not None:\n # Multi-byte delimiters (e.g. '\\r\\n') may straddle two\n # chunks in the read buffer, so we can't easily find them\n # without collapsing the buffer. However, since protocols\n # using delimited reads (as opposed to reads of a known\n # length) tend to be \"line\" oriented, the delimiter is likely\n # to be in the first few chunks. Merge the buffer gradually\n # since large merges are relatively expensive and get undone in\n # _consume().\n if self._read_buffer:\n while True:\n loc = self._read_buffer[0].find(self._read_delimiter)\n if loc != -1:\n delimiter_len = len(self._read_delimiter)\n self._check_max_bytes(self._read_delimiter,\n loc + delimiter_len)\n return loc + delimiter_len\n if len(self._read_buffer) == 1:\n break\n _double_prefix(self._read_buffer)\n self._check_max_bytes(self._read_delimiter,\n len(self._read_buffer[0]))\n elif self._read_regex is not None:\n if self._read_buffer:\n while True:\n m = self._read_regex.search(self._read_buffer[0])\n if m is not None:\n self._check_max_bytes(self._read_regex, m.end())\n return m.end()\n if len(self._read_buffer) == 1:\n break\n _double_prefix(self._read_buffer)\n self._check_max_bytes(self._read_regex,\n len(self._read_buffer[0]))\n return None\n\n def _check_max_bytes(self, delimiter, size):\n if (self._read_max_bytes is not None and\n size > self._read_max_bytes):\n raise UnsatisfiableReadError(\n \"delimiter %r not found within %d bytes\" % (\n delimiter, self._read_max_bytes))\n\n def _handle_write(self):\n while self._write_buffer:\n try:\n if not self._write_buffer_frozen:\n # On windows, socket.send blows up if given a\n # write buffer that's too large, instead of just\n # returning the number of bytes it was able to\n # process. Therefore we must not call socket.send\n # with more than 128KB at a time.\n _merge_prefix(self._write_buffer, 128 * 1024)\n num_bytes = self.write_to_fd(self._write_buffer[0])\n if num_bytes == 0:\n # With OpenSSL, if we couldn't write the entire buffer,\n # the very same string object must be used on the\n # next call to send. Therefore we suppress\n # merging the write buffer after an incomplete send.\n # A cleaner solution would be to set\n # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER, but this is\n # not yet accessible from python\n # (http://bugs.python.org/issue8240)\n self._write_buffer_frozen = True\n break\n self._write_buffer_frozen = False\n _merge_prefix(self._write_buffer, num_bytes)\n self._write_buffer.popleft()\n self._write_buffer_size -= num_bytes\n except (socket.error, IOError, OSError) as e:\n if e.args[0] in _ERRNO_WOULDBLOCK:\n self._write_buffer_frozen = True\n break\n else:\n if e.args[0] not in _ERRNO_CONNRESET:\n # Broken pipe errors are usually caused by connection\n # reset, and its better to not log EPIPE errors to\n # minimize log spam\n gen_log.warning(\"Write error on %s: %s\",\n self.fileno(), e)\n self.close(exc_info=True)\n return\n if not self._write_buffer:\n if self._write_callback:\n callback = self._write_callback\n self._write_callback = None\n self._run_callback(callback)\n if self._write_future:\n future = self._write_future\n self._write_future = None\n future.set_result(None)\n\n def _consume(self, loc):\n if loc == 0:\n return b\"\"\n _merge_prefix(self._read_buffer, loc)\n self._read_buffer_size -= loc\n return self._read_buffer.popleft()\n\n def _check_closed(self):\n if self.closed():\n raise StreamClosedError(\"Stream is closed\")\n\n def _maybe_add_error_listener(self):\n # This method is part of an optimization: to detect a connection that\n # is closed when we're not actively reading or writing, we must listen\n # for read events. However, it is inefficient to do this when the\n # connection is first established because we are going to read or write\n # immediately anyway. Instead, we insert checks at various times to\n # see if the connection is idle and add the read listener then.\n if self._pending_callbacks != 0:\n return\n if self._state is None or self._state == ioloop.IOLoop.ERROR:\n if self.closed():\n self._maybe_run_close_callback()\n elif (self._read_buffer_size == 0 and\n self._close_callback is not None):\n self._add_io_state(ioloop.IOLoop.READ)\n\n def _add_io_state(self, state):\n \"\"\"Adds `state` (IOLoop.{READ,WRITE} flags) to our event handler.\n\n Implementation notes: Reads and writes have a fast path and a\n slow path. The fast path reads synchronously from socket\n buffers, while the slow path uses `_add_io_state` to schedule\n an IOLoop callback. Note that in both cases, the callback is\n run asynchronously with `_run_callback`.\n\n To detect closed connections, we must have called\n `_add_io_state` at some point, but we want to delay this as\n much as possible so we don't have to set an `IOLoop.ERROR`\n listener that will be overwritten by the next slow-path\n operation. As long as there are callbacks scheduled for\n fast-path ops, those callbacks may do more reads.\n If a sequence of fast-path ops do not end in a slow-path op,\n (e.g. for an @asynchronous long-poll request), we must add\n the error handler. This is done in `_run_callback` and `write`\n (since the write callback is optional so we can have a\n fast-path write with no `_run_callback`)\n \"\"\"\n if self.closed():\n # connection has been closed, so there can be no future events\n return\n if self._state is None:\n self._state = ioloop.IOLoop.ERROR | state\n with stack_context.NullContext():\n self.io_loop.add_handler(\n self.fileno(), self._handle_events, self._state)\n elif not self._state & state:\n self._state = self._state | state\n self.io_loop.update_handler(self.fileno(), self._state)\n\nclass IOStream(BaseIOStream):\n r\"\"\"Socket-based `IOStream` implementation.\n\n This class supports the read and write methods from `BaseIOStream`\n plus a `connect` method.\n\n The ``socket`` parameter may either be connected or unconnected.\n For server operations the socket is the result of calling\n `socket.accept `. For client operations the\n socket is created with `socket.socket`, and may either be\n connected before passing it to the `IOStream` or connected with\n `IOStream.connect`.\n\n A very simple (and broken) HTTP client using this class::\n\n import tornado.ioloop\n import tornado.iostream\n import socket\n\n def send_request():\n stream.write(b\"GET / HTTP/1.0\\r\\nHost: friendfeed.com\\r\\n\\r\\n\")\n stream.read_until(b\"\\r\\n\\r\\n\", on_headers)\n\n def on_headers(data):\n headers = {}\n for line in data.split(b\"\\r\\n\"):\n parts = line.split(b\":\")\n if len(parts) == 2:\n headers[parts[0].strip()] = parts[1].strip()\n stream.read_bytes(int(headers[b\"Content-Length\"]), on_body)\n\n def on_body(data):\n print data\n stream.close()\n tornado.ioloop.IOLoop.instance().stop()\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n stream = tornado.iostream.IOStream(s)\n stream.connect((\"friendfeed.com\", 80), send_request)\n tornado.ioloop.IOLoop.instance().start()\n \"\"\"\n def __init__(self, socket, *args, **kwargs):\n self.socket = socket\n self.socket.setblocking(False)\n super(IOStream, self).__init__(*args, **kwargs)\n\n def fileno(self):\n return self.socket\n\n def close_fd(self):\n self.socket.close()\n self.socket = None\n\n def get_fd_error(self):\n errno = self.socket.getsockopt(socket.SOL_SOCKET,\n socket.SO_ERROR)\n return socket.error(errno, os.strerror(errno))\n\n def read_from_fd(self):\n try:\n chunk = self.socket.recv(self.read_chunk_size)\n except socket.error as e:\n if e.args[0] in _ERRNO_WOULDBLOCK:\n return None\n else:\n raise\n if not chunk:\n self.close()\n return None\n return chunk\n\n def write_to_fd(self, data):\n return self.socket.send(data)\n\n def connect(self, address, callback=None, server_hostname=None):\n \"\"\"Connects the socket to a remote address without blocking.\n\n May only be called if the socket passed to the constructor was\n not previously connected. The address parameter is in the\n same format as for `socket.connect ` for\n the type of socket passed to the IOStream constructor,\n e.g. an ``(ip, port)`` tuple. Hostnames are accepted here,\n but will be resolved synchronously and block the IOLoop.\n If you have a hostname instead of an IP address, the `.TCPClient`\n class is recommended instead of calling this method directly.\n `.TCPClient` will do asynchronous DNS resolution and handle\n both IPv4 and IPv6.\n\n If ``callback`` is specified, it will be called with no\n arguments when the connection is completed; if not this method\n returns a `.Future` (whose result after a successful\n connection will be the stream itself).\n\n If specified, the ``server_hostname`` parameter will be used\n in SSL connections for certificate validation (if requested in\n the ``ssl_options``) and SNI (if supported; requires\n Python 3.2+).\n\n Note that it is safe to call `IOStream.write\n ` while the connection is pending, in\n which case the data will be written as soon as the connection\n is ready. Calling `IOStream` read methods before the socket is\n connected works on some platforms but is non-portable.\n\n .. versionchanged:: 4.0\n If no callback is given, returns a `.Future`.\n\n \"\"\"\n self._connecting = True\n if callback is not None:\n self._connect_callback = stack_context.wrap(callback)\n future = None\n else:\n future = self._connect_future = TracebackFuture()\n try:\n self.socket.connect(address)\n except socket.error as e:\n # In non-blocking mode we expect connect() to raise an\n # exception with EINPROGRESS or EWOULDBLOCK.\n #\n # On freebsd, other errors such as ECONNREFUSED may be\n # returned immediately when attempting to connect to\n # localhost, so handle them the same way as an error\n # reported later in _handle_connect.\n if (errno_from_exception(e) not in _ERRNO_INPROGRESS and\n errno_from_exception(e) not in _ERRNO_WOULDBLOCK):\n if future is None:\n gen_log.warning(\"Connect error on fd %s: %s\",\n self.socket.fileno(), e)\n self.close(exc_info=True)\n return future\n self._add_io_state(self.io_loop.WRITE)\n return future\n\n def start_tls(self, server_side, ssl_options=None, server_hostname=None):\n \"\"\"Convert this `IOStream` to an `SSLIOStream`.\n\n This enables protocols that begin in clear-text mode and\n switch to SSL after some initial negotiation (such as the\n ``STARTTLS`` extension to SMTP and IMAP).\n\n This method cannot be used if there are outstanding reads\n or writes on the stream, or if there is any data in the\n IOStream's buffer (data in the operating system's socket\n buffer is allowed). This means it must generally be used\n immediately after reading or writing the last clear-text\n data. It can also be used immediately after connecting,\n before any reads or writes.\n\n The ``ssl_options`` argument may be either a dictionary\n of options or an `ssl.SSLContext`. If a ``server_hostname``\n is given, it will be used for certificate verification\n (as configured in the ``ssl_options``).\n\n This method returns a `.Future` whose result is the new\n `SSLIOStream`. After this method has been called,\n any other operation on the original stream is undefined.\n\n If a close callback is defined on this stream, it will be\n transferred to the new stream.\n\n .. versionadded:: 4.0\n \"\"\"\n if (self._read_callback or self._read_future or\n self._write_callback or self._write_future or\n self._connect_callback or self._connect_future or\n self._pending_callbacks or self._closed or\n self._read_buffer or self._write_buffer):\n raise ValueError(\"IOStream is not idle; cannot convert to SSL\")\n if ssl_options is None:\n ssl_options = {}\n\n socket = self.socket\n self.io_loop.remove_handler(socket)\n self.socket = None\n socket = ssl_wrap_socket(socket, ssl_options,\n server_hostname=server_hostname,\n server_side=server_side,\n do_handshake_on_connect=False)\n orig_close_callback = self._close_callback\n self._close_callback = None\n\n future = TracebackFuture()\n ssl_stream = SSLIOStream(socket, ssl_options=ssl_options,\n io_loop=self.io_loop)\n # Wrap the original close callback so we can fail our Future as well.\n # If we had an \"unwrap\" counterpart to this method we would need\n # to restore the original callback after our Future resolves\n # so that repeated wrap/unwrap calls don't build up layers.\n def close_callback():\n if not future.done():\n future.set_exception(ssl_stream.error or StreamClosedError())\n if orig_close_callback is not None:\n orig_close_callback()\n ssl_stream.set_close_callback(close_callback)\n ssl_stream._ssl_connect_callback = lambda: future.set_result(ssl_stream)\n ssl_stream.max_buffer_size = self.max_buffer_size\n ssl_stream.read_chunk_size = self.read_chunk_size\n return future\n\n def _handle_connect(self):\n err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)\n if err != 0:\n self.error = socket.error(err, os.strerror(err))\n # IOLoop implementations may vary: some of them return\n # an error state before the socket becomes writable, so\n # in that case a connection failure would be handled by the\n # error path in _handle_events instead of here.\n if self._connect_future is None:\n gen_log.warning(\"Connect error on fd %s: %s\",\n self.socket.fileno(), errno.errorcode[err])\n self.close()\n return\n if self._connect_callback is not None:\n callback = self._connect_callback\n self._connect_callback = None\n self._run_callback(callback)\n if self._connect_future is not None:\n future = self._connect_future\n self._connect_future = None\n future.set_result(self)\n self._connecting = False\n\n def set_nodelay(self, value):\n if (self.socket is not None and\n self.socket.family in (socket.AF_INET, socket.AF_INET6)):\n try:\n self.socket.setsockopt(socket.IPPROTO_TCP,\n socket.TCP_NODELAY, 1 if value else 0)\n except socket.error as e:\n # Sometimes setsockopt will fail if the socket is closed\n # at the wrong time. This can happen with HTTPServer\n # resetting the value to false between requests.\n if e.errno not in (errno.EINVAL, errno.ECONNRESET):\n raise\n\nclass SSLIOStream(IOStream):\n \"\"\"A utility class to write to and read from a non-blocking SSL socket.\n\n If the socket passed to the constructor is already connected,\n it should be wrapped with::\n\n ssl.wrap_socket(sock, do_handshake_on_connect=False, **kwargs)\n\n before constructing the `SSLIOStream`. Unconnected sockets will be\n wrapped when `IOStream.connect` is finished.\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"The ``ssl_options`` keyword argument may either be a dictionary\n of keywords arguments for `ssl.wrap_socket`, or an `ssl.SSLContext`\n object.\n \"\"\"\n self._ssl_options = kwargs.pop('ssl_options', {})\n super(SSLIOStream, self).__init__(*args, **kwargs)\n self._ssl_accepting = True\n self._handshake_reading = False\n self._handshake_writing = False\n self._ssl_connect_callback = None\n self._server_hostname = None\n\n # If the socket is already connected, attempt to start the handshake.\n try:\n self.socket.getpeername()\n except socket.error:\n pass\n else:\n # Indirectly start the handshake, which will run on the next\n # IOLoop iteration and then the real IO state will be set in\n # _handle_events.\n self._add_io_state(self.io_loop.WRITE)\n\n def reading(self):\n return self._handshake_reading or super(SSLIOStream, self).reading()\n\n def writing(self):\n return self._handshake_writing or super(SSLIOStream, self).writing()\n\n def _do_ssl_handshake(self):\n # Based on code from test_ssl.py in the python stdlib\n try:\n self._handshake_reading = False\n self._handshake_writing = False\n self.socket.do_handshake()\n except ssl.SSLError as err:\n if err.args[0] == ssl.SSL_ERROR_WANT_READ:\n self._handshake_reading = True\n return\n elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:\n self._handshake_writing = True\n return\n elif err.args[0] in (ssl.SSL_ERROR_EOF,\n ssl.SSL_ERROR_ZERO_RETURN):\n return self.close(exc_info=True)\n elif err.args[0] == ssl.SSL_ERROR_SSL:\n try:\n peer = self.socket.getpeername()\n except Exception:\n peer = '(not connected)'\n gen_log.warning(\"SSL Error on %s %s: %s\",\n self.socket.fileno(), peer, err)\n return self.close(exc_info=True)\n raise\n except socket.error as err:\n # Some port scans (e.g. nmap in -sT mode) have been known\n # to cause do_handshake to raise EBADF, so make that error\n # quiet as well.\n # https://groups.google.com/forum/?fromgroups#!topic/python-tornado/ApucKJat1_0\n if (err.args[0] in _ERRNO_CONNRESET or\n err.args[0] == errno.EBADF):\n return self.close(exc_info=True)\n raise\n except AttributeError:\n # On Linux, if the connection was reset before the call to\n # wrap_socket, do_handshake will fail with an\n # AttributeError.\n return self.close(exc_info=True)\n else:\n self._ssl_accepting = False\n if not self._verify_cert(self.socket.getpeercert()):\n self.close()\n return\n if self._ssl_connect_callback is not None:\n callback = self._ssl_connect_callback\n self._ssl_connect_callback = None\n self._run_callback(callback)\n\n def _verify_cert(self, peercert):\n \"\"\"Returns True if peercert is valid according to the configured\n validation mode and hostname.\n\n The ssl handshake already tested the certificate for a valid\n CA signature; the only thing that remains is to check\n the hostname.\n \"\"\"\n if isinstance(self._ssl_options, dict):\n verify_mode = self._ssl_options.get('cert_reqs', ssl.CERT_NONE)\n elif isinstance(self._ssl_options, ssl.SSLContext):\n verify_mode = self._ssl_options.verify_mode\n assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED, ssl.CERT_OPTIONAL)\n if verify_mode == ssl.CERT_NONE or self._server_hostname is None:\n return True\n cert = self.socket.getpeercert()\n if cert is None and verify_mode == ssl.CERT_REQUIRED:\n gen_log.warning(\"No SSL certificate given\")\n return False\n try:\n ssl_match_hostname(peercert, self._server_hostname)\n except SSLCertificateError:\n gen_log.warning(\"Invalid SSL certificate\", exc_info=True)\n return False\n else:\n return True\n\n def _handle_read(self):\n if self._ssl_accepting:\n self._do_ssl_handshake()\n return\n super(SSLIOStream, self)._handle_read()\n\n def _handle_write(self):\n if self._ssl_accepting:\n self._do_ssl_handshake()\n return\n super(SSLIOStream, self)._handle_write()\n\n def connect(self, address, callback=None, server_hostname=None):\n # Save the user's callback and run it after the ssl handshake\n # has completed.\n self._ssl_connect_callback = stack_context.wrap(callback)\n self._server_hostname = server_hostname\n # Note: Since we don't pass our callback argument along to\n # super.connect(), this will always return a Future.\n # This is harmless, but a bit less efficient than it could be.\n return super(SSLIOStream, self).connect(address, callback=None)\n\n def _handle_connect(self):\n # Call the superclass method to check for errors.\n super(SSLIOStream, self)._handle_connect()\n if self.closed():\n return\n # When the connection is complete, wrap the socket for SSL\n # traffic. Note that we do this by overriding _handle_connect\n # instead of by passing a callback to super().connect because\n # user callbacks are enqueued asynchronously on the IOLoop,\n # but since _handle_events calls _handle_connect immediately\n # followed by _handle_write we need this to be synchronous.\n #\n # The IOLoop will get confused if we swap out self.socket while the\n # fd is registered, so remove it now and re-register after\n # wrap_socket().\n self.io_loop.remove_handler(self.socket)\n old_state = self._state\n self._state = None\n self.socket = ssl_wrap_socket(self.socket, self._ssl_options,\n server_hostname=self._server_hostname,\n do_handshake_on_connect=False)\n self._add_io_state(old_state)\n\n def read_from_fd(self):\n if self._ssl_accepting:\n # If the handshake hasn't finished yet, there can't be anything\n # to read (attempting to read may or may not raise an exception\n # depending on the SSL version)\n return None\n try:\n # SSLSocket objects have both a read() and recv() method,\n # while regular sockets only have recv().\n # The recv() method blocks (at least in python 2.6) if it is\n # called when there is nothing to read, so we have to use\n # read() instead.\n chunk = self.socket.read(self.read_chunk_size)\n except ssl.SSLError as e:\n # SSLError is a subclass of socket.error, so this except\n # block must come first.\n if e.args[0] == ssl.SSL_ERROR_WANT_READ:\n return None\n else:\n raise\n except socket.error as e:\n if e.args[0] in _ERRNO_WOULDBLOCK:\n return None\n else:\n raise\n if not chunk:\n self.close()\n return None\n return chunk\n\nclass PipeIOStream(BaseIOStream):\n \"\"\"Pipe-based `IOStream` implementation.\n\n The constructor takes an integer file descriptor (such as one returned\n by `os.pipe`) rather than an open file object. Pipes are generally\n one-way, so a `PipeIOStream` can be used for reading or writing but not\n both.\n \"\"\"\n def __init__(self, fd, *args, **kwargs):\n self.fd = fd\n _set_nonblocking(fd)\n super(PipeIOStream, self).__init__(*args, **kwargs)\n\n def fileno(self):\n return self.fd\n\n def close_fd(self):\n os.close(self.fd)\n\n def write_to_fd(self, data):\n return os.write(self.fd, data)\n\n def read_from_fd(self):\n try:\n chunk = os.read(self.fd, self.read_chunk_size)\n except (IOError, OSError) as e:\n if errno_from_exception(e) in _ERRNO_WOULDBLOCK:\n return None\n elif errno_from_exception(e) == errno.EBADF:\n # If the writing half of a pipe is closed, select will\n # report it as readable but reads will fail with EBADF.\n self.close(exc_info=True)\n return None\n else:\n raise\n if not chunk:\n self.close()\n return None\n return chunk\n\ndef _double_prefix(deque):\n \"\"\"Grow by doubling, but don't split the second chunk just because the\n first one is small.\n \"\"\"\n new_len = max(len(deque[0]) * 2,\n (len(deque[0]) + len(deque[1])))\n _merge_prefix(deque, new_len)\n\ndef _merge_prefix(deque, size):\n \"\"\"Replace the first entries in a deque of strings with a single\n string of up to size bytes.\n\n >>> d = collections.deque(['abc', 'de', 'fghi', 'j'])\n >>> _merge_prefix(d, 5); print(d)\n deque(['abcde', 'fghi', 'j'])\n\n Strings will be split as necessary to reach the desired size.\n >>> _merge_prefix(d, 7); print(d)\n deque(['abcdefg', 'hi', 'j'])\n\n >>> _merge_prefix(d, 3); print(d)\n deque(['abc', 'defg', 'hi', 'j'])\n\n >>> _merge_prefix(d, 100); print(d)\n deque(['abcdefghij'])\n \"\"\"\n if len(deque) == 1 and len(deque[0]) <= size:\n return\n prefix = []\n remaining = size\n while deque and remaining > 0:\n chunk = deque.popleft()\n if len(chunk) > remaining:\n deque.appendleft(chunk[remaining:])\n chunk = chunk[:remaining]\n prefix.append(chunk)\n remaining -= len(chunk)\n # This data structure normally just contains byte strings, but\n # the unittest gets messy if it doesn't use the default str() type,\n # so do the merge based on the type of data that's actually present.\n if prefix:\n deque.appendleft(type(prefix[0])().join(prefix))\n if not deque:\n deque.appendleft(b\"\")\n\ndef doctests():\n import doctest\n return doctest.DocTestSuite()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_sysadmin.py from tiagochiavericosta/edx-platform (path: lms/djangoapps/dashboard/tests/test_sysadmin.py)."}, {"role": "assistant", "content": "# lms/djangoapps/dashboard/tests/test_sysadmin.py (from tiagochiavericosta/edx-platform, license: agpl-3.0)\n\n\"\"\"\nProvide tests for sysadmin dashboard feature in sysadmin.py\n\"\"\"\nimport glob\nimport os\nimport re\nimport shutil\nimport unittest\nfrom util.date_utils import get_time_display, DEFAULT_DATE_TIME_FORMAT\nfrom nose.plugins.attrib import attr\n\nfrom django.conf import settings\nfrom django.contrib.auth.hashers import check_password\nfrom django.contrib.auth.models import User\nfrom django.core.urlresolvers import reverse\nfrom django.test.client import Client\nfrom django.test.utils import override_settings\nfrom django.utils.timezone import utc as UTC\nfrom django.utils.translation import ugettext as _\nimport mongoengine\nfrom opaque_keys.edx.locations import SlashSeparatedCourseKey\n\nfrom xmodule.modulestore.tests.django_utils import TEST_DATA_XML_MODULESTORE\n\nfrom dashboard.models import CourseImportLog\nfrom dashboard.sysadmin import Users\nfrom dashboard.git_import import GitImportError\nfrom datetime import datetime\nfrom external_auth.models import ExternalAuthMap\nfrom student.roles import CourseStaffRole, GlobalStaff\nfrom student.tests.factories import UserFactory\nfrom xmodule.modulestore.django import modulestore\nfrom xmodule.modulestore.tests.django_utils import ModuleStoreTestCase\nfrom xmodule.modulestore.tests.mongo_connection import MONGO_PORT_NUM, MONGO_HOST\n\nTEST_MONGODB_LOG = {\n 'host': MONGO_HOST,\n 'port': MONGO_PORT_NUM,\n 'user': '',\n 'password': '',\n 'db': 'test_xlog',\n}\n\nFEATURES_WITH_SSL_AUTH = settings.FEATURES.copy()\nFEATURES_WITH_SSL_AUTH['AUTH_USE_CERTIFICATES'] = True\n\nclass SysadminBaseTestCase(ModuleStoreTestCase):\n \"\"\"\n Base class with common methods used in XML and Mongo tests\n \"\"\"\n\n TEST_REPO = 'https://github.com/mitocw/edx4edx_lite.git'\n TEST_BRANCH = 'testing_do_not_delete'\n TEST_BRANCH_COURSE = SlashSeparatedCourseKey('MITx', 'edx4edx_branch', 'edx4edx')\n\n def setUp(self):\n \"\"\"Setup test case by adding primary user.\"\"\"\n super(SysadminBaseTestCase, self).setUp(create_user=False)\n self.user = UserFactory.create(username='test_user',\n email='test_user+sysadmin@edx.org',\n password='foo')\n self.client = Client()\n\n def _setstaff_login(self):\n \"\"\"Makes the test user staff and logs them in\"\"\"\n GlobalStaff().add_users(self.user)\n self.client.login(username=self.user.username, password='foo')\n\n def _add_edx4edx(self, branch=None):\n \"\"\"Adds the edx4edx sample course\"\"\"\n post_dict = {'repo_location': self.TEST_REPO, 'action': 'add_course', }\n if branch:\n post_dict['repo_branch'] = branch\n return self.client.post(reverse('sysadmin_courses'), post_dict)\n\n def _rm_edx4edx(self):\n \"\"\"Deletes the sample course from the XML store\"\"\"\n def_ms = modulestore()\n course_path = '{0}/edx4edx_lite'.format(\n os.path.abspath(settings.DATA_DIR))\n try:\n # using XML store\n course = def_ms.courses.get(course_path, None)\n except AttributeError:\n # Using mongo store\n course = def_ms.get_course(SlashSeparatedCourseKey('MITx', 'edx4edx', 'edx4edx'))\n\n # Delete git loaded course\n response = self.client.post(\n reverse('sysadmin_courses'),\n {\n 'course_id': course.id.to_deprecated_string(),\n 'action': 'del_course',\n }\n )\n self.addCleanup(self._rm_glob, '{0}_deleted_*'.format(course_path))\n\n return response\n\n def _rm_glob(self, path):\n \"\"\"\n Create a shell expansion of passed in parameter and iteratively\n remove them. Must only expand to directories.\n \"\"\"\n for path in glob.glob(path):\n shutil.rmtree(path)\n\n def _mkdir(self, path):\n \"\"\"\n Create directory and add the cleanup for it.\n \"\"\"\n os.mkdir(path)\n self.addCleanup(shutil.rmtree, path)\n\n@attr('shard_1')\n@unittest.skipUnless(settings.FEATURES.get('ENABLE_SYSADMIN_DASHBOARD'),\n \"ENABLE_SYSADMIN_DASHBOARD not set\")\n@override_settings(GIT_IMPORT_WITH_XMLMODULESTORE=True)\nclass TestSysadmin(SysadminBaseTestCase):\n \"\"\"\n Test sysadmin dashboard features using XMLModuleStore\n \"\"\"\n MODULESTORE = TEST_DATA_XML_MODULESTORE\n\n def test_staff_access(self):\n \"\"\"Test access controls.\"\"\"\n\n test_views = ['sysadmin', 'sysadmin_courses', 'sysadmin_staffing', ]\n for view in test_views:\n response = self.client.get(reverse(view))\n self.assertEqual(response.status_code, 302)\n\n self.user.is_staff = False\n self.user.save()\n\n logged_in = self.client.login(username=self.user.username,\n password='foo')\n self.assertTrue(logged_in)\n\n for view in test_views:\n response = self.client.get(reverse(view))\n self.assertEqual(response.status_code, 404)\n\n response = self.client.get(reverse('gitlogs'))\n self.assertEqual(response.status_code, 404)\n\n self.user.is_staff = True\n self.user.save()\n\n self.client.logout()\n self.client.login(username=self.user.username, password='foo')\n\n for view in test_views:\n response = self.client.get(reverse(view))\n self.assertTrue(response.status_code, 200)\n\n response = self.client.get(reverse('gitlogs'))\n self.assertTrue(response.status_code, 200)\n\n def test_user_mod(self):\n \"\"\"Create and delete a user\"\"\"\n\n self._setstaff_login()\n\n self.client.login(username=self.user.username, password='foo')\n\n # Create user tests\n\n # No uname\n response = self.client.post(reverse('sysadmin'),\n {'action': 'create_user',\n 'student_fullname': 'blah',\n 'student_password': 'foozor', })\n self.assertIn('Must provide username', response.content.decode('utf-8'))\n # no full name\n response = self.client.post(reverse('sysadmin'),\n {'action': 'create_user',\n 'student_uname': 'test_cuser+sysadmin@edx.org',\n 'student_password': 'foozor', })\n self.assertIn('Must provide full name', response.content.decode('utf-8'))\n\n # Test create valid user\n self.client.post(reverse('sysadmin'),\n {'action': 'create_user',\n 'student_uname': 'test_cuser+sysadmin@edx.org',\n 'student_fullname': 'test cuser',\n 'student_password': 'foozor', })\n\n self.assertIsNotNone(\n User.objects.get(username='test_cuser+sysadmin@edx.org',\n email='test_cuser+sysadmin@edx.org'))\n\n # login as new user to confirm\n self.assertTrue(self.client.login(\n username='test_cuser+sysadmin@edx.org', password='foozor'))\n\n self.client.logout()\n self.client.login(username=self.user.username, password='foo')\n\n # Delete user tests\n\n # Try no username\n response = self.client.post(reverse('sysadmin'),\n {'action': 'del_user', })\n self.assertIn('Must provide username', response.content.decode('utf-8'))\n\n # Try bad usernames\n response = self.client.post(reverse('sysadmin'),\n {'action': 'del_user',\n 'student_uname': 'flabbergast@example.com',\n 'student_fullname': 'enigma jones', })\n self.assertIn('Cannot find user with email address', response.content.decode('utf-8'))\n\n response = self.client.post(reverse('sysadmin'),\n {'action': 'del_user',\n 'student_uname': 'flabbergast',\n 'student_fullname': 'enigma jones', })\n self.assertIn('Cannot find user with username', response.content.decode('utf-8'))\n\n self.client.post(reverse('sysadmin'),\n {'action': 'del_user',\n 'student_uname': 'test_cuser+sysadmin@edx.org',\n 'student_fullname': 'test cuser', })\n\n self.assertEqual(0, len(User.objects.filter(\n username='test_cuser+sysadmin@edx.org',\n email='test_cuser+sysadmin@edx.org')))\n\n self.assertEqual(1, len(User.objects.all()))\n\n def test_user_csv(self):\n \"\"\"Download and validate user CSV\"\"\"\n\n num_test_users = 100\n self._setstaff_login()\n\n # Stuff full of users to test streaming\n for user_num in xrange(num_test_users):\n Users().create_user('testingman_with_long_name{}'.format(user_num),\n 'test test')\n\n response = self.client.post(reverse('sysadmin'),\n {'action': 'download_users', })\n\n self.assertIn('attachment', response['Content-Disposition'])\n self.assertEqual('text/csv', response['Content-Type'])\n self.assertIn('test_user', response.content)\n self.assertTrue(num_test_users + 2, len(response.content.splitlines()))\n\n # Clean up\n User.objects.filter(\n username__startswith='testingman_with_long_name').delete()\n\n @override_settings(FEATURES=FEATURES_WITH_SSL_AUTH)\n def test_authmap_repair(self):\n \"\"\"Run authmap check and repair\"\"\"\n\n self._setstaff_login()\n\n Users().create_user('test0', 'test test')\n # Will raise exception, so no assert needed\n eamap = ExternalAuthMap.objects.get(external_name='test test')\n mitu = User.objects.get(username='test0')\n\n self.assertTrue(check_password(eamap.internal_password, mitu.password))\n mitu.set_password('not autogenerated')\n mitu.save()\n self.assertFalse(check_password(eamap.internal_password, mitu.password))\n\n # Create really non user AuthMap\n ExternalAuthMap(external_id='ll',\n external_domain='ll',\n external_credentials='{}',\n external_email='a@b.c',\n external_name='c',\n internal_password='').save()\n\n response = self.client.post(reverse('sysadmin'),\n {'action': 'repair_eamap', })\n\n self.assertIn('{0} test0'.format('Failed in authenticating'),\n response.content)\n self.assertIn('fixed password', response.content.decode('utf-8'))\n\n self.assertTrue(self.client.login(username='test0',\n password=eamap.internal_password))\n\n # Check for all OK\n self._setstaff_login()\n response = self.client.post(reverse('sysadmin'),\n {'action': 'repair_eamap', })\n self.assertIn('All ok!', response.content.decode('utf-8'))\n\n def test_xml_course_add_delete(self):\n \"\"\"add and delete course from xml module store\"\"\"\n\n self._setstaff_login()\n\n # Try bad git repo\n response = self.client.post(reverse('sysadmin_courses'), {\n 'repo_location': 'github.com/mitocw/edx4edx_lite',\n 'action': 'add_course', })\n self.assertIn(_(\"The git repo location should end with '.git', \"\n \"and be a valid url\"), response.content.decode('utf-8'))\n\n response = self.client.post(reverse('sysadmin_courses'), {\n 'repo_location': 'http://example.com/not_real.git',\n 'action': 'add_course', })\n self.assertIn('Unable to clone or pull repository',\n response.content.decode('utf-8'))\n # Create git loaded course\n response = self._add_edx4edx()\n\n def_ms = modulestore()\n\n self.assertEqual('xml', def_ms.get_modulestore_type(None))\n course = def_ms.courses.get('{0}/edx4edx_lite'.format(\n os.path.abspath(settings.DATA_DIR)), None)\n self.assertIsNotNone(course)\n\n # Delete a course\n self._rm_edx4edx()\n course = def_ms.courses.get('{0}/edx4edx_lite'.format(\n os.path.abspath(settings.DATA_DIR)), None)\n self.assertIsNone(course)\n\n # Load a bad git branch\n response = self._add_edx4edx('asdfasdfasdf')\n self.assertIn(GitImportError.REMOTE_BRANCH_MISSING,\n response.content.decode('utf-8'))\n\n # Load a course from a git branch\n self._add_edx4edx(self.TEST_BRANCH)\n course = def_ms.courses.get('{0}/edx4edx_lite'.format(\n os.path.abspath(settings.DATA_DIR)), None)\n self.assertIsNotNone(course)\n self.assertEqual(self.TEST_BRANCH_COURSE, course.id)\n self._rm_edx4edx()\n\n # Try and delete a non-existent course\n response = self.client.post(reverse('sysadmin_courses'),\n {'course_id': 'foobar/foo/blah',\n 'action': 'del_course', })\n self.assertIn('Error - cannot get course with ID',\n response.content.decode('utf-8'))\n\n @override_settings(GIT_IMPORT_WITH_XMLMODULESTORE=False)\n def test_xml_safety_flag(self):\n \"\"\"Make sure the settings flag to disable xml imports is working\"\"\"\n\n self._setstaff_login()\n response = self._add_edx4edx()\n self.assertIn('GIT_IMPORT_WITH_XMLMODULESTORE', response.content)\n\n def_ms = modulestore()\n course = def_ms.courses.get('{0}/edx4edx_lite'.format(\n os.path.abspath(settings.DATA_DIR)), None)\n self.assertIsNone(course)\n\n def test_git_pull(self):\n \"\"\"Make sure we can pull\"\"\"\n\n self._setstaff_login()\n\n response = self._add_edx4edx()\n response = self._add_edx4edx()\n self.assertIn(_(\"The course {0} already exists in the data directory! \"\n \"(reloading anyway)\").format('edx4edx_lite'),\n response.content.decode('utf-8'))\n self._rm_edx4edx()\n\n def test_staff_csv(self):\n \"\"\"Download and validate staff CSV\"\"\"\n\n self._setstaff_login()\n self._add_edx4edx()\n\n def_ms = modulestore()\n course = def_ms.get_course(SlashSeparatedCourseKey('MITx', 'edx4edx', 'edx4edx'))\n CourseStaffRole(course.id).add_users(self.user)\n\n response = self.client.post(reverse('sysadmin_staffing'),\n {'action': 'get_staff_csv', })\n self.assertIn('attachment', response['Content-Disposition'])\n self.assertEqual('text/csv', response['Content-Type'])\n columns = ['course_id', 'role', 'username',\n 'email', 'full_name', ]\n self.assertIn(','.join('\"' + c + '\"' for c in columns),\n response.content)\n\n self._rm_edx4edx()\n\n def test_enrollment_page(self):\n \"\"\"\n Adds a course and makes sure that it shows up on the staffing and\n enrollment page\n \"\"\"\n\n self._setstaff_login()\n self._add_edx4edx()\n response = self.client.get(reverse('sysadmin_staffing'))\n self.assertIn('edx4edx', response.content)\n self._rm_edx4edx()\n\n@attr('shard_1')\n@override_settings(MONGODB_LOG=TEST_MONGODB_LOG)\n@unittest.skipUnless(settings.FEATURES.get('ENABLE_SYSADMIN_DASHBOARD'),\n \"ENABLE_SYSADMIN_DASHBOARD not set\")\nclass TestSysAdminMongoCourseImport(SysadminBaseTestCase):\n \"\"\"\n Check that importing into the mongo module store works\n \"\"\"\n\n @classmethod\n def tearDownClass(cls):\n \"\"\"Delete mongo log entries after test.\"\"\"\n super(TestSysAdminMongoCourseImport, cls).tearDownClass()\n try:\n mongoengine.connect(TEST_MONGODB_LOG['db'])\n CourseImportLog.objects.all().delete()\n except mongoengine.connection.ConnectionError:\n pass\n\n def _setstaff_login(self):\n \"\"\"\n Makes the test user staff and logs them in\n \"\"\"\n\n self.user.is_staff = True\n self.user.save()\n\n self.client.login(username=self.user.username, password='foo')\n\n def test_missing_repo_dir(self):\n \"\"\"\n Ensure that we handle a missing repo dir\n \"\"\"\n\n self._setstaff_login()\n\n if os.path.isdir(getattr(settings, 'GIT_REPO_DIR')):\n shutil.rmtree(getattr(settings, 'GIT_REPO_DIR'))\n\n # Create git loaded course\n response = self._add_edx4edx()\n self.assertIn(GitImportError.NO_DIR,\n response.content.decode('UTF-8'))\n\n def test_mongo_course_add_delete(self):\n \"\"\"\n This is the same as TestSysadmin.test_xml_course_add_delete,\n but it uses a mongo store\n \"\"\"\n\n self._setstaff_login()\n self._mkdir(getattr(settings, 'GIT_REPO_DIR'))\n\n def_ms = modulestore()\n self.assertFalse('xml' == def_ms.get_modulestore_type(None))\n\n self._add_edx4edx()\n course = def_ms.get_course(SlashSeparatedCourseKey('MITx', 'edx4edx', 'edx4edx'))\n self.assertIsNotNone(course)\n\n self._rm_edx4edx()\n course = def_ms.get_course(SlashSeparatedCourseKey('MITx', 'edx4edx', 'edx4edx'))\n self.assertIsNone(course)\n\n def test_course_info(self):\n \"\"\"\n Check to make sure we are getting git info for courses\n \"\"\"\n # Regex of first 3 columns of course information table row for\n # test course loaded from git. Would not have sha1 if\n # git_info_for_course failed.\n table_re = re.compile(r\"\"\"\n \\s+\n edX\\sAuthor\\sCourse\\s+ # expected test git course name\n MITx/edx4edx/edx4edx\\s+ # expected test git course_id\n [a-fA-F\\d]{40} # git sha1 hash\n \"\"\", re.VERBOSE)\n\n self._setstaff_login()\n self._mkdir(getattr(settings, 'GIT_REPO_DIR'))\n\n # Make sure we don't have any git hashes on the page\n response = self.client.get(reverse('sysadmin_courses'))\n self.assertNotRegexpMatches(response.content, table_re)\n\n # Now add the course and make sure it does match\n response = self._add_edx4edx()\n self.assertRegexpMatches(response.content, table_re)\n\n def test_gitlogs(self):\n \"\"\"\n Create a log entry and make sure it exists\n \"\"\"\n\n self._setstaff_login()\n self._mkdir(getattr(settings, 'GIT_REPO_DIR'))\n\n self._add_edx4edx()\n response = self.client.get(reverse('gitlogs'))\n\n # Check that our earlier import has a log with a link to details\n self.assertIn('/gitlogs/MITx/edx4edx/edx4edx', response.content)\n\n response = self.client.get(\n reverse('gitlogs_detail', kwargs={\n 'course_id': 'MITx/edx4edx/edx4edx'}))\n\n self.assertIn('======> IMPORTING course',\n response.content)\n\n self._rm_edx4edx()\n\n def test_gitlog_date(self):\n \"\"\"\n Make sure the date is timezone-aware and being converted/formatted\n properly.\n \"\"\"\n\n tz_names = [\n 'America/New_York', # UTC - 5\n 'Asia/Pyongyang', # UTC + 9\n 'Europe/London', # UTC\n 'Canada/Yukon', # UTC - 8\n 'Europe/Moscow', # UTC + 4\n ]\n tz_format = DEFAULT_DATE_TIME_FORMAT\n\n self._setstaff_login()\n self._mkdir(getattr(settings, 'GIT_REPO_DIR'))\n\n self._add_edx4edx()\n date = CourseImportLog.objects.first().created.replace(tzinfo=UTC)\n\n for timezone in tz_names:\n with (override_settings(TIME_ZONE=timezone)):\n date_text = get_time_display(date, tz_format, settings.TIME_ZONE)\n response = self.client.get(reverse('gitlogs'))\n self.assertIn(date_text, response.content.decode('UTF-8'))\n\n self._rm_edx4edx()\n\n def test_gitlog_bad_course(self):\n \"\"\"\n Make sure we gracefully handle courses that don't exist.\n \"\"\"\n self._setstaff_login()\n response = self.client.get(\n reverse('gitlogs_detail', kwargs={\n 'course_id': 'Not/Real/Testing'}))\n self.assertEqual(404, response.status_code)\n\n def test_gitlog_no_logs(self):\n \"\"\"\n Make sure the template behaves well when rendered despite there not being any logs.\n (This is for courses imported using methods other than the git_add_course command)\n \"\"\"\n\n self._setstaff_login()\n self._mkdir(getattr(settings, 'GIT_REPO_DIR'))\n\n self._add_edx4edx()\n\n # Simulate a lack of git import logs\n import_logs = CourseImportLog.objects.all()\n import_logs.delete()\n\n response = self.client.get(\n reverse('gitlogs_detail', kwargs={\n 'course_id': 'MITx/edx4edx/edx4edx'\n })\n )\n self.assertIn(\n 'No git import logs have been recorded for this course.',\n response.content\n )\n\n self._rm_edx4edx()\n\n def test_gitlog_pagination_out_of_range_invalid(self):\n \"\"\"\n Make sure the pagination behaves properly when the requested page is out\n of range.\n \"\"\"\n\n self._setstaff_login()\n\n mongoengine.connect(TEST_MONGODB_LOG['db'])\n\n for _ in xrange(15):\n CourseImportLog(\n course_id=SlashSeparatedCourseKey(\"test\", \"test\", \"test\"),\n location=\"location\",\n import_log=\"import_log\",\n git_log=\"git_log\",\n repo_dir=\"repo_dir\",\n created=datetime.now()\n ).save()\n\n for page, expected in [(-1, 1), (1, 1), (2, 2), (30, 2), ('abc', 1)]:\n response = self.client.get(\n '{}?page={}'.format(\n reverse('gitlogs'),\n page\n )\n )\n self.assertIn(\n 'Page {} of 2'.format(expected),\n response.content\n )\n\n CourseImportLog.objects.delete()\n\n def test_gitlog_courseteam_access(self):\n \"\"\"\n Ensure course team users are allowed to access only their own course.\n \"\"\"\n\n self._mkdir(getattr(settings, 'GIT_REPO_DIR'))\n\n self._setstaff_login()\n self._add_edx4edx()\n self.user.is_staff = False\n self.user.save()\n logged_in = self.client.login(username=self.user.username,\n password='foo')\n response = self.client.get(reverse('gitlogs'))\n # Make sure our non privileged user doesn't have access to all logs\n self.assertEqual(response.status_code, 404)\n # Or specific logs\n response = self.client.get(reverse('gitlogs_detail', kwargs={\n 'course_id': 'MITx/edx4edx/edx4edx'\n }))\n self.assertEqual(response.status_code, 404)\n\n # Add user as staff in course team\n def_ms = modulestore()\n course = def_ms.get_course(SlashSeparatedCourseKey('MITx', 'edx4edx', 'edx4edx'))\n CourseStaffRole(course.id).add_users(self.user)\n\n self.assertTrue(CourseStaffRole(course.id).has_user(self.user))\n logged_in = self.client.login(username=self.user.username,\n password='foo')\n self.assertTrue(logged_in)\n\n response = self.client.get(\n reverse('gitlogs_detail', kwargs={\n 'course_id': 'MITx/edx4edx/edx4edx'\n }))\n self.assertIn('======> IMPORTING course',\n response.content)\n\n self._rm_edx4edx()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements abstractsequencedcommand.py from windyuuy/opera (path: chromium/src/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/abstractsequencedcommand.py)."}, {"role": "assistant", "content": "# chromium/src/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/abstractsequencedcommand.py (from windyuuy/opera, license: bsd-3-clause)\n\n# Copyright (C) 2010 Google Inc. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport logging\n\nfrom webkitpy.common.system.executive import ScriptError\nfrom webkitpy.tool.commands.stepsequence import StepSequence\nfrom webkitpy.tool.multicommandtool import AbstractDeclarativeCommand\n\n_log = logging.getLogger(__name__)\n\nclass AbstractSequencedCommand(AbstractDeclarativeCommand):\n steps = None\n def __init__(self):\n self._sequence = StepSequence(self.steps)\n AbstractDeclarativeCommand.__init__(self, self._sequence.options())\n\n def _prepare_state(self, options, args, tool):\n return None\n\n def execute(self, options, args, tool):\n try:\n state = self._prepare_state(options, args, tool)\n except ScriptError, e:\n _log.error(e.message_with_output())\n self._exit(e.exit_code or 2)\n\n self._sequence.run_and_handle_errors(tool, options, state)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements __init__.py from edisonlz/fruit (path: web_project/base/site-packages/django_extensions/db/fields/__init__.py)."}, {"role": "assistant", "content": "# web_project/base/site-packages/django_extensions/db/fields/__init__.py (from edisonlz/fruit, license: apache-2.0)\n\n\"\"\"\nDjango Extensions additional model fields\n\"\"\"\nimport re\nimport six\nimport warnings\n\ntry:\n import uuid\n HAS_UUID = True\nexcept ImportError:\n HAS_UUID = False\n\ntry:\n import shortuuid\n HAS_SHORT_UUID = True\nexcept ImportError:\n HAS_SHORT_UUID = False\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.template.defaultfilters import slugify\nfrom django.db.models import DateTimeField, CharField, SlugField\n\ntry:\n from django.utils.timezone import now as datetime_now\n assert datetime_now\nexcept ImportError:\n import datetime\n datetime_now = datetime.datetime.now\n\ntry:\n from django.utils.encoding import force_unicode # NOQA\nexcept ImportError:\n from django.utils.encoding import force_text as force_unicode # NOQA\n\nclass AutoSlugField(SlugField):\n \"\"\" AutoSlugField\n\n By default, sets editable=False, blank=True.\n\n Required arguments:\n\n populate_from\n Specifies which field or list of fields the slug is populated from.\n\n Optional arguments:\n\n separator\n Defines the used separator (default: '-')\n\n overwrite\n If set to True, overwrites the slug on every save (default: False)\n\n Inspired by SmileyChris' Unique Slugify snippet:\n http://www.djangosnippets.org/snippets/690/\n \"\"\"\n def __init__(self, *args, **kwargs):\n kwargs.setdefault('blank', True)\n kwargs.setdefault('editable', False)\n\n populate_from = kwargs.pop('populate_from', None)\n if populate_from is None:\n raise ValueError(\"missing 'populate_from' argument\")\n else:\n self._populate_from = populate_from\n\n self.slugify_function = kwargs.pop('slugify_function', slugify)\n self.separator = kwargs.pop('separator', six.u('-'))\n self.overwrite = kwargs.pop('overwrite', False)\n if not isinstance(self.overwrite, bool):\n raise ValueError(\"'overwrite' argument must be True or False\")\n self.allow_duplicates = kwargs.pop('allow_duplicates', False)\n if not isinstance(self.allow_duplicates, bool):\n raise ValueError(\"'allow_duplicates' argument must be True or False\")\n super(AutoSlugField, self).__init__(*args, **kwargs)\n\n def _slug_strip(self, value):\n \"\"\"\n Cleans up a slug by removing slug separator characters that occur at\n the beginning or end of a slug.\n\n If an alternate separator is used, it will also replace any instances\n of the default '-' separator with the new separator.\n \"\"\"\n re_sep = '(?:-|%s)' % re.escape(self.separator)\n value = re.sub('%s+' % re_sep, self.separator, value)\n return re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value)\n\n def get_queryset(self, model_cls, slug_field):\n for field, model in model_cls._meta.get_fields_with_model():\n if model and field == slug_field:\n return model._default_manager.all()\n return model_cls._default_manager.all()\n\n def slugify_func(self, content):\n if content:\n return self.slugify_function(content)\n return ''\n\n def create_slug(self, model_instance, add):\n # get fields to populate from and slug field to set\n if not isinstance(self._populate_from, (list, tuple)):\n self._populate_from = (self._populate_from, )\n slug_field = model_instance._meta.get_field(self.attname)\n\n if add or self.overwrite:\n # slugify the original field content and set next step to 2\n slug_for_field = lambda field: self.slugify_func(getattr(model_instance, field))\n slug = self.separator.join(map(slug_for_field, self._populate_from))\n next = 2\n else:\n # get slug from the current model instance\n slug = getattr(model_instance, self.attname)\n # model_instance is being modified, and overwrite is False,\n # so instead of doing anything, just return the current slug\n return slug\n\n # strip slug depending on max_length attribute of the slug field\n # and clean-up\n slug_len = slug_field.max_length\n if slug_len:\n slug = slug[:slug_len]\n slug = self._slug_strip(slug)\n original_slug = slug\n\n if self.allow_duplicates:\n return slug\n\n # exclude the current model instance from the queryset used in finding\n # the next valid slug\n queryset = self.get_queryset(model_instance.__class__, slug_field)\n if model_instance.pk:\n queryset = queryset.exclude(pk=model_instance.pk)\n\n # form a kwarg dict used to impliment any unique_together contraints\n kwargs = {}\n for params in model_instance._meta.unique_together:\n if self.attname in params:\n for param in params:\n kwargs[param] = getattr(model_instance, param, None)\n kwargs[self.attname] = slug\n\n # increases the number while searching for the next valid slug\n # depending on the given slug, clean-up\n while not slug or queryset.filter(**kwargs):\n slug = original_slug\n end = '%s%s' % (self.separator, next)\n end_len = len(end)\n if slug_len and len(slug) + end_len > slug_len:\n slug = slug[:slug_len - end_len]\n slug = self._slug_strip(slug)\n slug = '%s%s' % (slug, end)\n kwargs[self.attname] = slug\n next += 1\n return slug\n\n def pre_save(self, model_instance, add):\n value = force_unicode(self.create_slug(model_instance, add))\n setattr(model_instance, self.attname, value)\n return value\n\n def get_internal_type(self):\n return \"SlugField\"\n\n def south_field_triple(self):\n \"Returns a suitable description of this field for South.\"\n # We'll just introspect the _actual_ field.\n from south.modelsinspector import introspector\n field_class = '%s.AutoSlugField' % self.__module__\n args, kwargs = introspector(self)\n kwargs.update({\n 'populate_from': repr(self._populate_from),\n 'separator': repr(self.separator),\n 'overwrite': repr(self.overwrite),\n 'allow_duplicates': repr(self.allow_duplicates),\n })\n # That's our definition!\n return (field_class, args, kwargs)\n\n def deconstruct(self):\n name, path, args, kwargs = super(AutoSlugField, self).deconstruct()\n kwargs['populate_from'] = self._populate_from\n if not self.separator == six.u('-'):\n kwargs['separator'] = self.separator\n if self.overwrite is not False:\n kwargs['overwrite'] = True\n if self.allow_duplicates is not False:\n kwargs['allow_duplicates'] = True\n return name, path, args, kwargs\n\nclass CreationDateTimeField(DateTimeField):\n \"\"\" CreationDateTimeField\n\n By default, sets editable=False, blank=True, default=datetime.now\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n kwargs.setdefault('editable', False)\n kwargs.setdefault('blank', True)\n kwargs.setdefault('default', datetime_now)\n DateTimeField.__init__(self, *args, **kwargs)\n\n def get_internal_type(self):\n return \"DateTimeField\"\n\n def south_field_triple(self):\n \"Returns a suitable description of this field for South.\"\n # We'll just introspect ourselves, since we inherit.\n from south.modelsinspector import introspector\n field_class = \"django.db.models.fields.DateTimeField\"\n args, kwargs = introspector(self)\n return (field_class, args, kwargs)\n\n def deconstruct(self):\n name, path, args, kwargs = super(CreationDateTimeField, self).deconstruct()\n if self.editable is not False:\n kwargs['editable'] = True\n if self.blank is not True:\n kwargs['blank'] = False\n if self.default is not datetime_now:\n kwargs['default'] = self.default\n return name, path, args, kwargs\n\nclass ModificationDateTimeField(CreationDateTimeField):\n \"\"\" ModificationDateTimeField\n\n By default, sets editable=False, blank=True, default=datetime.now\n\n Sets value to datetime.now() on each save of the model.\n \"\"\"\n\n def pre_save(self, model, add):\n value = datetime_now()\n setattr(model, self.attname, value)\n return value\n\n def get_internal_type(self):\n return \"DateTimeField\"\n\n def south_field_triple(self):\n \"Returns a suitable description of this field for South.\"\n # We'll just introspect ourselves, since we inherit.\n from south.modelsinspector import introspector\n field_class = \"django.db.models.fields.DateTimeField\"\n args, kwargs = introspector(self)\n return (field_class, args, kwargs)\n\nclass UUIDVersionError(Exception):\n pass\n\nclass UUIDField(CharField):\n \"\"\" UUIDField\n\n By default uses UUID version 4 (randomly generated UUID).\n\n The field support all uuid versions which are natively supported by the uuid python module, except version 2.\n For more information see: http://docs.python.org/lib/module-uuid.html\n \"\"\"\n DEFAULT_MAX_LENGTH = 36\n\n def __init__(self, verbose_name=None, name=None, auto=True, version=4, node=None, clock_seq=None, namespace=None, uuid_name=None, *args, **kwargs):\n warnings.warn(\"Django 1.8 features a native UUIDField, this UUIDField will be removed after Django 1.7 becomes unsupported.\", DeprecationWarning)\n\n if not HAS_UUID:\n raise ImproperlyConfigured(\"'uuid' module is required for UUIDField. (Do you have Python 2.5 or higher installed ?)\")\n kwargs.setdefault('max_length', self.DEFAULT_MAX_LENGTH)\n if auto:\n self.empty_strings_allowed = False\n kwargs['blank'] = True\n kwargs.setdefault('editable', False)\n self.auto = auto\n self.version = version\n self.node = node\n self.clock_seq = clock_seq\n self.namespace = namespace\n self.uuid_name = uuid_name or name\n super(UUIDField, self).__init__(verbose_name=verbose_name, *args, **kwargs)\n\n def create_uuid(self):\n if not self.version or self.version == 4:\n return uuid.uuid4()\n elif self.version == 1:\n return uuid.uuid1(self.node, self.clock_seq)\n elif self.version == 2:\n raise UUIDVersionError(\"UUID version 2 is not supported.\")\n elif self.version == 3:\n return uuid.uuid3(self.namespace, self.uuid_name)\n elif self.version == 5:\n return uuid.uuid5(self.namespace, self.uuid_name)\n else:\n raise UUIDVersionError(\"UUID version %s is not valid.\" % self.version)\n\n def pre_save(self, model_instance, add):\n value = super(UUIDField, self).pre_save(model_instance, add)\n if self.auto and add and value is None:\n value = force_unicode(self.create_uuid())\n setattr(model_instance, self.attname, value)\n return value\n else:\n if self.auto and not value:\n value = force_unicode(self.create_uuid())\n setattr(model_instance, self.attname, value)\n return value\n\n def formfield(self, **kwargs):\n if self.auto:\n return None\n return super(UUIDField, self).formfield(**kwargs)\n\n def south_field_triple(self):\n \"Returns a suitable description of this field for South.\"\n # We'll just introspect the _actual_ field.\n from south.modelsinspector import introspector\n field_class = \"django.db.models.fields.CharField\"\n args, kwargs = introspector(self)\n # That's our definition!\n return (field_class, args, kwargs)\n\n def deconstruct(self):\n name, path, args, kwargs = super(UUIDField, self).deconstruct()\n if kwargs.get('max_length', None) == self.DEFAULT_MAX_LENGTH:\n del kwargs['max_length']\n if self.auto is not True:\n kwargs['auto'] = self.auto\n if self.version != 4:\n kwargs['version'] = self.version\n if self.node is not None:\n kwargs['node'] = self.node\n if self.clock_seq is not None:\n kwargs['clock_seq'] = self.clock_seq\n if self.namespace is not None:\n kwargs['namespace'] = self.namespace\n if self.uuid_name is not None:\n kwargs['uuid_name'] = self.name\n return name, path, args, kwargs\n\nclass PostgreSQLUUIDField(UUIDField):\n def __init__(self, *args, **kwargs):\n warnings.warn(\"Django 1.8 features a native UUIDField, this UUIDField will be removed after Django 1.7 becomes unsupported.\", DeprecationWarning)\n super(PostgreSQLUUIDField, self).__init__(*args, **kwargs)\n\n def db_type(self, connection=None):\n return \"UUID\"\n\n def get_db_prep_value(self, value, connection, prepared=False):\n if isinstance(value, six.integer_types):\n value = uuid.UUID(int=value)\n elif isinstance(value, (six.string_types, six.binary_type)):\n if len(value) == 16:\n value = uuid.UUID(bytes=value)\n else:\n value = uuid.UUID(value)\n return super(PostgreSQLUUIDField, self).get_db_prep_value(\n value, connection, prepared=False)\n\nclass ShortUUIDField(UUIDField):\n \"\"\" ShortUUIDFied\n\n Generates concise (22 characters instead of 36), unambiguous, URL-safe UUIDs.\n\n Based on `shortuuid`: https://github.com/stochastic-technologies/shortuuid\n \"\"\"\n DEFAULT_MAX_LENGTH = 22\n\n def __init__(self, *args, **kwargs):\n super(ShortUUIDField, self).__init__(*args, **kwargs)\n if not HAS_SHORT_UUID:\n raise ImproperlyConfigured(\"'shortuuid' module is required for ShortUUIDField. (Do you have Python 2.5 or higher installed ?)\")\n kwargs.setdefault('max_length', self.DEFAULT_MAX_LENGTH)\n\n def create_uuid(self):\n if not self.version or self.version == 4:\n return shortuuid.uuid()\n elif self.version == 1:\n return shortuuid.uuid()\n elif self.version == 2:\n raise UUIDVersionError(\"UUID version 2 is not supported.\")\n elif self.version == 3:\n raise UUIDVersionError(\"UUID version 3 is not supported.\")\n elif self.version == 5:\n return shortuuid.uuid(name=self.namespace)\n else:\n raise UUIDVersionError(\"UUID version %s is not valid.\" % self.version)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_event_pipeline.py from openstack/ceilometer (path: ceilometer/tests/unit/test_event_pipeline.py)."}, {"role": "assistant", "content": "# ceilometer/tests/unit/test_event_pipeline.py (from openstack/ceilometer, license: apache-2.0)\n\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport datetime\nimport traceback\nimport uuid\n\nimport fixtures\n\nfrom ceilometer.event import models\nfrom ceilometer.pipeline import base as pipeline\nfrom ceilometer.pipeline import event\nfrom ceilometer import publisher\nfrom ceilometer.publisher import test as test_publisher\nfrom ceilometer import service\nfrom ceilometer.tests import base\n\nclass EventPipelineTestCase(base.BaseTestCase):\n\n def get_publisher(self, conf, url, namespace=''):\n fake_drivers = {'test://': test_publisher.TestPublisher,\n 'new://': test_publisher.TestPublisher,\n 'except://': self.PublisherClassException}\n return fake_drivers[url](conf, url)\n\n class PublisherClassException(publisher.ConfigPublisherBase):\n def publish_samples(self, samples):\n pass\n\n def publish_events(self, events):\n raise Exception()\n\n def setUp(self):\n super(EventPipelineTestCase, self).setUp()\n self.CONF = service.prepare_service([], [])\n\n self.test_event = models.Event(\n message_id=uuid.uuid4(),\n event_type='a',\n generated=datetime.datetime.utcnow(),\n traits=[\n models.Trait('t_text', 1, 'text_trait'),\n models.Trait('t_int', 2, 'int_trait'),\n models.Trait('t_float', 3, 'float_trait'),\n models.Trait('t_datetime', 4, 'datetime_trait')\n ],\n raw={'status': 'started'}\n )\n\n self.test_event2 = models.Event(\n message_id=uuid.uuid4(),\n event_type='b',\n generated=datetime.datetime.utcnow(),\n traits=[\n models.Trait('t_text', 1, 'text_trait'),\n models.Trait('t_int', 2, 'int_trait'),\n models.Trait('t_float', 3, 'float_trait'),\n models.Trait('t_datetime', 4, 'datetime_trait')\n ],\n raw={'status': 'stopped'}\n )\n\n self.useFixture(fixtures.MockPatchObject(\n publisher, 'get_publisher', side_effect=self.get_publisher))\n\n self._setup_pipeline_cfg()\n\n self._reraise_exception = True\n self.useFixture(fixtures.MockPatch(\n 'ceilometer.pipeline.base.LOG.exception',\n side_effect=self._handle_reraise_exception))\n\n def _handle_reraise_exception(self, *args, **kwargs):\n if self._reraise_exception:\n raise Exception(traceback.format_exc())\n\n def _setup_pipeline_cfg(self):\n \"\"\"Setup the appropriate form of pipeline config.\"\"\"\n source = {'name': 'test_source',\n 'events': ['a'],\n 'sinks': ['test_sink']}\n sink = {'name': 'test_sink',\n 'publishers': ['test://']}\n self.pipeline_cfg = {'sources': [source], 'sinks': [sink]}\n\n def _augment_pipeline_cfg(self):\n \"\"\"Augment the pipeline config with an additional element.\"\"\"\n self.pipeline_cfg['sources'].append({\n 'name': 'second_source',\n 'events': ['b'],\n 'sinks': ['second_sink']\n })\n self.pipeline_cfg['sinks'].append({\n 'name': 'second_sink',\n 'publishers': ['new://'],\n })\n\n def _break_pipeline_cfg(self):\n \"\"\"Break the pipeline config with a malformed element.\"\"\"\n self.pipeline_cfg['sources'].append({\n 'name': 'second_source',\n 'events': ['b'],\n 'sinks': ['second_sink']\n })\n self.pipeline_cfg['sinks'].append({\n 'name': 'second_sink',\n 'publishers': ['except'],\n })\n\n def _dup_pipeline_name_cfg(self):\n \"\"\"Break the pipeline config with duplicate pipeline name.\"\"\"\n self.pipeline_cfg['sources'].append({\n 'name': 'test_source',\n 'events': ['a'],\n 'sinks': ['test_sink']\n })\n\n def _set_pipeline_cfg(self, field, value):\n if field in self.pipeline_cfg['sources'][0]:\n self.pipeline_cfg['sources'][0][field] = value\n else:\n self.pipeline_cfg['sinks'][0][field] = value\n\n def _extend_pipeline_cfg(self, field, value):\n if field in self.pipeline_cfg['sources'][0]:\n self.pipeline_cfg['sources'][0][field].extend(value)\n else:\n self.pipeline_cfg['sinks'][0][field].extend(value)\n\n def _unset_pipeline_cfg(self, field):\n if field in self.pipeline_cfg['sources'][0]:\n del self.pipeline_cfg['sources'][0][field]\n else:\n del self.pipeline_cfg['sinks'][0][field]\n\n def _build_and_set_new_pipeline(self):\n name = self.cfg2file(self.pipeline_cfg)\n self.CONF.set_override('event_pipeline_cfg_file', name)\n\n def _exception_create_pipelinemanager(self):\n self._build_and_set_new_pipeline()\n self.assertRaises(pipeline.PipelineException,\n event.EventPipelineManager, self.CONF)\n\n def test_no_events(self):\n self._unset_pipeline_cfg('events')\n self._exception_create_pipelinemanager()\n\n def test_no_name(self):\n self._unset_pipeline_cfg('name')\n self._exception_create_pipelinemanager()\n\n def test_name(self):\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n for pipe in pipeline_manager.pipelines:\n self.assertTrue(pipe.name.startswith('event:'))\n\n def test_no_publishers(self):\n self._unset_pipeline_cfg('publishers')\n self._exception_create_pipelinemanager()\n\n def test_check_events_include_exclude_same(self):\n event_cfg = ['a', '!a']\n self._set_pipeline_cfg('events', event_cfg)\n self._exception_create_pipelinemanager()\n\n def test_check_events_include_exclude(self):\n event_cfg = ['a', '!b']\n self._set_pipeline_cfg('events', event_cfg)\n self._exception_create_pipelinemanager()\n\n def test_check_events_wildcard_included(self):\n event_cfg = ['a', '*']\n self._set_pipeline_cfg('events', event_cfg)\n self._exception_create_pipelinemanager()\n\n def test_check_publishers_invalid_publisher(self):\n publisher_cfg = ['test_invalid']\n self._set_pipeline_cfg('publishers', publisher_cfg)\n\n def test_multiple_included_events(self):\n event_cfg = ['a', 'b']\n self._set_pipeline_cfg('events', event_cfg)\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n\n with pipeline_manager.publisher() as p:\n p([self.test_event])\n\n publisher = pipeline_manager.pipelines[0].publishers[0]\n self.assertEqual(1, len(publisher.events))\n\n with pipeline_manager.publisher() as p:\n p([self.test_event2])\n\n self.assertEqual(2, len(publisher.events))\n self.assertEqual('a', getattr(publisher.events[0], 'event_type'))\n self.assertEqual('b', getattr(publisher.events[1], 'event_type'))\n\n def test_event_non_match(self):\n event_cfg = ['nomatch']\n self._set_pipeline_cfg('events', event_cfg)\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n with pipeline_manager.publisher() as p:\n p([self.test_event])\n\n publisher = pipeline_manager.pipelines[0].publishers[0]\n self.assertEqual(0, len(publisher.events))\n self.assertEqual(0, publisher.calls)\n\n def test_wildcard_event(self):\n event_cfg = ['*']\n self._set_pipeline_cfg('events', event_cfg)\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n with pipeline_manager.publisher() as p:\n p([self.test_event])\n\n publisher = pipeline_manager.pipelines[0].publishers[0]\n self.assertEqual(1, len(publisher.events))\n self.assertEqual('a', getattr(publisher.events[0], 'event_type'))\n\n def test_wildcard_excluded_events(self):\n event_cfg = ['*', '!a']\n self._set_pipeline_cfg('events', event_cfg)\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n pipe = pipeline_manager.pipelines[0]\n self.assertFalse(pipe.source.support_event('a'))\n\n def test_wildcard_excluded_events_not_excluded(self):\n event_cfg = ['*', '!b']\n self._set_pipeline_cfg('events', event_cfg)\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n with pipeline_manager.publisher() as p:\n p([self.test_event])\n publisher = pipeline_manager.pipelines[0].publishers[0]\n self.assertEqual(1, len(publisher.events))\n self.assertEqual('a', getattr(publisher.events[0], 'event_type'))\n\n def test_all_excluded_events_not_excluded(self):\n event_cfg = ['!b', '!c']\n self._set_pipeline_cfg('events', event_cfg)\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n with pipeline_manager.publisher() as p:\n p([self.test_event])\n\n publisher = pipeline_manager.pipelines[0].publishers[0]\n self.assertEqual(1, len(publisher.events))\n self.assertEqual('a', getattr(publisher.events[0], 'event_type'))\n\n def test_all_excluded_events_excluded(self):\n event_cfg = ['!a', '!c']\n self._set_pipeline_cfg('events', event_cfg)\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n pipe = pipeline_manager.pipelines[0]\n self.assertFalse(pipe.source.support_event('a'))\n self.assertTrue(pipe.source.support_event('b'))\n self.assertFalse(pipe.source.support_event('c'))\n\n def test_wildcard_and_excluded_wildcard_events(self):\n event_cfg = ['*', '!compute.*']\n self._set_pipeline_cfg('events', event_cfg)\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n pipe = pipeline_manager.pipelines[0]\n self.assertFalse(pipe.source.\n support_event('compute.instance.create.start'))\n self.assertTrue(pipe.source.support_event('identity.user.create'))\n\n def test_included_event_and_wildcard_events(self):\n event_cfg = ['compute.instance.create.start', 'identity.*']\n self._set_pipeline_cfg('events', event_cfg)\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n pipe = pipeline_manager.pipelines[0]\n self.assertTrue(pipe.source.support_event('identity.user.create'))\n self.assertTrue(pipe.source.\n support_event('compute.instance.create.start'))\n self.assertFalse(pipe.source.\n support_event('compute.instance.create.stop'))\n\n def test_excluded_event_and_excluded_wildcard_events(self):\n event_cfg = ['!compute.instance.create.start', '!identity.*']\n self._set_pipeline_cfg('events', event_cfg)\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n pipe = pipeline_manager.pipelines[0]\n self.assertFalse(pipe.source.support_event('identity.user.create'))\n self.assertFalse(pipe.source.\n support_event('compute.instance.create.start'))\n self.assertTrue(pipe.source.\n support_event('compute.instance.create.stop'))\n\n def test_multiple_pipeline(self):\n self._augment_pipeline_cfg()\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n with pipeline_manager.publisher() as p:\n p([self.test_event, self.test_event2])\n\n publisher = pipeline_manager.pipelines[0].publishers[0]\n self.assertEqual(1, len(publisher.events))\n self.assertEqual(1, publisher.calls)\n self.assertEqual('a', getattr(publisher.events[0], 'event_type'))\n new_publisher = pipeline_manager.pipelines[1].publishers[0]\n self.assertEqual(1, len(new_publisher.events))\n self.assertEqual(1, new_publisher.calls)\n self.assertEqual('b', getattr(new_publisher.events[0], 'event_type'))\n\n def test_multiple_publisher(self):\n self._set_pipeline_cfg('publishers', ['test://', 'new://'])\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n\n with pipeline_manager.publisher() as p:\n p([self.test_event])\n\n publisher = pipeline_manager.pipelines[0].publishers[0]\n new_publisher = pipeline_manager.pipelines[0].publishers[1]\n self.assertEqual(1, len(publisher.events))\n self.assertEqual(1, len(new_publisher.events))\n self.assertEqual('a', getattr(new_publisher.events[0], 'event_type'))\n self.assertEqual('a', getattr(publisher.events[0], 'event_type'))\n\n def test_multiple_publisher_isolation(self):\n self._reraise_exception = False\n self._set_pipeline_cfg('publishers', ['except://', 'new://'])\n self._build_and_set_new_pipeline()\n pipeline_manager = event.EventPipelineManager(self.CONF)\n with pipeline_manager.publisher() as p:\n p([self.test_event])\n\n publisher = pipeline_manager.pipelines[0].publishers[1]\n self.assertEqual(1, len(publisher.events))\n self.assertEqual('a', getattr(publisher.events[0], 'event_type'))\n\n def test_unique_pipeline_names(self):\n self._dup_pipeline_name_cfg()\n self._exception_create_pipelinemanager()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements delete.py from csachs/openmicroscopy (path: components/tools/OmeroPy/src/omero/plugins/delete.py)."}, {"role": "assistant", "content": "# components/tools/OmeroPy/src/omero/plugins/delete.py (from csachs/openmicroscopy, license: gpl-2.0)\n\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n Startup plugin for command-line deletes\n\n Copyright 2009-2015 Glencoe Software, Inc. All rights reserved.\n Use is subject to license terms supplied in LICENSE.txt\n\n\"\"\"\n\nimport sys\n\nfrom omero.cli import CLI, GraphControl\n\nHELP = \"\"\"Delete OMERO data.\n\nRemove entire graphs of data based on the ID of the top-node.\n\nBy default linked tag, file and term annotations are not deleted.\nTo delete linked annoations they must be explicitly included.\n\nExamples:\n\n # Delete an image but not its linked tag, file and term annotations\n omero delete Image:50\n # Delete an image including linked tag, file and term annotations\n omero delete Image:51 --include TagAnnotation,FileAnnotation,TermAnnotation\n # Delete an image including all linked annotations\n omero delete Image:52 --include Annotation\n\n # Delete three images and two datasets including their contents\n omero delete omero delete Image:101,102,103 Dataset:201,202\n # Delete a project excluding contained datasets and linked annotations\n omero delete Project:101 --exclude Dataset,Annotation\n\n # Delete all images contained under a project\n omero delete Project/Dataset/Image:53\n # Delete all images contained under two projects\n omero delete Project/Image:201,202\n\n # Do a dry run of a delete reporting the outcome if the delete had been run\n omero delete Dataset:53 --dry-run\n # Do a dry run of a delete, reporting all the objects\n # that would have been deleted\n omero delete Dataset:53 --dry-run --report\n\n\"\"\"\n\nclass DeleteControl(GraphControl):\n\n def cmd_type(self):\n import omero\n import omero.all\n return omero.cmd.Delete2\n\n def print_detailed_report(self, req, rsp, status):\n import omero\n if isinstance(rsp, omero.cmd.DoAllRsp):\n for response in rsp.responses:\n if isinstance(response, omero.cmd.Delete2Response):\n self.print_delete_response(response)\n elif isinstance(rsp, omero.cmd.Delete2Response):\n self.print_delete_response(rsp)\n\n def print_delete_response(self, rsp):\n if rsp.deletedObjects:\n self.ctx.out(\"Deleted objects\")\n objIds = self._get_object_ids(rsp.deletedObjects)\n for k in objIds:\n self.ctx.out(\" %s:%s\" % (k, objIds[k]))\n\n def default_exclude(self):\n \"\"\"\n Don't delete these three types of Annotation by default\n \"\"\"\n return [\"TagAnnotation\", \"TermAnnotation\", \"FileAnnotation\"]\n\ntry:\n register(\"delete\", DeleteControl, HELP)\nexcept NameError:\n if __name__ == \"__main__\":\n cli = CLI()\n cli.register(\"delete\", DeleteControl, HELP)\n cli.invoke(sys.argv[1:])"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_fetch_url.py from pmarques/ansible (path: test/units/module_utils/urls/test_fetch_url.py)."}, {"role": "assistant", "content": "# test/units/module_utils/urls/test_fetch_url.py (from pmarques/ansible, license: gpl-3.0)\n\n# -*- coding: utf-8 -*-\n# (c) 2018 Matt Martz \n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nimport socket\n\nfrom ansible.module_utils.six import StringIO\nfrom ansible.module_utils.six.moves.http_cookiejar import Cookie\nfrom ansible.module_utils.six.moves.http_client import HTTPMessage\nfrom ansible.module_utils.urls import fetch_url, urllib_error, ConnectionError, NoSSLError, httplib\n\nimport pytest\nfrom mock import MagicMock\n\nclass AnsibleModuleExit(Exception):\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\nclass ExitJson(AnsibleModuleExit):\n pass\n\nclass FailJson(AnsibleModuleExit):\n pass\n\n@pytest.fixture\ndef open_url_mock(mocker):\n return mocker.patch('ansible.module_utils.urls.open_url')\n\n@pytest.fixture\ndef fake_ansible_module():\n return FakeAnsibleModule()\n\nclass FakeAnsibleModule:\n def __init__(self):\n self.params = {}\n self.tmpdir = None\n\n def exit_json(self, *args, **kwargs):\n raise ExitJson(*args, **kwargs)\n\n def fail_json(self, *args, **kwargs):\n raise FailJson(*args, **kwargs)\n\ndef test_fetch_url_no_urlparse(mocker, fake_ansible_module):\n mocker.patch('ansible.module_utils.urls.HAS_URLPARSE', new=False)\n\n with pytest.raises(FailJson):\n fetch_url(fake_ansible_module, 'http://ansible.com/')\n\ndef test_fetch_url(open_url_mock, fake_ansible_module):\n r, info = fetch_url(fake_ansible_module, 'http://ansible.com/')\n\n dummy, kwargs = open_url_mock.call_args\n\n open_url_mock.assert_called_once_with('http://ansible.com/', client_cert=None, client_key=None, cookies=kwargs['cookies'], data=None,\n follow_redirects='urllib2', force=False, force_basic_auth='', headers=None,\n http_agent='ansible-httpget', last_mod_time=None, method=None, timeout=10, url_password='', url_username='',\n use_proxy=True, validate_certs=True, use_gssapi=False, unix_socket=None, ca_path=None)\n\ndef test_fetch_url_params(open_url_mock, fake_ansible_module):\n fake_ansible_module.params = {\n 'validate_certs': False,\n 'url_username': 'user',\n 'url_password': 'passwd',\n 'http_agent': 'ansible-test',\n 'force_basic_auth': True,\n 'follow_redirects': 'all',\n 'client_cert': 'client.pem',\n 'client_key': 'client.key',\n }\n\n r, info = fetch_url(fake_ansible_module, 'http://ansible.com/')\n\n dummy, kwargs = open_url_mock.call_args\n\n open_url_mock.assert_called_once_with('http://ansible.com/', client_cert='client.pem', client_key='client.key', cookies=kwargs['cookies'], data=None,\n follow_redirects='all', force=False, force_basic_auth=True, headers=None,\n http_agent='ansible-test', last_mod_time=None, method=None, timeout=10, url_password='passwd', url_username='user',\n use_proxy=True, validate_certs=False, use_gssapi=False, unix_socket=None, ca_path=None)\n\ndef test_fetch_url_cookies(mocker, fake_ansible_module):\n def make_cookies(*args, **kwargs):\n cookies = kwargs['cookies']\n r = MagicMock()\n try:\n r.headers = HTTPMessage()\n add_header = r.headers.add_header\n except TypeError:\n # PY2\n r.headers = HTTPMessage(StringIO())\n add_header = r.headers.addheader\n r.info.return_value = r.headers\n for name, value in (('Foo', 'bar'), ('Baz', 'qux')):\n cookie = Cookie(\n version=0,\n name=name,\n value=value,\n port=None,\n port_specified=False,\n domain=\"ansible.com\",\n domain_specified=True,\n domain_initial_dot=False,\n path=\"/\",\n path_specified=True,\n secure=False,\n expires=None,\n discard=False,\n comment=None,\n comment_url=None,\n rest=None\n )\n cookies.set_cookie(cookie)\n add_header('Set-Cookie', '%s=%s' % (name, value))\n\n return r\n\n mocker = mocker.patch('ansible.module_utils.urls.open_url', new=make_cookies)\n\n r, info = fetch_url(fake_ansible_module, 'http://ansible.com/')\n\n assert info['cookies'] == {'Baz': 'qux', 'Foo': 'bar'}\n # Python sorts cookies in order of most specific (ie. longest) path first\n # items with the same path are reversed from response order\n assert info['cookies_string'] == 'Baz=qux; Foo=bar'\n # The key here has a `-` as opposed to what we see in the `uri` module that converts to `_`\n # Note: this is response order, which differs from cookies_string\n assert info['set-cookie'] == 'Foo=bar, Baz=qux'\n\ndef test_fetch_url_nossl(open_url_mock, fake_ansible_module, mocker):\n mocker.patch('ansible.module_utils.urls.get_distribution', return_value='notredhat')\n\n open_url_mock.side_effect = NoSSLError\n with pytest.raises(FailJson) as excinfo:\n fetch_url(fake_ansible_module, 'http://ansible.com/')\n\n assert 'python-ssl' not in excinfo.value.kwargs['msg']\n\n mocker.patch('ansible.module_utils.urls.get_distribution', return_value='redhat')\n\n open_url_mock.side_effect = NoSSLError\n with pytest.raises(FailJson) as excinfo:\n fetch_url(fake_ansible_module, 'http://ansible.com/')\n\n assert 'python-ssl' in excinfo.value.kwargs['msg']\n assert 'http://ansible.com/' == excinfo.value.kwargs['url']\n assert excinfo.value.kwargs['status'] == -1\n\ndef test_fetch_url_connectionerror(open_url_mock, fake_ansible_module):\n open_url_mock.side_effect = ConnectionError('TESTS')\n with pytest.raises(FailJson) as excinfo:\n fetch_url(fake_ansible_module, 'http://ansible.com/')\n\n assert excinfo.value.kwargs['msg'] == 'TESTS'\n assert 'http://ansible.com/' == excinfo.value.kwargs['url']\n assert excinfo.value.kwargs['status'] == -1\n\n open_url_mock.side_effect = ValueError('TESTS')\n with pytest.raises(FailJson) as excinfo:\n fetch_url(fake_ansible_module, 'http://ansible.com/')\n\n assert excinfo.value.kwargs['msg'] == 'TESTS'\n assert 'http://ansible.com/' == excinfo.value.kwargs['url']\n assert excinfo.value.kwargs['status'] == -1\n\ndef test_fetch_url_httperror(open_url_mock, fake_ansible_module):\n open_url_mock.side_effect = urllib_error.HTTPError(\n 'http://ansible.com/',\n 500,\n 'Internal Server Error',\n {'Content-Type': 'application/json'},\n StringIO('TESTS')\n )\n\n r, info = fetch_url(fake_ansible_module, 'http://ansible.com/')\n\n assert info == {'msg': 'HTTP Error 500: Internal Server Error', 'body': 'TESTS',\n 'status': 500, 'url': 'http://ansible.com/', 'content-type': 'application/json'}\n\ndef test_fetch_url_urlerror(open_url_mock, fake_ansible_module):\n open_url_mock.side_effect = urllib_error.URLError('TESTS')\n r, info = fetch_url(fake_ansible_module, 'http://ansible.com/')\n assert info == {'msg': 'Request failed: ', 'status': -1, 'url': 'http://ansible.com/'}\n\ndef test_fetch_url_socketerror(open_url_mock, fake_ansible_module):\n open_url_mock.side_effect = socket.error('TESTS')\n r, info = fetch_url(fake_ansible_module, 'http://ansible.com/')\n assert info == {'msg': 'Connection failure: TESTS', 'status': -1, 'url': 'http://ansible.com/'}\n\ndef test_fetch_url_exception(open_url_mock, fake_ansible_module):\n open_url_mock.side_effect = Exception('TESTS')\n r, info = fetch_url(fake_ansible_module, 'http://ansible.com/')\n exception = info.pop('exception')\n assert info == {'msg': 'An unknown error occurred: TESTS', 'status': -1, 'url': 'http://ansible.com/'}\n assert \"Exception: TESTS\" in exception\n\ndef test_fetch_url_badstatusline(open_url_mock, fake_ansible_module):\n open_url_mock.side_effect = httplib.BadStatusLine('TESTS')\n r, info = fetch_url(fake_ansible_module, 'http://ansible.com/')\n assert info == {'msg': 'Connection failure: connection was closed before a valid response was received: TESTS', 'status': -1, 'url': 'http://ansible.com/'}"}]} {"messages": [{"role": "user", "content": "Write Python code that implements settings.py from Regner/will (path: will/settings.py)."}, {"role": "assistant", "content": "# will/settings.py (from Regner/will, license: mit)\n\nimport os\nfrom utils import show_valid, warn, note\nfrom clint.textui import puts, indent\nfrom urlparse import urlparse\n\ndef import_settings(quiet=True):\n \"\"\"This method takes care of importing settings from the environment, and config.py file.\n\n Order of operations:\n 1. Imports all WILL_ settings from the environment, and strips off the WILL_\n 2. Imports settings from config.py\n 3. Sets defaults for any missing, required settings.\n\n This method takes a quiet kwarg, that when False, prints helpful output. Called that way during bootstrapping.\n \"\"\"\n\n settings = {}\n\n # Import from environment, handle environment-specific parsing.\n for k, v in os.environ.items():\n if k[:5] == \"WILL_\":\n k = k[5:]\n settings[k] = v\n if \"ROOMS\" in settings:\n settings[\"ROOMS\"] = settings[\"ROOMS\"].split(\";\")\n\n # If HIPCHAT_SERVER is set, we need to change the USERNAME slightly\n # for XMPP to work.\n if \"HIPCHAT_SERVER\" in settings:\n settings[\"USERNAME\"] = \"{user}@{host}\".\\\n format(user=settings[\"USERNAME\"].split(\"@\")[0],\n host=settings[\"HIPCHAT_SERVER\"])\n else:\n settings[\"HIPCHAT_SERVER\"] = \"api.hipchat.com\"\n\n # Import from config\n if not quiet:\n puts(\"Importing config.py... \")\n with indent(2):\n try:\n had_warning = False\n import config\n for k, v in config.__dict__.items():\n # Ignore private variables\n if \"__\" not in k:\n if k in os.environ and v != os.environ[k] and not quiet:\n warn(\"%s is set in the environment as '%s', but overridden in\"\n \" config.py as '%s'.\" % (k, os.environ[k], v))\n had_warning = True\n settings[k] = v\n\n if not had_warning and not quiet:\n show_valid(\"Valid.\")\n except:\n # TODO: Check to see if there's a config.py.dist\n if not quiet:\n warn(\"no config.py found. This might be ok, but more likely, \"\n \"you haven't copied config.py.dist over to config.py\")\n\n if not quiet:\n puts(\"Verifying settings... \")\n\n with indent(2):\n # Set defaults\n if \"ROOMS\" not in settings:\n if not quiet:\n warn(\"no ROOMS list found in the environment or config. \"\n \"This is ok - Will will just join all available rooms.\")\n settings[\"ROOMS\"] = None\n\n if \"DEFAULT_ROOM\" not in settings and \"ROOMS\" in settings and settings[\"ROOMS\"] and len(settings[\"ROOMS\"]) > 0:\n if not quiet:\n warn(\"no DEFAULT_ROOM found in the environment or config. \"\n \"Defaulting to '%s', the first one.\" % settings[\"ROOMS\"][0])\n settings[\"DEFAULT_ROOM\"] = settings[\"ROOMS\"][0]\n\n if \"HTTPSERVER_PORT\" not in settings:\n # For heroku\n if \"PORT\" in os.environ:\n settings[\"HTTPSERVER_PORT\"] = os.environ[\"PORT\"]\n else:\n if not quiet:\n warn(\"no HTTPSERVER_PORT found in the environment or config. Defaulting to ':80'.\")\n settings[\"HTTPSERVER_PORT\"] = \"80\"\n\n if \"STORAGE_BACKEND\" not in settings:\n settings[\"STORAGE_BACKEND\"] = \"redis\"\n\n if settings[\"STORAGE_BACKEND\"] == \"redis\":\n if \"REDIS_URL\" not in settings:\n # For heroku\n if \"REDISCLOUD_URL\" in os.environ:\n settings[\"REDIS_URL\"] = os.environ[\"REDISCLOUD_URL\"]\n if not quiet:\n note(\"WILL_REDIS_URL not set, but it appears you're using RedisCloud. If so, all good.\")\n elif \"REDISTOGO_URL\" in os.environ:\n settings[\"REDIS_URL\"] = os.environ[\"REDISTOGO_URL\"]\n if not quiet:\n note(\"WILL_REDIS_URL not set, but it appears you're using RedisToGo. If so, all good.\")\n elif \"OPENREDIS_URL\" in os.environ:\n settings[\"REDIS_URL\"] = os.environ[\"OPENREDIS_URL\"]\n if not quiet:\n note(\"WILL_REDIS_URL not set, but it appears you're using OpenRedis. If so, all good.\")\n else:\n settings[\"REDIS_URL\"] = \"redis://localhost:6379/7\"\n if not quiet:\n note(\"WILL_REDIS_URL not set. Defaulting to redis://localhost:6379/7.\")\n\n if not settings[\"REDIS_URL\"].startswith(\"redis://\"):\n settings[\"REDIS_URL\"] = \"redis://%s\" % settings[\"REDIS_URL\"]\n\n if \"REDIS_MAX_CONNECTIONS\" not in settings:\n settings[\"REDIS_MAX_CONNECTIONS\"] = 4\n if not quiet:\n note(\"REDIS_MAX_CONNECTIONS not set. Defaulting to 4.\")\n\n if settings[\"STORAGE_BACKEND\"] == \"file\":\n if \"FILE_DIR\" not in settings:\n settings[\"FILE_DIR\"] = \"~/.will/\"\n if not quiet:\n note(\"FILE_DIR not set. Defaulting to ~/.will/\")\n\n if settings[\"STORAGE_BACKEND\"] == \"couchbase\":\n if \"COUCHBASE_URL\" not in settings:\n settings[\"COUCHBASE_URL\"] = \"couchbase:///will\"\n if not quiet:\n note(\"COUCHBASE_URL not set. Defaulting to couchbase:///will\")\n\n if \"PUBLIC_URL\" not in settings:\n default_public = \"http://localhost:%s\" % settings[\"HTTPSERVER_PORT\"]\n settings[\"PUBLIC_URL\"] = default_public\n if not quiet:\n warn(\"no PUBLIC_URL found in the environment or config. Defaulting to '%s'.\" % default_public)\n\n if \"V1_TOKEN\" not in settings:\n if not quiet:\n warn(\n \"no V1_TOKEN found in the environment or config.\"\n \"This is generally ok, but if you have more than 30 rooms, \"\n \"you may recieve rate-limit errors without one.\"\n )\n\n if \"TEMPLATE_DIRS\" not in settings:\n if \"WILL_TEMPLATE_DIRS_PICKLED\" in os.environ:\n # All good\n pass\n else:\n settings[\"TEMPLATE_DIRS\"] = []\n if \"ALLOW_INSECURE_HIPCHAT_SERVER\" in settings and\\\n (settings[\"ALLOW_INSECURE_HIPCHAT_SERVER\"] is True or\n settings[\"ALLOW_INSECURE_HIPCHAT_SERVER\"].lower() == \"true\"):\n warn(\"You are choosing to run will with SSL disabled. \"\n \"This is INSECURE and should NEVER be deployed outside a development environment.\")\n settings[\"ALLOW_INSECURE_HIPCHAT_SERVER\"] = True\n settings[\"REQUESTS_OPTIONS\"] = {\n \"verify\": False,\n }\n else:\n settings[\"ALLOW_INSECURE_HIPCHAT_SERVER\"] = False\n settings[\"REQUESTS_OPTIONS\"] = {}\n\n if \"ADMINS\" not in settings:\n settings[\"ADMINS\"] = \"*\"\n else:\n if \"WILL_ADMINS\" in os.environ:\n settings[\"ADMINS\"] = [a.strip().lower() for a in settings.get('ADMINS', '').split(';') if a.strip()]\n\n if \"PROXY_URL\" in settings:\n parsed_proxy_url = urlparse(settings[\"PROXY_URL\"])\n settings[\"USE_PROXY\"] = True\n settings[\"PROXY_HOSTNAME\"] = parsed_proxy_url.hostname\n settings[\"PROXY_USERNAME\"] = parsed_proxy_url.username\n settings[\"PROXY_PASSWORD\"] = parsed_proxy_url.password\n settings[\"PROXY_PORT\"] = parsed_proxy_url.port\n else:\n settings[\"USE_PROXY\"] = False\n\n # Set them in the module namespace\n for k in sorted(settings, key=lambda x: x[0]):\n if not quiet:\n show_valid(k)\n globals()[k] = settings[k]\n\nimport_settings()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements _stops.py from JaDogg/__py_playground (path: reference/pages/sum1/_stops.py)."}, {"role": "assistant", "content": "# reference/pages/sum1/_stops.py (from JaDogg/__py_playground, license: mit)\n\nnltkStops = {\n '.': True,\n ',': True,\n ':': True,\n 'a': True,\n \"a's\": True,\n 'able': True,\n 'about': True,\n 'above': True,\n 'according': True,\n 'accordingly': True,\n 'across': True,\n 'actually': True,\n 'after': True,\n 'afterwards': True,\n 'again': True,\n 'against': True,\n \"ain't\": True,\n 'all': True,\n 'allow': True,\n 'allows': True,\n 'almost': True,\n 'alone': True,\n 'along': True,\n 'already': True,\n 'also': True,\n 'although': True,\n 'always': True,\n 'am': True,\n 'among': True,\n 'amongst': True,\n 'an': True,\n 'and': True,\n 'another': True,\n 'any': True,\n 'anybody': True,\n 'anyhow': True,\n 'anyone': True,\n 'anything': True,\n 'anyway': True,\n 'anyways': True,\n 'anywhere': True,\n 'apart': True,\n 'appear': True,\n 'appreciate': True,\n 'appropriate': True,\n 'are': True,\n \"aren't\": True,\n 'around': True,\n 'as': True,\n 'aside': True,\n 'ask': True,\n 'asking': True,\n 'associated': True,\n 'at': True,\n 'available': True,\n 'away': True,\n 'awfully': True,\n 'b': True,\n 'be': True,\n 'became': True,\n 'because': True,\n 'become': True,\n 'becomes': True,\n 'becoming': True,\n 'been': True,\n 'before': True,\n 'beforehand': True,\n 'behind': True,\n 'being': True,\n 'believe': True,\n 'below': True,\n 'beside': True,\n 'besides': True,\n 'best': True,\n 'better': True,\n 'between': True,\n 'beyond': True,\n 'both': True,\n 'brief': True,\n 'but': True,\n 'by': True,\n 'c': True,\n \"c'mon\": True,\n \"c's\": True,\n 'came': True,\n 'can': True,\n \"can't\": True,\n 'cannot': True,\n 'cant': True,\n 'cause': True,\n 'causes': True,\n 'certain': True,\n 'certainly': True,\n 'changes': True,\n 'clearly': True,\n 'co': True,\n 'com': True,\n 'come': True,\n 'comes': True,\n 'concerning': True,\n 'consequently': True,\n 'consider': True,\n 'considering': True,\n 'contain': True,\n 'containing': True,\n 'contains': True,\n 'corresponding': True,\n 'could': True,\n \"couldn't\": True,\n 'course': True,\n 'currently': True,\n 'd': True,\n 'definitely': True,\n 'described': True,\n 'despite': True,\n 'did': True,\n \"didn't\": True,\n 'different': True,\n 'do': True,\n 'does': True,\n \"doesn't\": True,\n 'doing': True,\n \"don't\": True,\n 'done': True,\n 'down': True,\n 'downwards': True,\n 'during': True,\n 'e': True,\n 'each': True,\n 'edu': True,\n 'eg': True,\n 'eight': True,\n 'either': True,\n 'else': True,\n 'elsewhere': True,\n 'enough': True,\n 'entirely': True,\n 'especially': True,\n 'et': True,\n 'etc': True,\n 'even': True,\n 'ever': True,\n 'every': True,\n 'everybody': True,\n 'everyone': True,\n 'everything': True,\n 'everywhere': True,\n 'ex': True,\n 'exactly': True,\n 'example': True,\n 'except': True,\n 'f': True,\n 'far': True,\n 'few': True,\n 'fifth': True,\n 'first': True,\n 'five': True,\n 'followed': True,\n 'following': True,\n 'follows': True,\n 'for': True,\n 'former': True,\n 'formerly': True,\n 'forth': True,\n 'four': True,\n 'from': True,\n 'further': True,\n 'furthermore': True,\n 'g': True,\n 'get': True,\n 'gets': True,\n 'getting': True,\n 'given': True,\n 'gives': True,\n 'go': True,\n 'goes': True,\n 'going': True,\n 'gone': True,\n 'got': True,\n 'gotten': True,\n 'greetings': True,\n 'h': True,\n 'had': True,\n \"hadn't\": True,\n 'happens': True,\n 'hardly': True,\n 'has': True,\n \"hasn't\": True,\n 'have': True,\n \"haven't\": True,\n 'having': True,\n 'he': True,\n \"he's\": True,\n 'hello': True,\n 'help': True,\n 'hence': True,\n 'her': True,\n 'here': True,\n \"here's\": True,\n 'hereafter': True,\n 'hereby': True,\n 'herein': True,\n 'hereupon': True,\n 'hers': True,\n 'herself': True,\n 'hi': True,\n 'him': True,\n 'himself': True,\n 'his': True,\n 'hither': True,\n 'hopefully': True,\n 'how': True,\n 'howbeit': True,\n 'however': True,\n 'i': True,\n \"i'd\": True,\n \"i'll\": True,\n \"i'm\": True,\n \"i've\": True,\n 'ie': True,\n 'if': True,\n 'ignored': True,\n 'immediate': True,\n 'in': True,\n 'inasmuch': True,\n 'inc': True,\n 'indeed': True,\n 'indicate': True,\n 'indicated': True,\n 'indicates': True,\n 'inner': True,\n 'insofar': True,\n 'instead': True,\n 'into': True,\n 'inward': True,\n 'is': True,\n \"isn't\": True,\n 'it': True,\n \"it'd\": True,\n \"it'll\": True,\n \"it's\": True,\n 'its': True,\n 'itself': True,\n 'j': True,\n 'just': True,\n 'k': True,\n 'keep': True,\n 'keeps': True,\n 'kept': True,\n 'know': True,\n 'knows': True,\n 'known': True,\n 'l': True,\n 'last': True,\n 'lately': True,\n 'later': True,\n 'latter': True,\n 'latterly': True,\n 'least': True,\n 'less': True,\n 'lest': True,\n 'let': True,\n \"let's\": True,\n 'like': True,\n 'liked': True,\n 'likely': True,\n 'little': True,\n 'look': True,\n 'looking': True,\n 'looks': True,\n 'ltd': True,\n 'm': True,\n 'mainly': True,\n 'many': True,\n 'may': True,\n 'maybe': True,\n 'me': True,\n 'mean': True,\n 'meanwhile': True,\n 'merely': True,\n 'might': True,\n 'more': True,\n 'moreover': True,\n 'most': True,\n 'mostly': True,\n 'much': True,\n 'must': True,\n 'my': True,\n 'myself': True,\n 'n': True,\n 'name': True,\n 'namely': True,\n 'nd': True,\n 'near': True,\n 'nearly': True,\n 'necessary': True,\n 'need': True,\n 'needs': True,\n 'neither': True,\n 'never': True,\n 'nevertheless': True,\n 'new': True,\n 'next': True,\n 'nine': True,\n 'no': True,\n 'nobody': True,\n 'non': True,\n 'none': True,\n 'noone': True,\n 'nor': True,\n 'normally': True,\n 'not': True,\n 'nothing': True,\n 'novel': True,\n 'now': True,\n 'nowhere': True,\n 'o': True,\n 'obviously': True,\n 'of': True,\n 'off': True,\n 'often': True,\n 'oh': True,\n 'ok': True,\n 'okay': True,\n 'old': True,\n 'on': True,\n 'once': True,\n 'one': True,\n 'ones': True,\n 'only': True,\n 'onto': True,\n 'or': True,\n 'other': True,\n 'others': True,\n 'otherwise': True,\n 'ought': True,\n 'our': True,\n 'ours': True,\n 'ourselves': True,\n 'out': True,\n 'outside': True,\n 'over': True,\n 'overall': True,\n 'own': True,\n 'p': True,\n 'particular': True,\n 'particularly': True,\n 'per': True,\n 'perhaps': True,\n 'placed': True,\n 'please': True,\n 'plus': True,\n 'possible': True,\n 'presumably': True,\n 'probably': True,\n 'provides': True,\n 'q': True,\n 'que': True,\n 'quite': True,\n 'qv': True,\n 'r': True,\n 'rather': True,\n 'rd': True,\n 're': True,\n 'really': True,\n 'reasonably': True,\n 'regarding': True,\n 'regardless': True,\n 'regards': True,\n 'relatively': True,\n 'respectively': True,\n 'right': True,\n 's': True,\n 'said': True,\n 'same': True,\n 'saw': True,\n 'say': True,\n 'saying': True,\n 'says': True,\n 'second': True,\n 'secondly': True,\n 'see': True,\n 'seeing': True,\n 'seem': True,\n 'seemed': True,\n 'seeming': True,\n 'seems': True,\n 'seen': True,\n 'self': True,\n 'selves': True,\n 'sensible': True,\n 'sent': True,\n 'serious': True,\n 'seriously': True,\n 'seven': True,\n 'several': True,\n 'shall': True,\n 'she': True,\n 'should': True,\n \"shouldn't\": True,\n 'since': True,\n 'six': True,\n 'so': True,\n 'some': True,\n 'somebody': True,\n 'somehow': True,\n 'someone': True,\n 'something': True,\n 'sometime': True,\n 'sometimes': True,\n 'somewhat': True,\n 'somewhere': True,\n 'soon': True,\n 'sorry': True,\n 'specified': True,\n 'specify': True,\n 'specifying': True,\n 'still': True,\n 'sub': True,\n 'such': True,\n 'sup': True,\n 'sure': True,\n 't': True,\n \"t's\": True,\n 'take': True,\n 'taken': True,\n 'tell': True,\n 'tends': True,\n 'th': True,\n 'than': True,\n 'thank': True,\n 'thanks': True,\n 'thanx': True,\n 'that': True,\n \"that's\": True,\n 'thats': True,\n 'the': True,\n 'their': True,\n 'theirs': True,\n 'them': True,\n 'themselves': True,\n 'then': True,\n 'thence': True,\n 'there': True,\n \"there's\": True,\n 'thereafter': True,\n 'thereby': True,\n 'therefore': True,\n 'therein': True,\n 'theres': True,\n 'thereupon': True,\n 'these': True,\n 'they': True,\n \"they'd\": True,\n \"they'll\": True,\n \"they're\": True,\n \"they've\": True,\n 'think': True,\n 'third': True,\n 'this': True,\n 'thorough': True,\n 'thoroughly': True,\n 'those': True,\n 'though': True,\n 'three': True,\n 'through': True,\n 'throughout': True,\n 'thru': True,\n 'thus': True,\n 'to': True,\n 'together': True,\n 'too': True,\n 'took': True,\n 'toward': True,\n 'towards': True,\n 'tried': True,\n 'tries': True,\n 'truly': True,\n 'try': True,\n 'trying': True,\n 'twice': True,\n 'two': True,\n 'u': True,\n 'un': True,\n 'under': True,\n 'unfortunately': True,\n 'unless': True,\n 'unlikely': True,\n 'until': True,\n 'unto': True,\n 'up': True,\n 'upon': True,\n 'us': True,\n 'use': True,\n 'used': True,\n 'useful': True,\n 'uses': True,\n 'using': True,\n 'usually': True,\n 'uucp': True,\n 'v': True,\n 'value': True,\n 'various': True,\n 'very': True,\n 'via': True,\n 'viz': True,\n 'vs': True,\n 'w': True,\n 'want': True,\n 'wants': True,\n 'was': True,\n \"wasn't\": True,\n 'way': True,\n 'we': True,\n \"we'd\": True,\n \"we'll\": True,\n \"we're\": True,\n \"we've\": True,\n 'welcome': True,\n 'well': True,\n 'went': True,\n 'were': True,\n \"weren't\": True,\n 'what': True,\n \"what's\": True,\n 'whatever': True,\n 'when': True,\n 'whence': True,\n 'whenever': True,\n 'where': True,\n \"where's\": True,\n 'whereafter': True,\n 'whereas': True,\n 'whereby': True,\n 'wherein': True,\n 'whereupon': True,\n 'wherever': True,\n 'whether': True,\n 'which': True,\n 'while': True,\n 'whither': True,\n 'who': True,\n \"who's\": True,\n 'whoever': True,\n 'whole': True,\n 'whom': True,\n 'whose': True,\n 'why': True,\n 'will': True,\n 'willing': True,\n 'wish': True,\n 'with': True,\n 'within': True,\n 'without': True,\n \"won't\": True,\n 'wonder': True,\n 'would': True,\n 'would': True,\n \"wouldn't\": True,\n 'x': True,\n 'y': True,\n 'yes': True,\n 'yet': True,\n 'you': True,\n \"you'd\": True,\n \"you'll\": True,\n \"you're\": True,\n \"you've\": True,\n 'your': True,\n 'yours': True,\n 'yourself': True,\n 'yourselves': True,\n 'z': True,\n 'zero': True,\n \"'s\": True,\n \"'ll\": True,\n \"'re\": True}"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_join_counts.py from lanselin/pysal (path: pysal/esda/tests/test_join_counts.py)."}, {"role": "assistant", "content": "# pysal/esda/tests/test_join_counts.py (from lanselin/pysal, license: bsd-3-clause)\n\nimport unittest\nimport numpy as np\n\nfrom ..join_counts import Join_Counts\nfrom ...weights import lat2W\nfrom ...common import pandas\n\nPANDAS_EXTINCT = pandas is None\n\nclass Join_Counts_Tester(unittest.TestCase):\n \"\"\"Unit test for Join Counts\"\"\"\n def setUp(self):\n self.w = lat2W(4, 4)\n self.y = np.ones(16)\n self.y[0:8] = 0\n\n def test_Join_Counts(self):\n \"\"\"Test method\"\"\"\n np.random.seed(12345)\n jc = Join_Counts(self.y, self.w)\n self.assertAlmostEquals(jc.bb, 10.0)\n self.assertAlmostEquals(jc.bw, 4.0)\n self.assertAlmostEquals(jc.ww, 10.0)\n self.assertAlmostEquals(jc.J, 24.0)\n self.assertAlmostEquals(len(jc.sim_bb), 999)\n self.assertAlmostEquals(jc.p_sim_bb, 0.0030000000000000001)\n self.assertAlmostEquals(np.mean(jc.sim_bb), 5.5465465465465469)\n self.assertAlmostEquals(np.max(jc.sim_bb), 10.0)\n self.assertAlmostEquals(np.min(jc.sim_bb), 0.0)\n self.assertAlmostEquals(len(jc.sim_bw), 999)\n self.assertAlmostEquals(jc.p_sim_bw, 1.0)\n self.assertAlmostEquals(np.mean(jc.sim_bw), 12.811811811811811)\n self.assertAlmostEquals(np.max(jc.sim_bw), 24.0)\n self.assertAlmostEquals(np.min(jc.sim_bw), 7.0)\n \n @unittest.skipIf(PANDAS_EXTINCT, 'missing pandas')\n def test_by_col(self):\n import pandas as pd\n df = pd.DataFrame(self.y, columns=['y'])\n np.random.seed(12345)\n r1 = Join_Counts.by_col(df, ['y'], w=self.w, permutations=999)\n \n bb = np.unique(r1.y_bb.values)\n bw = np.unique(r1.y_bw.values)\n bb_p = np.unique(r1.y_p_sim_bb.values)\n bw_p = np.unique(r1.y_p_sim_bw.values)\n np.random.seed(12345)\n c = Join_Counts(self.y, self.w, permutations=999)\n self.assertAlmostEquals(bb, c.bb)\n self.assertAlmostEquals(bw, c.bw)\n self.assertAlmostEquals(bb_p, c.p_sim_bb)\n self.assertAlmostEquals(bw_p, c.p_sim_bw)\n\nsuite = unittest.TestSuite()\ntest_classes = [Join_Counts_Tester]\nfor i in test_classes:\n a = unittest.TestLoader().loadTestsFromTestCase(i)\n suite.addTest(a)\n\nif __name__ == '__main__':\n runner = unittest.TextTestRunner()\n runner.run(suite)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements concatenate_dataset_op_test.py from guschmue/tensorflow (path: tensorflow/python/kernel_tests/concatenate_dataset_op_test.py)."}, {"role": "assistant", "content": "# tensorflow/python/kernel_tests/concatenate_dataset_op_test.py (from guschmue/tensorflow, license: apache-2.0)\n\n# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for the experimental input pipeline ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.util import nest\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.platform import test\n\nclass ConcatenateDatasetTest(test.TestCase):\n\n def testConcatenateDataset(self):\n input_components = (\n np.tile(np.array([[1], [2], [3], [4]]), 20),\n np.tile(np.array([[12], [13], [14], [15]]), 15),\n np.array([37.0, 38.0, 39.0, 40.0]))\n to_concatenate_components = (\n np.tile(np.array([[1], [2], [3], [4], [5]]), 20),\n np.tile(np.array([[12], [13], [14], [15], [16]]), 15),\n np.array([37.0, 38.0, 39.0, 40.0, 41.0]))\n\n input_dataset = dataset_ops.Dataset.from_tensor_slices(input_components)\n dataset_to_concatenate = dataset_ops.Dataset.from_tensor_slices(\n to_concatenate_components)\n concatenated = input_dataset.concatenate(dataset_to_concatenate)\n self.assertEqual(concatenated.output_shapes, (tensor_shape.TensorShape(\n [20]), tensor_shape.TensorShape([15]), tensor_shape.TensorShape([])))\n\n iterator = concatenated.make_initializable_iterator()\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op)\n for i in range(9):\n result = sess.run(get_next)\n if i < 4:\n for component, result_component in zip(input_components, result):\n self.assertAllEqual(component[i], result_component)\n else:\n for component, result_component in zip(to_concatenate_components,\n result):\n self.assertAllEqual(component[i - 4], result_component)\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testConcatenateDatasetDifferentShape(self):\n input_components = (\n np.tile(np.array([[1], [2], [3], [4]]), 20),\n np.tile(np.array([[12], [13], [14], [15]]), 4))\n to_concatenate_components = (\n np.tile(np.array([[1], [2], [3], [4], [5]]), 20),\n np.tile(np.array([[12], [13], [14], [15], [16]]), 15))\n\n input_dataset = dataset_ops.Dataset.from_tensor_slices(input_components)\n dataset_to_concatenate = dataset_ops.Dataset.from_tensor_slices(\n to_concatenate_components)\n concatenated = input_dataset.concatenate(dataset_to_concatenate)\n self.assertEqual(\n [ts.as_list()\n for ts in nest.flatten(concatenated.output_shapes)], [[20], [None]])\n\n iterator = concatenated.make_initializable_iterator()\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op)\n for i in range(9):\n result = sess.run(get_next)\n if i < 4:\n for component, result_component in zip(input_components, result):\n self.assertAllEqual(component[i], result_component)\n else:\n for component, result_component in zip(to_concatenate_components,\n result):\n self.assertAllEqual(component[i - 4], result_component)\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testConcatenateDatasetDifferentStructure(self):\n input_components = (\n np.tile(np.array([[1], [2], [3], [4]]), 5),\n np.tile(np.array([[12], [13], [14], [15]]), 4))\n to_concatenate_components = (\n np.tile(np.array([[1], [2], [3], [4], [5]]), 20),\n np.tile(np.array([[12], [13], [14], [15], [16]]), 15),\n np.array([37.0, 38.0, 39.0, 40.0, 41.0]))\n\n input_dataset = dataset_ops.Dataset.from_tensor_slices(input_components)\n dataset_to_concatenate = dataset_ops.Dataset.from_tensor_slices(\n to_concatenate_components)\n\n with self.assertRaisesRegexp(ValueError,\n \"don't have the same number of elements\"):\n input_dataset.concatenate(dataset_to_concatenate)\n\n def testConcatenateDatasetDifferentType(self):\n input_components = (\n np.tile(np.array([[1], [2], [3], [4]]), 5),\n np.tile(np.array([[12], [13], [14], [15]]), 4))\n to_concatenate_components = (\n np.tile(np.array([[1.0], [2.0], [3.0], [4.0]]), 5),\n np.tile(np.array([[12], [13], [14], [15]]), 15))\n\n input_dataset = dataset_ops.Dataset.from_tensor_slices(input_components)\n dataset_to_concatenate = dataset_ops.Dataset.from_tensor_slices(\n to_concatenate_components)\n\n with self.assertRaisesRegexp(TypeError, \"have different types\"):\n input_dataset.concatenate(dataset_to_concatenate)\n\nif __name__ == \"__main__\":\n test.main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements providers.py from anthonypdawson/LazyLibrarian (path: lazylibrarian/providers.py)."}, {"role": "assistant", "content": "# lazylibrarian/providers.py (from anthonypdawson/LazyLibrarian, license: gpl-3.0)\n\nimport time, threading, urllib, urllib2, re\n\nfrom xml.etree import ElementTree\n\nimport lazylibrarian\n\nfrom lazylibrarian import logger, SimpleCache\n\ndef NewzNab(book=None):\n\n HOST = lazylibrarian.NEWZNAB_HOST\n results = []\n\n logger.info('Searching for %s.' % book['searchterm'])\n\n if lazylibrarian.EBOOK_TYPE == None:\n params = {\n \"t\": \"book\",\n \"apikey\": lazylibrarian.NEWZNAB_API,\n #\"cat\": 7020,\n \"author\": book['searchterm']\n }\n else:\n params = {\n \"t\": \"search\",\n \"apikey\": lazylibrarian.NEWZNAB_API,\n \"cat\": 7020,\n \"q\": book['searchterm'],\n \"extended\": 1,\n }\n\n if not str(HOST)[:4] == \"http\":\n HOST = 'http://' + HOST\n\n URL = HOST + '/api?' + urllib.urlencode(params)\n\n try :\n request = urllib2.Request(URL)\n request.add_header('User-Agent', 'lazylibrary/0.0 +https://github.com/LibrarianMike/LazyLibrarian')\n opener = urllib2.build_opener(SimpleCache.CacheHandler(\".urllib2cache\"), SimpleCache.ThrottlingProcessor(5))\n resp = opener.open(request)\n\n try:\n data = ElementTree.parse(resp)\n except (urllib2.URLError, IOError, EOFError), e:\n logger.warn('Error fetching data from %s: %s' % (lazylibrarian.NEWZNAB_HOST, e))\n data = None\n\n except Exception, e:\n logger.error(\"Error 403 openning url\")\n data = None\n\n if data:\n # to debug because of api\n logger.debug(u'Parsing results from %s' % (URL, lazylibrarian.NEWZNAB_HOST))\n rootxml = data.getroot()\n resultxml = rootxml.getiterator('item')\n nzbcount = 0\n for nzb in resultxml:\n try:\n nzbcount = nzbcount+1\n results.append({\n 'bookid': book['bookid'],\n 'nzbprov': \"NewzNab\",\n 'nzbtitle': nzb[0].text,\n 'nzburl': nzb[2].text,\n 'nzbdate': nzb[4].text,\n 'nzbsize': nzb[7].attrib.get('length')\n })\n except IndexError:\n logger.debug('No results')\n if nzbcount:\n logger.debug('Found %s nzb for: %s' % (nzbcount, book['searchterm']))\n else:\n logger.debug(u'Newznab returned 0 results for: ' + book['searchterm'] + '. Adding book to queue.')\n return results\n\ndef NZBMatrix(book=None):\n\n results = []\n\n if ((lazylibrarian.EBOOK_TYPE == None) or (lazylibrarian.EBOOK_TYPE == \"\")):\n params = {\n \"page\": \"download\",\n \"username\": lazylibrarian.NZBMATRIX_USER,\n \"apikey\": lazylibrarian.NZBMATRIX_API,\n \"subcat\": 36,\n \"age\": lazylibrarian.USENET_RETENTION,\n \"term\": book['searchterm']\n }\n else:\n params = {\n \"page\": \"download\",\n \"username\": lazylibrarian.NZBMATRIX_USER,\n \"apikey\": lazylibrarian.NZBMATRIX_API,\n \"subcat\": 36,\n \"age\": lazylibrarian.USENET_RETENTION,\n \"term\": book['searchterm']\n }\n logger.debug('Searching for: ' + book['searchterm'])\n URL = \"http://rss.nzbmatrix.com/rss.php?\" + urllib.urlencode(params)\n # to debug because of api\n logger.debug(u'Parsing results from NZBMatrix' % (URL))\n\n try:\n data = ElementTree.parse(urllib2.urlopen(URL, timeout=30))\n except (urllib2.URLError, IOError, EOFError), e:\n logger.warn('Error fetching data from NZBMatrix: %s' % e)\n data = None\n\n if data:\n rootxml = data.getroot()\n resultxml = rootxml.getiterator('item')\n nzbcount = 0\n for nzb in resultxml:\n try:\n results.append({\n 'bookid': book['bookid'],\n 'nzbprov': \"NZBMatrix\",\n 'nzbtitle': nzb[0].text,\n 'nzburl': nzb[2].text,\n 'nzbsize': nzb[7].attrib.get('length')\n })\n nzbcount = nzbcount+1\n except IndexError:\n logger.debug('No results')\n\n if nzbcount:\n logger.debug('Found %s nzb for: %s' % (nzbcount, book['searchterm']))\n else:\n logger.debug('NZBMatrix returned 0 results for: ' + book['searchterm'] + '. Adding book to queue.')\n return results"}]} {"messages": [{"role": "user", "content": "Write Python code that implements snakebite_test.py from Viktor-Evst/fixed-luigi (path: test/snakebite_test.py)."}, {"role": "assistant", "content": "# test/snakebite_test.py (from Viktor-Evst/fixed-luigi, license: apache-2.0)\n\n# -*- coding: utf-8 -*-\n#\n# Copyright 2012-2015 Spotify AB\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport datetime\nimport os\nimport posixpath\nimport time\nimport unittest\n\nimport luigi.target\nfrom luigi import six\nfrom nose.plugins.attrib import attr\n\nif six.PY3:\n raise unittest.SkipTest(\"snakebite doesn't work on Python 3 yet.\")\n\ntry:\n from luigi.contrib.hdfs import SnakebiteHdfsClient\n from minicluster import MiniClusterTestCase\nexcept ImportError:\n raise unittest.SkipTest('Snakebite not installed')\n\n@attr('minicluster')\nclass TestSnakebiteClient(MiniClusterTestCase):\n\n \"\"\"This test requires a snakebite -- it finds it from your\n luigi.cfg\"\"\"\n snakebite = None\n\n def get_client(self):\n return SnakebiteHdfsClient()\n\n def setUp(self):\n \"\"\" We override setUp because we want to also use snakebite for\n creating the testing directory. \"\"\"\n self.testDir = \"/tmp/luigi-test-{0}-{1}\".format(\n os.environ[\"USER\"],\n time.mktime(datetime.datetime.now().timetuple())\n )\n self.snakebite = self.get_client()\n self.assertTrue(self.snakebite.mkdir(self.testDir))\n\n def tearDown(self):\n if self.snakebite.exists(self.testDir):\n self.snakebite.remove(self.testDir, True)\n\n def test_exists(self):\n self.assertTrue(self.snakebite.exists(self.testDir))\n\n def test_rename(self):\n foo = posixpath.join(self.testDir, \"foo\")\n bar = posixpath.join(self.testDir, \"bar\")\n self.assertTrue(self.snakebite.mkdir(foo))\n self.assertTrue(self.snakebite.rename(foo, bar))\n self.assertTrue(self.snakebite.exists(bar))\n\n def test_rename_trailing_slash(self):\n foo = posixpath.join(self.testDir, \"foo\")\n bar = posixpath.join(self.testDir, \"bar/\")\n self.assertTrue(self.snakebite.mkdir(foo))\n self.assertTrue(self.snakebite.rename(foo, bar))\n self.assertTrue(self.snakebite.exists(bar))\n self.assertFalse(self.snakebite.exists(posixpath.join(bar, 'foo')))\n\n def test_relativepath(self):\n rel_test_dir = \".\" + os.path.split(self.testDir)[1]\n try:\n self.assertFalse(self.snakebite.exists(rel_test_dir))\n self.snakebite.mkdir(rel_test_dir)\n self.assertTrue(self.snakebite.exists(rel_test_dir))\n finally:\n if self.snakebite.exists(rel_test_dir):\n self.snakebite.remove(rel_test_dir, True)\n\n def test_rename_dont_move(self):\n foo = posixpath.join(self.testDir, \"foo\")\n bar = posixpath.join(self.testDir, \"bar\")\n self.assertTrue(self.snakebite.mkdir(foo))\n self.assertTrue(self.snakebite.mkdir(bar))\n self.assertTrue(self.snakebite.exists(foo)) # For sanity\n self.assertTrue(self.snakebite.exists(bar)) # For sanity\n\n self.assertRaises(luigi.target.FileAlreadyExists,\n lambda: self.snakebite.rename_dont_move(foo, bar))\n self.assertTrue(self.snakebite.exists(foo))\n self.assertTrue(self.snakebite.exists(bar))\n\n self.snakebite.rename_dont_move(foo, foo + '2')\n self.assertFalse(self.snakebite.exists(foo))\n self.assertTrue(self.snakebite.exists(foo + '2'))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements local_dialog.py from IZSVenezie/VetEpiGIS-Stat (path: plugin/local_dialog.py)."}, {"role": "assistant", "content": "# plugin/local_dialog.py (from IZSVenezie/VetEpiGIS-Stat, license: gpl-3.0)\n\n# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'local_dialog_base.ui'\n#\n# Created: Sat Jan 7 15:11:01 2017\n# by: PyQt4 UI code generator 4.10.4\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_Dialog(object):\n def setupUi(self, Dialog):\n Dialog.setObjectName(_fromUtf8(\"Dialog\"))\n Dialog.resize(588, 551)\n self.gridLayout_3 = QtGui.QGridLayout(Dialog)\n self.gridLayout_3.setObjectName(_fromUtf8(\"gridLayout_3\"))\n self.splitter = QtGui.QSplitter(Dialog)\n self.splitter.setOrientation(QtCore.Qt.Horizontal)\n self.splitter.setObjectName(_fromUtf8(\"splitter\"))\n self.label = QtGui.QLabel(self.splitter)\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.comboBox = QtGui.QComboBox(self.splitter)\n self.comboBox.setMinimumSize(QtCore.QSize(251, 0))\n self.comboBox.setObjectName(_fromUtf8(\"comboBox\"))\n self.gridLayout_3.addWidget(self.splitter, 0, 0, 1, 6)\n self.label_5 = QtGui.QLabel(Dialog)\n self.label_5.setObjectName(_fromUtf8(\"label_5\"))\n self.gridLayout_3.addWidget(self.label_5, 1, 0, 1, 1)\n self.comboBox_5 = QtGui.QComboBox(Dialog)\n self.comboBox_5.setObjectName(_fromUtf8(\"comboBox_5\"))\n self.gridLayout_3.addWidget(self.comboBox_5, 1, 1, 1, 1)\n self.lineEdit = QtGui.QLineEdit(Dialog)\n self.lineEdit.setInputMethodHints(QtCore.Qt.ImhNone)\n self.lineEdit.setInputMask(_fromUtf8(\"\"))\n self.lineEdit.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)\n self.lineEdit.setObjectName(_fromUtf8(\"lineEdit\"))\n self.gridLayout_3.addWidget(self.lineEdit, 1, 3, 1, 1)\n self.comboBox_6 = QtGui.QComboBox(Dialog)\n self.comboBox_6.setObjectName(_fromUtf8(\"comboBox_6\"))\n self.gridLayout_3.addWidget(self.comboBox_6, 1, 4, 1, 1)\n spacerItem = QtGui.QSpacerItem(21, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.gridLayout_3.addItem(spacerItem, 1, 5, 1, 1)\n self.gridLayout = QtGui.QGridLayout()\n self.gridLayout.setObjectName(_fromUtf8(\"gridLayout\"))\n self.comboBox_2 = QtGui.QComboBox(Dialog)\n self.comboBox_2.setObjectName(_fromUtf8(\"comboBox_2\"))\n self.gridLayout.addWidget(self.comboBox_2, 0, 1, 1, 1)\n self.label_2 = QtGui.QLabel(Dialog)\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1)\n self.gridLayout_3.addLayout(self.gridLayout, 2, 0, 1, 2)\n spacerItem1 = QtGui.QSpacerItem(39, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.gridLayout_3.addItem(spacerItem1, 2, 2, 1, 1)\n self.label_4 = QtGui.QLabel(Dialog)\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\n self.gridLayout_3.addWidget(self.label_4, 2, 3, 1, 1)\n self.comboBox_4 = QtGui.QComboBox(Dialog)\n self.comboBox_4.setObjectName(_fromUtf8(\"comboBox_4\"))\n self.gridLayout_3.addWidget(self.comboBox_4, 2, 4, 1, 1)\n self.gridLayout_2 = QtGui.QGridLayout()\n self.gridLayout_2.setObjectName(_fromUtf8(\"gridLayout_2\"))\n self.label_3 = QtGui.QLabel(Dialog)\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.gridLayout_2.addWidget(self.label_3, 0, 0, 1, 1)\n self.comboBox_3 = QtGui.QComboBox(Dialog)\n self.comboBox_3.setObjectName(_fromUtf8(\"comboBox_3\"))\n self.gridLayout_2.addWidget(self.comboBox_3, 0, 1, 1, 1)\n self.gridLayout_3.addLayout(self.gridLayout_2, 3, 0, 1, 2)\n spacerItem2 = QtGui.QSpacerItem(233, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)\n self.gridLayout_3.addItem(spacerItem2, 3, 3, 1, 2)\n self.toolButton = QtGui.QToolButton(Dialog)\n self.toolButton.setIconSize(QtCore.QSize(30, 30))\n self.toolButton.setObjectName(_fromUtf8(\"toolButton\"))\n self.gridLayout_3.addWidget(self.toolButton, 3, 5, 1, 1)\n self.tableView = QtGui.QTableView(Dialog)\n self.tableView.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)\n self.tableView.setObjectName(_fromUtf8(\"tableView\"))\n self.gridLayout_3.addWidget(self.tableView, 4, 0, 1, 6)\n self.buttonBox = QtGui.QDialogButtonBox(Dialog)\n self.buttonBox.setOrientation(QtCore.Qt.Horizontal)\n self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Close|QtGui.QDialogButtonBox.Save)\n self.buttonBox.setObjectName(_fromUtf8(\"buttonBox\"))\n self.gridLayout_3.addWidget(self.buttonBox, 5, 3, 1, 3)\n\n self.retranslateUi(Dialog)\n QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8(\"accepted()\")), Dialog.accept)\n QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8(\"rejected()\")), Dialog.reject)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n def retranslateUi(self, Dialog):\n Dialog.setWindowTitle(_translate(\"Dialog\", \"Dialog\", None))\n self.label.setText(_translate(\"Dialog\", \"Data field:\", None))\n self.label_5.setText(_translate(\"Dialog\", \"Neighbouring method:\", None))\n self.label_2.setText(_translate(\"Dialog\", \"Weighting scheme:\", None))\n self.label_4.setText(_translate(\"Dialog\", \"Variance assumption:\", None))\n self.label_3.setText(_translate(\"Dialog\", \"Alternative hypothesis:\", None))\n self.toolButton.setText(_translate(\"Dialog\", \"...\", None))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements graph-dav-servers.py from centic9/subversion-ppa (path: tools/dev/graph-dav-servers.py)."}, {"role": "assistant", "content": "# tools/dev/graph-dav-servers.py (from centic9/subversion-ppa, license: apache-2.0)\n\n#!/usr/bin/env python\n#\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n#\n#\n# graph-svn-dav.py by Brian W. Fitzpatrick \n#\n# This was originally a quick hack to make a pretty picture of svn DAV servers.\n#\n# I've dropped it in Subversion's repository at the request of Karl Fogel.\n#\n# Be warned this this script has many dependencies that don't ship with Python.\n\nimport sys\nimport os\nimport fileinput\nimport datetime\nimport time\nimport datetime\nfrom matplotlib import dates\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pylab\nimport Image\n\nOUTPUT_FILE = '../../www/images/svn-dav-securityspace-survey.png'\nOUTPUT_IMAGE_WIDTH = 800\n\nSTATS = [\n ('1/1/2003', 70),\n ('2/1/2003', 158),\n ('3/1/2003', 222),\n ('4/1/2003', 250),\n ('5/1/2003', 308),\n ('6/1/2003', 369),\n ('7/1/2003', 448),\n ('8/1/2003', 522),\n ('9/1/2003', 665),\n ('10/1/2003', 782),\n ('11/1/2003', 969),\n ('12/1/2003', 1009),\n ('1/1/2004', 1162),\n ('2/1/2004', 1307),\n ('3/1/2004', 1424),\n ('4/1/2004', 1792),\n ('5/1/2004', 2113),\n ('6/1/2004', 2502),\n ('7/1/2004', 2941),\n ('8/1/2004', 3863),\n ('9/1/2004', 4174),\n ('10/1/2004', 4187),\n ('11/1/2004', 4783),\n ('12/1/2004', 4995),\n ('1/1/2005', 5565),\n ('2/1/2005', 6505),\n ('3/1/2005', 7897),\n ('4/1/2005', 8751),\n ('5/1/2005', 9793),\n ('6/1/2005', 11534),\n ('7/1/2005', 12808),\n ('8/1/2005', 13545),\n ('9/1/2005', 15233),\n ('10/1/2005', 17588),\n ('11/1/2005', 18893),\n ('12/1/2005', 20278),\n ('1/1/2006', 21084),\n ('2/1/2006', 23861),\n ('3/1/2006', 26540),\n ('4/1/2006', 29396),\n ('5/1/2006', 33001),\n ('6/1/2006', 35082),\n ('7/1/2006', 38939),\n ('8/1/2006', 40672),\n ('9/1/2006', 46525),\n ('10/1/2006', 54247),\n ('11/1/2006', 63145),\n ('12/1/2006', 68988),\n ('1/1/2007', 77027),\n ('2/1/2007', 84813),\n ('3/1/2007', 95679),\n ('4/1/2007', 103852),\n ('5/1/2007', 117267),\n ('6/1/2007', 133665),\n ('7/1/2007', 137575),\n ('8/1/2007', 155426),\n ('9/1/2007', 159055),\n ('10/1/2007', 169939),\n ('11/1/2007', 180831),\n ('12/1/2007', 187093),\n ('1/1/2008', 199432),\n ('2/1/2008', 221547),\n ('3/1/2008', 240794),\n ('4/1/2008', 255520),\n ('5/1/2008', 269478),\n ('6/1/2008', 286614),\n ('7/1/2008', 294579),\n ('8/1/2008', 307923),\n ('9/1/2008', 254757),\n ('10/1/2008', 268081),\n ('11/1/2008', 299071),\n ('12/1/2008', 330884),\n ('1/1/2009', 369719),\n ('2/1/2009', 378434),\n ('3/1/2009', 390502),\n ('4/1/2009', 408658),\n ('5/1/2009', 407044),\n ('6/1/2009', 406520),\n ('7/1/2009', 334276),\n ]\n\ndef get_date(raw_date):\n month, day, year = map(int, raw_date.split('/'))\n return datetime.datetime(year, month, day)\n\ndef get_ordinal_date(date):\n # This is the only way I can get matplotlib to do the dates right.\n return int(dates.date2num(get_date(date)))\n\ndef load_stats():\n dates = [get_ordinal_date(date) for date, value in STATS]\n counts = [x[1] for x in STATS]\n\n return dates, counts\n\ndef draw_graph(dates, counts):\n ###########################################################\n # Drawing takes place here.\n pylab.figure(1)\n\n ax = pylab.subplot(111)\n pylab.plot_date(dates, counts,\n color='r', linestyle='-', marker='o', markersize=3)\n\n ax.xaxis.set_major_formatter( pylab.DateFormatter('%Y') )\n ax.xaxis.set_major_locator( pylab.YearLocator() )\n ax.xaxis.set_minor_locator( pylab.MonthLocator() )\n ax.set_xlim( (dates[0] - 92, dates[len(dates) - 1] + 92) )\n\n ax.yaxis.set_major_formatter( pylab.FormatStrFormatter('%d') )\n\n pylab.ylabel('Total # of Public DAV Servers')\n\n lastdate = datetime.datetime.fromordinal(dates[len(dates) - 1]).strftime(\"%B %Y\")\n pylab.xlabel(\"Data as of \" + lastdate)\n pylab.title('Security Space Survey of\\nPublic Subversion DAV Servers')\n # End drawing\n ###########################################################\n png = open(OUTPUT_FILE, 'w')\n pylab.savefig(png)\n png.close()\n os.rename(OUTPUT_FILE, OUTPUT_FILE + \".tmp.png\")\n try:\n im = Image.open(OUTPUT_FILE + \".tmp.png\", 'r')\n (width, height) = im.size\n print(\"Original size: %d x %d pixels\" % (width, height))\n scale = float(OUTPUT_IMAGE_WIDTH) / float(width)\n width = OUTPUT_IMAGE_WIDTH\n height = int(float(height) * scale)\n print(\"Final size: %d x %d pixels\" % (width, height))\n im = im.resize((width, height), Image.ANTIALIAS)\n im.save(OUTPUT_FILE, im.format)\n os.unlink(OUTPUT_FILE + \".tmp.png\")\n except Exception, e:\n sys.stderr.write(\"Error attempting to resize the graphic: %s\\n\" % (str(e)))\n os.rename(OUTPUT_FILE + \".tmp.png\", OUTPUT_FILE)\n raise\n pylab.close()\n\nif __name__ == '__main__':\n dates, counts = load_stats()\n draw_graph(dates, counts)\n print(\"Don't forget to update ../../www/svn-dav-securityspace-survey.html!\")"}]} {"messages": [{"role": "user", "content": "Write Python code that implements iso8859_10.py from molebot/brython (path: www/src/Lib/encodings/iso8859_10.py)."}, {"role": "assistant", "content": "# www/src/Lib/encodings/iso8859_10.py (from molebot/brython, license: bsd-3-clause)\n\n\"\"\" Python Character Mapping Codec iso8859_10 generated from 'MAPPINGS/ISO8859/8859-10.TXT' with gencodec.py.\n\n\"\"\"#\"\n\nimport codecs\n\n### Codec APIs\n\nclass Codec(codecs.Codec):\n\n def encode(self,input,errors='strict'):\n return codecs.charmap_encode(input,errors,encoding_table)\n\n def decode(self,input,errors='strict'):\n return codecs.charmap_decode(input,errors,decoding_table)\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n def encode(self, input, final=False):\n return codecs.charmap_encode(input,self.errors,encoding_table)[0]\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n def decode(self, input, final=False):\n return codecs.charmap_decode(input,self.errors,decoding_table)[0]\n\nclass StreamWriter(Codec,codecs.StreamWriter):\n pass\n\nclass StreamReader(Codec,codecs.StreamReader):\n pass\n\n### encodings module API\n\ndef getregentry():\n return codecs.CodecInfo(\n name='iso8859-10',\n encode=Codec().encode,\n decode=Codec().decode,\n incrementalencoder=IncrementalEncoder,\n incrementaldecoder=IncrementalDecoder,\n streamreader=StreamReader,\n streamwriter=StreamWriter,\n )\n\n### Decoding Table\n\ndecoding_table = (\n '\\x00' # 0x00 -> NULL\n '\\x01' # 0x01 -> START OF HEADING\n '\\x02' # 0x02 -> START OF TEXT\n '\\x03' # 0x03 -> END OF TEXT\n '\\x04' # 0x04 -> END OF TRANSMISSION\n '\\x05' # 0x05 -> ENQUIRY\n '\\x06' # 0x06 -> ACKNOWLEDGE\n '\\x07' # 0x07 -> BELL\n '\\x08' # 0x08 -> BACKSPACE\n '\\t' # 0x09 -> HORIZONTAL TABULATION\n '\\n' # 0x0A -> LINE FEED\n '\\x0b' # 0x0B -> VERTICAL TABULATION\n '\\x0c' # 0x0C -> FORM FEED\n '\\r' # 0x0D -> CARRIAGE RETURN\n '\\x0e' # 0x0E -> SHIFT OUT\n '\\x0f' # 0x0F -> SHIFT IN\n '\\x10' # 0x10 -> DATA LINK ESCAPE\n '\\x11' # 0x11 -> DEVICE CONTROL ONE\n '\\x12' # 0x12 -> DEVICE CONTROL TWO\n '\\x13' # 0x13 -> DEVICE CONTROL THREE\n '\\x14' # 0x14 -> DEVICE CONTROL FOUR\n '\\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE\n '\\x16' # 0x16 -> SYNCHRONOUS IDLE\n '\\x17' # 0x17 -> END OF TRANSMISSION BLOCK\n '\\x18' # 0x18 -> CANCEL\n '\\x19' # 0x19 -> END OF MEDIUM\n '\\x1a' # 0x1A -> SUBSTITUTE\n '\\x1b' # 0x1B -> ESCAPE\n '\\x1c' # 0x1C -> FILE SEPARATOR\n '\\x1d' # 0x1D -> GROUP SEPARATOR\n '\\x1e' # 0x1E -> RECORD SEPARATOR\n '\\x1f' # 0x1F -> UNIT SEPARATOR\n ' ' # 0x20 -> SPACE\n '!' # 0x21 -> EXCLAMATION MARK\n '\"' # 0x22 -> QUOTATION MARK\n '#' # 0x23 -> NUMBER SIGN\n '$' # 0x24 -> DOLLAR SIGN\n '%' # 0x25 -> PERCENT SIGN\n '&' # 0x26 -> AMPERSAND\n \"'\" # 0x27 -> APOSTROPHE\n '(' # 0x28 -> LEFT PARENTHESIS\n ')' # 0x29 -> RIGHT PARENTHESIS\n '*' # 0x2A -> ASTERISK\n '+' # 0x2B -> PLUS SIGN\n ',' # 0x2C -> COMMA\n '-' # 0x2D -> HYPHEN-MINUS\n '.' # 0x2E -> FULL STOP\n '/' # 0x2F -> SOLIDUS\n '0' # 0x30 -> DIGIT ZERO\n '1' # 0x31 -> DIGIT ONE\n '2' # 0x32 -> DIGIT TWO\n '3' # 0x33 -> DIGIT THREE\n '4' # 0x34 -> DIGIT FOUR\n '5' # 0x35 -> DIGIT FIVE\n '6' # 0x36 -> DIGIT SIX\n '7' # 0x37 -> DIGIT SEVEN\n '8' # 0x38 -> DIGIT EIGHT\n '9' # 0x39 -> DIGIT NINE\n ':' # 0x3A -> COLON\n ';' # 0x3B -> SEMICOLON\n '<' # 0x3C -> LESS-THAN SIGN\n '=' # 0x3D -> EQUALS SIGN\n '>' # 0x3E -> GREATER-THAN SIGN\n '?' # 0x3F -> QUESTION MARK\n '@' # 0x40 -> COMMERCIAL AT\n 'A' # 0x41 -> LATIN CAPITAL LETTER A\n 'B' # 0x42 -> LATIN CAPITAL LETTER B\n 'C' # 0x43 -> LATIN CAPITAL LETTER C\n 'D' # 0x44 -> LATIN CAPITAL LETTER D\n 'E' # 0x45 -> LATIN CAPITAL LETTER E\n 'F' # 0x46 -> LATIN CAPITAL LETTER F\n 'G' # 0x47 -> LATIN CAPITAL LETTER G\n 'H' # 0x48 -> LATIN CAPITAL LETTER H\n 'I' # 0x49 -> LATIN CAPITAL LETTER I\n 'J' # 0x4A -> LATIN CAPITAL LETTER J\n 'K' # 0x4B -> LATIN CAPITAL LETTER K\n 'L' # 0x4C -> LATIN CAPITAL LETTER L\n 'M' # 0x4D -> LATIN CAPITAL LETTER M\n 'N' # 0x4E -> LATIN CAPITAL LETTER N\n 'O' # 0x4F -> LATIN CAPITAL LETTER O\n 'P' # 0x50 -> LATIN CAPITAL LETTER P\n 'Q' # 0x51 -> LATIN CAPITAL LETTER Q\n 'R' # 0x52 -> LATIN CAPITAL LETTER R\n 'S' # 0x53 -> LATIN CAPITAL LETTER S\n 'T' # 0x54 -> LATIN CAPITAL LETTER T\n 'U' # 0x55 -> LATIN CAPITAL LETTER U\n 'V' # 0x56 -> LATIN CAPITAL LETTER V\n 'W' # 0x57 -> LATIN CAPITAL LETTER W\n 'X' # 0x58 -> LATIN CAPITAL LETTER X\n 'Y' # 0x59 -> LATIN CAPITAL LETTER Y\n 'Z' # 0x5A -> LATIN CAPITAL LETTER Z\n '[' # 0x5B -> LEFT SQUARE BRACKET\n '\\\\' # 0x5C -> REVERSE SOLIDUS\n ']' # 0x5D -> RIGHT SQUARE BRACKET\n '^' # 0x5E -> CIRCUMFLEX ACCENT\n '_' # 0x5F -> LOW LINE\n '`' # 0x60 -> GRAVE ACCENT\n 'a' # 0x61 -> LATIN SMALL LETTER A\n 'b' # 0x62 -> LATIN SMALL LETTER B\n 'c' # 0x63 -> LATIN SMALL LETTER C\n 'd' # 0x64 -> LATIN SMALL LETTER D\n 'e' # 0x65 -> LATIN SMALL LETTER E\n 'f' # 0x66 -> LATIN SMALL LETTER F\n 'g' # 0x67 -> LATIN SMALL LETTER G\n 'h' # 0x68 -> LATIN SMALL LETTER H\n 'i' # 0x69 -> LATIN SMALL LETTER I\n 'j' # 0x6A -> LATIN SMALL LETTER J\n 'k' # 0x6B -> LATIN SMALL LETTER K\n 'l' # 0x6C -> LATIN SMALL LETTER L\n 'm' # 0x6D -> LATIN SMALL LETTER M\n 'n' # 0x6E -> LATIN SMALL LETTER N\n 'o' # 0x6F -> LATIN SMALL LETTER O\n 'p' # 0x70 -> LATIN SMALL LETTER P\n 'q' # 0x71 -> LATIN SMALL LETTER Q\n 'r' # 0x72 -> LATIN SMALL LETTER R\n 's' # 0x73 -> LATIN SMALL LETTER S\n 't' # 0x74 -> LATIN SMALL LETTER T\n 'u' # 0x75 -> LATIN SMALL LETTER U\n 'v' # 0x76 -> LATIN SMALL LETTER V\n 'w' # 0x77 -> LATIN SMALL LETTER W\n 'x' # 0x78 -> LATIN SMALL LETTER X\n 'y' # 0x79 -> LATIN SMALL LETTER Y\n 'z' # 0x7A -> LATIN SMALL LETTER Z\n '{' # 0x7B -> LEFT CURLY BRACKET\n '|' # 0x7C -> VERTICAL LINE\n '}' # 0x7D -> RIGHT CURLY BRACKET\n '~' # 0x7E -> TILDE\n '\\x7f' # 0x7F -> DELETE\n '\\x80' # 0x80 -> \n '\\x81' # 0x81 -> \n '\\x82' # 0x82 -> \n '\\x83' # 0x83 -> \n '\\x84' # 0x84 -> \n '\\x85' # 0x85 -> \n '\\x86' # 0x86 -> \n '\\x87' # 0x87 -> \n '\\x88' # 0x88 -> \n '\\x89' # 0x89 -> \n '\\x8a' # 0x8A -> \n '\\x8b' # 0x8B -> \n '\\x8c' # 0x8C -> \n '\\x8d' # 0x8D -> \n '\\x8e' # 0x8E -> \n '\\x8f' # 0x8F -> \n '\\x90' # 0x90 -> \n '\\x91' # 0x91 -> \n '\\x92' # 0x92 -> \n '\\x93' # 0x93 -> \n '\\x94' # 0x94 -> \n '\\x95' # 0x95 -> \n '\\x96' # 0x96 -> \n '\\x97' # 0x97 -> \n '\\x98' # 0x98 -> \n '\\x99' # 0x99 -> \n '\\x9a' # 0x9A -> \n '\\x9b' # 0x9B -> \n '\\x9c' # 0x9C -> \n '\\x9d' # 0x9D -> \n '\\x9e' # 0x9E -> \n '\\x9f' # 0x9F -> \n '\\xa0' # 0xA0 -> NO-BREAK SPACE\n '\\u0104' # 0xA1 -> LATIN CAPITAL LETTER A WITH OGONEK\n '\\u0112' # 0xA2 -> LATIN CAPITAL LETTER E WITH MACRON\n '\\u0122' # 0xA3 -> LATIN CAPITAL LETTER G WITH CEDILLA\n '\\u012a' # 0xA4 -> LATIN CAPITAL LETTER I WITH MACRON\n '\\u0128' # 0xA5 -> LATIN CAPITAL LETTER I WITH TILDE\n '\\u0136' # 0xA6 -> LATIN CAPITAL LETTER K WITH CEDILLA\n '\\xa7' # 0xA7 -> SECTION SIGN\n '\\u013b' # 0xA8 -> LATIN CAPITAL LETTER L WITH CEDILLA\n '\\u0110' # 0xA9 -> LATIN CAPITAL LETTER D WITH STROKE\n '\\u0160' # 0xAA -> LATIN CAPITAL LETTER S WITH CARON\n '\\u0166' # 0xAB -> LATIN CAPITAL LETTER T WITH STROKE\n '\\u017d' # 0xAC -> LATIN CAPITAL LETTER Z WITH CARON\n '\\xad' # 0xAD -> SOFT HYPHEN\n '\\u016a' # 0xAE -> LATIN CAPITAL LETTER U WITH MACRON\n '\\u014a' # 0xAF -> LATIN CAPITAL LETTER ENG\n '\\xb0' # 0xB0 -> DEGREE SIGN\n '\\u0105' # 0xB1 -> LATIN SMALL LETTER A WITH OGONEK\n '\\u0113' # 0xB2 -> LATIN SMALL LETTER E WITH MACRON\n '\\u0123' # 0xB3 -> LATIN SMALL LETTER G WITH CEDILLA\n '\\u012b' # 0xB4 -> LATIN SMALL LETTER I WITH MACRON\n '\\u0129' # 0xB5 -> LATIN SMALL LETTER I WITH TILDE\n '\\u0137' # 0xB6 -> LATIN SMALL LETTER K WITH CEDILLA\n '\\xb7' # 0xB7 -> MIDDLE DOT\n '\\u013c' # 0xB8 -> LATIN SMALL LETTER L WITH CEDILLA\n '\\u0111' # 0xB9 -> LATIN SMALL LETTER D WITH STROKE\n '\\u0161' # 0xBA -> LATIN SMALL LETTER S WITH CARON\n '\\u0167' # 0xBB -> LATIN SMALL LETTER T WITH STROKE\n '\\u017e' # 0xBC -> LATIN SMALL LETTER Z WITH CARON\n '\\u2015' # 0xBD -> HORIZONTAL BAR\n '\\u016b' # 0xBE -> LATIN SMALL LETTER U WITH MACRON\n '\\u014b' # 0xBF -> LATIN SMALL LETTER ENG\n '\\u0100' # 0xC0 -> LATIN CAPITAL LETTER A WITH MACRON\n '\\xc1' # 0xC1 -> LATIN CAPITAL LETTER A WITH ACUTE\n '\\xc2' # 0xC2 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX\n '\\xc3' # 0xC3 -> LATIN CAPITAL LETTER A WITH TILDE\n '\\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS\n '\\xc5' # 0xC5 -> LATIN CAPITAL LETTER A WITH RING ABOVE\n '\\xc6' # 0xC6 -> LATIN CAPITAL LETTER AE\n '\\u012e' # 0xC7 -> LATIN CAPITAL LETTER I WITH OGONEK\n '\\u010c' # 0xC8 -> LATIN CAPITAL LETTER C WITH CARON\n '\\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE\n '\\u0118' # 0xCA -> LATIN CAPITAL LETTER E WITH OGONEK\n '\\xcb' # 0xCB -> LATIN CAPITAL LETTER E WITH DIAERESIS\n '\\u0116' # 0xCC -> LATIN CAPITAL LETTER E WITH DOT ABOVE\n '\\xcd' # 0xCD -> LATIN CAPITAL LETTER I WITH ACUTE\n '\\xce' # 0xCE -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX\n '\\xcf' # 0xCF -> LATIN CAPITAL LETTER I WITH DIAERESIS\n '\\xd0' # 0xD0 -> LATIN CAPITAL LETTER ETH (Icelandic)\n '\\u0145' # 0xD1 -> LATIN CAPITAL LETTER N WITH CEDILLA\n '\\u014c' # 0xD2 -> LATIN CAPITAL LETTER O WITH MACRON\n '\\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE\n '\\xd4' # 0xD4 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX\n '\\xd5' # 0xD5 -> LATIN CAPITAL LETTER O WITH TILDE\n '\\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS\n '\\u0168' # 0xD7 -> LATIN CAPITAL LETTER U WITH TILDE\n '\\xd8' # 0xD8 -> LATIN CAPITAL LETTER O WITH STROKE\n '\\u0172' # 0xD9 -> LATIN CAPITAL LETTER U WITH OGONEK\n '\\xda' # 0xDA -> LATIN CAPITAL LETTER U WITH ACUTE\n '\\xdb' # 0xDB -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX\n '\\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS\n '\\xdd' # 0xDD -> LATIN CAPITAL LETTER Y WITH ACUTE\n '\\xde' # 0xDE -> LATIN CAPITAL LETTER THORN (Icelandic)\n '\\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S (German)\n '\\u0101' # 0xE0 -> LATIN SMALL LETTER A WITH MACRON\n '\\xe1' # 0xE1 -> LATIN SMALL LETTER A WITH ACUTE\n '\\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX\n '\\xe3' # 0xE3 -> LATIN SMALL LETTER A WITH TILDE\n '\\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS\n '\\xe5' # 0xE5 -> LATIN SMALL LETTER A WITH RING ABOVE\n '\\xe6' # 0xE6 -> LATIN SMALL LETTER AE\n '\\u012f' # 0xE7 -> LATIN SMALL LETTER I WITH OGONEK\n '\\u010d' # 0xE8 -> LATIN SMALL LETTER C WITH CARON\n '\\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE\n '\\u0119' # 0xEA -> LATIN SMALL LETTER E WITH OGONEK\n '\\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS\n '\\u0117' # 0xEC -> LATIN SMALL LETTER E WITH DOT ABOVE\n '\\xed' # 0xED -> LATIN SMALL LETTER I WITH ACUTE\n '\\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX\n '\\xef' # 0xEF -> LATIN SMALL LETTER I WITH DIAERESIS\n '\\xf0' # 0xF0 -> LATIN SMALL LETTER ETH (Icelandic)\n '\\u0146' # 0xF1 -> LATIN SMALL LETTER N WITH CEDILLA\n '\\u014d' # 0xF2 -> LATIN SMALL LETTER O WITH MACRON\n '\\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE\n '\\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX\n '\\xf5' # 0xF5 -> LATIN SMALL LETTER O WITH TILDE\n '\\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS\n '\\u0169' # 0xF7 -> LATIN SMALL LETTER U WITH TILDE\n '\\xf8' # 0xF8 -> LATIN SMALL LETTER O WITH STROKE\n '\\u0173' # 0xF9 -> LATIN SMALL LETTER U WITH OGONEK\n '\\xfa' # 0xFA -> LATIN SMALL LETTER U WITH ACUTE\n '\\xfb' # 0xFB -> LATIN SMALL LETTER U WITH CIRCUMFLEX\n '\\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS\n '\\xfd' # 0xFD -> LATIN SMALL LETTER Y WITH ACUTE\n '\\xfe' # 0xFE -> LATIN SMALL LETTER THORN (Icelandic)\n '\\u0138' # 0xFF -> LATIN SMALL LETTER KRA\n)\n\n### Encoding table\nencoding_table=codecs.charmap_build(decoding_table)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements rcs380.py from PHSCRC/phsled (path: nfc/clf/rcs380.py)."}, {"role": "assistant", "content": "# nfc/clf/rcs380.py (from PHSCRC/phsled, license: mit)\n\n# -*- coding: latin-1 -*-\n# -----------------------------------------------------------------------------\n# Copyright 2012-2015 Stephen Tiedemann \n#\n# Licensed under the EUPL, Version 1.1 or - as soon they \n# will be approved by the European Commission - subsequent\n# versions of the EUPL (the \"Licence\");\n# You may not use this work except in compliance with the\n# Licence.\n# You may obtain a copy of the Licence at:\n#\n# http://www.osor.eu/eupl\n#\n# Unless required by applicable law or agreed to in\n# writing, software distributed under the Licence is\n# distributed on an \"AS IS\" basis,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied.\n# See the Licence for the specific language governing\n# permissions and limitations under the Licence.\n# -----------------------------------------------------------------------------\n\"\"\"Driver module for contactless devices based on the Sony NFC Port-100\nchipset. The only product known to use this chipset is the PaSoRi\nRC-S380. The RC-S380 connects to the host as a native USB device.\n\nThe RC-S380 has been the first NFC Forum certified device. It supports\nreading and writing of all NFC Forum tags as well as peer-to-peer\nmode. In addition, the NFC Port-100 also supports card emulation Type\nA and Type F Technology. A notable restriction is that peer-to-peer\nactive communication mode (not required for NFC Forum certification)\nis not supported.\n\n========== ======= ============\nfunction support remarks\n========== ======= ============\nsense_tta yes \nsense_ttb yes \nsense_ttf yes\nsense_dep no\nlisten_tta yes Type F responses can not be disabled\nlisten_ttb no\nlisten_ttf yes\nlisten_dep yes Only passive communication mode\n========== ======= ============\n\n\"\"\"\n\nimport logging\nlog = logging.getLogger(__name__)\n\nimport os\nimport time\nimport errno\nimport struct\nimport operator\nfrom binascii import hexlify\n\nimport nfc.clf\nfrom . import device\n\nclass Frame():\n def __init__(self, data):\n self._data = None\n self._frame = None\n\n if data[0:3] == bytearray(\"\\x00\\x00\\xff\"):\n frame = bytearray(data)\n if frame == bytearray(\"\\x00\\x00\\xff\\x00\\xff\\x00\"):\n self._type = \"ack\"\n elif frame == bytearray(\"\\x00\\x00\\xFF\\xFF\\xFF\"):\n self._type = \"err\"\n elif frame[3:5] == bytearray(\"\\xff\\xff\"):\n self._type = \"data\"\n if self.type == \"data\":\n length = struct.unpack(\"Q\", str(data[0:8]))\n \n def set_command_type(self, command_type):\n data = self.send_command(0x2A, [command_type], 100)\n if data and data[0] != 0:\n raise StatusError(data[0])\n\nclass Device(device.Device):\n # Device driver for the Sony NFC Port-100 chipset.\n \n def __init__(self, chipset, logger):\n self.chipset = chipset\n self.log = logger\n\n minor, major = self.chipset.get_firmware_version()\n self._chipset_name = \"NFC Port-100 v{0:x}.{1:02x}\".format(major, minor)\n \n def close(self):\n self.chipset.close()\n self.chipset = None\n\n def mute(self):\n self.chipset.switch_rf(\"off\")\n\n def sense_tta(self, target):\n \"\"\"Sense for a Type A Target is supported for 106, 212 and 424\n kbps. However, there may not be any target that understands the\n activation commands in other than 106 kbps.\n\n \"\"\"\n log.debug(\"polling for NFC-A technology\")\n \n if target.brty not in (\"106A\", \"212A\", \"424A\"):\n message = \"unsupported bitrate {0}\".format(target.brty)\n raise nfc.clf.UnsupportedTargetError(message)\n\n self.chipset.in_set_rf(target.brty)\n self.chipset.in_set_protocol(self.chipset.in_set_protocol_defaults)\n self.chipset.in_set_protocol(initial_guard_time=6, add_crc=0,\n check_crc=0, check_parity=1,\n last_byte_bit_count=7)\n \n sens_req = (target.sens_req if target.sens_req else\n bytearray.fromhex(\"26\"))\n \n try:\n sens_res = self.chipset.in_comm_rf(sens_req, 30)\n if len(sens_res) != 2: return None\n except CommunicationError as error:\n if error != \"RECEIVE_TIMEOUT_ERROR\": log.debug(error)\n return None\n \n log.debug(\"rcvd SENS_RES \" + hexlify(sens_res))\n\n if sens_res[0] & 0x1F == 0:\n log.debug(\"type 1 tag target found\")\n self.chipset.in_set_protocol(last_byte_bit_count=8, add_crc=2,\n check_crc=2, type_1_tag_rrdd=2)\n target = nfc.clf.RemoteTarget(target.brty, sens_res=sens_res)\n if sens_res[1] & 0x0F == 0b1100:\n rid_cmd = bytearray.fromhex(\"78 0000 00000000\")\n log.debug(\"send RID_CMD \" + hexlify(rid_cmd))\n try:\n target.rid_res = self.chipset.in_comm_rf(rid_cmd, 30)\n except CommunicationError as error:\n log.debug(error)\n return None\n return target\n\n # other than type 1 tag\n try:\n self.chipset.in_set_protocol(last_byte_bit_count=8, add_parity=1)\n if target.sel_req:\n uid = target.sel_req\n if len(uid) > 4: uid = \"\\x88\" + uid\n if len(uid) > 8: uid = uid[0:4] + \"\\x88\" + uid[4:]\n self.chipset.in_set_protocol(add_crc=1, check_crc=1)\n for i, sel_cmd in zip(range(0,len(uid),4),\"\\x93\\x95\\x97\"):\n sel_req = sel_cmd + \"\\x70\" + uid[i:i+4]\n sel_req.append(reduce(operator.xor, sel_req[2:6])) # BCC\n log.debug(\"send SEL_REQ \" + hexlify(sel_req))\n sel_res = self.chipset.in_comm_rf(sel_req, 30)\n log.debug(\"rcvd SEL_RES \" + hexlify(sel_res))\n uid = target.sel_req\n else:\n uid = bytearray()\n for sel_cmd in \"\\x93\\x95\\x97\":\n self.chipset.in_set_protocol(add_crc=0, check_crc=0)\n sdd_req = sel_cmd + \"\\x20\"\n log.debug(\"send SDD_REQ \" + hexlify(sdd_req))\n sdd_res = self.chipset.in_comm_rf(sdd_req, 30)\n log.debug(\"rcvd SDD_RES \" + hexlify(sdd_res))\n self.chipset.in_set_protocol(add_crc=1, check_crc=1)\n sel_req = sel_cmd + \"\\x70\" + sdd_res\n log.debug(\"send SEL_REQ \" + hexlify(sel_req))\n sel_res = self.chipset.in_comm_rf(sel_req, 30)\n log.debug(\"rcvd SEL_RES \" + hexlify(sel_res))\n if sel_res[0] & 0b00000100: uid = uid + sdd_res[1:4]\n else: uid = uid + sdd_res[0:4]; break\n if sel_res[0] & 0b00000100 == 0:\n return nfc.clf.RemoteTarget(target.brty, sens_res=sens_res,\n sel_res=sel_res, sdd_res=uid)\n except CommunicationError as error:\n log.debug(error)\n\n def sense_ttb(self, target):\n \"\"\"Sense for a Type B Target is supported for 106, 212 and 424\n kbps. However, there may not be any target that understands the\n activation command in other than 106 kbps.\n\n \"\"\"\n log.debug(\"polling for NFC-B technology\")\n\n if target.brty not in (\"106B\", \"212B\", \"424B\"):\n message = \"unsupported bitrate {0}\".format(target.brty)\n raise nfc.clf.UnsupportedTargetError(message)\n\n self.chipset.in_set_rf(target.brty)\n self.chipset.in_set_protocol(self.chipset.in_set_protocol_defaults)\n self.chipset.in_set_protocol(initial_guard_time=20, add_sof=1,\n check_sof=1, add_eof=1, check_eof=1)\n\n sensb_req = (target.sensb_req if target.sensb_req else\n bytearray.fromhex(\"050010\"))\n \n log.debug(\"send SENSB_REQ \" + hexlify(sensb_req))\n try:\n sensb_res = self.chipset.in_comm_rf(sensb_req, 30)\n except CommunicationError as error:\n if error != \"RECEIVE_TIMEOUT_ERROR\": log.debug(error)\n return None\n \n if len(sensb_res) >= 12 and sensb_res[0] == 0x50:\n log.debug(\"rcvd SENSB_RES \" + hexlify(sensb_res))\n return nfc.clf.RemoteTarget(target.brty, sensb_res=sensb_res)\n\n def sense_ttf(self, target):\n \"\"\"Sense for a Type F Target is supported for 212 and 424 kbps.\n\n \"\"\"\n log.debug(\"polling for NFC-F technology\")\n\n if target.brty not in (\"212F\", \"424F\"):\n message = \"unsupported bitrate {0}\".format(target.brty)\n raise nfc.clf.UnsupportedTargetError(message)\n\n self.chipset.in_set_rf(target.brty)\n self.chipset.in_set_protocol(self.chipset.in_set_protocol_defaults)\n self.chipset.in_set_protocol(initial_guard_time=24)\n\n sensf_req = (target.sensf_req if target.sensf_req else\n bytearray.fromhex(\"00FFFF0100\"))\n \n log.debug(\"send SENSF_REQ \" + hexlify(sensf_req))\n try:\n frame = chr(len(sensf_req)+1) + sensf_req\n frame = self.chipset.in_comm_rf(frame, 10)\n except CommunicationError as error:\n if error != \"RECEIVE_TIMEOUT_ERROR\": log.debug(error)\n return None\n \n if len(frame) >= 18 and frame[0] == len(frame) and frame[1] == 1:\n log.debug(\"rcvd SENSF_RES \" + hexlify(frame[1:]))\n return nfc.clf.RemoteTarget(target.brty, sensf_res=frame[1:])\n\n def sense_dep(self, target):\n \"\"\"Sense for an active DEP Target is not supported. The device only\n supports passive activation via sense_tta/sense_ttf.\n\n \"\"\"\n message = \"{device} does not support sense for active DEP Target\"\n raise nfc.clf.UnsupportedTargetError(message.format(device=self))\n \n def listen_tta(self, target, timeout):\n \"\"\"Listen as Type A Target in 106 kbps.\n\n Restrictions:\n\n * It is not possible to send short frames that are required\n for ACK and NAK responses. This means that a Type 2 Tag\n emulation can only implement a single sector memory model.\n \n * It can not be avoided that the chipset responds to SENSF_REQ\n commands. The driver configures the SENSF_RES response to\n all zero and ignores all Type F communication but eventually\n it depends on the remote device whether Type A Target\n activation will still be attempted.\n\n \"\"\"\n if not target.brty == '106A':\n info = \"unsupported target bitrate: %r\" % target.brty\n raise nfc.clf.UnsupportedTargetError(info)\n \n if target.rid_res:\n info = \"listening for type 1 tag activation is not supported\"\n raise nfc.clf.UnsupportedTargetError(info)\n \n try:\n assert target.sens_res is not None, \"sens_res is required\"\n assert target.sdd_res is not None, \"sdd_res is required\"\n assert target.sel_res is not None, \"sel_res is required\"\n assert len(target.sens_res) == 2, \"sens_res must be 2 byte\"\n assert len(target.sdd_res) == 4, \"sdd_res must be 4 byte\"\n assert len(target.sel_res) == 1, \"sel_res must be 1 byte\"\n assert target.sdd_res[0] == 0x08, \"sdd_res[0] must be 08h\"\n except AssertionError as error:\n raise ValueError(str(error))\n \n nfca_params = target.sens_res + target.sdd_res[1:4] + target.sel_res\n log.debug(\"nfca_params %s\", hexlify(nfca_params))\n \n self.chipset.tg_set_rf(\"106A\")\n self.chipset.tg_set_protocol(self.chipset.tg_set_protocol_defaults)\n self.chipset.tg_set_protocol(rf_off_error=False)\n\n time_to_return = time.time() + timeout\n tg_comm_rf_args = {'mdaa': True, 'nfca_params': nfca_params}\n tg_comm_rf_args['recv_timeout'] = min(int(1000 * timeout), 0xFFFF)\n \n def listen_tta_tt2():\n recv_timeout = tg_comm_rf_args['recv_timeout']\n while recv_timeout > 0:\n log.debug(\"wait %d ms for Type 2 Tag activation\", recv_timeout)\n try:\n data = self.chipset.tg_comm_rf(**tg_comm_rf_args)\n except CommunicationError as error:\n log.debug(error)\n else:\n brty = ('106A', '212F', '424F')[data[0]-11]\n log.debug(\"%s rcvd %s\", brty, hexlify(buffer(data, 7)))\n if brty == \"106A\" and data[2] & 0x03 == 3:\n self.chipset.tg_set_protocol(rf_off_error=True)\n return nfc.clf.LocalTarget(\n \"106A\", sens_res=nfca_params[0:2],\n sdd_res='\\x08'+nfca_params[2:5],\n sel_res=nfca_params[5:6], tt2_cmd=data[7:])\n else:\n log.debug(\"not a 106A Type 2 Tag command\")\n finally:\n recv_timeout = int(1000 * (time_to_return - time.time()))\n tg_comm_rf_args['recv_timeout'] = recv_timeout\n\n def listen_tta_tt4():\n rats_cmd = rats_res = None\n recv_timeout = tg_comm_rf_args['recv_timeout']\n while recv_timeout > 0:\n log.debug(\"wait %d ms for 106A TT4 command\", recv_timeout)\n try:\n data = self.chipset.tg_comm_rf(**tg_comm_rf_args)\n tg_comm_rf_args['transmit_data'] = None\n except CommunicationError as error:\n tg_comm_rf_args['transmit_data'] = None\n rats_cmd, rats_res = None\n log.debug(error)\n else:\n brty = ('106A', '212F', '424F')[data[0]-11]\n log.debug(\"%s rcvd %s\", brty, hexlify(buffer(data, 7)))\n if brty==\"106A\" and data[2]==3 and data[7]==0xE0:\n (rats_cmd, rats_res) = (data[7:], target.rats_res)\n log.debug(\"rcvd RATS_CMD %s\", hexlify(rats_cmd))\n if rats_res is None:\n rats_res = bytearray.fromhex(\"05 78 80 70 02\")\n log.debug(\"send RATS_RES %s\", hexlify(rats_res))\n tg_comm_rf_args['transmit_data'] = rats_res\n elif brty==\"106A\" and data[7]!=0xF0 and rats_cmd:\n (did, cmd) = (rats_cmd[1] & 0x0F, data[7:])\n ta_tb_tc = rats_res[2:]\n ta = ta_tb_tc.pop(0) if rats_res[1]&0x10 else None\n tb = ta_tb_tc.pop(0) if rats_res[1]&0x20 else None\n tc = ta_tb_tc.pop(0) if rats_res[1]&0x40 else None\n did_supported = tc is None or bool(tc & 0x02)\n cmd_with_did = bool(cmd[0] & 0x08)\n if ((cmd_with_did and did_supported and cmd[1]==did)\n or (did==0 and not cmd_with_did)):\n if cmd[0] in (0xC2, 0xCA):\n log.debug(\"rcvd S(DESELECT) %s\", hexlify(cmd))\n tg_comm_rf_args['transmit_data'] = cmd\n log.debug(\"send S(DESELECT) %s\", hexlify(cmd))\n rats_cmd = rats_res = None\n else:\n log.debug(\"rcvd TT4_CMD %s\", hexlify(cmd))\n self.chipset.tg_set_protocol(rf_off_error=True)\n return nfc.clf.LocalTarget(\n \"106A\", sens_res=nfca_params[0:2],\n sdd_res='\\x08'+nfca_params[2:5],\n sel_res=nfca_params[5:6], tt4_cmd=cmd,\n rats_cmd=rats_cmd, rats_res=rats_res)\n else: log.debug(\"skip TT4_CMD %s (DID)\", hexlify(cmd))\n else: log.debug(\"not a 106A TT4 command\")\n finally:\n recv_timeout = int(1000 * (time_to_return - time.time()))\n tg_comm_rf_args['recv_timeout'] = recv_timeout\n\n if target.sel_res[0] & 0x60 == 0x00:\n return listen_tta_tt2()\n if target.sel_res[0] & 0x20 == 0x20:\n return listen_tta_tt4()\n \n reason = \"sel_res does not indicate any tag target support\"\n raise nfc.clf.UnsupportedTargetError(reason)\n\n def listen_ttb(self, target, timeout):\n \"\"\"Listen as Type B Target is not supported.\"\"\"\n message = \"{device} does not support listen as Type A Target\"\n raise nfc.clf.UnsupportedTargetError(message.format(device=self))\n \n def listen_ttf(self, target, timeout):\n \"\"\"Listen as Type F Target is supported for either 212 or 424 kbps.\"\"\"\n assert target.sensf_res is not None\n assert len(target.sensf_res) == 19\n \n if target.brty not in ('212F', '424F'):\n info = \"unsupported target bitrate: %r\" % target.brty\n raise nfc.clf.UnsupportedTargetError(info)\n \n self.chipset.tg_set_rf(target.brty)\n self.chipset.tg_set_protocol(self.chipset.tg_set_protocol_defaults)\n self.chipset.tg_set_protocol(rf_off_error=False)\n\n recv_timeout = min(int(1000 * timeout), 0xFFFF)\n time_to_return = time.time() + timeout\n transmit_data = sensf_req = sensf_res = None\n\n while recv_timeout > 0:\n if transmit_data:\n log.debug(\"%s send %s\", target.brty, hexlify(transmit_data))\n log.debug(\"%s wait recv %d ms\", target.brty, recv_timeout)\n try:\n data = self.chipset.tg_comm_rf(recv_timeout=recv_timeout,\n transmit_data=transmit_data)\n except CommunicationError as error:\n log.debug(error); continue\n finally:\n recv_timeout = int((time_to_return - time.time()) * 1E3)\n transmit_data = None\n \n assert target.brty == ('106A', '212F', '424F')[data[0]-11]\n log.debug(\"%s rcvd %s\", target.brty, hexlify(buffer(data, 7)))\n \n if len(data) > 7 and len(data)-7 == data[7]:\n if sensf_req and data[9:17] == target.sensf_res[1:9]:\n self.chipset.tg_set_protocol(rf_off_error=True)\n target = nfc.clf.LocalTarget(target.brty)\n target.sensf_req = sensf_req\n target.sensf_res = sensf_res\n target.tt3_cmd = data[8:]\n return target\n \n if len(data) == 13 and data[7] == 6 and data[8] == 0:\n (sensf_req, sensf_res) = (data[8:], target.sensf_res[:])\n if ((sensf_req[1]==255 or sensf_req[1]==sensf_res[17]) and\n (sensf_req[2]==255 or sensf_req[2]==sensf_res[18])):\n transmit_data = sensf_res[0:17]\n if sensf_req[3] == 1:\n transmit_data += sensf_res[17:19]\n if sensf_req[3] == 2:\n transmit_data += \"\\x00\" + chr(1<<(target.brty==\"424F\"))\n transmit_data = chr(len(transmit_data)+1) + transmit_data\n \n def listen_dep(self, target, timeout):\n log.debug(\"listen_dep for {0:.3f} sec\".format(timeout))\n assert target.sensf_res is not None\n assert target.sens_res is not None\n assert target.sdd_res is not None\n assert target.sel_res is not None\n assert target.atr_res is not None\n \n nfca_params = target.sens_res + target.sdd_res[1:4] + target.sel_res\n nfcf_params = target.sensf_res[1:19]\n log.debug(\"nfca_params %s\", hexlify(nfca_params))\n log.debug(\"nfcf_params %s\", hexlify(nfcf_params))\n assert len(nfca_params) == 6\n assert len(nfcf_params) == 18\n \n self.chipset.tg_set_rf(\"106A\")\n self.chipset.tg_set_protocol(self.chipset.tg_set_protocol_defaults)\n self.chipset.tg_set_protocol(rf_off_error=False)\n\n tg_comm_rf_args = {'mdaa': True}\n tg_comm_rf_args['nfca_params'] = nfca_params\n tg_comm_rf_args['nfcf_params'] = nfcf_params\n\n recv_timeout = min(int(1000 * timeout), 0xFFFF)\n time_to_return = time.time() + timeout\n\n while recv_timeout > 0:\n tg_comm_rf_args['recv_timeout'] = recv_timeout\n log.debug(\"wait %d ms for activation\", recv_timeout)\n try:\n data = self.chipset.tg_comm_rf(**tg_comm_rf_args)\n except CommunicationError as error:\n if error != \"RECEIVE_TIMEOUT_ERROR\": log.warning(error)\n else:\n brty = ('106A', '212F', '424F')[data[0]-11]\n log.debug(\"%s %s\", brty, hexlify(data))\n if data[2] & 0x03 == 3: data = data[7:]; break\n else: log.debug(\"not a passive mode activation\")\n recv_timeout = int(1000 * (time_to_return - time.time()))\n else:\n return None\n\n # further tg_comm_rf commands return RF_OFF_ERROR when field is gone\n self.chipset.tg_set_protocol(rf_off_error=True)\n\n if brty == \"106A\" and len(data)>1 and data[0] != 0xF0:\n # We received a Type A card activation, probably because\n # sel_res has indicated Type 2 or Type 4A Tag support.\n target = nfc.clf.LocalTarget(\"106A\", tag_cmd=data[:])\n target.sens_res = nfca_params[0:2]\n target.sdd_res = '\\x08' + nfca_params[2:5]\n target.sel_res = nfca_params[5:6]\n return target\n \n try:\n if brty == \"106A\": assert data.pop(0) == 0xF0\n assert len(data) == data.pop(0)\n assert data.startswith(\"\\xD4\\x00\")\n except (IndexError, AssertionError):\n return None\n\n activation_params = nfca_params if brty=='106A' else nfcf_params\n \n def send_res_recv_req(brty, data, timeout):\n if data: data = (\"\", \"\\xF0\")[brty==\"106A\"] + chr(len(data)) + data\n args = {'transmit_data': data, 'recv_timeout': timeout}\n data = self.chipset.tg_comm_rf(**args)[7:]\n if timeout > 0:\n try:\n if brty == \"106A\":\n assert data.pop(0) == 0xF0, \"invalid start byte\"\n assert len(data) == data.pop(0), \"incorrect length byte\"\n assert data[0] == 0xD4, \"invalid command byte 1\"\n assert data[1] in (0,4,6,8,10), \"invalid command byte 2\"\n except IndexError:\n raise AssertionError(\"insufficient receive data\")\n return data\n\n while data and data[1] == 0:\n try:\n (atr_req, atr_res) = (data[:], target.atr_res)\n log.debug(\"%s rcvd ATR_REQ %s\", brty, hexlify(atr_req))\n assert len(atr_req) >= 16, \"ATR_REQ has less than 16 byte\"\n assert len(atr_req) <= 64, \"ATR_REQ has more than 64 byte\"\n log.debug(\"%s send ATR_RES %s\", brty, hexlify(atr_res))\n data = send_res_recv_req(brty, atr_res, 1000)\n except (CommunicationError, AssertionError) as error:\n log.warning(str(error))\n return None\n\n psl_req = dep_req = None\n while data and data[1] in (4,6,8,10):\n did = atr_req[12] if atr_req[12]>0 else None\n cmd = (\"PSL\", \"DEP\", \"DSL\", \"RLS\")[(data[1]-4)//2] + \"_REQ\"\n log.debug(\"%s rcvd %s %s\", brty, cmd, hexlify(data))\n try:\n if cmd==\"DEP_REQ\" and did==(data[3] if data[2]>>2&1 else None):\n dep_req = data[:]\n break\n \n if cmd==\"DSL_REQ\" and did==(data[2] if len(data)>2 else None):\n data = \"\\xD5\\x09\" + data[2:3]\n log.debug(\"%s send DSL_RES %s\", brty, hexlify(data))\n send_res_recv_req(brty, data, 0)\n return None\n \n if cmd==\"RLS_REQ\" and did==(data[2] if len(data)>2 else None):\n data = \"\\xD5\\x0B\" + data[2:3]\n log.debug(\"%s send RLS_RES %s\", brty, hexlify(data))\n send_res_recv_req(brty, data, 0)\n return None\n \n if cmd==\"PSL_REQ\" and did==(data[2] if data[2]>0 else None):\n (dsi, dri) = ((data[3] >> 3) & 7, data[3] & 7)\n if dsi != dri:\n log.warning(\"DSI != DRI is not supported\")\n return None\n (psl_req, psl_res) = (data[:], \"\\xD5\\x05\"+data[2:3])\n log.debug(\"%s send PSL_RES %s\", brty, hexlify(psl_res))\n send_res_recv_req(brty, psl_res, 0)\n brty = ('106A', '212F', '424F')[dsi]\n self.chipset.tg_set_rf(brty)\n \n log.debug(\"%s wait recv 1000 ms\", brty)\n data = send_res_recv_req(brty, None, 1000)\n except (CommunicationError, AssertionError) as error:\n log.warning(str(error))\n return None\n else: # while data and data[1] in (4,6,8,10)\n return None\n\n target = nfc.clf.LocalTarget(brty, atr_req=atr_req, dep_req=dep_req)\n if psl_req: target.psl_req = psl_req\n if activation_params == nfca_params:\n target.sens_res = nfca_params[0:2]\n target.sdd_res = '\\x08' + nfca_params[2:5]\n target.sel_res = nfca_params[5:6]\n else:\n target.sensf_res = \"\\x01\" + nfcf_params\n return target\n\n def get_max_send_data_size(self, target):\n return 290\n\n def get_max_recv_data_size(self, target):\n return 290\n\n def send_cmd_recv_rsp(self, target, data, timeout):\n timeout_msec = min(int(timeout * 1000), 0xFFFF) if timeout else 0\n self.chipset.in_set_rf(target.brty_send, target.brty_recv)\n self.chipset.in_set_protocol(self.chipset.in_set_protocol_defaults)\n in_set_protocol_settings = {\n 'add_parity': 1 if target.brty_send.endswith('A') else 0,\n 'check_parity': 1 if target.brty_recv.endswith('A') else 0\n }\n try:\n if (target.brty == '106A' and target.sel_res and\n target.sel_res[0] & 0x60 == 0x00):\n # Driver must check TT2 CRC to get ACK/NAK\n in_set_protocol_settings['check_crc'] = 0\n self.chipset.in_set_protocol(**in_set_protocol_settings)\n return self._tt2_send_cmd_recv_rsp(data, timeout_msec)\n else:\n self.chipset.in_set_protocol(**in_set_protocol_settings)\n return self.chipset.in_comm_rf(data, timeout_msec)\n except CommunicationError as error:\n log.debug(error)\n if error == \"RECEIVE_TIMEOUT_ERROR\":\n raise nfc.clf.TimeoutError\n raise nfc.clf.TransmissionError\n\n def _tt2_send_cmd_recv_rsp(self, data, timeout_msec):\n # The Type2Tag implementation needs to receive the Mifare\n # ACK/NAK responses but the chipset reports them as crc error\n # (indistinguishable from a real crc error). We thus had to\n # switch off the crc check and do it here.\n data = self.chipset.in_comm_rf(data, timeout_msec)\n if len(data) > 2 and self.check_crc_a(data) is False:\n raise nfc.clf.TransmissionError(\"crc_a check error\")\n return data[:-2] if len(data) > 2 else data\n\n def send_rsp_recv_cmd(self, target, data, timeout):\n assert timeout is None or timeout >= 0\n timeout_msec = min(int(timeout * 1000), 0xFFFF) if timeout else 0\n kwargs = {\n 'guard_time': 500,\n 'transmit_data': data,\n 'recv_timeout': 0xFFFF if timeout is None else int(timeout*1E3),\n }\n try:\n data = self.chipset.tg_comm_rf(**kwargs)\n return data[7:] if data else None\n except CommunicationError as error:\n log.debug(error)\n if error == \"RF_OFF_ERROR\":\n raise nfc.clf.BrokenLinkError(str(error))\n if error == \"RECEIVE_TIMEOUT_ERROR\":\n raise nfc.clf.TimeoutError(str(error))\n raise nfc.clf.TransmissionError(str(error))\n\ndef init(transport):\n chipset = Chipset(transport, logger=log)\n device = Device(chipset, logger=log)\n device._vendor_name = transport.manufacturer_name\n device._device_name = transport.product_name\n return device"}]} {"messages": [{"role": "user", "content": "Write Python code that implements ina.py from lodemo/CATANA (path: src/face_recognition/youtube_dl/extractor/ina.py)."}, {"role": "assistant", "content": "# src/face_recognition/youtube_dl/extractor/ina.py (from lodemo/CATANA, license: mit)\n\n# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport re\n\nfrom .common import InfoExtractor\n\nclass InaIE(InfoExtractor):\n _VALID_URL = r'https?://(?:www\\.)?ina\\.fr/video/(?PI?[A-Z0-9]+)'\n _TEST = {\n 'url': 'http://www.ina.fr/video/I12055569/francois-hollande-je-crois-que-c-est-clair-video.html',\n 'md5': 'a667021bf2b41f8dc6049479d9bb38a3',\n 'info_dict': {\n 'id': 'I12055569',\n 'ext': 'mp4',\n 'title': 'François Hollande \"Je crois que c\\'est clair\"',\n }\n }\n\n def _real_extract(self, url):\n mobj = re.match(self._VALID_URL, url)\n\n video_id = mobj.group('id')\n mrss_url = 'http://player.ina.fr/notices/%s.mrss' % video_id\n info_doc = self._download_xml(mrss_url, video_id)\n\n self.report_extraction(video_id)\n\n video_url = info_doc.find('.//{http://search.yahoo.com/mrss/}player').attrib['url']\n\n return {\n 'id': video_id,\n 'url': video_url,\n 'title': info_doc.find('.//title').text,\n }"}]} {"messages": [{"role": "user", "content": "Write Python code that implements abstraction.py from hjanime/VisTrails (path: vistrails/db/versions/v0_9_0/domain/abstraction.py)."}, {"role": "assistant", "content": "# vistrails/db/versions/v0_9_0/domain/abstraction.py (from hjanime/VisTrails, license: bsd-3-clause)\n\n###############################################################################\n##\n## Copyright (C) 2014-2015, New York University.\n## Copyright (C) 2011-2014, NYU-Poly.\n## Copyright (C) 2006-2011, University of Utah.\n## All rights reserved.\n## Contact: contact@vistrails.org\n##\n## This file is part of VisTrails.\n##\n## \"Redistribution and use in source and binary forms, with or without\n## modification, are permitted provided that the following conditions are met:\n##\n## - Redistributions of source code must retain the above copyright notice,\n## this list of conditions and the following disclaimer.\n## - Redistributions in binary form must reproduce the above copyright\n## notice, this list of conditions and the following disclaimer in the\n## documentation and/or other materials provided with the distribution.\n## - Neither the name of the New York University nor the names of its\n## contributors may be used to endorse or promote products derived from\n## this software without specific prior written permission.\n##\n## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n##\n###############################################################################\n\nfrom __future__ import division\n\nimport copy\nfrom auto_gen import DBAbstraction as _DBAbstraction\nfrom auto_gen import DBAbstractionRef, DBModule\nfrom id_scope import IdScope\n\nclass DBAbstraction(_DBAbstraction):\n def __init__(self, *args, **kwargs):\n _DBAbstraction.__init__(self, *args, **kwargs)\n self.idScope = IdScope(remap={DBAbstractionRef.vtType: DBModule.vtType})\n self.idScope.setBeginId('action', 1)\n\n def __copy__(self):\n return DBAbstraction.do_copy(self)\n\n def do_copy(self, new_ids=False, id_scope=None, id_remap=None):\n cp = _DBAbstraction.do_copy(self, new_ids, id_scope, id_remap)\n cp.__class__ = DBAbstraction\n # need to go through and reset the index to the copied objects\n cp.idScope = copy.copy(self.idScope)\n return cp"}]} {"messages": [{"role": "user", "content": "Write Python code that implements settings.py from hushaoqing/my_notes (path: Python/Scrapy/mytest/testScrapyGraphite/settings.py)."}, {"role": "assistant", "content": "# Python/Scrapy/mytest/testScrapyGraphite/settings.py (from hushaoqing/my_notes, license: mit)\n\n# -*- coding: utf-8 -*-\n\n# Scrapy settings for mytest project\n#\n# For simplicity, this file contains only settings considered important or\n# commonly used. You can find more settings consulting the documentation:\n#\n# http://doc.scrapy.org/en/latest/topics/settings.html\n# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html\n# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html\n\nBOT_NAME = 'testScrapyGraphite'\n\nSPIDER_MODULES = ['testScrapyGraphite.spiders']\nNEWSPIDER_MODULE = 'testScrapyGraphite.spiders'\n\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\n#USER_AGENT = 'mytest (+http://www.yourdomain.com)'\n\n# Obey robots.txt rules\nROBOTSTXT_OBEY = True\n\n# Configure maximum concurrent requests performed by Scrapy (default: 16)\n#CONCURRENT_REQUESTS = 32\n\n# Configure a delay for requests for the same website (default: 0)\n# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay\n# See also autothrottle settings and docs\nDOWNLOAD_DELAY = 3\n# The download delay setting will honor only one of:\n#CONCURRENT_REQUESTS_PER_DOMAIN = 16\n#CONCURRENT_REQUESTS_PER_IP = 16\n\n# Disable cookies (enabled by default)\n#COOKIES_ENABLED = False\n\n# Disable Telnet Console (enabled by default)\n#TELNETCONSOLE_ENABLED = False\n\n# Override the default request headers:\n# DEFAULT_REQUEST_HEADERS = {\n# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n# 'Accept-Language': 'en',\n#}\n\n# Enable or disable spider middlewares\n# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html\n# SPIDER_MIDDLEWARES = {\n# 'mytest.middlewares.MytestSpiderMiddleware': 543,\n#}\n\n# Enable or disable downloader middlewares\n# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html\n# DOWNLOADER_MIDDLEWARES = {\n# 'mytest.middlewares.MyCustomDownloaderMiddleware': 543,\n#}\n\n# Enable or disable extensions\n# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html\n# EXTENSIONS = {\n# 'scrapy.extensions.telnet.TelnetConsole': None,\n#}\n\n# Configure item pipelines\n# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html\n# ITEM_PIPELINES = {\n# 'mytest.pipelines.MytestPipeline': 300,\n#}\n\n# Enable and configure the AutoThrottle extension (disabled by default)\n# See http://doc.scrapy.org/en/latest/topics/autothrottle.html\n#AUTOTHROTTLE_ENABLED = True\n# The initial download delay\n#AUTOTHROTTLE_START_DELAY = 5\n# The maximum download delay to be set in case of high latencies\n#AUTOTHROTTLE_MAX_DELAY = 60\n# The average number of requests Scrapy should be sending in parallel to\n# each remote server\n#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0\n# Enable showing throttling stats for every response received:\n#AUTOTHROTTLE_DEBUG = False\n\n# Enable and configure HTTP caching (disabled by default)\n# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings\n#HTTPCACHE_ENABLED = True\n#HTTPCACHE_EXPIRATION_SECS = 0\n#HTTPCACHE_DIR = 'httpcache'\n#HTTPCACHE_IGNORE_HTTP_CODES = []\n#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'\n\nSTATS_CLASS = 'testScrapyGraphite.spiders.stat_redis.GraphiteStatsCollector'"}]} {"messages": [{"role": "user", "content": "Write Python code that implements bigip_device_group_member.py from Nitaco/ansible (path: lib/ansible/modules/network/f5/bigip_device_group_member.py)."}, {"role": "assistant", "content": "# lib/ansible/modules/network/f5/bigip_device_group_member.py (from Nitaco/ansible, license: gpl-3.0)\n\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2017 F5 Networks Inc.\n# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\nDOCUMENTATION = r'''\n---\nmodule: bigip_device_group_member\nshort_description: Manages members in a device group\ndescription:\n - Manages members in a device group. Members in a device group can only\n be added or removed, never updated. This is because the members are\n identified by unique name values and changing that name would invalidate\n the uniqueness.\nversion_added: 2.5\noptions:\n name:\n description:\n - Specifies the name of the device that you want to add to the\n device group. Often this will be the hostname of the device.\n This member must be trusted by the device already. Trusting\n can be done with the C(bigip_device_trust) module and the\n C(peer_hostname) option to that module.\n required: True\n device_group:\n description:\n - The device group that you want to add the member to.\n required: True\n state:\n description:\n - When C(present), ensures that the device group member.\n - When C(absent), ensures the device group member is removed.\n default: present\n choices:\n - present\n - absent\nextends_documentation_fragment: f5\nauthor:\n - Tim Rupp (@caphrim007)\n'''\n\nEXAMPLES = r'''\n- name: Add the current device to the \"device_trust_group\" device group\n bigip_device_group_member:\n name: \"{{ inventory_hostname }}\"\n device_group: device_trust_group\n password: secret\n server: lb.mydomain.com\n state: present\n user: admin\n delegate_to: localhost\n\n- name: Add the hosts in the current scope to \"device_trust_group\"\n bigip_device_group_member:\n name: \"{{ item }}\"\n device_group: device_trust_group\n password: secret\n server: lb.mydomain.com\n state: present\n user: admin\n with_items: \"{{ hostvars.keys() }}\"\n run_once: true\n delegate_to: localhost\n'''\n\nRETURN = r'''\n# only common fields returned\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\n\ntry:\n from library.module_utils.network.f5.bigip import HAS_F5SDK\n from library.module_utils.network.f5.bigip import F5Client\n from library.module_utils.network.f5.common import F5ModuleError\n from library.module_utils.network.f5.common import AnsibleF5Parameters\n from library.module_utils.network.f5.common import cleanup_tokens\n from library.module_utils.network.f5.common import f5_argument_spec\n try:\n from library.module_utils.network.f5.common import iControlUnexpectedHTTPError\n except ImportError:\n HAS_F5SDK = False\nexcept ImportError:\n from ansible.module_utils.network.f5.bigip import HAS_F5SDK\n from ansible.module_utils.network.f5.bigip import F5Client\n from ansible.module_utils.network.f5.common import F5ModuleError\n from ansible.module_utils.network.f5.common import AnsibleF5Parameters\n from ansible.module_utils.network.f5.common import cleanup_tokens\n from ansible.module_utils.network.f5.common import f5_argument_spec\n try:\n from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError\n except ImportError:\n HAS_F5SDK = False\n\nclass Parameters(AnsibleF5Parameters):\n api_map = {}\n\n api_attributes = []\n\n returnables = []\n\n updatables = []\n\n def to_return(self):\n result = {}\n try:\n for returnable in self.returnables:\n result[returnable] = getattr(self, returnable)\n result = self._filter_params(result)\n except Exception:\n pass\n return result\n\nclass Changes(Parameters):\n pass\n\nclass ModuleManager(object):\n def __init__(self, *args, **kwargs):\n self.module = kwargs.get('module', None)\n self.client = kwargs.get('client', None)\n self.want = Parameters(params=self.module.params)\n self.have = None\n self.changes = Changes()\n\n def _set_changed_options(self):\n changed = {}\n for key in Parameters.returnables:\n if getattr(self.want, key) is not None:\n changed[key] = getattr(self.want, key)\n if changed:\n self.changes = Changes(params=changed)\n\n def exec_module(self):\n changed = False\n result = dict()\n state = self.want.state\n\n try:\n if state == \"present\":\n changed = self.present()\n elif state == \"absent\":\n changed = self.absent()\n except iControlUnexpectedHTTPError as e:\n raise F5ModuleError(str(e))\n\n changes = self.changes.to_return()\n result.update(**changes)\n result.update(dict(changed=changed))\n return result\n\n def present(self):\n if self.exists():\n return False\n else:\n return self.create()\n\n def exists(self):\n parent = self.client.api.tm.cm.device_groups.device_group.load(\n name=self.want.device_group\n )\n exists = parent.devices_s.devices.exists(name=self.want.name)\n if exists:\n return True\n return False\n\n def remove(self):\n if self.module.check_mode:\n return True\n self.remove_from_device()\n if self.exists():\n raise F5ModuleError(\"Failed to remove the member from the device group.\")\n return True\n\n def create(self):\n self._set_changed_options()\n if self.module.check_mode:\n return True\n self.create_on_device()\n return True\n\n def create_on_device(self):\n parent = self.client.api.tm.cm.device_groups.device_group.load(\n name=self.want.device_group\n )\n parent.devices_s.devices.create(name=self.want.name)\n\n def absent(self):\n if self.exists():\n return self.remove()\n return False\n\n def remove_from_device(self):\n parent = self.client.api.tm.cm.device_groups.device_group.load(\n name=self.want.device_group\n )\n resource = parent.devices_s.devices.load(name=self.want.name)\n if resource:\n resource.delete()\n\nclass ArgumentSpec(object):\n def __init__(self):\n self.supports_check_mode = True\n argument_spec = dict(\n name=dict(required=True),\n device_group=dict(required=True),\n state=dict(\n default='present',\n choices=['absent', 'present']\n )\n )\n self.argument_spec = {}\n self.argument_spec.update(f5_argument_spec)\n self.argument_spec.update(argument_spec)\n\ndef main():\n spec = ArgumentSpec()\n\n module = AnsibleModule(\n argument_spec=spec.argument_spec,\n supports_check_mode=spec.supports_check_mode\n )\n if not HAS_F5SDK:\n module.fail_json(msg=\"The python f5-sdk module is required\")\n\n try:\n client = F5Client(**module.params)\n mm = ModuleManager(module=module, client=client)\n results = mm.exec_module()\n cleanup_tokens(client)\n module.exit_json(**results)\n except F5ModuleError as ex:\n cleanup_tokens(client)\n module.fail_json(msg=str(ex))\n\nif __name__ == '__main__':\n main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements environment.py from nvie/python-mode (path: pymode/environment.py)."}, {"role": "assistant", "content": "# pymode/environment.py (from nvie/python-mode, license: lgpl-3.0)\n\n\"\"\" Define interfaces. \"\"\"\n\nfrom __future__ import print_function\n\nimport vim\nimport json\nimport time\nimport os.path\n\nfrom ._compat import PY2\n\nclass VimPymodeEnviroment(object):\n\n \"\"\" Vim User interface. \"\"\"\n\n prefix = '[Pymode]'\n\n def __init__(self):\n \"\"\" Init VIM environment. \"\"\"\n self.current = vim.current\n self.options = dict(encoding=vim.eval('&enc'))\n self.options['debug'] = self.var('g:pymode_debug', True)\n\n @property\n def curdir(self):\n \"\"\" Return current working directory. \"\"\"\n return self.var('getcwd()')\n\n @property\n def curbuf(self):\n \"\"\" Return current buffer. \"\"\"\n return self.current.buffer\n\n @property\n def cursor(self):\n \"\"\" Return current window position.\n\n :return tuple: (row, col)\n\n \"\"\"\n return self.current.window.cursor\n\n @property\n def source(self):\n \"\"\" Return source of current buffer. \"\"\"\n return \"\\n\".join(self.lines)\n\n @property\n def lines(self):\n \"\"\" Iterate by lines in current file.\n\n :return list:\n\n \"\"\"\n if not PY2:\n return self.curbuf\n\n return [l.decode(self.options.get('encoding')) for l in self.curbuf]\n\n @staticmethod\n def var(name, to_bool=False, silence=False):\n \"\"\" Get vim variable.\n\n :return vimobj:\n\n \"\"\"\n try:\n value = vim.eval(name)\n except vim.error:\n if silence:\n return None\n raise\n\n if to_bool:\n try:\n value = bool(int(value))\n except ValueError:\n value = value\n return value\n\n @staticmethod\n def message(msg, history=False):\n \"\"\" Show message to user.\n\n :return: :None\n\n \"\"\"\n if history:\n return vim.command('echom \"%s\"' % str(msg))\n\n return vim.command('call pymode#wide_message(\"%s\")' % str(msg))\n\n def user_input(self, msg, default=''):\n \"\"\" Return user input or default.\n\n :return str:\n\n \"\"\"\n msg = '%s %s ' % (self.prefix, msg)\n\n if default != '':\n msg += '[%s] ' % default\n\n try:\n vim.command('echohl Debug')\n input_str = vim.eval('input(\"%s> \")' % msg)\n vim.command('echohl none')\n except KeyboardInterrupt:\n input_str = ''\n\n return input_str or default\n\n def user_confirm(self, msg, yes=False):\n \"\"\" Get user confirmation.\n\n :return bool:\n\n \"\"\"\n default = 'yes' if yes else 'no'\n action = self.user_input(msg, default)\n return action and 'yes'.startswith(action)\n\n def user_input_choices(self, msg, *options):\n \"\"\" Get one of many options.\n\n :return str: A choosen option\n\n \"\"\"\n choices = ['%s %s' % (self.prefix, msg)]\n choices += [\n \"%s. %s\" % (num, opt) for num, opt in enumerate(options, 1)]\n try:\n input_str = int(\n vim.eval('inputlist(%s)' % self.prepare_value(choices)))\n except (KeyboardInterrupt, ValueError):\n input_str = 0\n\n if not input_str:\n self.message('Cancelled!')\n return False\n\n try:\n return options[input_str - 1]\n except (IndexError, ValueError):\n self.error('Invalid option: %s' % input_str)\n return self.user_input_choices(msg, *options)\n\n @staticmethod\n def error(msg):\n \"\"\" Show error to user. \"\"\"\n vim.command('call pymode#error(\"%s\")' % str(msg))\n\n def debug(self, msg, *args):\n \"\"\" Print debug information. \"\"\"\n if self.options.get('debug'):\n print(\"%s %s [%s]\" % (\n int(time.time()), msg, ', '.join([str(a) for a in args])))\n\n def stop(self, value=None):\n \"\"\" Break Vim function. \"\"\"\n cmd = 'return'\n if value is not None:\n cmd += ' ' + self.prepare_value(value)\n vim.command(cmd)\n\n def catch_exceptions(self, func):\n \"\"\" Decorator. Make execution more silence.\n\n :return func:\n\n \"\"\"\n def _wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except (Exception, vim.error) as e: # noqa\n if self.options.get('debug'):\n raise\n self.error(e)\n return None\n return _wrapper\n\n def run(self, name, *args):\n \"\"\" Run vim function. \"\"\"\n vim.command('call %s(%s)' % (name, \", \".join([\n self.prepare_value(a) for a in args\n ])))\n\n def let(self, name, value):\n \"\"\" Set variable. \"\"\"\n cmd = 'let %s = %s' % (name, self.prepare_value(value))\n self.debug(cmd)\n vim.command(cmd)\n\n def prepare_value(self, value, dumps=True):\n \"\"\" Decode bstr to vim encoding.\n\n :return unicode string:\n\n \"\"\"\n if dumps:\n value = json.dumps(value)\n\n if PY2:\n value = value.decode('utf-8').encode(self.options.get('encoding'))\n\n return value\n\n def get_offset_params(self, cursor=None, base=\"\"):\n \"\"\" Calculate current offset.\n\n :return tuple: (source, offset)\n\n \"\"\"\n row, col = cursor or env.cursor\n source = \"\"\n offset = 0\n for i, line in enumerate(self.lines, 1):\n if i == row:\n source += line[:col] + base\n offset = len(source)\n source += line[col:]\n else:\n source += line\n source += '\\n'\n env.debug('Get offset', base or None, row, col, offset)\n return source, offset\n\n @staticmethod\n def goto_line(line):\n \"\"\" Go to line. \"\"\"\n vim.command('normal %sggzz' % line)\n\n def goto_file(self, path, cmd='e', force=False):\n \"\"\" Function description. \"\"\"\n if force or os.path.abspath(path) != self.curbuf.name:\n self.debug('read', path)\n if ' ' in path and os.name == 'posix':\n path = path.replace(' ', '\\\\ ')\n vim.command(\"%s %s\" % (cmd, path))\n\n @staticmethod\n def goto_buffer(bufnr):\n \"\"\" Open buffer. \"\"\"\n if str(bufnr) != '-1':\n vim.command('buffer %s' % bufnr)\n\nenv = VimPymodeEnviroment()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_zs_degd_latest_1.5_on_cos7.py from zstackio/zstack-woodpecker (path: integrationtest/vm/installation/upgrade/test_zs_degd_latest_1.5_on_cos7.py)."}, {"role": "assistant", "content": "# integrationtest/vm/installation/upgrade/test_zs_degd_latest_1.5_on_cos7.py (from zstackio/zstack-woodpecker, license: apache-2.0)\n\n'''\n\n@author: MengLai\n'''\nimport os\nimport tempfile\nimport uuid\nimport time\n\nimport zstackwoodpecker.test_util as test_util\nimport zstackwoodpecker.test_lib as test_lib\nimport zstackwoodpecker.test_state as test_state\n\ntest_stub = test_lib.lib_get_test_stub()\ntest_obj_dict = test_state.TestStateDict()\ntmp_file = '/tmp/%s' % uuid.uuid1().get_hex()\n\ndef test():\n test_util.test_dsc('Create test vm to test zstack upgrade by -u.')\n image_name = os.environ.get('imageName_i_c7')\n vm = test_stub.create_vlan_vm(image_name)\n test_obj_dict.add_vm(vm)\n if os.environ.get('zstackManagementIp') == None:\n vm.check()\n else:\n time.sleep(60)\n\n vm_inv = vm.get_vm()\n vm_ip = vm_inv.vmNics[0].ip\n test_util.test_dsc('Install latest zstack')\n target_file = '/root/zstack-all-in-one.tgz'\n test_stub.prepare_test_env(vm_inv, target_file)\n ssh_cmd = 'ssh -oStrictHostKeyChecking=no -oCheckHostIP=no -oUserKnownHostsFile=/dev/null %s' % vm_ip\n test_stub.copy_id_dsa(vm_inv, ssh_cmd, tmp_file)\n test_stub.copy_id_dsa_pub(vm_inv)\n test_stub.execute_all_install(ssh_cmd, target_file, tmp_file)\n test_stub.check_installation(ssh_cmd, tmp_file, vm_inv)\n\n test_util.test_dsc('Degrade zstack to 1.5')\n degrade_target_file = '/root/zstack-degrade-all-in-one.tgz'\n install_pkg = os.environ.get('zstackPkg_1.5')\n test_stub.prepare_upgrade_test_env(vm_inv, degrade_target_file, install_pkg)\n test_stub.upgrade_zstack(ssh_cmd, degrade_target_file, tmp_file)\n test_stub.check_installation(ssh_cmd, tmp_file, vm_inv)\n\n os.system('rm -f %s' % tmp_file)\n vm.destroy()\n test_util.test_pass('ZStack upgrade Test Success')\n\n#Will be called only if exception happens in test().\ndef error_cleanup():\n os.system('rm -f %s' % tmp_file)\n test_lib.lib_error_cleanup(test_obj_dict)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements MulticlassKeras.py from abhinavmoudgil95/root (path: tutorials/tmva/keras/MulticlassKeras.py)."}, {"role": "assistant", "content": "# tutorials/tmva/keras/MulticlassKeras.py (from abhinavmoudgil95/root, license: lgpl-2.1)\n\n#!/usr/bin/env python\n\nfrom ROOT import TMVA, TFile, TTree, TCut, gROOT\nfrom os.path import isfile\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\nfrom keras.regularizers import l2\nfrom keras import initializations\nfrom keras.optimizers import SGD\n\n# Setup TMVA\nTMVA.Tools.Instance()\nTMVA.PyMethodBase.PyInitialize()\n\noutput = TFile.Open('TMVA.root', 'RECREATE')\nfactory = TMVA.Factory('TMVAClassification', output,\n '!V:!Silent:Color:DrawProgressBar:Transformations=D,G:AnalysisType=multiclass')\n\n# Load data\nif not isfile('tmva_example_multiple_background.root'):\n createDataMacro = str(gROOT.GetTutorialDir()) + '/tmva/createData.C'\n print(createDataMacro)\n gROOT.ProcessLine('.L {}'.format(createDataMacro))\n gROOT.ProcessLine('create_MultipleBackground(4000)')\n\ndata = TFile.Open('tmva_example_multiple_background.root')\nsignal = data.Get('TreeS')\nbackground0 = data.Get('TreeB0')\nbackground1 = data.Get('TreeB1')\nbackground2 = data.Get('TreeB2')\n\ndataloader = TMVA.DataLoader('dataset')\nfor branch in signal.GetListOfBranches():\n dataloader.AddVariable(branch.GetName())\n\ndataloader.AddTree(signal, 'Signal')\ndataloader.AddTree(background0, 'Background_0')\ndataloader.AddTree(background1, 'Background_1')\ndataloader.AddTree(background2, 'Background_2')\ndataloader.PrepareTrainingAndTestTree(TCut(''),\n 'SplitMode=Random:NormMode=NumEvents:!V')\n\n# Generate model\n\n# Define initialization\ndef normal(shape, name=None):\n return initializations.normal(shape, scale=0.05, name=name)\n\n# Define model\nmodel = Sequential()\nmodel.add(Dense(32, init=normal, activation='relu', W_regularizer=l2(1e-5), input_dim=4))\n#model.add(Dense(32, init=normal, activation='relu', W_regularizer=l2(1e-5)))\nmodel.add(Dense(4, init=normal, activation='softmax'))\n\n# Set loss and optimizer\nmodel.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.01), metrics=['accuracy',])\n\n# Store model to file\nmodel.save('model.h5')\nmodel.summary()\n\n# Book methods\nfactory.BookMethod(dataloader, TMVA.Types.kFisher, 'Fisher',\n '!H:!V:Fisher:VarTransform=D,G')\nfactory.BookMethod(dataloader, TMVA.Types.kPyKeras, \"PyKeras\",\n 'H:!V:VarTransform=D,G:FilenameModel=model.h5:NumEpochs=20:BatchSize=32')\n\n# Run TMVA\nfactory.TrainAllMethods()\nfactory.TestAllMethods()\nfactory.EvaluateAllMethods()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements tests.py from nathanial/lettuce (path: tests/integration/lib/Django-1.3/django/contrib/gis/tests/geogapp/tests.py)."}, {"role": "assistant", "content": "# tests/integration/lib/Django-1.3/django/contrib/gis/tests/geogapp/tests.py (from nathanial/lettuce, license: gpl-3.0)\n\n\"\"\"\nTests for geography support in PostGIS 1.5+\n\"\"\"\nimport os\nfrom django.contrib.gis import gdal\nfrom django.contrib.gis.measure import D\nfrom django.test import TestCase\nfrom models import City, County, Zipcode\n\nclass GeographyTest(TestCase):\n\n def test01_fixture_load(self):\n \"Ensure geography features loaded properly.\"\n self.assertEqual(8, City.objects.count())\n\n def test02_distance_lookup(self):\n \"Testing GeoQuerySet distance lookup support on non-point geography fields.\"\n z = Zipcode.objects.get(code='77002')\n cities1 = list(City.objects\n .filter(point__distance_lte=(z.poly, D(mi=500)))\n .order_by('name')\n .values_list('name', flat=True))\n cities2 = list(City.objects\n .filter(point__dwithin=(z.poly, D(mi=500)))\n .order_by('name')\n .values_list('name', flat=True))\n for cities in [cities1, cities2]:\n self.assertEqual(['Dallas', 'Houston', 'Oklahoma City'], cities)\n\n def test03_distance_method(self):\n \"Testing GeoQuerySet.distance() support on non-point geography fields.\"\n # `GeoQuerySet.distance` is not allowed geometry fields.\n htown = City.objects.get(name='Houston')\n qs = Zipcode.objects.distance(htown.point)\n\n def test04_invalid_operators_functions(self):\n \"Ensuring exceptions are raised for operators & functions invalid on geography fields.\"\n # Only a subset of the geometry functions & operator are available\n # to PostGIS geography types. For more information, visit:\n # http://postgis.refractions.net/documentation/manual-1.5/ch08.html#PostGIS_GeographyFunctions\n z = Zipcode.objects.get(code='77002')\n # ST_Within not available.\n self.assertRaises(ValueError, City.objects.filter(point__within=z.poly).count)\n # `@` operator not available.\n self.assertRaises(ValueError, City.objects.filter(point__contained=z.poly).count)\n\n # Regression test for #14060, `~=` was never really implemented for PostGIS.\n htown = City.objects.get(name='Houston')\n self.assertRaises(ValueError, City.objects.get, point__exact=htown.point)\n\n def test05_geography_layermapping(self):\n \"Testing LayerMapping support on models with geography fields.\"\n # There is a similar test in `layermap` that uses the same data set,\n # but the County model here is a bit different.\n if not gdal.HAS_GDAL: return\n from django.contrib.gis.utils import LayerMapping\n\n # Getting the shapefile and mapping dictionary.\n shp_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'data'))\n co_shp = os.path.join(shp_path, 'counties', 'counties.shp')\n co_mapping = {'name' : 'Name',\n 'state' : 'State',\n 'mpoly' : 'MULTIPOLYGON',\n }\n\n # Reference county names, number of polygons, and state names.\n names = ['Bexar', 'Galveston', 'Harris', 'Honolulu', 'Pueblo']\n num_polys = [1, 2, 1, 19, 1] # Number of polygons for each.\n st_names = ['Texas', 'Texas', 'Texas', 'Hawaii', 'Colorado']\n\n lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269, unique='name')\n lm.save(silent=True, strict=True)\n\n for c, name, num_poly, state in zip(County.objects.order_by('name'), names, num_polys, st_names):\n self.assertEqual(4326, c.mpoly.srid)\n self.assertEqual(num_poly, len(c.mpoly))\n self.assertEqual(name, c.name)\n self.assertEqual(state, c.state)\n\n def test06_geography_area(self):\n \"Testing that Area calculations work on geography columns.\"\n from django.contrib.gis.measure import A\n # SELECT ST_Area(poly) FROM geogapp_zipcode WHERE code='77002';\n ref_area = 5439084.70637573\n tol = 5\n z = Zipcode.objects.area().get(code='77002')\n self.assertAlmostEqual(z.area.sq_m, ref_area, tol)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements db.py from cloud-engineering/wifi (path: db.py)."}, {"role": "assistant", "content": "# db.py (from cloud-engineering/wifi, license: mit)\n\n# Python Standard Library Imports\nimport logging\n\n# External Imports\nfrom sqlalchemy import Column\nfrom sqlalchemy import String, INTEGER, FLOAT\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\n# Custom Imports\nimport config\nimport json\n\nengine = create_engine('sqlite:///' + config.db.PATH, echo=config.db.DEBUG)\nDeclarativeBase = declarative_base(engine)\nSession = scoped_session(sessionmaker(engine))\n\nclass Event(DeclarativeBase):\n __tablename__ = 'events'\n id = Column(INTEGER, primary_key=True)\n device_serial = Column(String)\n mode = Column(INTEGER)\n time_stamp = Column(INTEGER)\n phaseA = Column(FLOAT)\n phaseB = Column(FLOAT)\n phaseC = Column(FLOAT)\n voltage = Column(FLOAT)\n \n def __init__(self, device_serial, mode, time_stamp, phaseA, phaseB, phaseC, voltage):\n self.device_serial = device_serial\n self.mode = mode\n self.time_stamp = time_stamp\n self.phaseA = phaseA\n self.phaseB = phaseB\n self.phaseC = phaseC\n self.voltage = voltage\n '''\n After spending more than 2 days in data formating, it turns out python suprised me again with its simplicity.\n _repr_ function can serialise a standard python dictionary I created into a json object and return it.\n I can now recieve serialezed json each time I query against the database - thanks to SQLAlchemy - see implementation below.\n '''\n def __repr__(self):\n return json.dumps({\n \"DeviceSerial\" : self.device_serial,\n \"Mode\" : self.mode,\n \"Events\" : [{\"TimeStamp\":self.time_stamp,\"PhaseA\":self.phaseA,\"PhaseB\":self.phaseB,\"PhaseC\":self.phaseC,\"Voltage\":self.voltage}]\n })\n#'(%s,%d, %d, %f, %f, %f, %f0' % (self.device_serial, self.mode, self.time_stamp, self.phase_1, self.phase_2, self.phase_3, self.voltage)\n \n\ndef initialise():\n logging.info('Initialising the database.')\n DeclarativeBase.metadata.create_all()\n Session.execute('PRAGMA journal_mode = WAL')"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_hazard_metadata.py from kant/inasafe (path: safe/metadata/test/test_hazard_metadata.py)."}, {"role": "assistant", "content": "# safe/metadata/test/test_hazard_metadata.py (from kant/inasafe, license: gpl-3.0)\n\n# coding=utf-8\n\"\"\"\nInaSAFE Disaster risk assessment tool developed by AusAid -\n**Exception Classes.**\n\nCustom exception classes for the IS application.\n\nContact : ole.moller.nielsen@gmail.com\n\n.. note:: This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n\"\"\"\n\n__author__ = 'marco@opengis.ch'\n__revision__ = '$Format:%H$'\n__date__ = '12/10/2014'\n__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '\n 'Disaster Reduction')\n\nfrom unittest import TestCase\n\nfrom safe.common.utilities import unique_filename\nfrom safe.metadata import HazardLayerMetadata\n\nclass TestHazardMetadata(TestCase):\n\n def test_standard_properties(self):\n metadata = HazardLayerMetadata(unique_filename())\n with self.assertRaises(KeyError):\n metadata.get_property('non_existing_key')\n\n # from BaseMetadata\n metadata.get_property('email')\n\n # from HazardLayerMetadata\n metadata.get_property('hazard')\n metadata.get_property('hazard_category')\n metadata.get_property('continuous_hazard_unit')\n metadata.get_property('vector_hazard_classification')\n metadata.get_property('raster_hazard_classification')"}]} {"messages": [{"role": "user", "content": "Write Python code that implements massage_qps_stats.py from simonkuang/grpc (path: tools/run_tests/performance/massage_qps_stats.py)."}, {"role": "assistant", "content": "# tools/run_tests/performance/massage_qps_stats.py (from simonkuang/grpc, license: apache-2.0)\n\n# Copyright 2017 gRPC authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Autogenerated by tools/codegen/core/gen_stats_data.py\n\nimport massage_qps_stats_helpers\n\ndef massage_qps_stats(scenario_result):\n for stats in scenario_result[\"serverStats\"] + scenario_result[\"clientStats\"]:\n if \"coreStats\" in stats:\n # Get rid of the \"coreStats\" element and replace it by statistics\n # that correspond to columns in the bigquery schema.\n core_stats = stats[\"coreStats\"]\n del stats[\"coreStats\"]\n stats[\n \"core_client_calls_created\"] = massage_qps_stats_helpers.counter(\n core_stats, \"client_calls_created\")\n stats[\n \"core_server_calls_created\"] = massage_qps_stats_helpers.counter(\n core_stats, \"server_calls_created\")\n stats[\"core_cqs_created\"] = massage_qps_stats_helpers.counter(\n core_stats, \"cqs_created\")\n stats[\n \"core_client_channels_created\"] = massage_qps_stats_helpers.counter(\n core_stats, \"client_channels_created\")\n stats[\n \"core_client_subchannels_created\"] = massage_qps_stats_helpers.counter(\n core_stats, \"client_subchannels_created\")\n stats[\n \"core_server_channels_created\"] = massage_qps_stats_helpers.counter(\n core_stats, \"server_channels_created\")\n stats[\"core_syscall_poll\"] = massage_qps_stats_helpers.counter(\n core_stats, \"syscall_poll\")\n stats[\"core_syscall_wait\"] = massage_qps_stats_helpers.counter(\n core_stats, \"syscall_wait\")\n stats[\"core_pollset_kick\"] = massage_qps_stats_helpers.counter(\n core_stats, \"pollset_kick\")\n stats[\n \"core_pollset_kicked_without_poller\"] = massage_qps_stats_helpers.counter(\n core_stats, \"pollset_kicked_without_poller\")\n stats[\n \"core_pollset_kicked_again\"] = massage_qps_stats_helpers.counter(\n core_stats, \"pollset_kicked_again\")\n stats[\n \"core_pollset_kick_wakeup_fd\"] = massage_qps_stats_helpers.counter(\n core_stats, \"pollset_kick_wakeup_fd\")\n stats[\n \"core_pollset_kick_wakeup_cv\"] = massage_qps_stats_helpers.counter(\n core_stats, \"pollset_kick_wakeup_cv\")\n stats[\n \"core_pollset_kick_own_thread\"] = massage_qps_stats_helpers.counter(\n core_stats, \"pollset_kick_own_thread\")\n stats[\"core_syscall_epoll_ctl\"] = massage_qps_stats_helpers.counter(\n core_stats, \"syscall_epoll_ctl\")\n stats[\n \"core_pollset_fd_cache_hits\"] = massage_qps_stats_helpers.counter(\n core_stats, \"pollset_fd_cache_hits\")\n stats[\n \"core_histogram_slow_lookups\"] = massage_qps_stats_helpers.counter(\n core_stats, \"histogram_slow_lookups\")\n stats[\"core_syscall_write\"] = massage_qps_stats_helpers.counter(\n core_stats, \"syscall_write\")\n stats[\"core_syscall_read\"] = massage_qps_stats_helpers.counter(\n core_stats, \"syscall_read\")\n stats[\n \"core_tcp_backup_pollers_created\"] = massage_qps_stats_helpers.counter(\n core_stats, \"tcp_backup_pollers_created\")\n stats[\n \"core_tcp_backup_poller_polls\"] = massage_qps_stats_helpers.counter(\n core_stats, \"tcp_backup_poller_polls\")\n stats[\"core_http2_op_batches\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_op_batches\")\n stats[\"core_http2_op_cancel\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_op_cancel\")\n stats[\n \"core_http2_op_send_initial_metadata\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_op_send_initial_metadata\")\n stats[\n \"core_http2_op_send_message\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_op_send_message\")\n stats[\n \"core_http2_op_send_trailing_metadata\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_op_send_trailing_metadata\")\n stats[\n \"core_http2_op_recv_initial_metadata\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_op_recv_initial_metadata\")\n stats[\n \"core_http2_op_recv_message\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_op_recv_message\")\n stats[\n \"core_http2_op_recv_trailing_metadata\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_op_recv_trailing_metadata\")\n stats[\n \"core_http2_settings_writes\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_settings_writes\")\n stats[\"core_http2_pings_sent\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_pings_sent\")\n stats[\n \"core_http2_writes_begun\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_writes_begun\")\n stats[\n \"core_http2_writes_offloaded\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_writes_offloaded\")\n stats[\n \"core_http2_writes_continued\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_writes_continued\")\n stats[\n \"core_http2_partial_writes\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_partial_writes\")\n stats[\n \"core_http2_initiate_write_due_to_initial_write\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_initial_write\")\n stats[\n \"core_http2_initiate_write_due_to_start_new_stream\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_start_new_stream\")\n stats[\n \"core_http2_initiate_write_due_to_send_message\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_send_message\")\n stats[\n \"core_http2_initiate_write_due_to_send_initial_metadata\"] = massage_qps_stats_helpers.counter(\n core_stats,\n \"http2_initiate_write_due_to_send_initial_metadata\")\n stats[\n \"core_http2_initiate_write_due_to_send_trailing_metadata\"] = massage_qps_stats_helpers.counter(\n core_stats,\n \"http2_initiate_write_due_to_send_trailing_metadata\")\n stats[\n \"core_http2_initiate_write_due_to_retry_send_ping\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_retry_send_ping\")\n stats[\n \"core_http2_initiate_write_due_to_continue_pings\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_continue_pings\")\n stats[\n \"core_http2_initiate_write_due_to_goaway_sent\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_goaway_sent\")\n stats[\n \"core_http2_initiate_write_due_to_rst_stream\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_rst_stream\")\n stats[\n \"core_http2_initiate_write_due_to_close_from_api\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_close_from_api\")\n stats[\n \"core_http2_initiate_write_due_to_stream_flow_control\"] = massage_qps_stats_helpers.counter(\n core_stats,\n \"http2_initiate_write_due_to_stream_flow_control\")\n stats[\n \"core_http2_initiate_write_due_to_transport_flow_control\"] = massage_qps_stats_helpers.counter(\n core_stats,\n \"http2_initiate_write_due_to_transport_flow_control\")\n stats[\n \"core_http2_initiate_write_due_to_send_settings\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_send_settings\")\n stats[\n \"core_http2_initiate_write_due_to_bdp_estimator_ping\"] = massage_qps_stats_helpers.counter(\n core_stats,\n \"http2_initiate_write_due_to_bdp_estimator_ping\")\n stats[\n \"core_http2_initiate_write_due_to_flow_control_unstalled_by_setting\"] = massage_qps_stats_helpers.counter(\n core_stats,\n \"http2_initiate_write_due_to_flow_control_unstalled_by_setting\"\n )\n stats[\n \"core_http2_initiate_write_due_to_flow_control_unstalled_by_update\"] = massage_qps_stats_helpers.counter(\n core_stats,\n \"http2_initiate_write_due_to_flow_control_unstalled_by_update\"\n )\n stats[\n \"core_http2_initiate_write_due_to_application_ping\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_application_ping\")\n stats[\n \"core_http2_initiate_write_due_to_keepalive_ping\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_keepalive_ping\")\n stats[\n \"core_http2_initiate_write_due_to_transport_flow_control_unstalled\"] = massage_qps_stats_helpers.counter(\n core_stats,\n \"http2_initiate_write_due_to_transport_flow_control_unstalled\"\n )\n stats[\n \"core_http2_initiate_write_due_to_ping_response\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_ping_response\")\n stats[\n \"core_http2_initiate_write_due_to_force_rst_stream\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_initiate_write_due_to_force_rst_stream\")\n stats[\n \"core_http2_spurious_writes_begun\"] = massage_qps_stats_helpers.counter(\n core_stats, \"http2_spurious_writes_begun\")\n stats[\n \"core_hpack_recv_indexed\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_recv_indexed\")\n stats[\n \"core_hpack_recv_lithdr_incidx\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_recv_lithdr_incidx\")\n stats[\n \"core_hpack_recv_lithdr_incidx_v\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_recv_lithdr_incidx_v\")\n stats[\n \"core_hpack_recv_lithdr_notidx\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_recv_lithdr_notidx\")\n stats[\n \"core_hpack_recv_lithdr_notidx_v\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_recv_lithdr_notidx_v\")\n stats[\n \"core_hpack_recv_lithdr_nvridx\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_recv_lithdr_nvridx\")\n stats[\n \"core_hpack_recv_lithdr_nvridx_v\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_recv_lithdr_nvridx_v\")\n stats[\n \"core_hpack_recv_uncompressed\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_recv_uncompressed\")\n stats[\n \"core_hpack_recv_huffman\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_recv_huffman\")\n stats[\"core_hpack_recv_binary\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_recv_binary\")\n stats[\n \"core_hpack_recv_binary_base64\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_recv_binary_base64\")\n stats[\n \"core_hpack_send_indexed\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_send_indexed\")\n stats[\n \"core_hpack_send_lithdr_incidx\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_send_lithdr_incidx\")\n stats[\n \"core_hpack_send_lithdr_incidx_v\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_send_lithdr_incidx_v\")\n stats[\n \"core_hpack_send_lithdr_notidx\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_send_lithdr_notidx\")\n stats[\n \"core_hpack_send_lithdr_notidx_v\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_send_lithdr_notidx_v\")\n stats[\n \"core_hpack_send_lithdr_nvridx\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_send_lithdr_nvridx\")\n stats[\n \"core_hpack_send_lithdr_nvridx_v\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_send_lithdr_nvridx_v\")\n stats[\n \"core_hpack_send_uncompressed\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_send_uncompressed\")\n stats[\n \"core_hpack_send_huffman\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_send_huffman\")\n stats[\"core_hpack_send_binary\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_send_binary\")\n stats[\n \"core_hpack_send_binary_base64\"] = massage_qps_stats_helpers.counter(\n core_stats, \"hpack_send_binary_base64\")\n stats[\n \"core_combiner_locks_initiated\"] = massage_qps_stats_helpers.counter(\n core_stats, \"combiner_locks_initiated\")\n stats[\n \"core_combiner_locks_scheduled_items\"] = massage_qps_stats_helpers.counter(\n core_stats, \"combiner_locks_scheduled_items\")\n stats[\n \"core_combiner_locks_scheduled_final_items\"] = massage_qps_stats_helpers.counter(\n core_stats, \"combiner_locks_scheduled_final_items\")\n stats[\n \"core_combiner_locks_offloaded\"] = massage_qps_stats_helpers.counter(\n core_stats, \"combiner_locks_offloaded\")\n stats[\n \"core_call_combiner_locks_initiated\"] = massage_qps_stats_helpers.counter(\n core_stats, \"call_combiner_locks_initiated\")\n stats[\n \"core_call_combiner_locks_scheduled_items\"] = massage_qps_stats_helpers.counter(\n core_stats, \"call_combiner_locks_scheduled_items\")\n stats[\n \"core_call_combiner_set_notify_on_cancel\"] = massage_qps_stats_helpers.counter(\n core_stats, \"call_combiner_set_notify_on_cancel\")\n stats[\n \"core_call_combiner_cancelled\"] = massage_qps_stats_helpers.counter(\n core_stats, \"call_combiner_cancelled\")\n stats[\n \"core_executor_scheduled_short_items\"] = massage_qps_stats_helpers.counter(\n core_stats, \"executor_scheduled_short_items\")\n stats[\n \"core_executor_scheduled_long_items\"] = massage_qps_stats_helpers.counter(\n core_stats, \"executor_scheduled_long_items\")\n stats[\n \"core_executor_scheduled_to_self\"] = massage_qps_stats_helpers.counter(\n core_stats, \"executor_scheduled_to_self\")\n stats[\n \"core_executor_wakeup_initiated\"] = massage_qps_stats_helpers.counter(\n core_stats, \"executor_wakeup_initiated\")\n stats[\n \"core_executor_queue_drained\"] = massage_qps_stats_helpers.counter(\n core_stats, \"executor_queue_drained\")\n stats[\n \"core_executor_push_retries\"] = massage_qps_stats_helpers.counter(\n core_stats, \"executor_push_retries\")\n stats[\n \"core_server_requested_calls\"] = massage_qps_stats_helpers.counter(\n core_stats, \"server_requested_calls\")\n stats[\n \"core_server_slowpath_requests_queued\"] = massage_qps_stats_helpers.counter(\n core_stats, \"server_slowpath_requests_queued\")\n stats[\n \"core_cq_ev_queue_trylock_failures\"] = massage_qps_stats_helpers.counter(\n core_stats, \"cq_ev_queue_trylock_failures\")\n stats[\n \"core_cq_ev_queue_trylock_successes\"] = massage_qps_stats_helpers.counter(\n core_stats, \"cq_ev_queue_trylock_successes\")\n stats[\n \"core_cq_ev_queue_transient_pop_failures\"] = massage_qps_stats_helpers.counter(\n core_stats, \"cq_ev_queue_transient_pop_failures\")\n h = massage_qps_stats_helpers.histogram(core_stats,\n \"call_initial_size\")\n stats[\"core_call_initial_size\"] = \",\".join(\n \"%f\" % x for x in h.buckets)\n stats[\"core_call_initial_size_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_call_initial_size_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_call_initial_size_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_call_initial_size_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)\n h = massage_qps_stats_helpers.histogram(core_stats,\n \"poll_events_returned\")\n stats[\"core_poll_events_returned\"] = \",\".join(\n \"%f\" % x for x in h.buckets)\n stats[\"core_poll_events_returned_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_poll_events_returned_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_poll_events_returned_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_poll_events_returned_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)\n h = massage_qps_stats_helpers.histogram(core_stats,\n \"tcp_write_size\")\n stats[\"core_tcp_write_size\"] = \",\".join(\"%f\" % x for x in h.buckets)\n stats[\"core_tcp_write_size_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_tcp_write_size_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_tcp_write_size_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_tcp_write_size_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)\n h = massage_qps_stats_helpers.histogram(core_stats,\n \"tcp_write_iov_size\")\n stats[\"core_tcp_write_iov_size\"] = \",\".join(\n \"%f\" % x for x in h.buckets)\n stats[\"core_tcp_write_iov_size_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_tcp_write_iov_size_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_tcp_write_iov_size_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_tcp_write_iov_size_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)\n h = massage_qps_stats_helpers.histogram(core_stats, \"tcp_read_size\")\n stats[\"core_tcp_read_size\"] = \",\".join(\"%f\" % x for x in h.buckets)\n stats[\"core_tcp_read_size_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_tcp_read_size_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_tcp_read_size_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_tcp_read_size_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)\n h = massage_qps_stats_helpers.histogram(core_stats,\n \"tcp_read_offer\")\n stats[\"core_tcp_read_offer\"] = \",\".join(\"%f\" % x for x in h.buckets)\n stats[\"core_tcp_read_offer_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_tcp_read_offer_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_tcp_read_offer_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_tcp_read_offer_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)\n h = massage_qps_stats_helpers.histogram(core_stats,\n \"tcp_read_offer_iov_size\")\n stats[\"core_tcp_read_offer_iov_size\"] = \",\".join(\n \"%f\" % x for x in h.buckets)\n stats[\"core_tcp_read_offer_iov_size_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_tcp_read_offer_iov_size_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_tcp_read_offer_iov_size_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_tcp_read_offer_iov_size_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)\n h = massage_qps_stats_helpers.histogram(core_stats,\n \"http2_send_message_size\")\n stats[\"core_http2_send_message_size\"] = \",\".join(\n \"%f\" % x for x in h.buckets)\n stats[\"core_http2_send_message_size_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_http2_send_message_size_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_http2_send_message_size_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_http2_send_message_size_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)\n h = massage_qps_stats_helpers.histogram(\n core_stats, \"http2_send_initial_metadata_per_write\")\n stats[\"core_http2_send_initial_metadata_per_write\"] = \",\".join(\n \"%f\" % x for x in h.buckets)\n stats[\"core_http2_send_initial_metadata_per_write_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_http2_send_initial_metadata_per_write_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_http2_send_initial_metadata_per_write_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_http2_send_initial_metadata_per_write_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)\n h = massage_qps_stats_helpers.histogram(\n core_stats, \"http2_send_message_per_write\")\n stats[\"core_http2_send_message_per_write\"] = \",\".join(\n \"%f\" % x for x in h.buckets)\n stats[\"core_http2_send_message_per_write_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_http2_send_message_per_write_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_http2_send_message_per_write_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_http2_send_message_per_write_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)\n h = massage_qps_stats_helpers.histogram(\n core_stats, \"http2_send_trailing_metadata_per_write\")\n stats[\"core_http2_send_trailing_metadata_per_write\"] = \",\".join(\n \"%f\" % x for x in h.buckets)\n stats[\n \"core_http2_send_trailing_metadata_per_write_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_http2_send_trailing_metadata_per_write_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_http2_send_trailing_metadata_per_write_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_http2_send_trailing_metadata_per_write_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)\n h = massage_qps_stats_helpers.histogram(\n core_stats, \"http2_send_flowctl_per_write\")\n stats[\"core_http2_send_flowctl_per_write\"] = \",\".join(\n \"%f\" % x for x in h.buckets)\n stats[\"core_http2_send_flowctl_per_write_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_http2_send_flowctl_per_write_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_http2_send_flowctl_per_write_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_http2_send_flowctl_per_write_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)\n h = massage_qps_stats_helpers.histogram(core_stats,\n \"server_cqs_checked\")\n stats[\"core_server_cqs_checked\"] = \",\".join(\n \"%f\" % x for x in h.buckets)\n stats[\"core_server_cqs_checked_bkts\"] = \",\".join(\n \"%f\" % x for x in h.boundaries)\n stats[\n \"core_server_cqs_checked_50p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 50, h.boundaries)\n stats[\n \"core_server_cqs_checked_95p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 95, h.boundaries)\n stats[\n \"core_server_cqs_checked_99p\"] = massage_qps_stats_helpers.percentile(\n h.buckets, 99, h.boundaries)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements pgraster.py from indevgr/django (path: django/contrib/gis/db/backends/postgis/pgraster.py)."}, {"role": "assistant", "content": "# django/contrib/gis/db/backends/postgis/pgraster.py (from indevgr/django, license: bsd-3-clause)\n\nimport binascii\nimport struct\n\nfrom django.forms import ValidationError\n\nfrom .const import (\n GDAL_TO_POSTGIS, GDAL_TO_STRUCT, POSTGIS_HEADER_STRUCTURE, POSTGIS_TO_GDAL,\n STRUCT_SIZE,\n)\n\ndef pack(structure, data):\n \"\"\"\n Pack data into hex string with little endian format.\n \"\"\"\n return binascii.hexlify(struct.pack('<' + structure, *data)).upper()\n\ndef unpack(structure, data):\n \"\"\"\n Unpack little endian hexlified binary string into a list.\n \"\"\"\n return struct.unpack('<' + structure, binascii.unhexlify(data))\n\ndef chunk(data, index):\n \"\"\"\n Split a string into two parts at the input index.\n \"\"\"\n return data[:index], data[index:]\n\ndef get_pgraster_srid(data):\n \"\"\"\n Extract the SRID from a PostGIS raster string.\n \"\"\"\n if data is None:\n return\n # The positional arguments here extract the hex-encoded srid from the\n # header of the PostGIS raster string. This can be understood through\n # the POSTGIS_HEADER_STRUCTURE constant definition in the const module.\n return unpack('i', data[106:114])[0]\n\ndef from_pgraster(data):\n \"\"\"\n Convert a PostGIS HEX String into a dictionary.\n \"\"\"\n if data is None:\n return\n\n # Split raster header from data\n header, data = chunk(data, 122)\n header = unpack(POSTGIS_HEADER_STRUCTURE, header)\n\n # Parse band data\n bands = []\n pixeltypes = []\n while data:\n # Get pixel type for this band\n pixeltype, data = chunk(data, 2)\n pixeltype = unpack('B', pixeltype)[0]\n\n # Subtract nodata byte from band nodata value if it exists\n has_nodata = pixeltype >= 64\n if has_nodata:\n pixeltype -= 64\n\n # Convert datatype from PostGIS to GDAL & get pack type and size\n pixeltype = POSTGIS_TO_GDAL[pixeltype]\n pack_type = GDAL_TO_STRUCT[pixeltype]\n pack_size = 2 * STRUCT_SIZE[pack_type]\n\n # Parse band nodata value. The nodata value is part of the\n # PGRaster string even if the nodata flag is True, so it always\n # has to be chunked off the data string.\n nodata, data = chunk(data, pack_size)\n nodata = unpack(pack_type, nodata)[0]\n\n # Chunk and unpack band data (pack size times nr of pixels)\n band, data = chunk(data, pack_size * header[10] * header[11])\n band_result = {'data': binascii.unhexlify(band)}\n\n # If the nodata flag is True, set the nodata value.\n if has_nodata:\n band_result['nodata_value'] = nodata\n\n # Append band data to band list\n bands.append(band_result)\n\n # Store pixeltype of this band in pixeltypes array\n pixeltypes.append(pixeltype)\n\n # Check that all bands have the same pixeltype.\n # This is required by GDAL. PostGIS rasters could have different pixeltypes\n # for bands of the same raster.\n if len(set(pixeltypes)) != 1:\n raise ValidationError(\"Band pixeltypes are not all equal.\")\n\n return {\n 'srid': int(header[9]),\n 'width': header[10], 'height': header[11],\n 'datatype': pixeltypes[0],\n 'origin': (header[5], header[6]),\n 'scale': (header[3], header[4]),\n 'skew': (header[7], header[8]),\n 'bands': bands,\n }\n\ndef to_pgraster(rast):\n \"\"\"\n Convert a GDALRaster into PostGIS Raster format.\n \"\"\"\n # Return if the raster is null\n if rast is None or rast == '':\n return\n\n # Prepare the raster header data as a tuple. The first two numbers are\n # the endianness and the PostGIS Raster Version, both are fixed by\n # PostGIS at the moment.\n rasterheader = (\n 1, 0, len(rast.bands), rast.scale.x, rast.scale.y,\n rast.origin.x, rast.origin.y, rast.skew.x, rast.skew.y,\n rast.srs.srid, rast.width, rast.height,\n )\n\n # Hexlify raster header\n result = pack(POSTGIS_HEADER_STRUCTURE, rasterheader)\n\n for band in rast.bands:\n # The PostGIS raster band header has exactly two elements, a 8BUI byte\n # and the nodata value.\n #\n # The 8BUI stores both the PostGIS pixel data type and a nodata flag.\n # It is composed as the datatype integer plus 64 as a flag for existing\n # nodata values:\n # 8BUI_VALUE = PG_PIXEL_TYPE (0-11) + FLAG (0 or 64)\n #\n # For example, if the byte value is 71, then the datatype is\n # 71-64 = 7 (32BSI) and the nodata value is True.\n structure = 'B' + GDAL_TO_STRUCT[band.datatype()]\n\n # Get band pixel type in PostGIS notation\n pixeltype = GDAL_TO_POSTGIS[band.datatype()]\n\n # Set the nodata flag\n if band.nodata_value is not None:\n pixeltype += 64\n\n # Pack band header\n bandheader = pack(structure, (pixeltype, band.nodata_value or 0))\n\n # Hexlify band data\n band_data_hex = binascii.hexlify(band.data(as_memoryview=True)).upper()\n\n # Add packed header and band data to result\n result += bandheader + band_data_hex\n\n # Cast raster to string before passing it to the DB\n return result.decode()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements statusfile.py from zero-rp/miniblink49 (path: v8_7_5/tools/testrunner/local/statusfile.py)."}, {"role": "assistant", "content": "# v8_7_5/tools/testrunner/local/statusfile.py (from zero-rp/miniblink49, license: apache-2.0)\n\n# Copyright 2012 the V8 project authors. All rights reserved.\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n# for py2/py3 compatibility\nfrom __future__ import print_function\n\nimport os\nimport re\n\nfrom variants import ALL_VARIANTS\nfrom utils import Freeze\n\n# Possible outcomes\nFAIL = \"FAIL\"\nPASS = \"PASS\"\nTIMEOUT = \"TIMEOUT\"\nCRASH = \"CRASH\"\n\n# Outcomes only for status file, need special handling\nFAIL_OK = \"FAIL_OK\"\nFAIL_SLOPPY = \"FAIL_SLOPPY\"\n\n# Modifiers\nSKIP = \"SKIP\"\nSLOW = \"SLOW\"\nNO_VARIANTS = \"NO_VARIANTS\"\nFAIL_PHASE_ONLY = \"FAIL_PHASE_ONLY\"\n\nALWAYS = \"ALWAYS\"\n\nKEYWORDS = {}\nfor key in [SKIP, FAIL, PASS, CRASH, SLOW, FAIL_OK, NO_VARIANTS, FAIL_SLOPPY,\n ALWAYS, FAIL_PHASE_ONLY]:\n KEYWORDS[key] = key\n\n# Support arches, modes to be written as keywords instead of strings.\nVARIABLES = {ALWAYS: True}\nfor var in [\"debug\", \"release\", \"big\", \"little\", \"android\",\n \"android_arm\", \"android_arm64\", \"android_ia32\", \"android_x64\",\n \"arm\", \"arm64\", \"ia32\", \"mips\", \"mipsel\", \"mips64\", \"mips64el\",\n \"x64\", \"ppc\", \"ppc64\", \"s390\", \"s390x\", \"macos\", \"windows\",\n \"linux\", \"aix\", \"r1\", \"r2\", \"r3\", \"r5\", \"r6\"]:\n VARIABLES[var] = var\n\n# Allow using variants as keywords.\nfor var in ALL_VARIANTS:\n VARIABLES[var] = var\n\nclass StatusFile(object):\n def __init__(self, path, variables):\n \"\"\"\n _rules: {variant: {test name: [rule]}}\n _prefix_rules: {variant: {test name prefix: [rule]}}\n \"\"\"\n with open(path) as f:\n self._rules, self._prefix_rules = ReadStatusFile(f.read(), variables)\n\n def get_outcomes(self, testname, variant=None):\n \"\"\"Merges variant dependent and independent rules.\"\"\"\n outcomes = frozenset()\n\n for key in set([variant or '', '']):\n rules = self._rules.get(key, {})\n prefix_rules = self._prefix_rules.get(key, {})\n\n if testname in rules:\n outcomes |= rules[testname]\n\n for prefix in prefix_rules:\n if testname.startswith(prefix):\n outcomes |= prefix_rules[prefix]\n\n return outcomes\n\n def warn_unused_rules(self, tests, check_variant_rules=False):\n \"\"\"Finds and prints unused rules in status file.\n\n Rule X is unused when it doesn't apply to any tests, which can also mean\n that all matching tests were skipped by another rule before evaluating X.\n\n Args:\n tests: list of pairs (testname, variant)\n check_variant_rules: if set variant dependent rules are checked\n \"\"\"\n\n if check_variant_rules:\n variants = list(ALL_VARIANTS)\n else:\n variants = ['']\n used_rules = set()\n\n for testname, variant in tests:\n variant = variant or ''\n\n if testname in self._rules.get(variant, {}):\n used_rules.add((testname, variant))\n if SKIP in self._rules[variant][testname]:\n continue\n\n for prefix in self._prefix_rules.get(variant, {}):\n if testname.startswith(prefix):\n used_rules.add((prefix, variant))\n if SKIP in self._prefix_rules[variant][prefix]:\n break\n\n for variant in variants:\n for rule, value in (\n list(self._rules.get(variant, {}).iteritems()) +\n list(self._prefix_rules.get(variant, {}).iteritems())):\n if (rule, variant) not in used_rules:\n if variant == '':\n variant_desc = 'variant independent'\n else:\n variant_desc = 'variant: %s' % variant\n print('Unused rule: %s -> %s (%s)' % (rule, value, variant_desc))\n\ndef _JoinsPassAndFail(outcomes1, outcomes2):\n \"\"\"Indicates if we join PASS and FAIL from two different outcome sets and\n the first doesn't already contain both.\n \"\"\"\n return (\n PASS in outcomes1 and\n not (FAIL in outcomes1 or FAIL_OK in outcomes1) and\n (FAIL in outcomes2 or FAIL_OK in outcomes2)\n )\n\nVARIANT_EXPRESSION = object()\n\ndef _EvalExpression(exp, variables):\n \"\"\"Evaluates expression and returns its result. In case of NameError caused by\n undefined \"variant\" identifier returns VARIANT_EXPRESSION marker.\n \"\"\"\n\n try:\n return eval(exp, variables)\n except NameError as e:\n identifier = re.match(\"name '(.*)' is not defined\", e.message).group(1)\n assert identifier == \"variant\", \"Unknown identifier: %s\" % identifier\n return VARIANT_EXPRESSION\n\ndef _EvalVariantExpression(\n condition, section, variables, variant, rules, prefix_rules):\n variables_with_variant = dict(variables)\n variables_with_variant[\"variant\"] = variant\n result = _EvalExpression(condition, variables_with_variant)\n assert result != VARIANT_EXPRESSION\n if result is True:\n _ReadSection(\n section,\n variables_with_variant,\n rules[variant],\n prefix_rules[variant],\n )\n else:\n assert result is False, \"Make sure expressions evaluate to boolean values\"\n\ndef _ParseOutcomeList(rule, outcomes, variables, target_dict):\n \"\"\"Outcome list format: [condition, outcome, outcome, ...]\"\"\"\n\n result = set([])\n if type(outcomes) == str:\n outcomes = [outcomes]\n for item in outcomes:\n if type(item) == str:\n result.add(item)\n elif type(item) == list:\n condition = item[0]\n exp = _EvalExpression(condition, variables)\n assert exp != VARIANT_EXPRESSION, (\n \"Nested variant expressions are not supported\")\n if exp is False:\n continue\n\n # Ensure nobody uses an identifier by mistake, like \"default\",\n # which would evaluate to true here otherwise.\n assert exp is True, \"Make sure expressions evaluate to boolean values\"\n\n for outcome in item[1:]:\n assert type(outcome) == str\n result.add(outcome)\n else:\n assert False\n if len(result) == 0:\n return\n if rule in target_dict:\n # A FAIL without PASS in one rule has always precedence over a single\n # PASS (without FAIL) in another. Otherwise the default PASS expectation\n # in a rule with a modifier (e.g. PASS, SLOW) would be joined to a FAIL\n # from another rule (which intended to mark a test as FAIL and not as\n # PASS and FAIL).\n if _JoinsPassAndFail(target_dict[rule], result):\n target_dict[rule] -= set([PASS])\n if _JoinsPassAndFail(result, target_dict[rule]):\n result -= set([PASS])\n target_dict[rule] |= result\n else:\n target_dict[rule] = result\n\ndef ReadContent(content):\n return eval(content, KEYWORDS)\n\ndef ReadStatusFile(content, variables):\n \"\"\"Status file format\n Status file := [section]\n section = [CONDITION, section_rules]\n section_rules := {path: outcomes}\n outcomes := outcome | [outcome, ...]\n outcome := SINGLE_OUTCOME | [CONDITION, SINGLE_OUTCOME, SINGLE_OUTCOME, ...]\n \"\"\"\n\n # Empty defaults for rules and prefix_rules. Variant-independent\n # rules are mapped by \"\", others by the variant name.\n rules = {variant: {} for variant in ALL_VARIANTS}\n rules[\"\"] = {}\n prefix_rules = {variant: {} for variant in ALL_VARIANTS}\n prefix_rules[\"\"] = {}\n\n variables.update(VARIABLES)\n for conditional_section in ReadContent(content):\n assert type(conditional_section) == list\n assert len(conditional_section) == 2\n condition, section = conditional_section\n exp = _EvalExpression(condition, variables)\n\n # The expression is variant-independent and evaluates to False.\n if exp is False:\n continue\n\n # The expression is variant-independent and evaluates to True.\n if exp is True:\n _ReadSection(\n section,\n variables,\n rules[''],\n prefix_rules[''],\n )\n continue\n\n # The expression is variant-dependent (contains \"variant\" keyword)\n if exp == VARIANT_EXPRESSION:\n # If the expression contains one or more \"variant\" keywords, we evaluate\n # it for all possible variants and create rules for those that apply.\n for variant in ALL_VARIANTS:\n _EvalVariantExpression(\n condition, section, variables, variant, rules, prefix_rules)\n continue\n\n assert False, \"Make sure expressions evaluate to boolean values\"\n\n return Freeze(rules), Freeze(prefix_rules)\n\ndef _ReadSection(section, variables, rules, prefix_rules):\n assert type(section) == dict\n for rule, outcome_list in section.iteritems():\n assert type(rule) == str\n\n if rule[-1] == '*':\n _ParseOutcomeList(rule[:-1], outcome_list, variables, prefix_rules)\n else:\n _ParseOutcomeList(rule, outcome_list, variables, rules)\n\nJS_TEST_PATHS = {\n 'debugger': [[]],\n 'inspector': [[]],\n 'intl': [[]],\n 'message': [[]],\n 'mjsunit': [[]],\n 'mozilla': [['data']],\n 'test262': [['data', 'test'], ['local-tests', 'test']],\n 'webkit': [[]],\n}\n\ndef PresubmitCheck(path):\n with open(path) as f:\n contents = ReadContent(f.read())\n basename = os.path.basename(os.path.dirname(path))\n root_prefix = basename + \"/\"\n status = {\"success\": True}\n def _assert(check, message): # Like \"assert\", but doesn't throw.\n if not check:\n print(\"%s: Error: %s\" % (path, message))\n status[\"success\"] = False\n try:\n for section in contents:\n _assert(type(section) == list, \"Section must be a list\")\n _assert(len(section) == 2, \"Section list must have exactly 2 entries\")\n section = section[1]\n _assert(type(section) == dict,\n \"Second entry of section must be a dictionary\")\n for rule in section:\n _assert(type(rule) == str, \"Rule key must be a string\")\n _assert(not rule.startswith(root_prefix),\n \"Suite name prefix must not be used in rule keys\")\n _assert(not rule.endswith('.js'),\n \".js extension must not be used in rule keys.\")\n _assert('*' not in rule or (rule.count('*') == 1 and rule[-1] == '*'),\n \"Only the last character of a rule key can be a wildcard\")\n if basename in JS_TEST_PATHS and '*' not in rule:\n _assert(any(os.path.exists(os.path.join(os.path.dirname(path),\n *(paths + [rule + \".js\"])))\n for paths in JS_TEST_PATHS[basename]),\n \"missing file for %s test %s\" % (basename, rule))\n return status[\"success\"]\n except Exception as e:\n print(e)\n return False"}]} {"messages": [{"role": "user", "content": "Write Python code that implements si_postalcodes.py from RaoUmer/django (path: django/contrib/localflavor/si/si_postalcodes.py)."}, {"role": "assistant", "content": "# django/contrib/localflavor/si/si_postalcodes.py (from RaoUmer/django, license: bsd-3-clause)\n\n# *-* coding: utf-8 *-*\nfrom __future__ import unicode_literals\n\nSI_POSTALCODES = [\n (1000, 'Ljubljana'),\n (1215, 'Medvode'),\n (1216, 'Smlednik'),\n (1217, 'Vodice'),\n (1218, 'Komenda'),\n (1219, 'Laze v Tuhinju'),\n (1221, 'Motnik'),\n (1222, 'Trojane'),\n (1223, 'Blagovica'),\n (1225, 'Lukovica'),\n (1230, 'Dom\\u017eale'),\n (1233, 'Dob'),\n (1234, 'Menge\\u0161'),\n (1235, 'Radomlje'),\n (1236, 'Trzin'),\n (1241, 'Kamnik'),\n (1242, 'Stahovica'),\n (1251, 'Morav\\u010de'),\n (1252, 'Va\\u010de'),\n (1262, 'Dol pri Ljubljani'),\n (1270, 'Litija'),\n (1272, 'Pol\\u0161nik'),\n (1273, 'Dole pri Litiji'),\n (1274, 'Gabrovka'),\n (1275, '\\u0160martno pri Litiji'),\n (1276, 'Primskovo'),\n (1281, 'Kresnice'),\n (1282, 'Sava'),\n (1290, 'Grosuplje'),\n (1291, '\\u0160kofljica'),\n (1292, 'Ig'),\n (1293, '\\u0160marje - Sap'),\n (1294, 'Vi\\u0161nja Gora'),\n (1295, 'Ivan\\u010dna Gorica'),\n (1296, '\\u0160entvid pri Sti\\u010dni'),\n (1301, 'Krka'),\n (1303, 'Zagradec'),\n (1310, 'Ribnica'),\n (1311, 'Turjak'),\n (1312, 'Videm - Dobrepolje'),\n (1313, 'Struge'),\n (1314, 'Rob'),\n (1315, 'Velike La\\u0161\\u010de'),\n (1316, 'Ortnek'),\n (1317, 'Sodra\\u017eica'),\n (1318, 'Lo\\u0161ki Potok'),\n (1319, 'Draga'),\n (1330, 'Ko\\u010devje'),\n (1331, 'Dolenja vas'),\n (1332, 'Stara Cerkev'),\n (1336, 'Kostel'),\n (1337, 'Osilnica'),\n (1338, 'Ko\\u010devska Reka'),\n (1351, 'Brezovica pri Ljubljani'),\n (1352, 'Preserje'),\n (1353, 'Borovnica'),\n (1354, 'Horjul'),\n (1355, 'Polhov Gradec'),\n (1356, 'Dobrova'),\n (1357, 'Notranje Gorice'),\n (1358, 'Log pri Brezovici'),\n (1360, 'Vrhnika'),\n (1370, 'Logatec'),\n (1372, 'Hotedr\\u0161ica'),\n (1373, 'Rovte'),\n (1380, 'Cerknica'),\n (1381, 'Rakek'),\n (1382, 'Begunje pri Cerknici'),\n (1384, 'Grahovo'),\n (1385, 'Nova vas'),\n (1386, 'Stari trg pri Lo\\u017eu'),\n (1410, 'Zagorje ob Savi'),\n (1411, 'Izlake'),\n (1412, 'Kisovec'),\n (1413, '\\u010cem\\u0161enik'),\n (1414, 'Podkum'),\n (1420, 'Trbovlje'),\n (1423, 'Dobovec'),\n (1430, 'Hrastnik'),\n (1431, 'Dol pri Hrastniku'),\n (1432, 'Zidani Most'),\n (1433, 'Rade\\u010de'),\n (1434, 'Loka pri Zidanem Mostu'),\n (2000, 'Maribor'),\n (2201, 'Zgornja Kungota'),\n (2204, 'Miklav\\u017e na Dravskem polju'),\n (2205, 'Star\\u0161e'),\n (2206, 'Marjeta na Dravskem polju'),\n (2208, 'Pohorje'),\n (2211, 'Pesnica pri Mariboru'),\n (2212, '\\u0160entilj v Slovenskih goricah'),\n (2213, 'Zgornja Velka'),\n (2214, 'Sladki vrh'),\n (2215, 'Cer\\u0161ak'),\n (2221, 'Jarenina'),\n (2222, 'Jakobski Dol'),\n (2223, 'Jurovski Dol'),\n (2229, 'Male\\u010dnik'),\n (2230, 'Lenart v Slovenskih goricah'),\n (2231, 'Pernica'),\n (2232, 'Voli\\u010dina'),\n (2233, 'Sveta Ana v Slovenskih goricah'),\n (2234, 'Benedikt'),\n (2235, 'Sveta Trojica v Slovenskih goricah'),\n (2236, 'Cerkvenjak'),\n (2241, 'Spodnji Duplek'),\n (2242, 'Zgornja Korena'),\n (2250, 'Ptuj'),\n (2252, 'Dornava'),\n (2253, 'Destrnik'),\n (2254, 'Trnovska vas'),\n (2255, 'Vitomarci'),\n (2256, 'Jur\\u0161inci'),\n (2257, 'Polen\\u0161ak'),\n (2258, 'Sveti Toma\\u017e'),\n (2259, 'Ivanjkovci'),\n (2270, 'Ormo\\u017e'),\n (2272, 'Gori\\u0161nica'),\n (2273, 'Podgorci'),\n (2274, 'Velika Nedelja'),\n (2275, 'Miklav\\u017e pri Ormo\\u017eu'),\n (2276, 'Kog'),\n (2277, 'Sredi\\u0161\\u010de ob Dravi'),\n (2281, 'Markovci'),\n (2282, 'Cirkulane'),\n (2283, 'Zavr\\u010d'),\n (2284, 'Videm pri Ptuju'),\n (2285, 'Zgornji Leskovec'),\n (2286, 'Podlehnik'),\n (2287, '\\u017detale'),\n (2288, 'Hajdina'),\n (2289, 'Stoperce'),\n (2310, 'Slovenska Bistrica'),\n (2311, 'Ho\\u010de'),\n (2312, 'Orehova vas'),\n (2313, 'Fram'),\n (2314, 'Zgornja Polskava'),\n (2315, '\\u0160martno na Pohorju'),\n (2316, 'Zgornja Lo\\u017enica'),\n (2317, 'Oplotnica'),\n (2318, 'Laporje'),\n (2319, 'Polj\\u010dane'),\n (2321, 'Makole'),\n (2322, 'Maj\\u0161perk'),\n (2323, 'Ptujska Gora'),\n (2324, 'Lovrenc na Dravskem polju'),\n (2325, 'Kidri\\u010devo'),\n (2326, 'Cirkovce'),\n (2327, 'Ra\\u010de'),\n (2331, 'Pragersko'),\n (2341, 'Limbu\\u0161'),\n (2342, 'Ru\\u0161e'),\n (2343, 'Fala'),\n (2344, 'Lovrenc na Pohorju'),\n (2345, 'Bistrica ob Dravi'),\n (2351, 'Kamnica'),\n (2352, 'Selnica ob Dravi'),\n (2353, 'Sv. Duh na Ostrem Vrhu'),\n (2354, 'Bresternica'),\n (2360, 'Radlje ob Dravi'),\n (2361, 'O\\u017ebalt'),\n (2362, 'Kapla'),\n (2363, 'Podvelka'),\n (2364, 'Ribnica na Pohorju'),\n (2365, 'Vuhred'),\n (2366, 'Muta'),\n (2367, 'Vuzenica'),\n (2370, 'Dravograd'),\n (2371, 'Trbonje'),\n (2372, 'Libeli\\u010de'),\n (2373, '\\u0160entjan\\u017e pri Dravogradu'),\n (2380, 'Slovenj Gradec'),\n (2381, 'Podgorje pri Slovenj Gradcu'),\n (2382, 'Mislinja'),\n (2383, '\\u0160martno pri Slovenj Gradcu'),\n (2390, 'Ravne na Koro\\u0161kem'),\n (2391, 'Prevalje'),\n (2392, 'Me\\u017eica'),\n (2393, '\\u010crna na Koro\\u0161kem'),\n (2394, 'Kotlje'),\n (3000, 'Celje'),\n (3201, '\\u0160martno v Ro\\u017eni dolini'),\n (3202, 'Ljube\\u010dna'),\n (3203, 'Nova Cerkev'),\n (3204, 'Dobrna'),\n (3205, 'Vitanje'),\n (3206, 'Stranice'),\n (3210, 'Slovenske Konjice'),\n (3211, '\\u0160kofja vas'),\n (3212, 'Vojnik'),\n (3213, 'Frankolovo'),\n (3214, 'Zre\\u010de'),\n (3215, 'Lo\\u010de'),\n (3220, '\\u0160tore'),\n (3221, 'Teharje'),\n (3222, 'Dramlje'),\n (3223, 'Loka pri \\u017dusmu'),\n (3224, 'Dobje pri Planini'),\n (3225, 'Planina pri Sevnici'),\n (3230, '\\u0160entjur'),\n (3231, 'Grobelno'),\n (3232, 'Ponikva'),\n (3233, 'Kalobje'),\n (3240, '\\u0160marje pri Jel\\u0161ah'),\n (3241, 'Podplat'),\n (3250, 'Roga\\u0161ka Slatina'),\n (3252, 'Rogatec'),\n (3253, 'Pristava pri Mestinju'),\n (3254, 'Pod\\u010detrtek'),\n (3255, 'Bu\\u010de'),\n (3256, 'Bistrica ob Sotli'),\n (3257, 'Podsreda'),\n (3260, 'Kozje'),\n (3261, 'Lesi\\u010dno'),\n (3262, 'Prevorje'),\n (3263, 'Gorica pri Slivnici'),\n (3264, 'Sveti \\u0160tefan'),\n (3270, 'La\\u0161ko'),\n (3271, '\\u0160entrupert'),\n (3272, 'Rimske Toplice'),\n (3273, 'Jurklo\\u0161ter'),\n (3301, 'Petrov\\u010de'),\n (3302, 'Gri\\u017ee'),\n (3303, 'Gomilsko'),\n (3304, 'Tabor'),\n (3305, 'Vransko'),\n (3310, '\\u017dalec'),\n (3311, '\\u0160empeter v Savinjski dolini'),\n (3312, 'Prebold'),\n (3313, 'Polzela'),\n (3314, 'Braslov\\u010de'),\n (3320, 'Velenje - dostava'),\n (3322, 'Velenje - po\\u0161tni predali'),\n (3325, '\\u0160o\\u0161tanj'),\n (3326, 'Topol\\u0161ica'),\n (3327, '\\u0160martno ob Paki'),\n (3330, 'Mozirje'),\n (3331, 'Nazarje'),\n (3332, 'Re\\u010dica ob Savinji'),\n (3333, 'Ljubno ob Savinji'),\n (3334, 'Lu\\u010de'),\n (3335, 'Sol\\u010dava'),\n (3341, '\\u0160martno ob Dreti'),\n (3342, 'Gornji Grad'),\n (4000, 'Kranj'),\n (4201, 'Zgornja Besnica'),\n (4202, 'Naklo'),\n (4203, 'Duplje'),\n (4204, 'Golnik'),\n (4205, 'Preddvor'),\n (4206, 'Zgornje Jezersko'),\n (4207, 'Cerklje na Gorenjskem'),\n (4208, '\\u0160en\\u010dur'),\n (4209, '\\u017dabnica'),\n (4210, 'Brnik - aerodrom'),\n (4211, 'Mav\\u010di\\u010de'),\n (4212, 'Visoko'),\n (4220, '\\u0160kofja Loka'),\n (4223, 'Poljane nad \\u0160kofjo Loko'),\n (4224, 'Gorenja vas'),\n (4225, 'Sovodenj'),\n (4226, '\\u017diri'),\n (4227, 'Selca'),\n (4228, '\\u017delezniki'),\n (4229, 'Sorica'),\n (4240, 'Radovljica'),\n (4243, 'Brezje'),\n (4244, 'Podnart'),\n (4245, 'Kropa'),\n (4246, 'Kamna Gorica'),\n (4247, 'Zgornje Gorje'),\n (4248, 'Lesce'),\n (4260, 'Bled'),\n (4263, 'Bohinjska Bela'),\n (4264, 'Bohinjska Bistrica'),\n (4265, 'Bohinjsko jezero'),\n (4267, 'Srednja vas v Bohinju'),\n (4270, 'Jesenice'),\n (4273, 'Blejska Dobrava'),\n (4274, '\\u017dirovnica'),\n (4275, 'Begunje na Gorenjskem'),\n (4276, 'Hru\\u0161ica'),\n (4280, 'Kranjska Gora'),\n (4281, 'Mojstrana'),\n (4282, 'Gozd Martuljek'),\n (4283, 'Rate\\u010de - Planica'),\n (4290, 'Tr\\u017ei\\u010d'),\n (4294, 'Kri\\u017ee'),\n (5000, 'Nova Gorica'),\n (5210, 'Deskle'),\n (5211, 'Kojsko'),\n (5212, 'Dobrovo v Brdih'),\n (5213, 'Kanal'),\n (5214, 'Kal nad Kanalom'),\n (5215, 'Ro\\u010dinj'),\n (5216, 'Most na So\\u010di'),\n (5220, 'Tolmin'),\n (5222, 'Kobarid'),\n (5223, 'Breginj'),\n (5224, 'Srpenica'),\n (5230, 'Bovec'),\n (5231, 'Log pod Mangartom'),\n (5232, 'So\\u010da'),\n (5242, 'Grahovo ob Ba\\u010di'),\n (5243, 'Podbrdo'),\n (5250, 'Solkan'),\n (5251, 'Grgar'),\n (5252, 'Trnovo pri Gorici'),\n (5253, '\\u010cepovan'),\n (5261, '\\u0160empas'),\n (5262, '\\u010crni\\u010de'),\n (5263, 'Dobravlje'),\n (5270, 'Ajdov\\u0161\\u010dina'),\n (5271, 'Vipava'),\n (5272, 'Podnanos'),\n (5273, 'Col'),\n (5274, '\\u010crni Vrh nad Idrijo'),\n (5275, 'Godovi\\u010d'),\n (5280, 'Idrija'),\n (5281, 'Spodnja Idrija'),\n (5282, 'Cerkno'),\n (5283, 'Slap ob Idrijci'),\n (5290, '\\u0160empeter pri Gorici'),\n (5291, 'Miren'),\n (5292, 'Ren\\u010de'),\n (5293, 'Vol\\u010dja Draga'),\n (5294, 'Dornberk'),\n (5295, 'Branik'),\n (5296, 'Kostanjevica na Krasu'),\n (5297, 'Prva\\u010dina'),\n (6000, 'Koper'),\n (6210, 'Se\\u017eana'),\n (6215, 'Diva\\u010da'),\n (6216, 'Podgorje'),\n (6217, 'Vremski Britof'),\n (6219, 'Lokev'),\n (6221, 'Dutovlje'),\n (6222, '\\u0160tanjel'),\n (6223, 'Komen'),\n (6224, 'Seno\\u017ee\\u010de'),\n (6225, 'Hru\\u0161evje'),\n (6230, 'Postojna'),\n (6232, 'Planina'),\n (6240, 'Kozina'),\n (6242, 'Materija'),\n (6243, 'Obrov'),\n (6244, 'Podgrad'),\n (6250, 'Ilirska Bistrica'),\n (6251, 'Ilirska Bistrica - Trnovo'),\n (6253, 'Kne\\u017eak'),\n (6254, 'Jel\\u0161ane'),\n (6255, 'Prem'),\n (6256, 'Ko\\u0161ana'),\n (6257, 'Pivka'),\n (6258, 'Prestranek'),\n (6271, 'Dekani'),\n (6272, 'Gra\\u010di\\u0161\\u010de'),\n (6273, 'Marezige'),\n (6274, '\\u0160marje'),\n (6275, '\\u010crni Kal'),\n (6276, 'Pobegi'),\n (6280, 'Ankaran - Ancarano'),\n (6281, '\\u0160kofije'),\n (6310, 'Izola - Isola'),\n (6320, 'Portoro\\u017e - Portorose'),\n (6330, 'Piran - Pirano'),\n (6333, 'Se\\u010dovlje - Sicciole'),\n (8000, 'Novo mesto'),\n (8210, 'Trebnje'),\n (8211, 'Dobrni\\u010d'),\n (8212, 'Velika Loka'),\n (8213, 'Veliki Gaber'),\n (8216, 'Mirna Pe\\u010d'),\n (8220, '\\u0160marje\\u0161ke Toplice'),\n (8222, 'Oto\\u010dec'),\n (8230, 'Mokronog'),\n (8231, 'Trebelno'),\n (8232, '\\u0160entrupert'),\n (8233, 'Mirna'),\n (8250, 'Bre\\u017eice'),\n (8251, '\\u010cate\\u017e ob Savi'),\n (8253, 'Arti\\u010de'),\n (8254, 'Globoko'),\n (8255, 'Pi\\u0161ece'),\n (8256, 'Sromlje'),\n (8257, 'Dobova'),\n (8258, 'Kapele'),\n (8259, 'Bizeljsko'),\n (8261, 'Jesenice na Dolenjskem'),\n (8262, 'Kr\\u0161ka vas'),\n (8263, 'Cerklje ob Krki'),\n (8270, 'Kr\\u0161ko'),\n (8272, 'Zdole'),\n (8273, 'Leskovec pri Kr\\u0161kem'),\n (8274, 'Raka'),\n (8275, '\\u0160kocjan'),\n (8276, 'Bu\\u010dka'),\n (8280, 'Brestanica'),\n (8281, 'Senovo'),\n (8282, 'Koprivnica'),\n (8283, 'Blanca'),\n (8290, 'Sevnica'),\n (8292, 'Zabukovje'),\n (8293, 'Studenec'),\n (8294, 'Bo\\u0161tanj'),\n (8295, 'Tr\\u017ei\\u0161\\u010de'),\n (8296, 'Krmelj'),\n (8297, '\\u0160entjan\\u017e'),\n (8310, '\\u0160entjernej'),\n (8311, 'Kostanjevica na Krki'),\n (8312, 'Podbo\\u010dje'),\n (8321, 'Brusnice'),\n (8322, 'Stopi\\u010de'),\n (8323, 'Ur\\u0161na sela'),\n (8330, 'Metlika'),\n (8331, 'Suhor'),\n (8332, 'Gradac'),\n (8333, 'Semi\\u010d'),\n (8340, '\\u010crnomelj'),\n (8341, 'Adle\\u0161i\\u010di'),\n (8342, 'Stari trg ob Kolpi'),\n (8343, 'Dragatu\\u0161'),\n (8344, 'Vinica pri \\u010crnomlju'),\n (8350, 'Dolenjske Toplice'),\n (8351, 'Stra\\u017ea'),\n (8360, '\\u017du\\u017eemberk'),\n (8361, 'Dvor'),\n (8362, 'Hinje'),\n (9000, 'Murska Sobota'),\n (9201, 'Puconci'),\n (9202, 'Ma\\u010dkovci'),\n (9203, 'Petrovci'),\n (9204, '\\u0160alovci'),\n (9205, 'Hodo\\u0161 - Hodos'),\n (9206, 'Kri\\u017eevci'),\n (9207, 'Prosenjakovci - Partosfalva'),\n (9208, 'Fokovci'),\n (9220, 'Lendava - Lendva'),\n (9221, 'Martjanci'),\n (9222, 'Bogojina'),\n (9223, 'Dobrovnik - Dobronak'),\n (9224, 'Turni\\u0161\\u010de'),\n (9225, 'Velika Polana'),\n (9226, 'Moravske Toplice'),\n (9227, 'Kobilje'),\n (9231, 'Beltinci'),\n (9232, '\\u010cren\\u0161ovci'),\n (9233, 'Odranci'),\n (9240, 'Ljutomer'),\n (9241, 'Ver\\u017eej'),\n (9242, 'Kri\\u017eevci pri Ljutomeru'),\n (9243, 'Mala Nedelja'),\n (9244, 'Sveti Jurij ob \\u0160\\u010davnici'),\n (9245, 'Spodnji Ivanjci'),\n (9250, 'Gornja Radgona'),\n (9251, 'Ti\\u0161ina'),\n (9252, 'Radenci'),\n (9253, 'Apa\\u010de'),\n (9261, 'Cankova'),\n (9262, 'Roga\\u0161ovci'),\n (9263, 'Kuzma'),\n (9264, 'Grad'),\n (9265, 'Bodonci'),\n]\n\nSI_POSTALCODES_CHOICES = sorted(SI_POSTALCODES, key=lambda k: k[1])"}]} {"messages": [{"role": "user", "content": "Write Python code that implements module_foo.py from treejames/shaka-player (path: third_party/gjslint/python-gflags-2.0/tests/flags_modules_for_testing/module_foo.py)."}, {"role": "assistant", "content": "# third_party/gjslint/python-gflags-2.0/tests/flags_modules_for_testing/module_foo.py (from treejames/shaka-player, license: apache-2.0)\n\n#!/usr/bin/env python\n#\n# Copyright (c) 2009, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Auxiliary module for testing gflags.py.\n\nThe purpose of this module is to define a few flags, and declare some\nother flags as being important. We want to make sure the unit tests\nfor gflags.py involve more than one module.\n\"\"\"\n\n__author__ = 'salcianu@google.com (Alex Salcianu)'\n\n__pychecker__ = 'no-local' # for unittest\n\nimport gflags\nfrom flags_modules_for_testing import module_bar\n\nFLAGS = gflags.FLAGS\n\nDECLARED_KEY_FLAGS = ['tmod_bar_x', 'tmod_bar_z', 'tmod_bar_t',\n # Special (not user-defined) flag:\n 'flagfile']\n\ndef DefineFlags(flag_values=FLAGS):\n \"\"\"Defines a few flags.\"\"\"\n module_bar.DefineFlags(flag_values=flag_values)\n # The 'tmod_foo_' prefix (short for 'test_module_foo') ensures that we\n # have no name clash with existing flags.\n gflags.DEFINE_boolean('tmod_foo_bool', True, 'Boolean flag from module foo.',\n flag_values=flag_values)\n gflags.DEFINE_string('tmod_foo_str', 'default', 'String flag.',\n flag_values=flag_values)\n gflags.DEFINE_integer('tmod_foo_int', 3, 'Sample int flag.',\n flag_values=flag_values)\n\ndef DeclareKeyFlags(flag_values=FLAGS):\n \"\"\"Declares a few key flags.\"\"\"\n for flag_name in DECLARED_KEY_FLAGS:\n gflags.DECLARE_key_flag(flag_name, flag_values=flag_values)\n\ndef DeclareExtraKeyFlags(flag_values=FLAGS):\n \"\"\"Declares some extra key flags.\"\"\"\n gflags.ADOPT_module_key_flags(module_bar, flag_values=flag_values)\n\ndef NamesOfDefinedFlags():\n \"\"\"Returns: list of names of flags defined by this module.\"\"\"\n return ['tmod_foo_bool', 'tmod_foo_str', 'tmod_foo_int']\n\ndef NamesOfDeclaredKeyFlags():\n \"\"\"Returns: list of names of key flags for this module.\"\"\"\n return NamesOfDefinedFlags() + DECLARED_KEY_FLAGS\n\ndef NamesOfDeclaredExtraKeyFlags():\n \"\"\"Returns the list of names of additional key flags for this module.\n\n These are the flags that became key for this module only as a result\n of a call to DeclareExtraKeyFlags() above. I.e., the flags declared\n by module_bar, that were not already declared as key for this\n module.\n\n Returns:\n The list of names of additional key flags for this module.\n \"\"\"\n names_of_extra_key_flags = list(module_bar.NamesOfDefinedFlags())\n for flag_name in NamesOfDeclaredKeyFlags():\n while flag_name in names_of_extra_key_flags:\n names_of_extra_key_flags.remove(flag_name)\n return names_of_extra_key_flags\n\ndef RemoveFlags(flag_values=FLAGS):\n \"\"\"Deletes the flag definitions done by the above DefineFlags().\"\"\"\n for flag_name in NamesOfDefinedFlags():\n module_bar.RemoveOneFlag(flag_name, flag_values=flag_values)\n module_bar.RemoveFlags(flag_values=flag_values)\n\ndef GetModuleName():\n \"\"\"Uses gflags._GetCallingModule() to return the name of this module.\n\n For checking that _GetCallingModule works as expected.\n\n Returns:\n A string, the name of this module.\n \"\"\"\n # Calling the protected _GetCallingModule generates a lint warning,\n # but we do not have any other alternative to test that function.\n return gflags._GetCallingModule()\n\ndef DuplicateFlags(flagnames=None):\n \"\"\"Returns a new FlagValues object with the requested flagnames.\n\n Used to test DuplicateFlagError detection.\n\n Args:\n flagnames: str, A list of flag names to create.\n\n Returns:\n A FlagValues object with one boolean flag for each name in flagnames.\n \"\"\"\n flag_values = gflags.FlagValues()\n for name in flagnames:\n gflags.DEFINE_boolean(name, False, 'Flag named %s' % (name,),\n flag_values=flag_values)\n return flag_values"}]} {"messages": [{"role": "user", "content": "Write Python code that implements productivity.py from variablehair/Eggplantato (path: cogs/productivity.py)."}, {"role": "assistant", "content": "# cogs/productivity.py (from variablehair/Eggplantato, license: mit)\n\nimport discord\nfrom discord.ext import commands\nimport sqlite3\nfrom cogs.utils import errors\nfrom ast import literal_eval\nimport re\nimport datetime\nimport aiohttp\nfrom urllib.parse import parse_qs\nfrom lxml import etree\n\n# Google functions are copied from RoboDanny, accessed on April 6, 2017. https://github.com/Rapptz/RoboDanny/blob/master/cogs/buttons.py#L78\n\ndef DayParser(str_arg):\n\t\"\"\"Parses the day of the week from a string.\"\"\"\n\tcompiled = re.compile(r\"^(?:(?P(?:m(?:on)?))|(?Ptu(?:es?)?)|(?Pw(?:ed)?)|\"\n\t\"(?Pth(?:u(?:rs)?)?)|(?Pf(?:ri)?)|(?Psat?)|(?Psun?))$|^(?P\"\n\t\"(?:(?:mon)|(?:tues)|(?:wednes)|(?:thurs)|(?:fri)|(?:satur)|(?:sun))day)$\")\n\tmatch = compiled.match(str_arg.lower())\n\tif match is None or not match.group(0):\n\t\traise commands.BadArgument('Failed to parse day.')\n\telif match.group(\"dayfull\"):\n\t\treturn match.group(\"dayfull\")\n\telse:\n\t\treturn [k for k, v in match.groupdict().items() if v][0]\n\t\t\ndef TimeParser(str_arg):\n\t\"\"\"Parses an amount of seconds from a string of *w*d*h*m*s. Max time of 1 year.\n\t\n\tDoes not require knowledge of the user's current time. Returns timedelta object.\"\"\"\n\t\n\tcompiled = re.compile(r\"^(?P[0-9]{1,2}[Ww])?(?P[0-9]{1,3}[Dd])?\"\n\t\"(?P[0-9]{1,4}[Hh])?(?P[0-9]{1,6}[Mm])?(?P[0-9]{1,8}[Ss])?$\")\n\tmatch = compiled.match(str_arg)\n\tif match is None or not match.group(0):\n\t\traise commands.BadArgument('Failed to parse time.')\n\tint_seconds = 0\n\t\n\tif match.group(\"weeks\") is not None:\n\t\tint_seconds += int(match.group(\"weeks\")) * 604800\n\tif match.group(\"days\") is not None:\n\t\tint_seconds += int(match.group(\"days\")) * 86400\n\tif match.group(\"hours\") is not None:\n\t\tint_seconds += int(match.group(\"hours\")) * 3600\n\tif match.group(\"minutes\") is not None:\n\t\tint_seconds += int(match.group(\"minutes\")) * 60\n\tif match.group(\"seconds\") is not None:\n\t\tint_seconds += int(match.group(\"seconds\"))\n\t\t\n\tif int_seconds < 31540000: #1 year\n\t\treturn datetime.timedelta(seconds=int_seconds)\n\telse:\n\t\traise commands.BadArgument('Time specified cannot exceed 1 year.')\n\t\t\ndef AmPmParser(str_arg):\n\t\"\"\"Parses a 4 digit time literal from user input with optional AM or PM\"\"\"\n\tcompiled = re.compile(r\"(?P^[0-9]{1,4})(?P[Aa][Mm]?$)?(?P[Pp][Mm]?$)?\")\n\tmatch = compiled.match(str_arg)\n\tif match is None or not match.group(0):\n\t\traise commands.BadArgument('Failed to parse time.')\n\t\n\tint_timelit = int(match.group(\"timelit\"))\n\t# check if <=12 with ampm (e.g. 12am), if >24 when it's a 2 char input, or >2399\n\tif int_timelit > 2399 or (len(match.group(\"timelit\")) <= 2 and int_timelit > 24) \\\n\t\tor (int_timelit > 12 and (match.group(\"pm\") or match.group(\"am\"))):\n\t\t\traise commands.BadArgument('Time argument too long.')\t\t\n\t\nclass Productivity():\n\t\"\"\"Tools to make your life easier (?)\"\"\"\n\t\n\tdef __init__(self, bot):\n\t\tself.bot = bot\n\t\tself.todoconn = sqlite3.connect('data/todo.db')\n\t\ttry:\n\t\t\tc = self.todoconn.cursor()\n\t\t\tc.execute(\"SELECT user FROM lists WHERE user='debug'\")\n\t\texcept sqlite3.OperationalError as e:\n\t\t\tprint(str(e))\n\t\t\traise errors.DatabaseError(\"Error loading todo database; did you run initdb?\")\n\t\tfinally:\n\t\t\tself.todoconn.close()\n\t\t\t\n\t@commands.command(pass_context=True, aliases=[\"\"])\n\tasync def settime(self, ctx, str_usertime):\n\t\t\"\"\"Set your time zone. You can tell me your UTC offset (`-8` or `+350`) **or** the most recent multiple of 30 \\\n\t\tminutes (e.g. if it is currently `1:54PM`, you use `settime 1330` or `settime 130pm`)\"\"\"\n\t\tpass #todo: this\n\t\t\t\n\t@commands.command(pass_context=True, aliases=[\"remind\", \"timer\"])\n\tasync def remindme(self, ctx, str_left : str, str_right: str=''):\n\t\tif str_right:\n\t\t\t# do stuff\n\t\t\tawait ctx.send(\"2 args\")\n\t\telse:\n\t\t\ttry:\n\t\t\t\tawait ctx.send(DayParser(str_left))\n\t\t\texcept commands.BadArgument:\n\t\t\t\tawait ctx.send(\"Your day is not formatted correctly!\"\n\t\t\t\t\" You can use shorthand `(m or TU or wEd)` or the full name of the day `(sunday)`\")\n\t\t\n\t@commands.group(pass_context=True, invoke_without_context=True)\n\tasync def todo(self, ctx):\n\t\t\"\"\"A simple todo list. `todo add [task]` to add something, `todo` to look at your list. `todo help` for more commands\"\"\"\n\t\tif ctx.invoked_subcommand is None:\n\t\t\tawait ctx.invoke(self._todoget)\t\t\t\n\t\t\t\t\n\t@todo.command(name=\"get\", alias=[\"list\"])\n\tasync def _todoget(self, ctx):\n\t\t\"\"\"Prints your todo list\"\"\"\n\t\tself.todoconn = sqlite3.connect('data/todo.db')\n\t\tc = self.todoconn.cursor()\n\t\tc.execute(\"SELECT tasks FROM lists WHERE user=?\", (str(ctx.message.author.id),))\n\t\ttup_data = c.fetchone()\n\t\tif tup_data is None:\n\t\t\tawait ctx.send(\"You don't have anything in your todo list! Add something with `todo add [task]`.\")\n\t\telse:\n\t\t\tlist_user_tasks = literal_eval(tup_data[0])\n\t\t\tstr_ret = \":eggplant: Your todo list:\\n\"\n\t\t\tfor i in range(len(list_user_tasks)):\n\t\t\t\tstr_ret = \"\".join([str_ret, str(i+1), \": \", list_user_tasks[i], \"\\n\"])\n\t\t\tawait ctx.send(str_ret)\n\t\tself.todoconn.close()\n\t\t\n\t@todo.command(pass_context=True, name=\"add\")\n\tasync def _todoadd(self, ctx, *args):\n\t\t\"\"\"Adds a task to your list\"\"\"\n\t\tif args == []:\n\t\t\tawait ctx.send(\"You must specify a task to add!\")\n\t\t\treturn\n\t\telse:\n\t\t\tself.todoconn = sqlite3.connect('data/todo.db')\n\t\t\tc = self.todoconn.cursor()\n\t\t\tc.execute(\"SELECT tasks FROM lists WHERE user=?\", (str(ctx.message.author.id),))\n\t\t\ttup_data = c.fetchone()\n\t\t\tstr_task = \" \".join(args)\n\t\t\tif tup_data is None:\n\t\t\t\tc.execute(\"INSERT INTO lists VALUES (?,?)\", (str(ctx.message.author.id), \"[\\'\" + str_task + \"\\']\"))\n\t\t\telse:\n\t\t\t\tlist_user_tasks = literal_eval(tup_data[0])\n\t\t\t\tlist_user_tasks.append(str_task)\n\t\t\t\tc.execute(\"UPDATE lists SET tasks=? WHERE user=?\", (str(list_user_tasks), str(ctx.message.author.id)))\n\t\t\tself.todoconn.commit()\n\t\t\tself.todoconn.close()\n\t\t\tawait ctx.send(\"{} added successfully!\".format(str_task))\n\n\t@todo.command(name=\"remove\", aliases=[\"delete\", \"rm\", \"del\"])\n\tasync def _todoremove(self, ctx, *args):\n\t\t\"\"\"Removes a task from your list\"\"\"\n\t\tif len(args) == 0:\n\t\t\tawait ctx.send(\"You must specify the number of a task to remove.\")\n\t\t\treturn\n\t\tself.todoconn = sqlite3.connect('data/todo.db')\n\t\tc = self.todoconn.cursor()\n\t\tc.execute(\"SELECT tasks FROM lists WHERE user=?\", (str(ctx.message.author.id),))\n\t\ttup_data = c.fetchone()\n\t\tif tup_data is None:\n\t\t\tawait ctx.send(\"Your todo list is empty.\")\n\t\telse:\n\t\t\tlist_user_tasks = literal_eval(tup_data[0])\n\t\t\ttry:\n\t\t\t\tint_taskid = int(args[0])\n\t\t\t\tif int_taskid <= 0 or int_taskid > len(list_user_tasks):\n\t\t\t\t\tawait ctx.send(\"Please enter a valid index!\")\n\t\t\t\telse: \n\t\t\t\t\tawait ctx.send(\"Task `{}` removed successfully.\".format(list_user_tasks.pop(int_taskid - 1)))\n\t\t\t\t\tc.execute(\"UPDATE lists SET tasks=? WHERE user=?\", (str(list_user_tasks), str(ctx.message.author.id)))\n\t\t\t\t\tself.todoconn.commit()\n\t\t\texcept ValueError:\n\t\t\t\tstr_task = \" \".join(args)\n\t\t\t\ttry:\n\t\t\t\t\tlist_user_tasks.remove(str_task)\n\t\t\t\t\tawait ctx.send(\"Task `{}` removed successfully.\".format(str_task))\n\t\t\t\t\tc.execute(\"UPDATE lists SET tasks=? WHERE user=?\", (str(list_user_tasks), str(ctx.message.author.id)))\n\t\t\t\t\tself.todoconn.commit()\n\t\t\t\texcept ValueError:\n\t\t\t\t\tawait ctx.send(\"Task `{}` not found.\".format(str_task))\n\t\tself.todoconn.close()\n\t\n\tdef parse_google_card(self, node):\n\t\tif node is None:\n\t\t\treturn None\n\n\t\te = discord.Embed(colour=0x738bd7)\n\n\t\t# check if it's a calculator card:\n\t\tcalculator = node.find(\".//table/tr/td/span[@class='nobr']/h2[@class='r']\")\n\t\tif calculator is not None:\n\t\t\te.title = 'Calculator'\n\t\t\te.description = ''.join(calculator.itertext())\n\t\t\treturn e\n\n\t\tparent = node.getparent()\n\n\t\t# check for unit conversion card\n\t\tunit = parent.find(\".//ol//div[@class='_Tsb']\")\n\t\tif unit is not None:\n\t\t\te.title = 'Unit Conversion'\n\t\t\te.description = ''.join(''.join(n.itertext()) for n in unit)\n\t\t\treturn e\n\n\t\t# check for currency conversion card\n\t\tcurrency = parent.find(\".//ol/table[@class='std _tLi']/tr/td/h2\")\n\t\tif currency is not None:\n\t\t\te.title = 'Currency Conversion'\n\t\t\te.description = ''.join(currency.itertext())\n\t\t\treturn e\n\n\t\t# check for release date card\n\t\trelease = parent.find(\".//div[@id='_vBb']\")\n\t\tif release is not None:\n\t\t\ttry:\n\t\t\t\te.description = ''.join(release[0].itertext()).strip()\n\t\t\t\te.title = ''.join(release[1].itertext()).strip()\n\t\t\t\treturn e\n\t\t\texcept:\n\t\t\t\treturn None\n\n\t\t# check for definition card\n\t\twords = parent.find(\".//ol/div[@class='g']/div/h3[@class='r']/div\")\n\t\tif words is not None:\n\t\t\ttry:\n\t\t\t\tdefinition_info = words.getparent().getparent()[1] # yikes\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\t# inside is a
with two \n\t\t\t\t\t# the first is the actual word, the second is the pronunciation\n\t\t\t\t\te.title = words[0].text\n\t\t\t\t\te.description = words[1].text\n\t\t\t\texcept:\n\t\t\t\t\treturn None\n\n\t\t\t\t# inside the table there's the actual definitions\n\t\t\t\t# they're separated as noun/verb/adjective with a list\n\t\t\t\t# of definitions\n\t\t\t\tfor row in definition_info:\n\t\t\t\t\tif len(row.attrib) != 0:\n\t\t\t\t\t\t# definitions are empty \n\t\t\t\t\t\t# if there is something in the then we're done\n\t\t\t\t\t\t# with the definitions\n\t\t\t\t\t\tbreak\n\n\t\t\t\t\ttry:\n\t\t\t\t\t\tdata = row[0]\n\t\t\t\t\t\tlexical_category = data[0].text\n\t\t\t\t\t\tbody = []\n\t\t\t\t\t\tfor index, definition in enumerate(data[1], 1):\n\t\t\t\t\t\t\tbody.append('%s. %s' % (index, definition.text))\n\n\t\t\t\t\t\te.add_field(name=lexical_category, value='\\n'.join(body), inline=False)\n\t\t\t\t\texcept:\n\t\t\t\t\t\tcontinue\n\n\t\t\t\treturn e\n\n\t\t# check for \"time in\" card\n\t\ttime_in = parent.find(\".//ol//div[@class='_Tsb _HOb _Qeb']\")\n\t\tif time_in is not None:\n\t\t\ttry:\n\t\t\t\ttime_place = ''.join(time_in.find(\"span[@class='_HOb _Qeb']\").itertext()).strip()\n\t\t\t\tthe_time = ''.join(time_in.find(\"div[@class='_rkc _Peb']\").itertext()).strip()\n\t\t\t\tthe_date = ''.join(time_in.find(\"div[@class='_HOb _Qeb']\").itertext()).strip()\n\t\t\texcept:\n\t\t\t\treturn None\n\t\t\telse:\n\t\t\t\te.title = time_place\n\t\t\t\te.description = '%s\\n%s' % (the_time, the_date)\n\t\t\t\treturn e\n\n\t\t# check for weather card\n\t\t# this one is the most complicated of the group lol\n\t\t# everything is under a
which has a\n\t\t#

{{ weather for place }}

\n\t\t# string, the rest is fucking table fuckery.\n\t\tweather = parent.find(\".//ol//div[@class='e']\")\n\t\tif weather is None:\n\t\t\treturn None\n\n\t\tlocation = weather.find('h3')\n\t\tif location is None:\n\t\t\treturn None\n\n\t\te.title = ''.join(location.itertext())\n\n\t\ttable = weather.find('table')\n\t\tif table is None:\n\t\t\treturn None\n\n\t\t# This is gonna be a bit fucky.\n\t\t# So the part we care about is on the second data\n\t\t# column of the first tr\n\t\ttry:\n\t\t\ttr = table[0]\n\t\t\timg = tr[0].find('img')\n\t\t\tcategory = img.get('alt')\n\t\t\timage = 'https:' + img.get('src')\n\t\t\ttemperature = tr[1].xpath(\"./span[@class='wob_t']//text()\")[0]\n\t\texcept:\n\t\t\treturn None # RIP\n\t\telse:\n\t\t\te.set_thumbnail(url=image)\n\t\t\te.description = '*%s*' % category\n\t\t\te.add_field(name='Temperature', value=temperature)\n\n\t\t# On the 4th column it tells us our wind speeds\n\t\ttry:\n\t\t\twind = ''.join(table[3].itertext()).replace('Wind: ', '')\n\t\texcept:\n\t\t\treturn None\n\t\telse:\n\t\t\te.add_field(name='Wind', value=wind)\n\n\t\t# On the 5th column it tells us our humidity\n\t\ttry:\n\t\t\thumidity = ''.join(table[4][0].itertext()).replace('Humidity: ', '')\n\t\texcept:\n\t\t\treturn None\n\t\telse:\n\t\t\te.add_field(name='Humidity', value=humidity)\n\n\t\treturn e\n\n\tasync def get_google_entries(self, query):\n\t\tparams = {\n\t\t\t'q': query,\n\t\t\t'safe': 'on'\n\t\t}\n\t\theaders = {\n\t\t\t'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64)'\n\t\t}\n\n\t\t# list of URLs\n\t\tentries = []\n\n\t\t# the result of a google card, an embed\n\t\tcard = None\n\n\t\tasync with aiohttp.get('https://www.google.com/search', params=params, headers=headers) as resp:\n\t\t\tif resp.status != 200:\n\t\t\t\traise RuntimeError('Google somehow failed to respond.')\n\n\t\t\troot = etree.fromstring(await resp.text(), etree.HTMLParser())\n\n\t\t\t# with open('google.html', 'w', encoding='utf-8') as f:\n\t\t\t# f.write(etree.tostring(root, pretty_print=True).decode('utf-8'))\n\n\t\t\t\"\"\"\n\t\t\tTree looks like this.. sort of..\n\t\t\t
\n\t\t\t\t...\n\t\t\t\t

\n\t\t\t\t\t\" ...>title\n\t\t\t\t

\n\t\t\t\t...\n\t\t\t\t\n\t\t\t\t\tdate here\n\t\t\t\t\tsummary here, can contain tag\n\t\t\t\t\n\t\t\t
\n\t\t\t\"\"\"\n\n\t\t\tcard_node = root.find(\".//div[@id='topstuff']\")\n\t\t\tcard = self.parse_google_card(card_node)\n\n\t\t\tsearch_nodes = root.findall(\".//div[@class='g']\")\n\t\t\tfor node in search_nodes:\n\t\t\t\turl_node = node.find('.//h3/a')\n\t\t\t\tif url_node is None:\n\t\t\t\t\tcontinue\n\n\t\t\t\turl = url_node.attrib['href']\n\t\t\t\tif not url.startswith('/url?'):\n\t\t\t\t\tcontinue\n\n\t\t\t\turl = parse_qs(url[5:])['q'][0] # get the URL from ?q query string\n\n\t\t\t\t# if I ever cared about the description, this is how\n\t\t\t\tentries.append(url)\n\n\t\t\t\t# short = node.find(\".//span[@class='st']\")\n\t\t\t\t# if short is None:\n\t\t\t\t# entries.append((url, ''))\n\t\t\t\t# else:\n\t\t\t\t# text = ''.join(short.itertext())\n\t\t\t\t# entries.append((url, text.replace('...', '')))\n\n\t\treturn card, entries\n\n\t@commands.command(aliases=['google'], pass_context=True)\n\tasync def g(self, ctx, *, query):\n\t\t\"\"\"Searches google and gives you top result.\"\"\"\n\t\ttry:\n\t\t\tcard, entries = await self.get_google_entries(query)\n\t\texcept RuntimeError as e:\n\t\t\tawait ctx.send(str(e))\n\t\telse:\n\t\t\tif card:\n\t\t\t\tvalue = '\\n'.join(entries[:3])\n\t\t\t\tif value:\n\t\t\t\t\tcard.add_field(name='Search Results', value=value, inline=False)\n\t\t\t\treturn await ctx.send(embed=card)\n\n\t\t\tif len(entries) == 0:\n\t\t\t\treturn await ctx.send('No results found... sorry.')\n\n\t\t\tnext_two = entries[1:3]\n\t\t\tfirst_entry = entries[0]\n\t\t\tif first_entry[-1] == ')':\n\t\t\t\tfirst_entry = first_entry[:-1] + '%29'\n\n\t\t\tif next_two:\n\t\t\t\tformatted = '\\n'.join(map(lambda x: '<%s>' % x, next_two))\n\t\t\t\tmsg = '{}\\n\\n**See also:**\\n{}'.format(first_entry, formatted)\n\t\t\telse:\n\t\t\t\tmsg = first_entry\n\n\t\t\tawait ctx.send(msg)\n\t\t\t\t\t\ndef setup(bot):\n\tbot.add_cog(Productivity(bot))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements showNet.py from thomashaw/SecGen (path: modules/utilities/unix/labtainers/files/Labtainers-master/scripts/gns3/showNet.py)."}, {"role": "assistant", "content": "# modules/utilities/unix/labtainers/files/Labtainers-master/scripts/gns3/showNet.py (from thomashaw/SecGen, license: gpl-3.0)\n\n#!/usr/bin/env python\nimport sys\nimport os\nimport argparse\nimport json\nfrom netaddr import IPNetwork\nlabtainer_dir = os.getenv('LABTAINER_DIR')\nif labtainer_dir is None:\n print('Must define LABTAINER_DIR environment variable')\n exit(1)\nsys.path.append(os.path.join(labtainer_dir, 'scripts', 'labtainer-student','bin'))\nsys.path.append(os.path.join(labtainer_dir, 'scripts', 'labtainer-student','lab_bin'))\nimport labutils\nimport LabtainerLogging\n'''\nShow network topology of a Labtainers lab\n'''\n\nlabtainers_path = os.path.join(labtainer_dir, 'labs')\nparser = argparse.ArgumentParser(description='Show Labtainer topology.')\nparser.add_argument('labname', help='Name of labtainers lab')\nargs = parser.parse_args()\n\nlabutils.logger = LabtainerLogging.LabtainerLogging(\"showNet.log\", 'eh', \"../../config/labtainer.config\")\nlabtainer_lab = os.path.join(labtainers_path, args.labname)\ndumb, start_config = labutils.GetBothConfigs(labtainer_lab, labutils.logger)\n\nnets = []\nfor subnet_name in start_config.subnets:\n #print('subnet: %s' % subnet_name)\n nets.append(subnet_name)\n\nprint('labname: %s has %d networks' % (args.labname, len(nets)))\n\nfor name, container in start_config.containers.items():\n eth_index = 0\n num_adapters = len(container.container_nets.items())\n print('Container: %s (# of adapters: %d)' % (name, num_adapters))\n for subnet_name, subnet_ip in container.container_nets.items():\n sub_index = nets.index(subnet_name)\n eth = 'eth %d' % eth_index\n print('\\t %s to network %d' % (eth, sub_index))\n eth_index += 1"}]} {"messages": [{"role": "user", "content": "Write Python code that implements __init__.py from yrizk/django-blog (path: blogvenv/lib/python3.4/site-packages/django/template/__init__.py)."}, {"role": "assistant", "content": "# blogvenv/lib/python3.4/site-packages/django/template/__init__.py (from yrizk/django-blog, license: apache-2.0)\n\n\"\"\"\nDjango's support for templates.\n\nThe django.template namespace contains two independent subsystems:\n\n1. Multiple Template Engines: support for pluggable template backends,\n built-in backends and backend-independent APIs\n2. Django Template Language: Django's own template engine, including its\n built-in loaders, context processors, tags and filters.\n\nIdeally these subsystems would be implemented in distinct packages. However\nkeeping them together made the implementation of Multiple Template Engines\nless disruptive .\n\nHere's a breakdown of which modules belong to which subsystem.\n\nMultiple Template Engines:\n\n- django.template.backends.*\n- django.template.loader\n- django.template.response\n\nDjango Template Language:\n\n- django.template.base\n- django.template.context\n- django.template.context_processors\n- django.template.loaders.*\n- django.template.debug\n- django.template.defaultfilters\n- django.template.defaulttags\n- django.template.engine\n- django.template.loader_tags\n- django.template.smartif\n\nShared:\n\n- django.template.utils\n\n\"\"\"\n\n# Multiple Template Engines\n\nfrom .engine import Engine\n\nfrom .utils import EngineHandler\n\nengines = EngineHandler()\n\n__all__ = ('Engine', 'engines')\n\n# Django Template Language\n\n# Public exceptions\nfrom .base import (TemplateDoesNotExist, TemplateSyntaxError, # NOQA\n VariableDoesNotExist)\nfrom .context import ContextPopException # NOQA\n\n# Template parts\nfrom .base import (Context, Node, NodeList, RequestContext, # NOQA\n StringOrigin, Template, Variable)\n\n# Deprecated in Django 1.8, will be removed in Django 2.0.\nfrom .base import resolve_variable # NOQA\n\n# Library management\nfrom .base import Library # NOQA\n\n__all__ += ('Template', 'Context', 'RequestContext')"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_pawn.py from LordDarkula/chess_py (path: tests/test_pieces/test_pawn.py)."}, {"role": "assistant", "content": "# tests/test_pieces/test_pawn.py (from LordDarkula/chess_py, license: mit)\n\nfrom unittest import TestCase\n\nfrom chess_py.core.algebraic import notation_const\nfrom chess_py.core import Board\nfrom chess_py.core.algebraic import Location, Move\nfrom chess_py.pieces import Queen, Rook, Bishop, Knight, Pawn\nfrom chess_py import color\n\nclass TestPawn(TestCase):\n def setUp(self):\n self.position = Board.init_default()\n\n self.white_pawn = Pawn(color.white, Location.from_string(\"e2\"))\n self.position.place_piece_at_square(self.white_pawn, Location.from_string(\"e2\"))\n\n self.black_pawn = Pawn(color.black, Location.from_string(\"a7\"))\n self.position.place_piece_at_square(self.black_pawn, Location.from_string(\"a7\"))\n\n def test_square_in_front(self):\n self.assertEqual(self.white_pawn.square_in_front(self.white_pawn.location), Location.from_string(\"e3\"))\n self.assertEqual(self.black_pawn.square_in_front(self.black_pawn.location), Location.from_string(\"a6\"))\n\n def test_two_squares_in_front(self):\n self.assertEqual(self.white_pawn.two_squares_in_front(self.white_pawn.location), Location.from_string(\"e4\"))\n self.assertEqual(self.black_pawn.two_squares_in_front(self.black_pawn.location), Location.from_string(\"a5\"))\n\n def test_would_move_be_promotion(self):\n self.assertTrue(self.white_pawn.would_move_be_promotion(Location.from_string(\"e7\")))\n self.assertTrue(self.black_pawn.would_move_be_promotion(Location.from_string(\"a2\")))\n self.assertFalse(self.white_pawn.would_move_be_promotion(Location.from_string(\"e2\")))\n self.assertFalse(self.black_pawn.would_move_be_promotion(Location.from_string(\"a7\")))\n\n def test_create_promotion_moves(self):\n self.white_pawn.location = Location.from_string(\"e7\")\n moves = list(self.white_pawn.create_promotion_moves(notation_const.CAPTURE,\n Location.from_string(\"e7\")))\n self.assertEqual(len(list(moves)), 4)\n self.assertEqual(moves[0].start_loc, Location.from_string(\"e7\"))\n\n self.assertEqual(moves[0].promoted_to_piece, Queen)\n self.assertEqual(moves[1].promoted_to_piece, Rook)\n self.assertEqual(moves[2].promoted_to_piece, Bishop)\n self.assertEqual(moves[3].promoted_to_piece, Knight)\n\n def test_forward_moves(self):\n self.white_pawn.location = Location.from_string(\"e2\")\n moves = list(self.white_pawn.forward_moves(self.position))\n\n self.assertEqual(len(moves), 2)\n self.assertEqual(moves[0], Move(end_loc=self.white_pawn.square_in_front(self.white_pawn.location),\n piece=self.white_pawn,\n status=notation_const.MOVEMENT,\n start_loc=self.white_pawn.location))\n\n self.assertEqual(moves[1], Move(end_loc=self.white_pawn.square_in_front(self.white_pawn.square_in_front(self.white_pawn.location)),\n piece=self.white_pawn,\n status=notation_const.MOVEMENT,\n start_loc=self.white_pawn.location))\n\n moves = list(self.black_pawn.forward_moves(self.position))\n self.assertEqual(len(moves), 2)\n\n self.assertEqual(moves[0], Move(end_loc=self.black_pawn.square_in_front(self.black_pawn.location),\n piece=self.black_pawn,\n status=notation_const.MOVEMENT,\n start_loc=self.black_pawn.location))\n\n self.assertEqual(moves[1], Move(end_loc=self.black_pawn.square_in_front(self.black_pawn.square_in_front(self.black_pawn.location)),\n piece=self.black_pawn,\n status=notation_const.MOVEMENT,\n start_loc=self.black_pawn.location))\n\n def test_capture_moves(self):\n self.position.move_piece(Location.from_string(\"d7\"), Location.from_string(\"d5\"))\n self.position.move_piece(Location.from_string(\"e2\"), Location.from_string(\"e4\"))\n\n black_pawn = self.position.piece_at_square(Location.from_string(\"d5\"))\n move = list(self.white_pawn.capture_moves(self.position))\n\n self.assertEqual(len(move), 1)\n\n self.assertEqual(move[0], Move(end_loc=black_pawn.location,\n piece=self.white_pawn,\n status=notation_const.CAPTURE,\n start_loc=self.white_pawn.location))\n\n def test_en_passant_moves(self):\n self.position.move_piece(Location.from_string(\"d7\"), Location.from_string(\"d4\"))\n self.position.move_piece(Location.from_string(\"e2\"), Location.from_string(\"e4\"))\n\n black_pawn = self.position.piece_at_square(Location.from_string(\"d4\"))\n self.position.piece_at_square(Location.from_string(\"e4\")).just_moved_two_steps = True\n\n move = list(black_pawn.en_passant_moves(self.position))\n\n self.assertEqual(len(move), 1)\n self.assertEqual(move[0], Move(end_loc=black_pawn.square_in_front(black_pawn.location.shift_right()),\n piece=black_pawn,\n status=notation_const.EN_PASSANT,\n start_loc=black_pawn.location))\n\n def test_possible_moves(self):\n self.assertEqual(len(list(self.white_pawn.possible_moves(self.position))), 2)\n self.position.move_piece(Location.from_string(\"e2\"), Location.from_string(\"e3\"))\n self.assertEqual(len(list(self.white_pawn.possible_moves(self.position))), 1)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements textView.py from xbmc/atv2 (path: xbmc/lib/libPython/Python/Lib/idlelib/textView.py)."}, {"role": "assistant", "content": "# xbmc/lib/libPython/Python/Lib/idlelib/textView.py (from xbmc/atv2, license: gpl-2.0)\n\n\"\"\"Simple text browser for IDLE\n\n\"\"\"\n\nfrom Tkinter import *\nimport tkMessageBox\n\nclass TextViewer(Toplevel):\n \"\"\"\n simple text viewer dialog for idle\n \"\"\"\n def __init__(self, parent, title, fileName, data=None):\n \"\"\"If data exists, load it into viewer, otherwise try to load file.\n\n fileName - string, should be an absoulute filename\n \"\"\"\n Toplevel.__init__(self, parent)\n self.configure(borderwidth=5)\n self.geometry(\"=%dx%d+%d+%d\" % (625, 500,\n parent.winfo_rootx() + 10,\n parent.winfo_rooty() + 10))\n #elguavas - config placeholders til config stuff completed\n self.bg = '#ffffff'\n self.fg = '#000000'\n\n self.CreateWidgets()\n self.title(title)\n self.transient(parent)\n self.grab_set()\n self.protocol(\"WM_DELETE_WINDOW\", self.Ok)\n self.parent = parent\n self.textView.focus_set()\n #key bindings for this dialog\n self.bind('',self.Ok) #dismiss dialog\n self.bind('',self.Ok) #dismiss dialog\n if data:\n self.textView.insert(0.0, data)\n else:\n self.LoadTextFile(fileName)\n self.textView.config(state=DISABLED)\n self.wait_window()\n\n def LoadTextFile(self, fileName):\n textFile = None\n try:\n textFile = open(fileName, 'r')\n except IOError:\n tkMessageBox.showerror(title='File Load Error',\n message='Unable to load file %r .' % (fileName,))\n else:\n self.textView.insert(0.0,textFile.read())\n\n def CreateWidgets(self):\n frameText = Frame(self, relief=SUNKEN, height=700)\n frameButtons = Frame(self)\n self.buttonOk = Button(frameButtons, text='Close',\n command=self.Ok, takefocus=FALSE)\n self.scrollbarView = Scrollbar(frameText, orient=VERTICAL,\n takefocus=FALSE, highlightthickness=0)\n self.textView = Text(frameText, wrap=WORD, highlightthickness=0,\n fg=self.fg, bg=self.bg)\n self.scrollbarView.config(command=self.textView.yview)\n self.textView.config(yscrollcommand=self.scrollbarView.set)\n self.buttonOk.pack()\n self.scrollbarView.pack(side=RIGHT,fill=Y)\n self.textView.pack(side=LEFT,expand=TRUE,fill=BOTH)\n frameButtons.pack(side=BOTTOM,fill=X)\n frameText.pack(side=TOP,expand=TRUE,fill=BOTH)\n\n def Ok(self, event=None):\n self.destroy()\n\nif __name__ == '__main__':\n #test the dialog\n root=Tk()\n Button(root,text='View',\n command=lambda:TextViewer(root,'Text','./textView.py')).pack()\n root.mainloop()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements account_report_common.py from xzYue/odoo (path: addons/account/wizard/account_report_common.py)."}, {"role": "assistant", "content": "# addons/account/wizard/account_report_common.py (from xzYue/odoo, license: agpl-3.0)\n\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nimport time\nfrom lxml import etree\n\nfrom openerp.osv import fields, osv\nfrom openerp.osv.orm import setup_modifiers\nfrom openerp.tools.translate import _\n\nclass account_common_report(osv.osv_memory):\n _name = \"account.common.report\"\n _description = \"Account Common Report\"\n\n def onchange_chart_id(self, cr, uid, ids, chart_account_id=False, context=None):\n res = {}\n if chart_account_id:\n company_id = self.pool.get('account.account').browse(cr, uid, chart_account_id, context=context).company_id.id\n now = time.strftime('%Y-%m-%d')\n domain = [('company_id', '=', company_id), ('date_start', '<', now), ('date_stop', '>', now)]\n fiscalyears = self.pool.get('account.fiscalyear').search(cr, uid, domain, limit=1)\n res['value'] = {'company_id': company_id, 'fiscalyear_id': fiscalyears and fiscalyears[0] or False}\n return res\n\n _columns = {\n 'chart_account_id': fields.many2one('account.account', 'Chart of Account', help='Select Charts of Accounts', required=True, domain = [('parent_id','=',False)]),\n 'company_id': fields.related('chart_account_id', 'company_id', type='many2one', relation='res.company', string='Company', readonly=True),\n 'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscal Year', help='Keep empty for all open fiscal year'),\n 'filter': fields.selection([('filter_no', 'No Filters'), ('filter_date', 'Date'), ('filter_period', 'Periods')], \"Filter by\", required=True),\n 'period_from': fields.many2one('account.period', 'Start Period'),\n 'period_to': fields.many2one('account.period', 'End Period'),\n 'journal_ids': fields.many2many('account.journal', string='Journals', required=True),\n 'date_from': fields.date(\"Start Date\"),\n 'date_to': fields.date(\"End Date\"),\n 'target_move': fields.selection([('posted', 'All Posted Entries'),\n ('all', 'All Entries'),\n ], 'Target Moves', required=True),\n\n }\n\n def _check_company_id(self, cr, uid, ids, context=None):\n for wiz in self.browse(cr, uid, ids, context=context):\n company_id = wiz.company_id.id\n if wiz.fiscalyear_id and company_id != wiz.fiscalyear_id.company_id.id:\n return False\n if wiz.period_from and company_id != wiz.period_from.company_id.id:\n return False\n if wiz.period_to and company_id != wiz.period_to.company_id.id:\n return False\n return True\n\n _constraints = [\n (_check_company_id, 'The fiscalyear, periods or chart of account chosen have to belong to the same company.', ['chart_account_id','fiscalyear_id','period_from','period_to']),\n ]\n\n def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):\n if context is None:context = {}\n res = super(account_common_report, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=False)\n if context.get('active_model', False) == 'account.account':\n doc = etree.XML(res['arch'])\n nodes = doc.xpath(\"//field[@name='chart_account_id']\")\n for node in nodes:\n node.set('readonly', '1')\n node.set('help', 'If you print the report from Account list/form view it will not consider Charts of account')\n setup_modifiers(node, res['fields']['chart_account_id'])\n res['arch'] = etree.tostring(doc)\n return res\n\n def onchange_filter(self, cr, uid, ids, filter='filter_no', fiscalyear_id=False, context=None):\n res = {'value': {}}\n if filter == 'filter_no':\n res['value'] = {'period_from': False, 'period_to': False, 'date_from': False ,'date_to': False}\n if filter == 'filter_date':\n res['value'] = {'period_from': False, 'period_to': False, 'date_from': time.strftime('%Y-01-01'), 'date_to': time.strftime('%Y-%m-%d')}\n if filter == 'filter_period' and fiscalyear_id:\n start_period = end_period = False\n cr.execute('''\n SELECT * FROM (SELECT p.id\n FROM account_period p\n LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)\n WHERE f.id = %s\n AND p.special = false\n ORDER BY p.date_start ASC, p.special ASC\n LIMIT 1) AS period_start\n UNION ALL\n SELECT * FROM (SELECT p.id\n FROM account_period p\n LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)\n WHERE f.id = %s\n AND p.date_start < NOW()\n AND p.special = false\n ORDER BY p.date_stop DESC\n LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id))\n periods = [i[0] for i in cr.fetchall()]\n if periods and len(periods) > 1:\n start_period = periods[0]\n end_period = periods[1]\n res['value'] = {'period_from': start_period, 'period_to': end_period, 'date_from': False, 'date_to': False}\n return res\n\n def _get_account(self, cr, uid, context=None):\n user = self.pool.get('res.users').browse(cr, uid, uid, context=context)\n accounts = self.pool.get('account.account').search(cr, uid, [('parent_id', '=', False), ('company_id', '=', user.company_id.id)], limit=1)\n return accounts and accounts[0] or False\n\n def _get_fiscalyear(self, cr, uid, context=None):\n if context is None:\n context = {}\n now = time.strftime('%Y-%m-%d')\n company_id = False\n ids = context.get('active_ids', [])\n if ids and context.get('active_model') == 'account.account':\n company_id = self.pool.get('account.account').browse(cr, uid, ids[0], context=context).company_id.id\n else: # use current company id\n company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id\n domain = [('company_id', '=', company_id), ('date_start', '<', now), ('date_stop', '>', now)]\n fiscalyears = self.pool.get('account.fiscalyear').search(cr, uid, domain, limit=1)\n return fiscalyears and fiscalyears[0] or False\n\n def _get_all_journal(self, cr, uid, context=None):\n return self.pool.get('account.journal').search(cr, uid ,[])\n\n _defaults = {\n 'fiscalyear_id': _get_fiscalyear,\n 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.common.report',context=c),\n 'journal_ids': _get_all_journal,\n 'filter': 'filter_no',\n 'chart_account_id': _get_account,\n 'target_move': 'posted',\n }\n\n def _build_contexts(self, cr, uid, ids, data, context=None):\n if context is None:\n context = {}\n result = {}\n result['fiscalyear'] = 'fiscalyear_id' in data['form'] and data['form']['fiscalyear_id'] or False\n result['journal_ids'] = 'journal_ids' in data['form'] and data['form']['journal_ids'] or False\n result['chart_account_id'] = 'chart_account_id' in data['form'] and data['form']['chart_account_id'] or False\n result['state'] = 'target_move' in data['form'] and data['form']['target_move'] or ''\n if data['form']['filter'] == 'filter_date':\n result['date_from'] = data['form']['date_from']\n result['date_to'] = data['form']['date_to']\n elif data['form']['filter'] == 'filter_period':\n if not data['form']['period_from'] or not data['form']['period_to']:\n raise osv.except_osv(_('Error!'),_('Select a starting and an ending period.'))\n result['period_from'] = data['form']['period_from']\n result['period_to'] = data['form']['period_to']\n return result\n\n def _print_report(self, cr, uid, ids, data, context=None):\n raise (_('Error!'), _('Not implemented.'))\n\n def check_report(self, cr, uid, ids, context=None):\n if context is None:\n context = {}\n data = {}\n data['ids'] = context.get('active_ids', [])\n data['model'] = context.get('active_model', 'ir.ui.menu')\n data['form'] = self.read(cr, uid, ids, ['date_from', 'date_to', 'fiscalyear_id', 'journal_ids', 'period_from', 'period_to', 'filter', 'chart_account_id', 'target_move'], context=context)[0]\n for field in ['fiscalyear_id', 'chart_account_id', 'period_from', 'period_to']:\n if isinstance(data['form'][field], tuple):\n data['form'][field] = data['form'][field][0]\n used_context = self._build_contexts(cr, uid, ids, data, context=context)\n data['form']['periods'] = used_context.get('periods', False) and used_context['periods'] or []\n data['form']['used_context'] = dict(used_context, lang=context.get('lang', 'en_US'))\n return self._print_report(cr, uid, ids, data, context=context)\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_functions.py from Jeff-Tian/mybnb (path: Python27/Lib/lib-tk/test/test_ttk/test_functions.py)."}, {"role": "assistant", "content": "# Python27/Lib/lib-tk/test/test_ttk/test_functions.py (from Jeff-Tian/mybnb, license: apache-2.0)\n\n# -*- encoding: utf-8 -*-\nimport sys\nimport unittest\nimport ttk\n\nclass MockTkApp:\n\n def splitlist(self, arg):\n if isinstance(arg, tuple):\n return arg\n return arg.split(':')\n\n def wantobjects(self):\n return True\n\nclass MockTclObj(object):\n typename = 'test'\n\n def __init__(self, val):\n self.val = val\n\n def __str__(self):\n return unicode(self.val)\n\nclass MockStateSpec(object):\n typename = 'StateSpec'\n\n def __init__(self, *args):\n self.val = args\n\n def __str__(self):\n return ' '.join(self.val)\n\nclass InternalFunctionsTest(unittest.TestCase):\n\n def test_format_optdict(self):\n def check_against(fmt_opts, result):\n for i in range(0, len(fmt_opts), 2):\n self.assertEqual(result.pop(fmt_opts[i]), fmt_opts[i + 1])\n if result:\n self.fail(\"result still got elements: %s\" % result)\n\n # passing an empty dict should return an empty object (tuple here)\n self.assertFalse(ttk._format_optdict({}))\n\n # check list formatting\n check_against(\n ttk._format_optdict({'fg': 'blue', 'padding': [1, 2, 3, 4]}),\n {'-fg': 'blue', '-padding': '1 2 3 4'})\n\n # check tuple formatting (same as list)\n check_against(\n ttk._format_optdict({'test': (1, 2, '', 0)}),\n {'-test': '1 2 {} 0'})\n\n # check untouched values\n check_against(\n ttk._format_optdict({'test': {'left': 'as is'}}),\n {'-test': {'left': 'as is'}})\n\n # check script formatting\n check_against(\n ttk._format_optdict(\n {'test': [1, -1, '', '2m', 0], 'test2': 3,\n 'test3': '', 'test4': 'abc def',\n 'test5': '\"abc\"', 'test6': '{}',\n 'test7': '} -spam {'}, script=True),\n {'-test': '{1 -1 {} 2m 0}', '-test2': '3',\n '-test3': '{}', '-test4': '{abc def}',\n '-test5': '{\"abc\"}', '-test6': r'\\{\\}',\n '-test7': r'\\}\\ -spam\\ \\{'})\n\n opts = {u'αβγ': True, u'á': False}\n orig_opts = opts.copy()\n # check if giving unicode keys is fine\n check_against(ttk._format_optdict(opts), {u'-αβγ': True, u'-á': False})\n # opts should remain unchanged\n self.assertEqual(opts, orig_opts)\n\n # passing values with spaces inside a tuple/list\n check_against(\n ttk._format_optdict(\n {'option': ('one two', 'three')}),\n {'-option': '{one two} three'})\n check_against(\n ttk._format_optdict(\n {'option': ('one\\ttwo', 'three')}),\n {'-option': '{one\\ttwo} three'})\n\n # passing empty strings inside a tuple/list\n check_against(\n ttk._format_optdict(\n {'option': ('', 'one')}),\n {'-option': '{} one'})\n\n # passing values with braces inside a tuple/list\n check_against(\n ttk._format_optdict(\n {'option': ('one} {two', 'three')}),\n {'-option': r'one\\}\\ \\{two three'})\n\n # passing quoted strings inside a tuple/list\n check_against(\n ttk._format_optdict(\n {'option': ('\"one\"', 'two')}),\n {'-option': '{\"one\"} two'})\n check_against(\n ttk._format_optdict(\n {'option': ('{one}', 'two')}),\n {'-option': r'\\{one\\} two'})\n\n # ignore an option\n amount_opts = len(ttk._format_optdict(opts, ignore=(u'á'))) // 2\n self.assertEqual(amount_opts, len(opts) - 1)\n\n # ignore non-existing options\n amount_opts = len(ttk._format_optdict(opts, ignore=(u'á', 'b'))) // 2\n self.assertEqual(amount_opts, len(opts) - 1)\n\n # ignore every option\n self.assertFalse(ttk._format_optdict(opts, ignore=opts.keys()))\n\n def test_format_mapdict(self):\n opts = {'a': [('b', 'c', 'val'), ('d', 'otherval'), ('', 'single')]}\n result = ttk._format_mapdict(opts)\n self.assertEqual(len(result), len(opts.keys()) * 2)\n self.assertEqual(result, ('-a', '{b c} val d otherval {} single'))\n self.assertEqual(ttk._format_mapdict(opts, script=True),\n ('-a', '{{b c} val d otherval {} single}'))\n\n self.assertEqual(ttk._format_mapdict({2: []}), ('-2', ''))\n\n opts = {u'üñíćódè': [(u'á', u'vãl')]}\n result = ttk._format_mapdict(opts)\n self.assertEqual(result, (u'-üñíćódè', u'á vãl'))\n\n # empty states\n valid = {'opt': [('', u'', 'hi')]}\n self.assertEqual(ttk._format_mapdict(valid), ('-opt', '{ } hi'))\n\n # when passing multiple states, they all must be strings\n invalid = {'opt': [(1, 2, 'valid val')]}\n self.assertRaises(TypeError, ttk._format_mapdict, invalid)\n invalid = {'opt': [([1], '2', 'valid val')]}\n self.assertRaises(TypeError, ttk._format_mapdict, invalid)\n # but when passing a single state, it can be anything\n valid = {'opt': [[1, 'value']]}\n self.assertEqual(ttk._format_mapdict(valid), ('-opt', '1 value'))\n # special attention to single states which evalute to False\n for stateval in (None, 0, False, '', set()): # just some samples\n valid = {'opt': [(stateval, 'value')]}\n self.assertEqual(ttk._format_mapdict(valid),\n ('-opt', '{} value'))\n\n # values must be iterable\n opts = {'a': None}\n self.assertRaises(TypeError, ttk._format_mapdict, opts)\n\n # items in the value must have size >= 2\n self.assertRaises(IndexError, ttk._format_mapdict,\n {'a': [('invalid', )]})\n\n def test_format_elemcreate(self):\n self.assertTrue(ttk._format_elemcreate(None), (None, ()))\n\n ## Testing type = image\n # image type expects at least an image name, so this should raise\n # IndexError since it tries to access the index 0 of an empty tuple\n self.assertRaises(IndexError, ttk._format_elemcreate, 'image')\n\n # don't format returned values as a tcl script\n # minimum acceptable for image type\n self.assertEqual(ttk._format_elemcreate('image', False, 'test'),\n (\"test \", ()))\n # specifying a state spec\n self.assertEqual(ttk._format_elemcreate('image', False, 'test',\n ('', 'a')), (\"test {} a\", ()))\n # state spec with multiple states\n self.assertEqual(ttk._format_elemcreate('image', False, 'test',\n ('a', 'b', 'c')), (\"test {a b} c\", ()))\n # state spec and options\n res = ttk._format_elemcreate('image', False, 'test',\n ('a', 'b'), a='x', b='y')\n self.assertEqual(res[0], \"test a b\")\n self.assertEqual(set(res[1]), {\"-a\", \"x\", \"-b\", \"y\"})\n # format returned values as a tcl script\n # state spec with multiple states and an option with a multivalue\n self.assertEqual(ttk._format_elemcreate('image', True, 'test',\n ('a', 'b', 'c', 'd'), x=[2, 3]), (\"{test {a b c} d}\", \"-x {2 3}\"))\n\n ## Testing type = vsapi\n # vsapi type expects at least a class name and a part_id, so this\n # should raise an ValueError since it tries to get two elements from\n # an empty tuple\n self.assertRaises(ValueError, ttk._format_elemcreate, 'vsapi')\n\n # don't format returned values as a tcl script\n # minimum acceptable for vsapi\n self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b'),\n (\"a b \", ()))\n # now with a state spec with multiple states\n self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b',\n ('a', 'b', 'c')), (\"a b {a b} c\", ()))\n # state spec and option\n self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b',\n ('a', 'b'), opt='x'), (\"a b a b\", (\"-opt\", \"x\")))\n # format returned values as a tcl script\n # state spec with a multivalue and an option\n self.assertEqual(ttk._format_elemcreate('vsapi', True, 'a', 'b',\n ('a', 'b', [1, 2]), opt='x'), (\"{a b {a b} {1 2}}\", \"-opt x\"))\n\n # Testing type = from\n # from type expects at least a type name\n self.assertRaises(IndexError, ttk._format_elemcreate, 'from')\n\n self.assertEqual(ttk._format_elemcreate('from', False, 'a'),\n ('a', ()))\n self.assertEqual(ttk._format_elemcreate('from', False, 'a', 'b'),\n ('a', ('b', )))\n self.assertEqual(ttk._format_elemcreate('from', True, 'a', 'b'),\n ('{a}', 'b'))\n\n def test_format_layoutlist(self):\n def sample(indent=0, indent_size=2):\n return ttk._format_layoutlist(\n [('a', {'other': [1, 2, 3], 'children':\n [('b', {'children':\n [('c', {'children':\n [('d', {'nice': 'opt'})], 'something': (1, 2)\n })]\n })]\n })], indent=indent, indent_size=indent_size)[0]\n\n def sample_expected(indent=0, indent_size=2):\n spaces = lambda amount=0: ' ' * (amount + indent)\n return (\n \"%sa -other {1 2 3} -children {\\n\"\n \"%sb -children {\\n\"\n \"%sc -something {1 2} -children {\\n\"\n \"%sd -nice opt\\n\"\n \"%s}\\n\"\n \"%s}\\n\"\n \"%s}\" % (spaces(), spaces(indent_size),\n spaces(2 * indent_size), spaces(3 * indent_size),\n spaces(2 * indent_size), spaces(indent_size), spaces()))\n\n # empty layout\n self.assertEqual(ttk._format_layoutlist([])[0], '')\n\n # smallest (after an empty one) acceptable layout\n smallest = ttk._format_layoutlist([('a', None)], indent=0)\n self.assertEqual(smallest,\n ttk._format_layoutlist([('a', '')], indent=0))\n self.assertEqual(smallest[0], 'a')\n\n # testing indentation levels\n self.assertEqual(sample(), sample_expected())\n for i in range(4):\n self.assertEqual(sample(i), sample_expected(i))\n self.assertEqual(sample(i, i), sample_expected(i, i))\n\n # invalid layout format, different kind of exceptions will be\n # raised\n\n # plain wrong format\n self.assertRaises(ValueError, ttk._format_layoutlist,\n ['bad', 'format'])\n self.assertRaises(TypeError, ttk._format_layoutlist, None)\n # _format_layoutlist always expects the second item (in every item)\n # to act like a dict (except when the value evalutes to False).\n self.assertRaises(AttributeError,\n ttk._format_layoutlist, [('a', 'b')])\n # bad children formatting\n self.assertRaises(ValueError, ttk._format_layoutlist,\n [('name', {'children': {'a': None}})])\n\n def test_script_from_settings(self):\n # empty options\n self.assertFalse(ttk._script_from_settings({'name':\n {'configure': None, 'map': None, 'element create': None}}))\n\n # empty layout\n self.assertEqual(\n ttk._script_from_settings({'name': {'layout': None}}),\n \"ttk::style layout name {\\nnull\\n}\")\n\n configdict = {u'αβγ': True, u'á': False}\n self.assertTrue(\n ttk._script_from_settings({'name': {'configure': configdict}}))\n\n mapdict = {u'üñíćódè': [(u'á', u'vãl')]}\n self.assertTrue(\n ttk._script_from_settings({'name': {'map': mapdict}}))\n\n # invalid image element\n self.assertRaises(IndexError,\n ttk._script_from_settings, {'name': {'element create': ['image']}})\n\n # minimal valid image\n self.assertTrue(ttk._script_from_settings({'name':\n {'element create': ['image', 'name']}}))\n\n image = {'thing': {'element create':\n ['image', 'name', ('state1', 'state2', 'val')]}}\n self.assertEqual(ttk._script_from_settings(image),\n \"ttk::style element create thing image {name {state1 state2} val} \")\n\n image['thing']['element create'].append({'opt': 30})\n self.assertEqual(ttk._script_from_settings(image),\n \"ttk::style element create thing image {name {state1 state2} val} \"\n \"-opt 30\")\n\n image['thing']['element create'][-1]['opt'] = [MockTclObj(3),\n MockTclObj('2m')]\n self.assertEqual(ttk._script_from_settings(image),\n \"ttk::style element create thing image {name {state1 state2} val} \"\n \"-opt {3 2m}\")\n\n def test_tclobj_to_py(self):\n self.assertEqual(\n ttk._tclobj_to_py((MockStateSpec('a', 'b'), 'val')),\n [('a', 'b', 'val')])\n self.assertEqual(\n ttk._tclobj_to_py([MockTclObj('1'), 2, MockTclObj('3m')]),\n [1, 2, '3m'])\n\n def test_list_from_statespec(self):\n def test_it(sspec, value, res_value, states):\n self.assertEqual(ttk._list_from_statespec(\n (sspec, value)), [states + (res_value, )])\n\n states_even = tuple('state%d' % i for i in range(6))\n statespec = MockStateSpec(*states_even)\n test_it(statespec, 'val', 'val', states_even)\n test_it(statespec, MockTclObj('val'), 'val', states_even)\n\n states_odd = tuple('state%d' % i for i in range(5))\n statespec = MockStateSpec(*states_odd)\n test_it(statespec, 'val', 'val', states_odd)\n\n test_it(('a', 'b', 'c'), MockTclObj('val'), 'val', ('a', 'b', 'c'))\n\n def test_list_from_layouttuple(self):\n tk = MockTkApp()\n\n # empty layout tuple\n self.assertFalse(ttk._list_from_layouttuple(tk, ()))\n\n # shortest layout tuple\n self.assertEqual(ttk._list_from_layouttuple(tk, ('name', )),\n [('name', {})])\n\n # not so interesting ltuple\n sample_ltuple = ('name', '-option', 'value')\n self.assertEqual(ttk._list_from_layouttuple(tk, sample_ltuple),\n [('name', {'option': 'value'})])\n\n # empty children\n self.assertEqual(ttk._list_from_layouttuple(tk,\n ('something', '-children', ())),\n [('something', {'children': []})]\n )\n\n # more interesting ltuple\n ltuple = (\n 'name', '-option', 'niceone', '-children', (\n ('otherone', '-children', (\n ('child', )), '-otheropt', 'othervalue'\n )\n )\n )\n self.assertEqual(ttk._list_from_layouttuple(tk, ltuple),\n [('name', {'option': 'niceone', 'children':\n [('otherone', {'otheropt': 'othervalue', 'children':\n [('child', {})]\n })]\n })]\n )\n\n # bad tuples\n self.assertRaises(ValueError, ttk._list_from_layouttuple, tk,\n ('name', 'no_minus'))\n self.assertRaises(ValueError, ttk._list_from_layouttuple, tk,\n ('name', 'no_minus', 'value'))\n self.assertRaises(ValueError, ttk._list_from_layouttuple, tk,\n ('something', '-children')) # no children\n\n def test_val_or_dict(self):\n def func(res, opt=None, val=None):\n if opt is None:\n return res\n if val is None:\n return \"test val\"\n return (opt, val)\n\n tk = MockTkApp()\n tk.call = func\n\n self.assertEqual(ttk._val_or_dict(tk, {}, '-test:3'),\n {'test': '3'})\n self.assertEqual(ttk._val_or_dict(tk, {}, ('-test', 3)),\n {'test': 3})\n\n self.assertEqual(ttk._val_or_dict(tk, {'test': None}, 'x:y'),\n 'test val')\n\n self.assertEqual(ttk._val_or_dict(tk, {'test': 3}, 'x:y'),\n {'test': 3})\n\n def test_convert_stringval(self):\n tests = (\n (0, 0), ('09', 9), ('a', 'a'), (u'áÚ', u'áÚ'), ([], '[]'),\n (None, 'None')\n )\n for orig, expected in tests:\n self.assertEqual(ttk._convert_stringval(orig), expected)\n\n if sys.getdefaultencoding() == 'ascii':\n self.assertRaises(UnicodeDecodeError,\n ttk._convert_stringval, 'á')\n\nclass TclObjsToPyTest(unittest.TestCase):\n\n def test_unicode(self):\n adict = {'opt': u'välúè'}\n self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'})\n\n adict['opt'] = MockTclObj(adict['opt'])\n self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'})\n\n def test_multivalues(self):\n adict = {'opt': [1, 2, 3, 4]}\n self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 2, 3, 4]})\n\n adict['opt'] = [1, 'xm', 3]\n self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 'xm', 3]})\n\n adict['opt'] = (MockStateSpec('a', 'b'), u'válũè')\n self.assertEqual(ttk.tclobjs_to_py(adict),\n {'opt': [('a', 'b', u'válũè')]})\n\n self.assertEqual(ttk.tclobjs_to_py({'x': ['y z']}),\n {'x': ['y z']})\n\n def test_nosplit(self):\n self.assertEqual(ttk.tclobjs_to_py({'text': 'some text'}),\n {'text': 'some text'})\n\ntests_nogui = (InternalFunctionsTest, TclObjsToPyTest)\n\nif __name__ == \"__main__\":\n from test.test_support import run_unittest\n run_unittest(*tests_nogui)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements resub.py from ptitjes/quodlibet (path: quodlibet/ext/editing/resub.py)."}, {"role": "assistant", "content": "# quodlibet/ext/editing/resub.py (from ptitjes/quodlibet, license: gpl-2.0)\n\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n\nimport re\n\nfrom gi.repository import Gtk, GObject\n\nfrom quodlibet import _\nfrom quodlibet.plugins.editing import RenameFilesPlugin, TagsFromPathPlugin\nfrom quodlibet.util import connect_obj\nfrom quodlibet.qltk import Icons\n\nclass RegExpSub(Gtk.HBox, RenameFilesPlugin, TagsFromPathPlugin):\n PLUGIN_ID = \"Regex Substitution\"\n PLUGIN_NAME = _(\"Regex Substitution\")\n PLUGIN_DESC = _(\"Allows arbitrary regex substitutions (s///) when \"\n \"tagging or renaming files.\")\n PLUGIN_ICON = Icons.EDIT_FIND_REPLACE\n\n __gsignals__ = {\n \"changed\": (GObject.SignalFlags.RUN_LAST, None, ())\n }\n active = True\n\n def __init__(self):\n super(RegExpSub, self).__init__()\n self._from = Gtk.Entry()\n self._to = Gtk.Entry()\n self.pack_start(Gtk.Label(\"s/\"), True, True, 0)\n self.pack_start(self._from, True, True, 0)\n self.pack_start(Gtk.Label(\"/\"), True, True, 0)\n self.pack_start(self._to, True, True, 0)\n self.pack_start(Gtk.Label(\"/\"), True, True, 0)\n\n connect_obj(self._from, 'changed', self.emit, 'changed')\n connect_obj(self._to, 'changed', self.emit, 'changed')\n\n def filter(self, orig_or_tag, value):\n fr = self._from.get_text()\n to = self._to.get_text()\n try:\n return re.sub(fr, to, value)\n except:\n return value"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_solvers.py from jamestwebber/scipy (path: scipy/linalg/tests/test_solvers.py)."}, {"role": "assistant", "content": "# scipy/linalg/tests/test_solvers.py (from jamestwebber/scipy, license: bsd-3-clause)\n\nfrom __future__ import division, print_function, absolute_import\n\nimport os\nimport numpy as np\n\nfrom numpy.testing import assert_array_almost_equal\nimport pytest\nfrom pytest import raises as assert_raises\n\nfrom scipy.linalg import solve_sylvester\nfrom scipy.linalg import solve_continuous_lyapunov, solve_discrete_lyapunov\nfrom scipy.linalg import solve_continuous_are, solve_discrete_are\nfrom scipy.linalg import block_diag, solve, LinAlgError\nfrom scipy.sparse.sputils import matrix\n\ndef _load_data(name):\n \"\"\"\n Load npz data file under data/\n Returns a copy of the data, rather than keeping the npz file open.\n \"\"\"\n filename = os.path.join(os.path.abspath(os.path.dirname(__file__)),\n 'data', name)\n with np.load(filename) as f:\n return dict(f.items())\n\nclass TestSolveLyapunov(object):\n\n cases = [\n (np.array([[1, 2], [3, 4]]),\n np.array([[9, 10], [11, 12]])),\n # a, q all complex.\n (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),\n np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),\n # a real; q complex.\n (np.array([[1.0, 2.0], [3.0, 5.0]]),\n np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),\n # a complex; q real.\n (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),\n np.array([[2.0, 2.0], [-1.0, 2.0]])),\n # An example from Kitagawa, 1977\n (np.array([[3, 9, 5, 1, 4], [1, 2, 3, 8, 4], [4, 6, 6, 6, 3],\n [1, 5, 2, 0, 7], [5, 3, 3, 1, 5]]),\n np.array([[2, 4, 1, 0, 1], [4, 1, 0, 2, 0], [1, 0, 3, 0, 3],\n [0, 2, 0, 1, 0], [1, 0, 3, 0, 4]])),\n # Companion matrix example. a complex; q real; a.shape[0] = 11\n (np.array([[0.100+0.j, 0.091+0.j, 0.082+0.j, 0.073+0.j, 0.064+0.j,\n 0.055+0.j, 0.046+0.j, 0.037+0.j, 0.028+0.j, 0.019+0.j,\n 0.010+0.j],\n [1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j],\n [0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j],\n [0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j],\n [0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j,\n 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j],\n [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j,\n 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j],\n [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j],\n [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j],\n [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j],\n [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j,\n 0.000+0.j],\n [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,\n 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j,\n 0.000+0.j]]),\n np.eye(11)),\n # https://github.com/scipy/scipy/issues/4176\n (matrix([[0, 1], [-1/2, -1]]),\n (matrix([0, 3]).T * matrix([0, 3]).T.T)),\n # https://github.com/scipy/scipy/issues/4176\n (matrix([[0, 1], [-1/2, -1]]),\n (np.array(matrix([0, 3]).T * matrix([0, 3]).T.T))),\n ]\n\n def test_continuous_squareness_and_shape(self):\n nsq = np.ones((3, 2))\n sq = np.eye(3)\n assert_raises(ValueError, solve_continuous_lyapunov, nsq, sq)\n assert_raises(ValueError, solve_continuous_lyapunov, sq, nsq)\n assert_raises(ValueError, solve_continuous_lyapunov, sq, np.eye(2))\n\n def check_continuous_case(self, a, q):\n x = solve_continuous_lyapunov(a, q)\n assert_array_almost_equal(\n np.dot(a, x) + np.dot(x, a.conj().transpose()), q)\n\n def check_discrete_case(self, a, q, method=None):\n x = solve_discrete_lyapunov(a, q, method=method)\n assert_array_almost_equal(\n np.dot(np.dot(a, x), a.conj().transpose()) - x, -1.0*q)\n\n def test_cases(self):\n for case in self.cases:\n self.check_continuous_case(case[0], case[1])\n self.check_discrete_case(case[0], case[1])\n self.check_discrete_case(case[0], case[1], method='direct')\n self.check_discrete_case(case[0], case[1], method='bilinear')\n\ndef test_solve_continuous_are():\n mat6 = _load_data('carex_6_data.npz')\n mat15 = _load_data('carex_15_data.npz')\n mat18 = _load_data('carex_18_data.npz')\n mat19 = _load_data('carex_19_data.npz')\n mat20 = _load_data('carex_20_data.npz')\n cases = [\n # Carex examples taken from (with default parameters):\n # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark\n # Examples for the Numerical Solution of Algebraic Riccati\n # Equations II: Continuous-Time Case', Tech. Report SPC 95_23,\n # Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995.\n #\n # The format of the data is (a, b, q, r, knownfailure), where\n # knownfailure is None if the test passes or a string\n # indicating the reason for failure.\n #\n # Test Case 0: carex #1\n (np.diag([1.], 1),\n np.array([[0], [1]]),\n block_diag(1., 2.),\n 1,\n None),\n # Test Case 1: carex #2\n (np.array([[4, 3], [-4.5, -3.5]]),\n np.array([[1], [-1]]),\n np.array([[9, 6], [6, 4.]]),\n 1,\n None),\n # Test Case 2: carex #3\n (np.array([[0, 1, 0, 0],\n [0, -1.89, 0.39, -5.53],\n [0, -0.034, -2.98, 2.43],\n [0.034, -0.0011, -0.99, -0.21]]),\n np.array([[0, 0], [0.36, -1.6], [-0.95, -0.032], [0.03, 0]]),\n np.array([[2.313, 2.727, 0.688, 0.023],\n [2.727, 4.271, 1.148, 0.323],\n [0.688, 1.148, 0.313, 0.102],\n [0.023, 0.323, 0.102, 0.083]]),\n np.eye(2),\n None),\n # Test Case 3: carex #4\n (np.array([[-0.991, 0.529, 0, 0, 0, 0, 0, 0],\n [0.522, -1.051, 0.596, 0, 0, 0, 0, 0],\n [0, 0.522, -1.118, 0.596, 0, 0, 0, 0],\n [0, 0, 0.522, -1.548, 0.718, 0, 0, 0],\n [0, 0, 0, 0.922, -1.64, 0.799, 0, 0],\n [0, 0, 0, 0, 0.922, -1.721, 0.901, 0],\n [0, 0, 0, 0, 0, 0.922, -1.823, 1.021],\n [0, 0, 0, 0, 0, 0, 0.922, -1.943]]),\n np.array([[3.84, 4.00, 37.60, 3.08, 2.36, 2.88, 3.08, 3.00],\n [-2.88, -3.04, -2.80, -2.32, -3.32, -3.82, -4.12, -3.96]]\n ).T * 0.001,\n np.array([[1.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.1],\n [0.0, 1.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0],\n [0.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0],\n [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],\n [0.5, 0.1, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.5, 0.0, 0.0, 0.1, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0],\n [0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1]]),\n np.eye(2),\n None),\n # Test Case 4: carex #5\n (np.array(\n [[-4.019, 5.120, 0., 0., -2.082, 0., 0., 0., 0.870],\n [-0.346, 0.986, 0., 0., -2.340, 0., 0., 0., 0.970],\n [-7.909, 15.407, -4.069, 0., -6.450, 0., 0., 0., 2.680],\n [-21.816, 35.606, -0.339, -3.870, -17.800, 0., 0., 0., 7.390],\n [-60.196, 98.188, -7.907, 0.340, -53.008, 0., 0., 0., 20.400],\n [0, 0, 0, 0, 94.000, -147.200, 0., 53.200, 0.],\n [0, 0, 0, 0, 0, 94.000, -147.200, 0, 0],\n [0, 0, 0, 0, 0, 12.800, 0.000, -31.600, 0],\n [0, 0, 0, 0, 12.800, 0.000, 0.000, 18.800, -31.600]]),\n np.array([[0.010, -0.011, -0.151],\n [0.003, -0.021, 0.000],\n [0.009, -0.059, 0.000],\n [0.024, -0.162, 0.000],\n [0.068, -0.445, 0.000],\n [0.000, 0.000, 0.000],\n [0.000, 0.000, 0.000],\n [0.000, 0.000, 0.000],\n [0.000, 0.000, 0.000]]),\n np.eye(9),\n np.eye(3),\n None),\n # Test Case 5: carex #6\n (mat6['A'], mat6['B'], mat6['Q'], mat6['R'], None),\n # Test Case 6: carex #7\n (np.array([[1, 0], [0, -2.]]),\n np.array([[1e-6], [0]]),\n np.ones((2, 2)),\n 1.,\n 'Bad residual accuracy'),\n # Test Case 7: carex #8\n (block_diag(-0.1, -0.02),\n np.array([[0.100, 0.000], [0.001, 0.010]]),\n np.array([[100, 1000], [1000, 10000]]),\n np.ones((2, 2)) + block_diag(1e-6, 0),\n None),\n # Test Case 8: carex #9\n (np.array([[0, 1e6], [0, 0]]),\n np.array([[0], [1.]]),\n np.eye(2),\n 1.,\n None),\n # Test Case 9: carex #10\n (np.array([[1.0000001, 1], [1., 1.0000001]]),\n np.eye(2),\n np.eye(2),\n np.eye(2),\n None),\n # Test Case 10: carex #11\n (np.array([[3, 1.], [4, 2]]),\n np.array([[1], [1]]),\n np.array([[-11, -5], [-5, -2.]]),\n 1.,\n None),\n # Test Case 11: carex #12\n (np.array([[7000000., 2000000., -0.],\n [2000000., 6000000., -2000000.],\n [0., -2000000., 5000000.]]) / 3,\n np.eye(3),\n np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]]).dot(\n np.diag([1e-6, 1, 1e6])).dot(\n np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]])) / 9,\n np.eye(3) * 1e6,\n 'Bad Residual Accuracy'),\n # Test Case 12: carex #13\n (np.array([[0, 0.4, 0, 0],\n [0, 0, 0.345, 0],\n [0, -0.524e6, -0.465e6, 0.262e6],\n [0, 0, 0, -1e6]]),\n np.array([[0, 0, 0, 1e6]]).T,\n np.diag([1, 0, 1, 0]),\n 1.,\n None),\n # Test Case 13: carex #14\n (np.array([[-1e-6, 1, 0, 0],\n [-1, -1e-6, 0, 0],\n [0, 0, 1e-6, 1],\n [0, 0, -1, 1e-6]]),\n np.ones((4, 1)),\n np.ones((4, 4)),\n 1.,\n None),\n # Test Case 14: carex #15\n (mat15['A'], mat15['B'], mat15['Q'], mat15['R'], None),\n # Test Case 15: carex #16\n (np.eye(64, 64, k=-1) + np.eye(64, 64)*(-2.) + np.rot90(\n block_diag(1, np.zeros((62, 62)), 1)) + np.eye(64, 64, k=1),\n np.eye(64),\n np.eye(64),\n np.eye(64),\n None),\n # Test Case 16: carex #17\n (np.diag(np.ones((20, )), 1),\n np.flipud(np.eye(21, 1)),\n np.eye(21, 1) * np.eye(21, 1).T,\n 1,\n 'Bad Residual Accuracy'),\n # Test Case 17: carex #18\n (mat18['A'], mat18['B'], mat18['Q'], mat18['R'], None),\n # Test Case 18: carex #19\n (mat19['A'], mat19['B'], mat19['Q'], mat19['R'],\n 'Bad Residual Accuracy'),\n # Test Case 19: carex #20\n (mat20['A'], mat20['B'], mat20['Q'], mat20['R'],\n 'Bad Residual Accuracy')\n ]\n # Makes the minimum precision requirements customized to the test.\n # Here numbers represent the number of decimals that agrees with zero\n # matrix when the solution x is plugged in to the equation.\n #\n # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2\n #\n # If the test is failing use \"None\" for that entry.\n #\n min_decimal = (14, 12, 13, 14, 11, 6, None, 5, 7, 14, 14,\n None, 9, 14, 13, 14, None, 12, None, None)\n\n def _test_factory(case, dec):\n \"\"\"Checks if 0 = XA + A'X - XB(R)^{-1} B'X + Q is true\"\"\"\n a, b, q, r, knownfailure = case\n if knownfailure:\n pytest.xfail(reason=knownfailure)\n\n x = solve_continuous_are(a, b, q, r)\n res = x.dot(a) + a.conj().T.dot(x) + q\n out_fact = x.dot(b)\n res -= out_fact.dot(solve(np.atleast_2d(r), out_fact.conj().T))\n assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)\n\n for ind, case in enumerate(cases):\n _test_factory(case, min_decimal[ind])\n\ndef test_solve_discrete_are():\n\n cases = [\n # Darex examples taken from (with default parameters):\n # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark\n # Examples for the Numerical Solution of Algebraic Riccati\n # Equations II: Discrete-Time Case', Tech. Report SPC 95_23,\n # Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995.\n # [2] T. GUDMUNDSSON, C. KENNEY, A.J. LAUB: 'Scaling of the\n # Discrete-Time Algebraic Riccati Equation to Enhance Stability\n # of the Schur Solution Method', IEEE Trans.Aut.Cont., vol.37(4)\n #\n # The format of the data is (a, b, q, r, knownfailure), where\n # knownfailure is None if the test passes or a string\n # indicating the reason for failure.\n #\n # TEST CASE 0 : Complex a; real b, q, r\n (np.array([[2, 1-2j], [0, -3j]]),\n np.array([[0], [1]]),\n np.array([[1, 0], [0, 2]]),\n np.array([[1]]),\n None),\n # TEST CASE 1 :Real a, q, r; complex b\n (np.array([[2, 1], [0, -1]]),\n np.array([[-2j], [1j]]),\n np.array([[1, 0], [0, 2]]),\n np.array([[1]]),\n None),\n # TEST CASE 2 : Real a, b; complex q, r\n (np.array([[3, 1], [0, -1]]),\n np.array([[1, 2], [1, 3]]),\n np.array([[1, 1+1j], [1-1j, 2]]),\n np.array([[2, -2j], [2j, 3]]),\n None),\n # TEST CASE 3 : User-reported gh-2251 (Trac #1732)\n (np.array([[0.63399379, 0.54906824, 0.76253406],\n [0.5404729, 0.53745766, 0.08731853],\n [0.27524045, 0.84922129, 0.4681622]]),\n np.array([[0.96861695], [0.05532739], [0.78934047]]),\n np.eye(3),\n np.eye(1),\n None),\n # TEST CASE 4 : darex #1\n (np.array([[4, 3], [-4.5, -3.5]]),\n np.array([[1], [-1]]),\n np.array([[9, 6], [6, 4]]),\n np.array([[1]]),\n None),\n # TEST CASE 5 : darex #2\n (np.array([[0.9512, 0], [0, 0.9048]]),\n np.array([[4.877, 4.877], [-1.1895, 3.569]]),\n np.array([[0.005, 0], [0, 0.02]]),\n np.array([[1/3, 0], [0, 3]]),\n None),\n # TEST CASE 6 : darex #3\n (np.array([[2, -1], [1, 0]]),\n np.array([[1], [0]]),\n np.array([[0, 0], [0, 1]]),\n np.array([[0]]),\n None),\n # TEST CASE 7 : darex #4 (skipped the gen. Ric. term S)\n (np.array([[0, 1], [0, -1]]),\n np.array([[1, 0], [2, 1]]),\n np.array([[-4, -4], [-4, 7]]) * (1/11),\n np.array([[9, 3], [3, 1]]),\n None),\n # TEST CASE 8 : darex #5\n (np.array([[0, 1], [0, 0]]),\n np.array([[0], [1]]),\n np.array([[1, 2], [2, 4]]),\n np.array([[1]]),\n None),\n # TEST CASE 9 : darex #6\n (np.array([[0.998, 0.067, 0, 0],\n [-.067, 0.998, 0, 0],\n [0, 0, 0.998, 0.153],\n [0, 0, -.153, 0.998]]),\n np.array([[0.0033, 0.0200],\n [0.1000, -.0007],\n [0.0400, 0.0073],\n [-.0028, 0.1000]]),\n np.array([[1.87, 0, 0, -0.244],\n [0, 0.744, 0.205, 0],\n [0, 0.205, 0.589, 0],\n [-0.244, 0, 0, 1.048]]),\n np.eye(2),\n None),\n # TEST CASE 10 : darex #7\n (np.array([[0.984750, -.079903, 0.0009054, -.0010765],\n [0.041588, 0.998990, -.0358550, 0.0126840],\n [-.546620, 0.044916, -.3299100, 0.1931800],\n [2.662400, -.100450, -.9245500, -.2632500]]),\n np.array([[0.0037112, 0.0007361],\n [-.0870510, 9.3411e-6],\n [-1.198440, -4.1378e-4],\n [-3.192700, 9.2535e-4]]),\n np.eye(4)*1e-2,\n np.eye(2),\n None),\n # TEST CASE 11 : darex #8\n (np.array([[-0.6000000, -2.2000000, -3.6000000, -5.4000180],\n [1.0000000, 0.6000000, 0.8000000, 3.3999820],\n [0.0000000, 1.0000000, 1.8000000, 3.7999820],\n [0.0000000, 0.0000000, 0.0000000, -0.9999820]]),\n np.array([[1.0, -1.0, -1.0, -1.0],\n [0.0, 1.0, -1.0, -1.0],\n [0.0, 0.0, 1.0, -1.0],\n [0.0, 0.0, 0.0, 1.0]]),\n np.array([[2, 1, 3, 6],\n [1, 2, 2, 5],\n [3, 2, 6, 11],\n [6, 5, 11, 22]]),\n np.eye(4),\n None),\n # TEST CASE 12 : darex #9\n (np.array([[95.4070, 1.9643, 0.3597, 0.0673, 0.0190],\n [40.8490, 41.3170, 16.0840, 4.4679, 1.1971],\n [12.2170, 26.3260, 36.1490, 15.9300, 12.3830],\n [4.1118, 12.8580, 27.2090, 21.4420, 40.9760],\n [0.1305, 0.5808, 1.8750, 3.6162, 94.2800]]) * 0.01,\n np.array([[0.0434, -0.0122],\n [2.6606, -1.0453],\n [3.7530, -5.5100],\n [3.6076, -6.6000],\n [0.4617, -0.9148]]) * 0.01,\n np.eye(5),\n np.eye(2),\n None),\n # TEST CASE 13 : darex #10\n (np.kron(np.eye(2), np.diag([1, 1], k=1)),\n np.kron(np.eye(2), np.array([[0], [0], [1]])),\n np.array([[1, 1, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, -1, 0],\n [0, 0, 0, -1, 1, 0],\n [0, 0, 0, 0, 0, 0]]),\n np.array([[3, 0], [0, 1]]),\n None),\n # TEST CASE 14 : darex #11\n (0.001 * np.array(\n [[870.1, 135.0, 11.59, .5014, -37.22, .3484, 0, 4.242, 7.249],\n [76.55, 897.4, 12.72, 0.5504, -40.16, .3743, 0, 4.53, 7.499],\n [-127.2, 357.5, 817, 1.455, -102.8, .987, 0, 11.85, 18.72],\n [-363.5, 633.9, 74.91, 796.6, -273.5, 2.653, 0, 31.72, 48.82],\n [-960, 1645.9, -128.9, -5.597, 71.42, 7.108, 0, 84.52, 125.9],\n [-664.4, 112.96, -88.89, -3.854, 84.47, 13.6, 0, 144.3, 101.6],\n [-410.2, 693, -54.71, -2.371, 66.49, 12.49, .1063, 99.97, 69.67],\n [-179.9, 301.7, -23.93, -1.035, 60.59, 22.16, 0, 213.9, 35.54],\n [-345.1, 580.4, -45.96, -1.989, 105.6, 19.86, 0, 219.1, 215.2]]),\n np.array([[4.7600, -0.5701, -83.6800],\n [0.8790, -4.7730, -2.7300],\n [1.4820, -13.1200, 8.8760],\n [3.8920, -35.1300, 24.8000],\n [10.3400, -92.7500, 66.8000],\n [7.2030, -61.5900, 38.3400],\n [4.4540, -36.8300, 20.2900],\n [1.9710, -15.5400, 6.9370],\n [3.7730, -30.2800, 14.6900]]) * 0.001,\n np.diag([50, 0, 0, 0, 50, 0, 0, 0, 0]),\n np.eye(3),\n None),\n # TEST CASE 15 : darex #12 - numerically least accurate example\n (np.array([[0, 1e6], [0, 0]]),\n np.array([[0], [1]]),\n np.eye(2),\n np.array([[1]]),\n None),\n # TEST CASE 16 : darex #13\n (np.array([[16, 10, -2],\n [10, 13, -8],\n [-2, -8, 7]]) * (1/9),\n np.eye(3),\n 1e6 * np.eye(3),\n 1e6 * np.eye(3),\n None),\n # TEST CASE 17 : darex #14\n (np.array([[1 - 1/1e8, 0, 0, 0],\n [1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0]]),\n np.array([[1e-08], [0], [0], [0]]),\n np.diag([0, 0, 0, 1]),\n np.array([[0.25]]),\n None),\n # TEST CASE 18 : darex #15\n (np.eye(100, k=1),\n np.flipud(np.eye(100, 1)),\n np.eye(100),\n np.array([[1]]),\n None)\n ]\n\n # Makes the minimum precision requirements customized to the test.\n # Here numbers represent the number of decimals that agrees with zero\n # matrix when the solution x is plugged in to the equation.\n #\n # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2\n #\n # If the test is failing use \"None\" for that entry.\n #\n min_decimal = (12, 14, 13, 14, 13, 16, 18, 14, 14, 13,\n 14, 13, 13, 14, 12, 2, 5, 6, 10)\n\n def _test_factory(case, dec):\n \"\"\"Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true\"\"\"\n a, b, q, r, knownfailure = case\n if knownfailure:\n pytest.xfail(reason=knownfailure)\n\n x = solve_discrete_are(a, b, q, r)\n res = a.conj().T.dot(x.dot(a)) - x + q\n res -= a.conj().T.dot(x.dot(b)).dot(\n solve(r+b.conj().T.dot(x.dot(b)), b.conj().T).dot(x.dot(a))\n )\n assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)\n\n for ind, case in enumerate(cases):\n _test_factory(case, min_decimal[ind])\n\n # An infeasible example taken from https://arxiv.org/abs/1505.04861v1\n A = np.triu(np.ones((3, 3)))\n A[0, 1] = -1\n B = np.array([[1, 1, 0], [0, 0, 1]]).T\n Q = np.full_like(A, -2) + np.diag([8, -1, -1.9])\n R = np.diag([-10, 0.1])\n assert_raises(LinAlgError, solve_continuous_are, A, B, Q, R)\n\ndef test_solve_generalized_continuous_are():\n cases = [\n # Two random examples differ by s term\n # in the absence of any literature for demanding examples.\n (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],\n [4.617139e-02, 6.948286e-01, 3.444608e-02],\n [9.713178e-02, 3.170995e-01, 4.387444e-01]]),\n np.array([[3.815585e-01, 1.868726e-01],\n [7.655168e-01, 4.897644e-01],\n [7.951999e-01, 4.455862e-01]]),\n np.eye(3),\n np.eye(2),\n np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],\n [7.093648e-01, 6.797027e-01, 1.189977e-01],\n [7.546867e-01, 6.550980e-01, 4.983641e-01]]),\n np.zeros((3, 2)),\n None),\n (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],\n [4.617139e-02, 6.948286e-01, 3.444608e-02],\n [9.713178e-02, 3.170995e-01, 4.387444e-01]]),\n np.array([[3.815585e-01, 1.868726e-01],\n [7.655168e-01, 4.897644e-01],\n [7.951999e-01, 4.455862e-01]]),\n np.eye(3),\n np.eye(2),\n np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],\n [7.093648e-01, 6.797027e-01, 1.189977e-01],\n [7.546867e-01, 6.550980e-01, 4.983641e-01]]),\n np.ones((3, 2)),\n None)\n ]\n\n min_decimal = (10, 10)\n\n def _test_factory(case, dec):\n \"\"\"Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true\"\"\"\n a, b, q, r, e, s, knownfailure = case\n if knownfailure:\n pytest.xfail(reason=knownfailure)\n\n x = solve_continuous_are(a, b, q, r, e, s)\n res = a.conj().T.dot(x.dot(e)) + e.conj().T.dot(x.dot(a)) + q\n out_fact = e.conj().T.dot(x).dot(b) + s\n res -= out_fact.dot(solve(np.atleast_2d(r), out_fact.conj().T))\n assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)\n\n for ind, case in enumerate(cases):\n _test_factory(case, min_decimal[ind])\n\ndef test_solve_generalized_discrete_are():\n mat20170120 = _load_data('gendare_20170120_data.npz')\n\n cases = [\n # Two random examples differ by s term\n # in the absence of any literature for demanding examples.\n (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],\n [4.617139e-02, 6.948286e-01, 3.444608e-02],\n [9.713178e-02, 3.170995e-01, 4.387444e-01]]),\n np.array([[3.815585e-01, 1.868726e-01],\n [7.655168e-01, 4.897644e-01],\n [7.951999e-01, 4.455862e-01]]),\n np.eye(3),\n np.eye(2),\n np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],\n [7.093648e-01, 6.797027e-01, 1.189977e-01],\n [7.546867e-01, 6.550980e-01, 4.983641e-01]]),\n np.zeros((3, 2)),\n None),\n (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],\n [4.617139e-02, 6.948286e-01, 3.444608e-02],\n [9.713178e-02, 3.170995e-01, 4.387444e-01]]),\n np.array([[3.815585e-01, 1.868726e-01],\n [7.655168e-01, 4.897644e-01],\n [7.951999e-01, 4.455862e-01]]),\n np.eye(3),\n np.eye(2),\n np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],\n [7.093648e-01, 6.797027e-01, 1.189977e-01],\n [7.546867e-01, 6.550980e-01, 4.983641e-01]]),\n np.ones((3, 2)),\n None),\n # user-reported (under PR-6616) 20-Jan-2017\n # tests against the case where E is None but S is provided\n (mat20170120['A'],\n mat20170120['B'],\n mat20170120['Q'],\n mat20170120['R'],\n None,\n mat20170120['S'],\n None),\n ]\n\n min_decimal = (11, 11, 16)\n\n def _test_factory(case, dec):\n \"\"\"Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true\"\"\"\n a, b, q, r, e, s, knownfailure = case\n if knownfailure:\n pytest.xfail(reason=knownfailure)\n\n x = solve_discrete_are(a, b, q, r, e, s)\n if e is None:\n e = np.eye(a.shape[0])\n if s is None:\n s = np.zeros_like(b)\n res = a.conj().T.dot(x.dot(a)) - e.conj().T.dot(x.dot(e)) + q\n res -= (a.conj().T.dot(x.dot(b)) + s).dot(\n solve(r+b.conj().T.dot(x.dot(b)),\n (b.conj().T.dot(x.dot(a)) + s.conj().T)\n )\n )\n assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)\n\n for ind, case in enumerate(cases):\n _test_factory(case, min_decimal[ind])\n\ndef test_are_validate_args():\n\n def test_square_shape():\n nsq = np.ones((3, 2))\n sq = np.eye(3)\n for x in (solve_continuous_are, solve_discrete_are):\n assert_raises(ValueError, x, nsq, 1, 1, 1)\n assert_raises(ValueError, x, sq, sq, nsq, 1)\n assert_raises(ValueError, x, sq, sq, sq, nsq)\n assert_raises(ValueError, x, sq, sq, sq, sq, nsq)\n\n def test_compatible_sizes():\n nsq = np.ones((3, 2))\n sq = np.eye(4)\n for x in (solve_continuous_are, solve_discrete_are):\n assert_raises(ValueError, x, sq, nsq, 1, 1)\n assert_raises(ValueError, x, sq, sq, sq, sq, sq, nsq)\n assert_raises(ValueError, x, sq, sq, np.eye(3), sq)\n assert_raises(ValueError, x, sq, sq, sq, np.eye(3))\n assert_raises(ValueError, x, sq, sq, sq, sq, np.eye(3))\n\n def test_symmetry():\n nsym = np.arange(9).reshape(3, 3)\n sym = np.eye(3)\n for x in (solve_continuous_are, solve_discrete_are):\n assert_raises(ValueError, x, sym, sym, nsym, sym)\n assert_raises(ValueError, x, sym, sym, sym, nsym)\n\n def test_singularity():\n sing = np.full((3, 3), 1e12)\n sing[2, 2] -= 1\n sq = np.eye(3)\n for x in (solve_continuous_are, solve_discrete_are):\n assert_raises(ValueError, x, sq, sq, sq, sq, sing)\n\n assert_raises(ValueError, solve_continuous_are, sq, sq, sq, sing)\n\n def test_finiteness():\n nm = np.full((2, 2), np.nan)\n sq = np.eye(2)\n for x in (solve_continuous_are, solve_discrete_are):\n assert_raises(ValueError, x, nm, sq, sq, sq)\n assert_raises(ValueError, x, sq, nm, sq, sq)\n assert_raises(ValueError, x, sq, sq, nm, sq)\n assert_raises(ValueError, x, sq, sq, sq, nm)\n assert_raises(ValueError, x, sq, sq, sq, sq, nm)\n assert_raises(ValueError, x, sq, sq, sq, sq, sq, nm)\n\nclass TestSolveSylvester(object):\n\n cases = [\n # a, b, c all real.\n (np.array([[1, 2], [0, 4]]),\n np.array([[5, 6], [0, 8]]),\n np.array([[9, 10], [11, 12]])),\n # a, b, c all real, 4x4. a and b have non-trival 2x2 blocks in their\n # quasi-triangular form.\n (np.array([[1.0, 0, 0, 0],\n [0, 1.0, 2.0, 0.0],\n [0, 0, 3.0, -4],\n [0, 0, 2, 5]]),\n np.array([[2.0, 0, 0, 1.0],\n [0, 1.0, 0.0, 0.0],\n [0, 0, 1.0, -1],\n [0, 0, 1, 1]]),\n np.array([[1.0, 0, 0, 0],\n [0, 1.0, 0, 0],\n [0, 0, 1.0, 0],\n [0, 0, 0, 1.0]])),\n # a, b, c all complex.\n (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),\n np.array([[-1.0, 2j], [3.0, 4.0]]),\n np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),\n # a and b real; c complex.\n (np.array([[1.0, 2.0], [3.0, 5.0]]),\n np.array([[-1.0, 0], [3.0, 4.0]]),\n np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),\n # a and c complex; b real.\n (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),\n np.array([[-1.0, 0], [3.0, 4.0]]),\n np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),\n # a complex; b and c real.\n (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),\n np.array([[-1.0, 0], [3.0, 4.0]]),\n np.array([[2.0, 2.0], [-1.0, 2.0]])),\n # not square matrices, real\n (np.array([[8, 1, 6], [3, 5, 7], [4, 9, 2]]),\n np.array([[2, 3], [4, 5]]),\n np.array([[1, 2], [3, 4], [5, 6]])),\n # not square matrices, complex\n (np.array([[8, 1j, 6+2j], [3, 5, 7], [4, 9, 2]]),\n np.array([[2, 3], [4, 5-1j]]),\n np.array([[1, 2j], [3, 4j], [5j, 6+7j]])),\n ]\n\n def check_case(self, a, b, c):\n x = solve_sylvester(a, b, c)\n assert_array_almost_equal(np.dot(a, x) + np.dot(x, b), c)\n\n def test_cases(self):\n for case in self.cases:\n self.check_case(case[0], case[1], case[2])\n\n def test_trivial(self):\n a = np.array([[1.0, 0.0], [0.0, 1.0]])\n b = np.array([[1.0]])\n c = np.array([2.0, 2.0]).reshape(-1, 1)\n x = solve_sylvester(a, b, c)\n assert_array_almost_equal(x, np.array([1.0, 1.0]).reshape(-1, 1))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements hook-salt.py from stingaci/heat-tutorial (path: partVI/lib/elements/heat-config-salt/install.d/hook-salt.py)."}, {"role": "assistant", "content": "# partVI/lib/elements/heat-config-salt/install.d/hook-salt.py (from stingaci/heat-tutorial, license: apache-2.0)\n\n#!/usr/bin/env python\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport json\nimport logging\nimport os\nimport sys\n\nimport salt.cli.caller\nimport salt.config\nfrom salt import exceptions\nimport yaml\n\nWORKING_DIR = os.environ.get('HEAT_SALT_WORKING',\n '/var/lib/heat-config/heat-config-salt')\nSALT_MINION_CONFIG = os.environ.get('SALT_MINION_CONFIG',\n '/etc/salt/minion')\n\ndef prepare_dir(path):\n if not os.path.isdir(path):\n os.makedirs(path, 0o700)\n\ndef main(argv=sys.argv):\n log = logging.getLogger('heat-config')\n handler = logging.StreamHandler(sys.stderr)\n handler.setFormatter(\n logging.Formatter(\n '[%(asctime)s] (%(name)s) [%(levelname)s] %(message)s'))\n log.addHandler(handler)\n log.setLevel('DEBUG')\n\n prepare_dir(WORKING_DIR)\n os.chdir(WORKING_DIR)\n\n c = json.load(sys.stdin)\n\n opts = salt.config.minion_config(SALT_MINION_CONFIG)\n\n opts['file_roots'] = {'base': [WORKING_DIR]}\n opts['file_client'] = 'local'\n opts['local'] = 'local'\n opts['fun'] = 'state.sls'\n opts['arg'] = [c['id']]\n\n for input in c['inputs']:\n key = input['name']\n opts[key] = input.get('value', '')\n\n state_file = '%s.sls' % c['id']\n config = c.get('config', '')\n\n if isinstance(config, dict):\n yaml_config = yaml.safe_dump(config, default_flow_style=False)\n else:\n yaml_config = config\n\n fn = os.path.join(WORKING_DIR, state_file)\n with os.fdopen(os.open(fn, os.O_CREAT | os.O_WRONLY, 0o700), 'w') as f:\n f.write(yaml_config.encode('utf-8'))\n\n caller = salt.cli.caller.Caller.factory(opts)\n\n log.debug('Applying Salt state %s' % state_file)\n\n stdout, stderr = None, None\n ret = {}\n\n try:\n ret = caller.call()\n except exceptions.SaltInvocationError as err:\n log.error(\n 'Salt invocation error while applying Salt sate %s' % state_file)\n stderr = err\n\n if ret:\n\n log.info('Results: %s' % ret)\n output = yaml.safe_dump(ret['return'])\n\n # returncode of 0 means there were successful changes\n if ret['retcode'] == 0:\n log.info('Completed applying salt state %s' % state_file)\n stdout = output\n else:\n # Salt doesn't always return sane return codes so we have to check\n # individual results\n runfailed = False\n for state, data in ret['return'].items():\n if not data['result']:\n runfailed = True\n break\n if runfailed:\n log.error('Error applying Salt state %s. [%s]\\n'\n % (state_file, ret['retcode']))\n stderr = output\n else:\n ret['retcode'] = 0\n stdout = output\n\n response = {}\n\n for output in c.get('outputs', []):\n output_name = output['name']\n response[output_name] = ret.get(output_name)\n\n response.update({\n 'deploy_stdout': stdout,\n 'deploy_stderr': stderr,\n 'deploy_status_code': ret['retcode'],\n })\n json.dump(response, sys.stdout)\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements discover_unittest.py from Gateworks/platform-external-chromium_org (path: tools/telemetry/telemetry/core/discover_unittest.py)."}, {"role": "assistant", "content": "# tools/telemetry/telemetry/core/discover_unittest.py (from Gateworks/platform-external-chromium_org, license: bsd-3-clause)\n\n# Copyright (c) 2013 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\nimport os\nimport unittest\n\nfrom telemetry.core import discover\nfrom telemetry.core import util\n\nclass DiscoverTest(unittest.TestCase):\n def setUp(self):\n self._base_dir = util.GetUnittestDataDir()\n self._start_dir = os.path.join(self._base_dir, 'discoverable_classes')\n self._base_class = Exception\n\n def testDiscoverClassesBasic(self):\n classes = discover.DiscoverClasses(\n self._start_dir, self._base_dir, self._base_class)\n\n actual_classes = dict(\n (name, cls.__name__) for name, cls in classes.iteritems())\n expected_classes = {\n 'discover_dummyclass': 'DummyException',\n 'another_discover_dummyclass': 'DummyExceptionImpl2',\n }\n self.assertEqual(actual_classes, expected_classes)\n\n def testDiscoverClassesWithPattern(self):\n classes = discover.DiscoverClasses(\n self._start_dir, self._base_dir, self._base_class,\n pattern='another*')\n\n actual_classes = dict(\n (name, cls.__name__) for name, cls in classes.iteritems())\n expected_classes = {\n 'another_discover_dummyclass': 'DummyExceptionImpl2',\n }\n self.assertEqual(actual_classes, expected_classes)\n\n def testDiscoverClassesByClassName(self):\n classes = discover.DiscoverClasses(\n self._start_dir, self._base_dir, self._base_class,\n index_by_class_name=True)\n\n actual_classes = dict(\n (name, cls.__name__) for name, cls in classes.iteritems())\n expected_classes = {\n 'dummy_exception': 'DummyException',\n 'dummy_exception_impl1': 'DummyExceptionImpl1',\n 'dummy_exception_impl2': 'DummyExceptionImpl2',\n }\n self.assertEqual(actual_classes, expected_classes)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_image_tags_resource.py from akash1808/glance (path: glance/tests/unit/v2/test_image_tags_resource.py)."}, {"role": "assistant", "content": "# glance/tests/unit/v2/test_image_tags_resource.py (from akash1808/glance, license: apache-2.0)\n\n# Copyright 2012 OpenStack Foundation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport webob\n\nimport glance.api.v2.image_tags\nfrom glance.common import exception\nfrom glance.tests.unit import base\nimport glance.tests.unit.utils as unit_test_utils\nimport glance.tests.unit.v2.test_image_data_resource as image_data_tests\nimport glance.tests.utils as test_utils\n\nclass TestImageTagsController(base.IsolatedUnitTest):\n\n def setUp(self):\n super(TestImageTagsController, self).setUp()\n self.db = unit_test_utils.FakeDB()\n self.controller = glance.api.v2.image_tags.Controller(self.db)\n\n def test_create_tag(self):\n request = unit_test_utils.get_fake_request()\n self.controller.update(request, unit_test_utils.UUID1, 'dink')\n context = request.context\n tags = self.db.image_tag_get_all(context, unit_test_utils.UUID1)\n self.assertEqual(1, len([tag for tag in tags if tag == 'dink']))\n\n def test_create_too_many_tags(self):\n self.config(image_tag_quota=0)\n request = unit_test_utils.get_fake_request()\n self.assertRaises(webob.exc.HTTPRequestEntityTooLarge,\n self.controller.update,\n request, unit_test_utils.UUID1, 'dink')\n\n def test_create_duplicate_tag_ignored(self):\n request = unit_test_utils.get_fake_request()\n self.controller.update(request, unit_test_utils.UUID1, 'dink')\n self.controller.update(request, unit_test_utils.UUID1, 'dink')\n context = request.context\n tags = self.db.image_tag_get_all(context, unit_test_utils.UUID1)\n self.assertEqual(1, len([tag for tag in tags if tag == 'dink']))\n\n def test_update_tag_of_non_existing_image(self):\n request = unit_test_utils.get_fake_request()\n self.assertRaises(webob.exc.HTTPNotFound, self.controller.update,\n request, \"abcd\", \"dink\")\n\n def test_delete_tag_forbidden(self):\n def fake_get(self):\n raise exception.Forbidden()\n\n image_repo = image_data_tests.FakeImageRepo()\n image_repo.get = fake_get\n\n def get_fake_repo(self):\n return image_repo\n\n self.controller.gateway.get_repo = get_fake_repo\n request = unit_test_utils.get_fake_request()\n self.assertRaises(webob.exc.HTTPForbidden, self.controller.update,\n request, unit_test_utils.UUID1, \"ping\")\n\n def test_delete_tag(self):\n request = unit_test_utils.get_fake_request()\n self.controller.delete(request, unit_test_utils.UUID1, 'ping')\n\n def test_delete_tag_not_found(self):\n request = unit_test_utils.get_fake_request()\n self.assertRaises(webob.exc.HTTPNotFound, self.controller.delete,\n request, unit_test_utils.UUID1, 'what')\n\n def test_delete_tag_of_non_existing_image(self):\n request = unit_test_utils.get_fake_request()\n self.assertRaises(webob.exc.HTTPNotFound, self.controller.delete,\n request, \"abcd\", \"dink\")\n\nclass TestImagesSerializer(test_utils.BaseTestCase):\n\n def setUp(self):\n super(TestImagesSerializer, self).setUp()\n self.serializer = glance.api.v2.image_tags.ResponseSerializer()\n\n def test_create_tag(self):\n response = webob.Response()\n self.serializer.update(response, None)\n self.assertEqual(204, response.status_int)\n\n def test_delete_tag(self):\n response = webob.Response()\n self.serializer.delete(response, None)\n self.assertEqual(204, response.status_int)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_loader.py from reinout/django (path: tests/migrations/test_loader.py)."}, {"role": "assistant", "content": "# tests/migrations/test_loader.py (from reinout/django, license: bsd-3-clause)\n\nfrom django.db import connection, connections\nfrom django.db.migrations.exceptions import (\n AmbiguityError, InconsistentMigrationHistory, NodeNotFoundError,\n)\nfrom django.db.migrations.loader import MigrationLoader\nfrom django.db.migrations.recorder import MigrationRecorder\nfrom django.test import TestCase, modify_settings, override_settings\n\nclass RecorderTests(TestCase):\n \"\"\"\n Tests recording migrations as applied or not.\n \"\"\"\n multi_db = True\n\n def test_apply(self):\n \"\"\"\n Tests marking migrations as applied/unapplied.\n \"\"\"\n recorder = MigrationRecorder(connection)\n self.assertEqual(\n {(x, y) for (x, y) in recorder.applied_migrations() if x == \"myapp\"},\n set(),\n )\n recorder.record_applied(\"myapp\", \"0432_ponies\")\n self.assertEqual(\n {(x, y) for (x, y) in recorder.applied_migrations() if x == \"myapp\"},\n {(\"myapp\", \"0432_ponies\")},\n )\n # That should not affect records of another database\n recorder_other = MigrationRecorder(connections['other'])\n self.assertEqual(\n {(x, y) for (x, y) in recorder_other.applied_migrations() if x == \"myapp\"},\n set(),\n )\n recorder.record_unapplied(\"myapp\", \"0432_ponies\")\n self.assertEqual(\n {(x, y) for (x, y) in recorder.applied_migrations() if x == \"myapp\"},\n set(),\n )\n\nclass LoaderTests(TestCase):\n \"\"\"\n Tests the disk and database loader, and running through migrations\n in memory.\n \"\"\"\n\n @override_settings(MIGRATION_MODULES={\"migrations\": \"migrations.test_migrations\"})\n @modify_settings(INSTALLED_APPS={'append': 'basic'})\n def test_load(self):\n \"\"\"\n Makes sure the loader can load the migrations for the test apps,\n and then render them out to a new Apps.\n \"\"\"\n # Load and test the plan\n migration_loader = MigrationLoader(connection)\n self.assertEqual(\n migration_loader.graph.forwards_plan((\"migrations\", \"0002_second\")),\n [\n (\"migrations\", \"0001_initial\"),\n (\"migrations\", \"0002_second\"),\n ],\n )\n # Now render it out!\n project_state = migration_loader.project_state((\"migrations\", \"0002_second\"))\n self.assertEqual(len(project_state.models), 2)\n\n author_state = project_state.models[\"migrations\", \"author\"]\n self.assertEqual(\n [x for x, y in author_state.fields],\n [\"id\", \"name\", \"slug\", \"age\", \"rating\"]\n )\n\n book_state = project_state.models[\"migrations\", \"book\"]\n self.assertEqual(\n [x for x, y in book_state.fields],\n [\"id\", \"author\"]\n )\n\n # Ensure we've included unmigrated apps in there too\n self.assertIn(\"basic\", project_state.real_apps)\n\n @override_settings(MIGRATION_MODULES={\"migrations\": \"migrations.test_migrations_unmigdep\"})\n def test_load_unmigrated_dependency(self):\n \"\"\"\n Makes sure the loader can load migrations with a dependency on an unmigrated app.\n \"\"\"\n # Load and test the plan\n migration_loader = MigrationLoader(connection)\n self.assertEqual(\n migration_loader.graph.forwards_plan((\"migrations\", \"0001_initial\")),\n [\n ('contenttypes', '0001_initial'),\n ('auth', '0001_initial'),\n (\"migrations\", \"0001_initial\"),\n ],\n )\n # Now render it out!\n project_state = migration_loader.project_state((\"migrations\", \"0001_initial\"))\n self.assertEqual(len([m for a, m in project_state.models if a == \"migrations\"]), 1)\n\n book_state = project_state.models[\"migrations\", \"book\"]\n self.assertEqual(\n [x for x, y in book_state.fields],\n [\"id\", \"user\"]\n )\n\n @override_settings(MIGRATION_MODULES={\"migrations\": \"migrations.test_migrations_run_before\"})\n def test_run_before(self):\n \"\"\"\n Makes sure the loader uses Migration.run_before.\n \"\"\"\n # Load and test the plan\n migration_loader = MigrationLoader(connection)\n self.assertEqual(\n migration_loader.graph.forwards_plan((\"migrations\", \"0002_second\")),\n [\n (\"migrations\", \"0001_initial\"),\n (\"migrations\", \"0003_third\"),\n (\"migrations\", \"0002_second\"),\n ],\n )\n\n @override_settings(MIGRATION_MODULES={\n \"migrations\": \"migrations.test_migrations_first\",\n \"migrations2\": \"migrations2.test_migrations_2_first\",\n })\n @modify_settings(INSTALLED_APPS={'append': 'migrations2'})\n def test_first(self):\n \"\"\"\n Makes sure the '__first__' migrations build correctly.\n \"\"\"\n migration_loader = MigrationLoader(connection)\n self.assertEqual(\n migration_loader.graph.forwards_plan((\"migrations\", \"second\")),\n [\n (\"migrations\", \"thefirst\"),\n (\"migrations2\", \"0001_initial\"),\n (\"migrations2\", \"0002_second\"),\n (\"migrations\", \"second\"),\n ],\n )\n\n @override_settings(MIGRATION_MODULES={\"migrations\": \"migrations.test_migrations\"})\n def test_name_match(self):\n \"Tests prefix name matching\"\n migration_loader = MigrationLoader(connection)\n self.assertEqual(\n migration_loader.get_migration_by_prefix(\"migrations\", \"0001\").name,\n \"0001_initial\",\n )\n with self.assertRaises(AmbiguityError):\n migration_loader.get_migration_by_prefix(\"migrations\", \"0\")\n with self.assertRaises(KeyError):\n migration_loader.get_migration_by_prefix(\"migrations\", \"blarg\")\n\n def test_load_import_error(self):\n with override_settings(MIGRATION_MODULES={\"migrations\": \"import_error_package\"}):\n with self.assertRaises(ImportError):\n MigrationLoader(connection)\n\n def test_load_module_file(self):\n with override_settings(MIGRATION_MODULES={\"migrations\": \"migrations.faulty_migrations.file\"}):\n loader = MigrationLoader(connection)\n self.assertIn(\n \"migrations\", loader.unmigrated_apps,\n \"App with migrations module file not in unmigrated apps.\"\n )\n\n def test_load_empty_dir(self):\n with override_settings(MIGRATION_MODULES={\"migrations\": \"migrations.faulty_migrations.namespace\"}):\n loader = MigrationLoader(connection)\n self.assertIn(\n \"migrations\", loader.unmigrated_apps,\n \"App missing __init__.py in migrations module not in unmigrated apps.\"\n )\n\n @override_settings(\n INSTALLED_APPS=['migrations.migrations_test_apps.migrated_app'],\n )\n def test_marked_as_migrated(self):\n \"\"\"\n Undefined MIGRATION_MODULES implies default migration module.\n \"\"\"\n migration_loader = MigrationLoader(connection)\n self.assertEqual(migration_loader.migrated_apps, {'migrated_app'})\n self.assertEqual(migration_loader.unmigrated_apps, set())\n\n @override_settings(\n INSTALLED_APPS=['migrations.migrations_test_apps.migrated_app'],\n MIGRATION_MODULES={\"migrated_app\": None},\n )\n def test_marked_as_unmigrated(self):\n \"\"\"\n MIGRATION_MODULES allows disabling of migrations for a particular app.\n \"\"\"\n migration_loader = MigrationLoader(connection)\n self.assertEqual(migration_loader.migrated_apps, set())\n self.assertEqual(migration_loader.unmigrated_apps, {'migrated_app'})\n\n @override_settings(\n INSTALLED_APPS=['migrations.migrations_test_apps.migrated_app'],\n MIGRATION_MODULES={'migrated_app': 'missing-module'},\n )\n def test_explicit_missing_module(self):\n \"\"\"\n If a MIGRATION_MODULES override points to a missing module, the error\n raised during the importation attempt should be propagated unless\n `ignore_no_migrations=True`.\n \"\"\"\n with self.assertRaisesMessage(ImportError, 'missing-module'):\n migration_loader = MigrationLoader(connection)\n migration_loader = MigrationLoader(connection, ignore_no_migrations=True)\n self.assertEqual(migration_loader.migrated_apps, set())\n self.assertEqual(migration_loader.unmigrated_apps, {'migrated_app'})\n\n @override_settings(MIGRATION_MODULES={\"migrations\": \"migrations.test_migrations_squashed\"})\n def test_loading_squashed(self):\n \"Tests loading a squashed migration\"\n migration_loader = MigrationLoader(connection)\n recorder = MigrationRecorder(connection)\n self.addCleanup(recorder.flush)\n # Loading with nothing applied should just give us the one node\n self.assertEqual(\n len([x for x in migration_loader.graph.nodes if x[0] == \"migrations\"]),\n 1,\n )\n # However, fake-apply one migration and it should now use the old two\n recorder.record_applied(\"migrations\", \"0001_initial\")\n migration_loader.build_graph()\n self.assertEqual(\n len([x for x in migration_loader.graph.nodes if x[0] == \"migrations\"]),\n 2,\n )\n\n @override_settings(MIGRATION_MODULES={\"migrations\": \"migrations.test_migrations_squashed_complex\"})\n def test_loading_squashed_complex(self):\n \"Tests loading a complex set of squashed migrations\"\n\n loader = MigrationLoader(connection)\n recorder = MigrationRecorder(connection)\n self.addCleanup(recorder.flush)\n\n def num_nodes():\n plan = set(loader.graph.forwards_plan(('migrations', '7_auto')))\n return len(plan - loader.applied_migrations)\n\n # Empty database: use squashed migration\n loader.build_graph()\n self.assertEqual(num_nodes(), 5)\n\n # Starting at 1 or 2 should use the squashed migration too\n recorder.record_applied(\"migrations\", \"1_auto\")\n loader.build_graph()\n self.assertEqual(num_nodes(), 4)\n\n recorder.record_applied(\"migrations\", \"2_auto\")\n loader.build_graph()\n self.assertEqual(num_nodes(), 3)\n\n # However, starting at 3 to 5 cannot use the squashed migration\n recorder.record_applied(\"migrations\", \"3_auto\")\n loader.build_graph()\n self.assertEqual(num_nodes(), 4)\n\n recorder.record_applied(\"migrations\", \"4_auto\")\n loader.build_graph()\n self.assertEqual(num_nodes(), 3)\n\n # Starting at 5 to 7 we are passed the squashed migrations\n recorder.record_applied(\"migrations\", \"5_auto\")\n loader.build_graph()\n self.assertEqual(num_nodes(), 2)\n\n recorder.record_applied(\"migrations\", \"6_auto\")\n loader.build_graph()\n self.assertEqual(num_nodes(), 1)\n\n recorder.record_applied(\"migrations\", \"7_auto\")\n loader.build_graph()\n self.assertEqual(num_nodes(), 0)\n\n @override_settings(MIGRATION_MODULES={\n \"app1\": \"migrations.test_migrations_squashed_complex_multi_apps.app1\",\n \"app2\": \"migrations.test_migrations_squashed_complex_multi_apps.app2\",\n })\n @modify_settings(INSTALLED_APPS={'append': [\n \"migrations.test_migrations_squashed_complex_multi_apps.app1\",\n \"migrations.test_migrations_squashed_complex_multi_apps.app2\",\n ]})\n def test_loading_squashed_complex_multi_apps(self):\n loader = MigrationLoader(connection)\n loader.build_graph()\n\n plan = set(loader.graph.forwards_plan(('app1', '4_auto')))\n expected_plan = {\n ('app1', '1_auto'),\n ('app2', '1_squashed_2'),\n ('app1', '2_squashed_3'),\n ('app1', '4_auto'),\n }\n self.assertEqual(plan, expected_plan)\n\n @override_settings(MIGRATION_MODULES={\n \"app1\": \"migrations.test_migrations_squashed_complex_multi_apps.app1\",\n \"app2\": \"migrations.test_migrations_squashed_complex_multi_apps.app2\",\n })\n @modify_settings(INSTALLED_APPS={'append': [\n \"migrations.test_migrations_squashed_complex_multi_apps.app1\",\n \"migrations.test_migrations_squashed_complex_multi_apps.app2\",\n ]})\n def test_loading_squashed_complex_multi_apps_partially_applied(self):\n loader = MigrationLoader(connection)\n recorder = MigrationRecorder(connection)\n recorder.record_applied('app1', '1_auto')\n recorder.record_applied('app1', '2_auto')\n loader.build_graph()\n\n plan = set(loader.graph.forwards_plan(('app1', '4_auto')))\n plan = plan - loader.applied_migrations\n expected_plan = {\n ('app2', '1_squashed_2'),\n ('app1', '3_auto'),\n ('app1', '4_auto'),\n }\n\n self.assertEqual(plan, expected_plan)\n\n @override_settings(MIGRATION_MODULES={\"migrations\": \"migrations.test_migrations_squashed_erroneous\"})\n def test_loading_squashed_erroneous(self):\n \"Tests loading a complex but erroneous set of squashed migrations\"\n\n loader = MigrationLoader(connection)\n recorder = MigrationRecorder(connection)\n self.addCleanup(recorder.flush)\n\n def num_nodes():\n plan = set(loader.graph.forwards_plan(('migrations', '7_auto')))\n return len(plan - loader.applied_migrations)\n\n # Empty database: use squashed migration\n loader.build_graph()\n self.assertEqual(num_nodes(), 5)\n\n # Starting at 1 or 2 should use the squashed migration too\n recorder.record_applied(\"migrations\", \"1_auto\")\n loader.build_graph()\n self.assertEqual(num_nodes(), 4)\n\n recorder.record_applied(\"migrations\", \"2_auto\")\n loader.build_graph()\n self.assertEqual(num_nodes(), 3)\n\n # However, starting at 3 or 4, nonexistent migrations would be needed.\n msg = (\"Migration migrations.6_auto depends on nonexistent node ('migrations', '5_auto'). \"\n \"Django tried to replace migration migrations.5_auto with any of \"\n \"[migrations.3_squashed_5] but wasn't able to because some of the replaced \"\n \"migrations are already applied.\")\n\n recorder.record_applied(\"migrations\", \"3_auto\")\n with self.assertRaisesMessage(NodeNotFoundError, msg):\n loader.build_graph()\n\n recorder.record_applied(\"migrations\", \"4_auto\")\n with self.assertRaisesMessage(NodeNotFoundError, msg):\n loader.build_graph()\n\n # Starting at 5 to 7 we are passed the squashed migrations\n recorder.record_applied(\"migrations\", \"5_auto\")\n loader.build_graph()\n self.assertEqual(num_nodes(), 2)\n\n recorder.record_applied(\"migrations\", \"6_auto\")\n loader.build_graph()\n self.assertEqual(num_nodes(), 1)\n\n recorder.record_applied(\"migrations\", \"7_auto\")\n loader.build_graph()\n self.assertEqual(num_nodes(), 0)\n\n @override_settings(\n MIGRATION_MODULES={'migrations': 'migrations.test_migrations'},\n INSTALLED_APPS=['migrations'],\n )\n def test_check_consistent_history(self):\n loader = MigrationLoader(connection=None)\n loader.check_consistent_history(connection)\n recorder = MigrationRecorder(connection)\n recorder.record_applied('migrations', '0002_second')\n msg = (\n \"Migration migrations.0002_second is applied before its dependency \"\n \"migrations.0001_initial on database 'default'.\"\n )\n with self.assertRaisesMessage(InconsistentMigrationHistory, msg):\n loader.check_consistent_history(connection)\n\n @override_settings(\n MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed_extra'},\n INSTALLED_APPS=['migrations'],\n )\n def test_check_consistent_history_squashed(self):\n \"\"\"\n MigrationLoader.check_consistent_history() should ignore unapplied\n squashed migrations that have all of their `replaces` applied.\n \"\"\"\n loader = MigrationLoader(connection=None)\n recorder = MigrationRecorder(connection)\n recorder.record_applied('migrations', '0001_initial')\n recorder.record_applied('migrations', '0002_second')\n loader.check_consistent_history(connection)\n recorder.record_applied('migrations', '0003_third')\n loader.check_consistent_history(connection)\n\n @override_settings(MIGRATION_MODULES={\n \"app1\": \"migrations.test_migrations_squashed_ref_squashed.app1\",\n \"app2\": \"migrations.test_migrations_squashed_ref_squashed.app2\",\n })\n @modify_settings(INSTALLED_APPS={'append': [\n \"migrations.test_migrations_squashed_ref_squashed.app1\",\n \"migrations.test_migrations_squashed_ref_squashed.app2\",\n ]})\n def test_loading_squashed_ref_squashed(self):\n \"Tests loading a squashed migration with a new migration referencing it\"\n r\"\"\"\n The sample migrations are structured like this:\n\n app_1 1 --> 2 ---------------------*--> 3 *--> 4\n \\ / /\n *-------------------*----/--> 2_sq_3 --*\n \\ / /\n =============== \\ ============= / == / ======================\n app_2 *--> 1_sq_2 --* /\n \\ /\n *--> 1 --> 2 --*\n\n Where 2_sq_3 is a replacing migration for 2 and 3 in app_1,\n as 1_sq_2 is a replacing migration for 1 and 2 in app_2.\n \"\"\"\n\n loader = MigrationLoader(connection)\n recorder = MigrationRecorder(connection)\n self.addCleanup(recorder.flush)\n\n # Load with nothing applied: both migrations squashed.\n loader.build_graph()\n plan = set(loader.graph.forwards_plan(('app1', '4_auto')))\n plan = plan - loader.applied_migrations\n expected_plan = {\n ('app1', '1_auto'),\n ('app2', '1_squashed_2'),\n ('app1', '2_squashed_3'),\n ('app1', '4_auto'),\n }\n self.assertEqual(plan, expected_plan)\n\n # Fake-apply a few from app1: unsquashes migration in app1.\n recorder.record_applied('app1', '1_auto')\n recorder.record_applied('app1', '2_auto')\n loader.build_graph()\n plan = set(loader.graph.forwards_plan(('app1', '4_auto')))\n plan = plan - loader.applied_migrations\n expected_plan = {\n ('app2', '1_squashed_2'),\n ('app1', '3_auto'),\n ('app1', '4_auto'),\n }\n self.assertEqual(plan, expected_plan)\n\n # Fake-apply one from app2: unsquashes migration in app2 too.\n recorder.record_applied('app2', '1_auto')\n loader.build_graph()\n plan = set(loader.graph.forwards_plan(('app1', '4_auto')))\n plan = plan - loader.applied_migrations\n expected_plan = {\n ('app2', '2_auto'),\n ('app1', '3_auto'),\n ('app1', '4_auto'),\n }\n self.assertEqual(plan, expected_plan)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements easy_xml.py from FMCalisto/FMCalisto.github.io (path: node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py)."}, {"role": "assistant", "content": "# node_modules/node-gyp/gyp/pylib/gyp/easy_xml.py (from FMCalisto/FMCalisto.github.io, license: mit)\n\n# Copyright (c) 2011 Google Inc. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport re\nimport os\nimport locale\n\ndef XmlToString(content, encoding='utf-8', pretty=False):\n \"\"\" Writes the XML content to disk, touching the file only if it has changed.\n\n Visual Studio files have a lot of pre-defined structures. This function makes\n it easy to represent these structures as Python data structures, instead of\n having to create a lot of function calls.\n\n Each XML element of the content is represented as a list composed of:\n 1. The name of the element, a string,\n 2. The attributes of the element, a dictionary (optional), and\n 3+. The content of the element, if any. Strings are simple text nodes and\n lists are child elements.\n\n Example 1:\n \n becomes\n ['test']\n\n Example 2:\n \n This is\n it!\n \n\n becomes\n ['myelement', {'a':'value1', 'b':'value2'},\n ['childtype', 'This is'],\n ['childtype', 'it!'],\n ]\n\n Args:\n content: The structured content to be converted.\n encoding: The encoding to report on the first XML line.\n pretty: True if we want pretty printing with indents and new lines.\n\n Returns:\n The XML content as a string.\n \"\"\"\n # We create a huge list of all the elements of the file.\n xml_parts = ['' % encoding]\n if pretty:\n xml_parts.append('\\n')\n _ConstructContentList(xml_parts, content, pretty)\n\n # Convert it to a string\n return ''.join(xml_parts)\n\ndef _ConstructContentList(xml_parts, specification, pretty, level=0):\n \"\"\" Appends the XML parts corresponding to the specification.\n\n Args:\n xml_parts: A list of XML parts to be appended to.\n specification: The specification of the element. See EasyXml docs.\n pretty: True if we want pretty printing with indents and new lines.\n level: Indentation level.\n \"\"\"\n # The first item in a specification is the name of the element.\n if pretty:\n indentation = ' ' * level\n new_line = '\\n'\n else:\n indentation = ''\n new_line = ''\n name = specification[0]\n if not isinstance(name, str):\n raise Exception('The first item of an EasyXml specification should be '\n 'a string. Specification was ' + str(specification))\n xml_parts.append(indentation + '<' + name)\n\n # Optionally in second position is a dictionary of the attributes.\n rest = specification[1:]\n if rest and isinstance(rest[0], dict):\n for at, val in sorted(rest[0].iteritems()):\n xml_parts.append(' %s=\"%s\"' % (at, _XmlEscape(val, attr=True)))\n rest = rest[1:]\n if rest:\n xml_parts.append('>')\n all_strings = reduce(lambda x, y: x and isinstance(y, str), rest, True)\n multi_line = not all_strings\n if multi_line and new_line:\n xml_parts.append(new_line)\n for child_spec in rest:\n # If it's a string, append a text node.\n # Otherwise recurse over that child definition\n if isinstance(child_spec, str):\n xml_parts.append(_XmlEscape(child_spec))\n else:\n _ConstructContentList(xml_parts, child_spec, pretty, level + 1)\n if multi_line and indentation:\n xml_parts.append(indentation)\n xml_parts.append('%s' % (name, new_line))\n else:\n xml_parts.append('/>%s' % new_line)\n\ndef WriteXmlIfChanged(content, path, encoding='utf-8', pretty=False,\n win32=False):\n \"\"\" Writes the XML content to disk, touching the file only if it has changed.\n\n Args:\n content: The structured content to be written.\n path: Location of the file.\n encoding: The encoding to report on the first line of the XML file.\n pretty: True if we want pretty printing with indents and new lines.\n \"\"\"\n xml_string = XmlToString(content, encoding, pretty)\n if win32 and os.linesep != '\\r\\n':\n xml_string = xml_string.replace('\\n', '\\r\\n')\n\n default_encoding = locale.getdefaultlocale()[1]\n if default_encoding.upper() != encoding.upper():\n xml_string = xml_string.decode(default_encoding).encode(encoding)\n\n # Get the old content\n try:\n f = open(path, 'r')\n existing = f.read()\n f.close()\n except:\n existing = None\n\n # It has changed, write it\n if existing != xml_string:\n f = open(path, 'w')\n f.write(xml_string)\n f.close()\n\n_xml_escape_map = {\n '\"': '"',\n \"'\": ''',\n '<': '<',\n '>': '>',\n '&': '&',\n '\\n': ' ',\n '\\r': ' ',\n}\n\n_xml_escape_re = re.compile(\n \"(%s)\" % \"|\".join(map(re.escape, _xml_escape_map.keys())))\n\ndef _XmlEscape(value, attr=False):\n \"\"\" Escape a string for inclusion in XML.\"\"\"\n def replace(match):\n m = match.string[match.start() : match.end()]\n # don't replace single quotes in attrs\n if attr and m == \"'\":\n return m\n return _xml_escape_map[m]\n return _xml_escape_re.sub(replace, value)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements webmessage.py from jrbl/invenio (path: modules/webmessage/lib/webmessage.py)."}, {"role": "assistant", "content": "# modules/webmessage/lib/webmessage.py (from jrbl/invenio, license: gpl-2.0)\n\n# -*- coding: utf-8 -*-\n##\n## This file is part of Invenio.\n## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.\n##\n## Invenio is free software; you can redistribute it and/or\n## modify it under the terms of the GNU General Public License as\n## published by the Free Software Foundation; either version 2 of the\n## License, or (at your option) any later version.\n##\n## Invenio is distributed in the hope that it will be useful, but\n## WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n## General Public License for more details.\n##\n## You should have received a copy of the GNU General Public License\n## along with Invenio; if not, write to the Free Software Foundation, Inc.,\n## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n\n\"\"\" WebMessage module, messaging system\"\"\"\n\n__revision__ = \"$Id$\"\n\nimport invenio.webmessage_dblayer as db\nfrom invenio.webmessage_config import CFG_WEBMESSAGE_STATUS_CODE, \\\n CFG_WEBMESSAGE_RESULTS_FIELD, \\\n CFG_WEBMESSAGE_SEPARATOR, \\\n CFG_WEBMESSAGE_ROLES_WITHOUT_QUOTA, \\\n InvenioWebMessageError\nfrom invenio.config import CFG_SITE_LANG, \\\n CFG_WEBMESSAGE_MAX_SIZE_OF_MESSAGE\nfrom invenio.messages import gettext_set_language\nfrom invenio.dateutils import datetext_default, get_datetext\nfrom invenio.htmlutils import escape_html\nfrom invenio.webuser import list_users_in_roles\ntry:\n import invenio.template\n webmessage_templates = invenio.template.load('webmessage')\nexcept:\n pass\nfrom invenio.errorlib import register_exception\n\ndef perform_request_display_msg(uid, msgid, ln=CFG_SITE_LANG):\n \"\"\"\n Displays a specific message\n @param uid: user id\n @param msgid: message id\n\n @return: body\n \"\"\"\n _ = gettext_set_language(ln)\n\n body = \"\"\n\n if (db.check_user_owns_message(uid, msgid) == 0):\n # The user doesn't own this message\n try:\n raise InvenioWebMessageError(_('Sorry, this message in not in your mailbox.'))\n except InvenioWebMessageError, exc:\n register_exception()\n body = webmessage_templates.tmpl_error(exc.message, ln)\n return body\n else:\n (msg_id,\n msg_from_id, msg_from_nickname,\n msg_sent_to, msg_sent_to_group,\n msg_subject, msg_body,\n msg_sent_date, msg_received_date,\n msg_status) = db.get_message(uid, msgid)\n\n if (msg_id == \"\"):\n # The message exists in table user_msgMESSAGE\n # but not in table msgMESSAGE => table inconsistency\n try:\n raise InvenioWebMessageError(_('This message does not exist.'))\n except InvenioWebMessageError, exc:\n register_exception()\n body = webmessage_templates.tmpl_error(exc.message, ln)\n return body\n else:\n if (msg_status == CFG_WEBMESSAGE_STATUS_CODE['NEW']):\n db.set_message_status(uid, msgid,\n CFG_WEBMESSAGE_STATUS_CODE['READ'])\n body = webmessage_templates.tmpl_display_msg(\n msg_id,\n msg_from_id,\n msg_from_nickname,\n msg_sent_to,\n msg_sent_to_group,\n msg_subject,\n msg_body,\n msg_sent_date,\n msg_received_date,\n ln)\n return body\n\ndef perform_request_display(uid, warnings=[], infos=[], ln=CFG_SITE_LANG):\n \"\"\"\n Displays the user's Inbox\n @param uid: user id\n\n @return: body with warnings\n \"\"\"\n body = \"\"\n rows = []\n rows = db.get_all_messages_for_user(uid)\n nb_messages = db.count_nb_messages(uid)\n no_quota_users = list_users_in_roles(CFG_WEBMESSAGE_ROLES_WITHOUT_QUOTA)\n no_quota = False\n if uid in no_quota_users:\n no_quota = True\n body = webmessage_templates.tmpl_display_inbox(messages=rows,\n infos=infos,\n warnings=warnings,\n nb_messages=nb_messages,\n no_quota=no_quota,\n ln=ln)\n return body\n\ndef perform_request_delete_msg(uid, msgid, ln=CFG_SITE_LANG):\n \"\"\"\n Delete a given message from user inbox\n @param uid: user id (int)\n @param msgid: message id (int)\n @param ln: language\n @return: body with warnings\n \"\"\"\n _ = gettext_set_language(ln)\n\n warnings = []\n infos = []\n body = \"\"\n\n if (db.check_user_owns_message(uid, msgid) == 0):\n # The user doesn't own this message\n try:\n raise InvenioWebMessageError(_('Sorry, this message in not in your mailbox.'))\n except InvenioWebMessageError, exc:\n register_exception()\n body = webmessage_templates.tmpl_error(exc.message, ln)\n return body\n else:\n if (db.delete_message_from_user_inbox(uid, msgid) == 0):\n warnings.append(_(\"The message could not be deleted.\"))\n else:\n infos.append(_(\"The message was successfully deleted.\"))\n return perform_request_display(uid, warnings, infos, ln)\n\ndef perform_request_delete_all(uid, confirmed=False, ln=CFG_SITE_LANG):\n \"\"\"\n Delete every message for a given user\n @param uid: user id (int)\n @param confirmed: 0 will produce a confirmation message\n @param ln: language\n @return: body with warnings\n \"\"\"\n infos = []\n warnings = []\n _ = gettext_set_language(ln)\n if confirmed:\n db.delete_all_messages(uid)\n infos = [_(\"Your mailbox has been emptied.\")]\n return perform_request_display(uid, warnings, infos, ln)\n else:\n body = webmessage_templates.tmpl_confirm_delete(ln)\n return body\n\ndef perform_request_write(uid,\n msg_reply_id=\"\",\n msg_to=\"\",\n msg_to_group=\"\",\n msg_subject=\"\",\n msg_body=\"\",\n ln=CFG_SITE_LANG):\n \"\"\"\n Display a write a message page.\n\n @param uid: user id.\n @type uid: int\n @param msg_reply_id: if this message is a reply to another, other's ID.\n @type msg_reply_id: int\n @param msg_to: comma separated usernames.\n @type msg_to: string\n @param msg_to_group: comma separated groupnames.\n @type msg_to_group: string\n @param msg_subject: message subject.\n @type msg_subject: string\n @param msg_body: message body.\n @type msg_body: string\n @param ln: language.\n @type ln: string\n @return: body with warnings.\n \"\"\"\n warnings = []\n body = \"\"\n _ = gettext_set_language(ln)\n msg_from_nickname = \"\"\n msg_id = 0\n if (msg_reply_id):\n if (db.check_user_owns_message(uid, msg_reply_id) == 0):\n # The user doesn't own this message\n try:\n raise InvenioWebMessageError(_('Sorry, this message in not in your mailbox.'))\n except InvenioWebMessageError, exc:\n register_exception()\n body = webmessage_templates.tmpl_error(exc.message, ln)\n return body\n else:\n # dummy == variable name to make pylint and pychecker happy!\n (msg_id,\n msg_from_id, msg_from_nickname,\n dummy, dummy,\n msg_subject, msg_body,\n dummy, dummy, dummy) = db.get_message(uid, msg_reply_id)\n if (msg_id == \"\"):\n # The message exists in table user_msgMESSAGE\n # but not in table msgMESSAGE => table inconsistency\n try:\n raise InvenioWebMessageError(_('This message does not exist.'))\n except InvenioWebMessageError, exc:\n register_exception()\n body = webmessage_templates.tmpl_error(exc.message, ln)\n return body\n else:\n msg_to = msg_from_nickname or str(msg_from_id)\n\n body = webmessage_templates.tmpl_write(msg_to=msg_to,\n msg_to_group=msg_to_group,\n msg_id=msg_id,\n msg_subject=msg_subject,\n msg_body=msg_body,\n warnings=[],\n ln=ln)\n return body\n\ndef perform_request_write_with_search(\n uid,\n msg_to_user=\"\",\n msg_to_group=\"\",\n msg_subject=\"\",\n msg_body=\"\",\n msg_send_year=0,\n msg_send_month=0,\n msg_send_day=0,\n names_selected=[],\n search_pattern=\"\",\n results_field=CFG_WEBMESSAGE_RESULTS_FIELD['NONE'],\n add_values=0,\n ln=CFG_SITE_LANG):\n \"\"\"\n Display a write message page, with prefilled values\n @param msg_to_user: comma separated usernames (str)\n @param msg_to_group: comma separated groupnames (str)\n @param msg_subject: message subject (str)\n @param msg_bidy: message body (string)\n @param msg_send_year: year to send this message on (int)\n @param_msg_send_month: month to send this message on (int)\n @param_msg_send_day: day to send this message on (int)\n @param users_to_add: list of usernames ['str'] to add to msg_to_user\n @param groups_to_add: list of groupnames ['str'] to add to msg_to_group\n @param user_search_pattern: will search users with this pattern (str)\n @param group_search_pattern: will search groups with this pattern (str)\n @param mode_user: if 1 display user search box, else group search box\n @param add_values: if 1 users_to_add will be added to msg_to_user field..\n @param ln: language\n @return: body with warnings\n \"\"\"\n warnings = []\n search_results_list = []\n def cat_names(name1, name2):\n \"\"\" name1, name2 => 'name1, name2' \"\"\"\n return name1 + CFG_WEBMESSAGE_SEPARATOR + \" \" + name2\n\n if results_field == CFG_WEBMESSAGE_RESULTS_FIELD['USER']:\n if add_values and len(names_selected):\n usernames_to_add = reduce(cat_names, names_selected)\n if msg_to_user:\n msg_to_user = cat_names(msg_to_user, usernames_to_add)\n else:\n msg_to_user = usernames_to_add\n\n users_found = db.get_nicknames_like(search_pattern)\n if users_found:\n for user_name in users_found:\n search_results_list.append((user_name[0],\n user_name[0] in names_selected))\n\n elif results_field == CFG_WEBMESSAGE_RESULTS_FIELD['GROUP']:\n if add_values and len(names_selected):\n groupnames_to_add = reduce(cat_names, names_selected)\n if msg_to_group:\n msg_to_group = cat_names(msg_to_group, groupnames_to_add)\n else:\n msg_to_group = groupnames_to_add\n groups_dict = db.get_groupnames_like(uid, search_pattern)\n groups_found = groups_dict.values()\n if groups_found:\n for group_name in groups_found:\n search_results_list.append((group_name,\n group_name in names_selected))\n\n body = webmessage_templates.tmpl_write(\n msg_to=msg_to_user,\n msg_to_group=msg_to_group,\n msg_subject=msg_subject,\n msg_body=msg_body,\n msg_send_year=msg_send_year,\n msg_send_month=msg_send_month,\n msg_send_day=msg_send_day,\n warnings=warnings,\n search_results_list=search_results_list,\n search_pattern=search_pattern,\n results_field=results_field,\n ln=ln)\n return body\n\ndef perform_request_send(uid,\n msg_to_user=\"\",\n msg_to_group=\"\",\n msg_subject=\"\",\n msg_body=\"\",\n msg_send_year=0,\n msg_send_month=0,\n msg_send_day=0,\n ln=CFG_SITE_LANG,\n use_email_address = 0):\n \"\"\"\n send a message. if unable return warnings to write page\n @param uid: id of user from (int)\n @param msg_to_user: comma separated usernames (recipients) (str)\n @param msg_to_group: comma separated groupnames (recipeints) (str)\n @param msg_subject: subject of message (str)\n @param msg_body: body of message (str)\n @param msg_send_year: send this message on year x (int)\n @param msg_send_month: send this message on month y (int)\n @param msg_send_day: send this message on day z (int)\n @param ln: language\n @return: (body with warnings, title, navtrail)\n \"\"\"\n _ = gettext_set_language(ln)\n\n def strip_spaces(text):\n \"\"\"suppress spaces before and after x (str)\"\"\"\n return text.strip()\n # wash user input\n users_to = map(strip_spaces, msg_to_user.split(CFG_WEBMESSAGE_SEPARATOR))\n groups_to = map(strip_spaces, msg_to_group.split(CFG_WEBMESSAGE_SEPARATOR))\n\n if users_to == ['']:\n users_to = []\n if groups_to == ['']:\n groups_to = []\n\n warnings = []\n infos = []\n problem = None\n\n users_to_str = CFG_WEBMESSAGE_SEPARATOR.join(users_to)\n groups_to_str = CFG_WEBMESSAGE_SEPARATOR.join(groups_to)\n\n send_on_date = get_datetext(msg_send_year, msg_send_month, msg_send_day)\n if (msg_send_year == msg_send_month == msg_send_day == 0):\n status = CFG_WEBMESSAGE_STATUS_CODE['NEW']\n else:\n status = CFG_WEBMESSAGE_STATUS_CODE['REMINDER']\n if send_on_date == datetext_default:\n warning = \\\n _(\"The chosen date (%(x_year)i/%(x_month)i/%(x_day)i) is invalid.\")\n warning = warning % {'x_year': msg_send_year,\n 'x_month': msg_send_month,\n 'x_day': msg_send_day}\n warnings.append(warning)\n problem = True\n\n if not(users_to_str or groups_to_str):\n # <=> not(users_to_str) AND not(groups_to_str)\n warnings.append(_(\"Please enter a user name or a group name.\"))\n problem = True\n\n if len(msg_body) > CFG_WEBMESSAGE_MAX_SIZE_OF_MESSAGE:\n warnings.append(_(\"Your message is too long, please edit it. Maximum size allowed is %i characters.\") % \\\n (CFG_WEBMESSAGE_MAX_SIZE_OF_MESSAGE,))\n problem = True\n\n if use_email_address == 0:\n users_dict = db.get_uids_from_nicks(users_to)\n users_to = users_dict.items() # users_to=[(nick, uid),(nick2, uid2)]\n elif use_email_address == 1:\n users_dict = db.get_uids_from_emails(users_to)\n users_to = users_dict.items() # users_to=[(email, uid),(email2, uid2)]\n groups_dict = db.get_gids_from_groupnames(groups_to)\n groups_to = groups_dict.items()\n gids_to = []\n for (group_name, group_id) in groups_to:\n if not(group_id):\n warnings.append(_(\"Group %s does not exist.\") % \\\n (escape_html(group_name)))\n problem = 1\n else:\n gids_to.append(group_id)\n\n # Get uids from gids\n uids_from_group = db.get_uids_members_of_groups(gids_to)\n # Add the original uids, and make sure there is no double values.\n tmp_dict = {}\n for uid_receiver in uids_from_group:\n tmp_dict[uid_receiver] = None\n for (user_nick, user_id) in users_to:\n if user_id:\n if user_id not in tmp_dict:\n uids_from_group.append(user_id)\n tmp_dict[user_id] = None\n else:\n if type(user_nick) == int or \\\n type(user_nick) == str and user_nick.isdigit():\n user_nick = int(user_nick)\n if db.user_exists(user_nick) and user_nick not in tmp_dict:\n uids_from_group.append(user_nick)\n tmp_dict[user_nick] = None\n else:\n warnings.append(_(\"User %s does not exist.\")% \\\n (escape_html(user_nick)))\n problem = True\n if problem:\n body = webmessage_templates.tmpl_write(msg_to=users_to_str,\n msg_to_group=groups_to_str,\n msg_subject=msg_subject,\n msg_body=msg_body,\n msg_send_year=msg_send_year,\n msg_send_month=msg_send_month,\n msg_send_day=msg_send_day,\n warnings=warnings,\n ln=ln)\n title = _(\"Write a message\")\n navtrail = get_navtrail(ln, title)\n return (body, title, navtrail)\n else:\n msg_id = db.create_message(uid,\n users_to_str, groups_to_str,\n msg_subject, msg_body,\n send_on_date)\n uid_problem = db.send_message(uids_from_group, msg_id, status)\n if len(uid_problem) > 0:\n usernames_problem_dict = db.get_nicks_from_uids(uid_problem)\n usernames_problem = usernames_problem_dict.values()\n def listing(name1, name2):\n \"\"\" name1, name2 => 'name1, name2' \"\"\"\n return str(name1) + \", \" + str(name2)\n warning = _(\"Your message could not be sent to the following recipients due to their quota:\") + \" \"\n warnings.append(warning + reduce(listing, usernames_problem))\n\n if len(uids_from_group) != len(uid_problem):\n infos.append(_(\"Your message has been sent.\"))\n else:\n db.check_if_need_to_delete_message_permanently([msg_id])\n body = perform_request_display(uid, warnings,\n infos, ln)\n title = _(\"Your Messages\")\n return (body, title, get_navtrail(ln))\n\ndef account_new_mail(uid, ln=CFG_SITE_LANG):\n \"\"\"\n display new mail info for myaccount.py page.\n @param uid: user id (int)\n @param ln: language\n @return: html body\n \"\"\"\n nb_new_mail = db.get_nb_new_messages_for_user(uid)\n total_mail = db.get_nb_readable_messages_for_user(uid)\n return webmessage_templates.tmpl_account_new_mail(nb_new_mail,\n total_mail, ln)\n\ndef get_navtrail(ln=CFG_SITE_LANG, title=\"\"):\n \"\"\"\n gets the navtrail for title...\n @param title: title of the page\n @param ln: language\n @return: HTML output\n \"\"\"\n navtrail = webmessage_templates.tmpl_navtrail(ln, title)\n return navtrail"}]} {"messages": [{"role": "user", "content": "Write Python code that implements pamd.py from tsdmgz/ansible (path: lib/ansible/modules/system/pamd.py)."}, {"role": "assistant", "content": "# lib/ansible/modules/system/pamd.py (from tsdmgz/ansible, license: gpl-3.0)\n\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# (c) 2017, Kenneth D. Evensen \n\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\nDOCUMENTATION = \"\"\"\nmodule: pamd\nauthor:\n - \"Kenneth D. Evensen (@kevensen)\"\nshort_description: Manage PAM Modules\ndescription:\n - Edit PAM service's type, control, module path and module arguments.\n In order for a PAM rule to be modified, the type, control and\n module_path must match an existing rule. See man(5) pam.d for details.\nversion_added: \"2.3\"\noptions:\n name:\n required: true\n description:\n - The name generally refers to the PAM service file to\n change, for example system-auth.\n type:\n required: true\n description:\n - The type of the PAM rule being modified. The type, control\n and module_path all must match a rule to be modified.\n control:\n required: true\n description:\n - The control of the PAM rule being modified. This may be a\n complicated control with brackets. If this is the case, be\n sure to put \"[bracketed controls]\" in quotes. The type,\n control and module_path all must match a rule to be modified.\n module_path:\n required: true\n description:\n - The module path of the PAM rule being modified. The type,\n control and module_path all must match a rule to be modified.\n new_type:\n description:\n - The new type to assign to the new rule.\n new_control:\n description:\n - The new control to assign to the new rule.\n new_module_path:\n description:\n - The new module path to be assigned to the new rule.\n module_arguments:\n description:\n - When state is 'updated', the module_arguments will replace existing\n module_arguments. When state is 'args_absent' args matching those\n listed in module_arguments will be removed. When state is\n 'args_present' any args listed in module_arguments are added if\n missing from the existing rule. Furthermore, if the module argument\n takes a value denoted by '=', the value will be changed to that specified\n in module_arguments. Note that module_arguments is a list. Please see\n the examples for usage.\n state:\n default: updated\n choices:\n - updated\n - before\n - after\n - args_present\n - args_absent\n - absent\n description:\n - The default of 'updated' will modify an existing rule if type,\n control and module_path all match an existing rule. With 'before',\n the new rule will be inserted before a rule matching type, control\n and module_path. Similarly, with 'after', the new rule will be inserted\n after an existing rule matching type, control and module_path. With\n either 'before' or 'after' new_type, new_control, and new_module_path\n must all be specified. If state is 'args_absent' or 'args_present',\n new_type, new_control, and new_module_path will be ignored. State\n 'absent' will remove the rule. The 'absent' state was added in version\n 2.4 and is only available in Ansible versions >= 2.4.\n path:\n default: /etc/pam.d/\n description:\n - This is the path to the PAM service files\n\"\"\"\n\nEXAMPLES = \"\"\"\n- name: Update pamd rule's control in /etc/pam.d/system-auth\n pamd:\n name: system-auth\n type: auth\n control: required\n module_path: pam_faillock.so\n new_control: sufficient\n\n- name: Update pamd rule's complex control in /etc/pam.d/system-auth\n pamd:\n name: system-auth\n type: session\n control: '[success=1 default=ignore]'\n module_path: pam_succeed_if.so\n new_control: '[success=2 default=ignore]'\n\n- name: Insert a new rule before an existing rule\n pamd:\n name: system-auth\n type: auth\n control: required\n module_path: pam_faillock.so\n new_type: auth\n new_control: sufficient\n new_module_path: pam_faillock.so\n state: before\n\n- name: Insert a new rule pam_wheel.so with argument 'use_uid' after an \\\n existing rule pam_rootok.so\n pamd:\n name: su\n type: auth\n control: sufficient\n module_path: pam_rootok.so\n new_type: auth\n new_control: required\n new_module_path: pam_wheel.so\n module_arguments: 'use_uid'\n state: after\n\n- name: Remove module arguments from an existing rule\n pamd:\n name: system-auth\n type: auth\n control: required\n module_path: pam_faillock.so\n module_arguments: ''\n state: updated\n\n- name: Replace all module arguments in an existing rule\n pamd:\n name: system-auth\n type: auth\n control: required\n module_path: pam_faillock.so\n module_arguments: 'preauth\n silent\n deny=3\n unlock_time=604800\n fail_interval=900'\n state: updated\n\n- name: Remove specific arguments from a rule\n pamd:\n name: system-auth\n type: session control='[success=1 default=ignore]'\n module_path: pam_succeed_if.so\n module_arguments: crond,quiet\n state: args_absent\n\n- name: Ensure specific arguments are present in a rule\n pamd:\n name: system-auth\n type: session\n control: '[success=1 default=ignore]'\n module_path: pam_succeed_if.so\n module_arguments: crond,quiet\n state: args_present\n\n- name: Ensure specific arguments are present in a rule (alternative)\n pamd:\n name: system-auth\n type: session\n control: '[success=1 default=ignore]'\n module_path: pam_succeed_if.so\n module_arguments:\n - crond\n - quiet\n state: args_present\n\n- name: Module arguments requiring commas must be listed as a Yaml list\n pamd:\n name: special-module\n type: account\n control: required\n module_path: pam_access.so\n module_arguments:\n - listsep=,\n state: args_present\n\n- name: Update specific argument value in a rule\n pamd:\n name: system-auth\n type: auth\n control: required\n module_path: pam_faillock.so\n module_arguments: 'fail_interval=300'\n state: args_present\n\"\"\"\n\nRETURN = '''\nchange_count:\n description: How many rules were changed\n type: int\n sample: 1\n returned: success\n version_added: 2.4\nnew_rule:\n description: The changes to the rule\n type: string\n sample: None None None sha512 shadow try_first_pass use_authtok\n returned: success\n version_added: 2.4\nupdated_rule_(n):\n description: The rule(s) that was/were changed\n type: string\n sample:\n - password sufficient pam_unix.so sha512 shadow try_first_pass\n use_authtok\n returned: success\n version_added: 2.4\naction:\n description:\n - \"That action that was taken and is one of: update_rule,\n insert_before_rule, insert_after_rule, args_present, args_absent,\n absent.\"\n returned: always\n type: string\n sample: \"update_rule\"\n version_added: 2.4\ndest:\n description:\n - \"Path to pam.d service that was changed. This is only available in\n Ansible version 2.3 and was removed in 2.4.\"\n returned: success\n type: string\n sample: \"/etc/pam.d/system-auth\"\n...\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.pycompat24 import get_exception\nimport os\nimport re\nimport time\n\n# The PamdRule class encapsulates a rule in a pam.d service\nclass PamdRule(object):\n\n def __init__(self, rule_type,\n rule_control, rule_module_path,\n rule_module_args=None):\n\n self.rule_type = rule_type\n self.rule_control = rule_control\n self.rule_module_path = rule_module_path\n\n try:\n if (rule_module_args is not None and\n type(rule_module_args) is list):\n self.rule_module_args = rule_module_args\n elif (rule_module_args is not None and\n type(rule_module_args) is str):\n self.rule_module_args = rule_module_args.split()\n except AttributeError:\n self.rule_module_args = []\n\n @classmethod\n def rulefromstring(cls, stringline):\n pattern = None\n\n rule_type = ''\n rule_control = ''\n rule_module_path = ''\n rule_module_args = ''\n complicated = False\n\n if '[' in stringline:\n pattern = re.compile(\n r\"\"\"([\\-A-Za-z0-9_]+)\\s* # Rule Type\n \\[([A-Za-z0-9_=\\s]+)\\]\\s* # Rule Control\n ([A-Za-z0-9_\\-\\.]+)\\s* # Rule Path\n ([A-Za-z0-9,_=<>\\-\\s\\./]*)\"\"\", # Rule Args\n re.X)\n complicated = True\n else:\n pattern = re.compile(\n r\"\"\"([\\-A-Za-z0-9_]+)\\s* # Rule Type\n ([A-Za-z0-9_]+)\\s* # Rule Control\n ([A-Za-z0-9_\\-\\.]+)\\s* # Rule Path\n ([A-Za-z0-9,_=<>\\-\\s\\./]*)\"\"\", # Rule Args\n re.X)\n\n result = pattern.match(stringline)\n\n rule_type = result.group(1)\n if complicated:\n rule_control = '[' + result.group(2) + ']'\n else:\n rule_control = result.group(2)\n rule_module_path = result.group(3)\n if result.group(4) is not None:\n rule_module_args = result.group(4)\n\n return cls(rule_type, rule_control, rule_module_path, rule_module_args)\n\n def get_module_args_as_string(self):\n try:\n if self.rule_module_args is not None:\n return ' '.join(self.rule_module_args)\n except AttributeError:\n pass\n return ''\n\n def __str__(self):\n return \"%-10s\\t%s\\t%s %s\" % (self.rule_type,\n self.rule_control,\n self.rule_module_path,\n self.get_module_args_as_string())\n\n# PamdService encapsulates an entire service and contains one or more rules\nclass PamdService(object):\n\n def __init__(self, ansible=None):\n\n if ansible is not None:\n self.check = ansible.check_mode\n self.check = False\n self.ansible = ansible\n self.preamble = []\n self.rules = []\n self.fname = None\n if ansible is not None:\n self.path = self.ansible.params[\"path\"]\n self.name = self.ansible.params[\"name\"]\n\n def load_rules_from_file(self):\n self.fname = self.path + \"/\" + self.name\n stringline = ''\n try:\n for line in open(self.fname, 'r'):\n stringline += line.rstrip()\n stringline += '\\n'\n self.load_rules_from_string(stringline)\n\n except IOError:\n e = get_exception()\n self.ansible.fail_json(msg='Unable to open/read PAM module \\\n file %s with error %s. And line %s' %\n (self.fname, str(e), stringline))\n\n def load_rules_from_string(self, stringvalue):\n for line in stringvalue.splitlines():\n stringline = line.rstrip()\n if line.startswith('#') and not line.isspace():\n self.preamble.append(line.rstrip())\n elif (not line.startswith('#') and\n not line.isspace() and\n len(line) != 0):\n self.rules.append(PamdRule.rulefromstring(stringline))\n\n def write(self):\n if self.fname is None:\n self.fname = self.path + \"/\" + self.name\n # If the file is a symbollic link, we'll write to the source.\n pamd_file = os.path.realpath(self.fname)\n temp_file = \"/tmp/\" + self.name + \"_\" + time.strftime(\"%y%m%d%H%M%S\")\n try:\n f = open(temp_file, 'w')\n f.write(str(self))\n f.close()\n except IOError:\n self.ansible.fail_json(msg='Unable to create temporary \\\n file %s' % self.temp_file)\n\n self.ansible.atomic_move(temp_file, pamd_file)\n\n def __str__(self):\n stringvalue = ''\n previous_rule = None\n for amble in self.preamble:\n stringvalue += amble\n stringvalue += '\\n'\n\n for rule in self.rules:\n if (previous_rule is not None and\n (previous_rule.rule_type.replace('-', '') !=\n rule.rule_type.replace('-', ''))):\n stringvalue += '\\n'\n stringvalue += str(rule).rstrip()\n stringvalue += '\\n'\n previous_rule = rule\n\n if stringvalue.endswith('\\n'):\n stringvalue = stringvalue[:-1]\n\n return stringvalue\n\ndef update_rule(service, old_rule, new_rule):\n\n changed = False\n change_count = 0\n result = {'action': 'update_rule'}\n\n for rule in service.rules:\n if (old_rule.rule_type == rule.rule_type and\n old_rule.rule_control == rule.rule_control and\n old_rule.rule_module_path == rule.rule_module_path):\n\n if (new_rule.rule_type is not None and\n new_rule.rule_type != rule.rule_type):\n rule.rule_type = new_rule.rule_type\n changed = True\n if (new_rule.rule_control is not None and\n new_rule.rule_control != rule.rule_control):\n rule.rule_control = new_rule.rule_control\n changed = True\n if (new_rule.rule_module_path is not None and\n new_rule.rule_module_path != rule.rule_module_path):\n rule.rule_module_path = new_rule.rule_module_path\n changed = True\n try:\n if (new_rule.rule_module_args is not None and\n new_rule.get_module_args_as_string() !=\n rule.get_module_args_as_string()):\n rule.rule_module_args = new_rule.rule_module_args\n changed = True\n except AttributeError:\n pass\n if changed:\n result['updated_rule_' + str(change_count)] = str(rule)\n result['new_rule'] = str(new_rule)\n\n change_count += 1\n\n result['change_count'] = change_count\n return changed, result\n\ndef insert_before_rule(service, old_rule, new_rule):\n index = 0\n change_count = 0\n result = {'action':\n 'insert_before_rule'}\n changed = False\n for rule in service.rules:\n if (old_rule.rule_type == rule.rule_type and\n old_rule.rule_control == rule.rule_control and\n old_rule.rule_module_path == rule.rule_module_path):\n if index == 0:\n service.rules.insert(0, new_rule)\n changed = True\n elif (new_rule.rule_type != service.rules[index - 1].rule_type or\n new_rule.rule_control !=\n service.rules[index - 1].rule_control or\n new_rule.rule_module_path !=\n service.rules[index - 1].rule_module_path):\n service.rules.insert(index, new_rule)\n changed = True\n if changed:\n result['new_rule'] = str(new_rule)\n result['before_rule_' + str(change_count)] = str(rule)\n change_count += 1\n index += 1\n result['change_count'] = change_count\n return changed, result\n\ndef insert_after_rule(service, old_rule, new_rule):\n index = 0\n change_count = 0\n result = {'action': 'insert_after_rule'}\n changed = False\n for rule in service.rules:\n if (old_rule.rule_type == rule.rule_type and\n old_rule.rule_control == rule.rule_control and\n old_rule.rule_module_path == rule.rule_module_path):\n if (new_rule.rule_type != service.rules[index + 1].rule_type or\n new_rule.rule_control !=\n service.rules[index + 1].rule_control or\n new_rule.rule_module_path !=\n service.rules[index + 1].rule_module_path):\n service.rules.insert(index + 1, new_rule)\n changed = True\n if changed:\n result['new_rule'] = str(new_rule)\n result['after_rule_' + str(change_count)] = str(rule)\n change_count += 1\n index += 1\n\n result['change_count'] = change_count\n return changed, result\n\ndef remove_module_arguments(service, old_rule, module_args):\n result = {'action': 'args_absent'}\n changed = False\n change_count = 0\n\n for rule in service.rules:\n if (old_rule.rule_type == rule.rule_type and\n old_rule.rule_control == rule.rule_control and\n old_rule.rule_module_path == rule.rule_module_path):\n for arg_to_remove in module_args:\n for arg in rule.rule_module_args:\n if arg == arg_to_remove:\n rule.rule_module_args.remove(arg)\n changed = True\n result['removed_arg_' + str(change_count)] = arg\n result['from_rule_' + str(change_count)] = str(rule)\n change_count += 1\n\n result['change_count'] = change_count\n return changed, result\n\ndef add_module_arguments(service, old_rule, module_args):\n result = {'action': 'args_present'}\n changed = False\n change_count = 0\n\n for rule in service.rules:\n if (old_rule.rule_type == rule.rule_type and\n old_rule.rule_control == rule.rule_control and\n old_rule.rule_module_path == rule.rule_module_path):\n for arg_to_add in module_args:\n if \"=\" in arg_to_add:\n pre_string = arg_to_add[:arg_to_add.index('=') + 1]\n indicies = [i for i, arg\n in enumerate(rule.rule_module_args)\n if arg.startswith(pre_string)]\n if len(indicies) == 0:\n rule.rule_module_args.append(arg_to_add)\n changed = True\n result['added_arg_' + str(change_count)] = arg_to_add\n result['to_rule_' + str(change_count)] = str(rule)\n change_count += 1\n else:\n for i in indicies:\n if rule.rule_module_args[i] != arg_to_add:\n rule.rule_module_args[i] = arg_to_add\n changed = True\n result['updated_arg_' +\n str(change_count)] = arg_to_add\n result['in_rule_' +\n str(change_count)] = str(rule)\n change_count += 1\n elif arg_to_add not in rule.rule_module_args:\n rule.rule_module_args.append(arg_to_add)\n changed = True\n result['added_arg_' + str(change_count)] = arg_to_add\n result['to_rule_' + str(change_count)] = str(rule)\n change_count += 1\n result['change_count'] = change_count\n return changed, result\n\ndef remove_rule(service, old_rule):\n result = {'action': 'absent'}\n changed = False\n change_count = 0\n for rule in service.rules:\n if (old_rule.rule_type == rule.rule_type and\n old_rule.rule_control == rule.rule_control and\n old_rule.rule_module_path == rule.rule_module_path):\n service.rules.remove(rule)\n changed = True\n return changed, result\n\ndef main():\n\n module = AnsibleModule(\n argument_spec=dict(\n name=dict(required=True, type='str'),\n type=dict(required=True,\n choices=['account', 'auth',\n 'password', 'session']),\n control=dict(required=True, type='str'),\n module_path=dict(required=True, type='str'),\n new_type=dict(required=False,\n choices=['account', 'auth',\n 'password', 'session']),\n new_control=dict(required=False, type='str'),\n new_module_path=dict(required=False, type='str'),\n module_arguments=dict(required=False, type='list'),\n state=dict(required=False, default=\"updated\",\n choices=['before', 'after', 'updated',\n 'args_absent', 'args_present', 'absent']),\n path=dict(required=False, default='/etc/pam.d', type='str')\n ),\n supports_check_mode=True,\n required_if=[\n (\"state\", \"args_present\", [\"module_arguments\"]),\n (\"state\", \"args_absent\", [\"module_arguments\"]),\n (\"state\", \"before\", [\"new_control\"]),\n (\"state\", \"before\", [\"new_type\"]),\n (\"state\", \"before\", [\"new_module_path\"]),\n (\"state\", \"after\", [\"new_control\"]),\n (\"state\", \"after\", [\"new_type\"]),\n (\"state\", \"after\", [\"new_module_path\"])\n\n ]\n )\n\n service = module.params['name']\n old_type = module.params['type']\n old_control = module.params['control']\n old_module_path = module.params['module_path']\n\n new_type = module.params['new_type']\n new_control = module.params['new_control']\n new_module_path = module.params['new_module_path']\n\n module_arguments = module.params['module_arguments']\n state = module.params['state']\n\n path = module.params['path']\n\n pamd = PamdService(module)\n pamd.load_rules_from_file()\n\n old_rule = PamdRule(old_type,\n old_control,\n old_module_path)\n new_rule = PamdRule(new_type,\n new_control,\n new_module_path,\n module_arguments)\n\n if state == 'updated':\n change, result = update_rule(pamd,\n old_rule,\n new_rule)\n elif state == 'before':\n change, result = insert_before_rule(pamd,\n old_rule,\n new_rule)\n elif state == 'after':\n change, result = insert_after_rule(pamd,\n old_rule,\n new_rule)\n elif state == 'args_absent':\n change, result = remove_module_arguments(pamd,\n old_rule,\n module_arguments)\n elif state == 'args_present':\n change, result = add_module_arguments(pamd,\n old_rule,\n module_arguments)\n elif state == 'absent':\n change, result = remove_rule(pamd,\n old_rule)\n\n if not module.check_mode and change:\n pamd.write()\n\n facts = {}\n facts['pamd'] = {'changed': change, 'result': result}\n\n module.params['dest'] = pamd.fname\n\n module.exit_json(changed=change, ansible_facts=facts)\n\nif __name__ == '__main__':\n main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements inner_selement_waiting_search_on_actions_like_click_test.py from SergeyPirogov/selene (path: tests/integration/inner_selement_waiting_search_on_actions_like_click_test.py)."}, {"role": "assistant", "content": "# tests/integration/inner_selement_waiting_search_on_actions_like_click_test.py (from SergeyPirogov/selene, license: mit)\n\nimport pytest\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\n\nfrom selene import config\nfrom selene.common.none_object import NoneObject\nfrom selene.driver import SeleneDriver\nfrom tests.acceptance.helpers.helper import get_test_driver\nfrom tests.integration.helpers.givenpage import GivenPage\n\n__author__ = 'yashaka'\n\ndriver = NoneObject('driver') # type: SeleneDriver\nGIVEN_PAGE = NoneObject('GivenPage') # type: GivenPage\nWHEN = GIVEN_PAGE # type: GivenPage\noriginal_timeout = config.timeout\n\ndef setup_module(m):\n global driver\n driver = SeleneDriver.wrap(get_test_driver())\n global GIVEN_PAGE\n GIVEN_PAGE = GivenPage(driver)\n global WHEN\n WHEN = GIVEN_PAGE\n\ndef teardown_module(m):\n driver.quit()\n\ndef setup_function(fn):\n global original_timeout\n\ndef test_waits_for_inner_visibility():\n GIVEN_PAGE\\\n .opened_with_body(\n '''\n

\n go to Heading 2\n

Heading 2

\n

''')\\\n .execute_script_with_timeout(\n 'document.getElementsByTagName(\"a\")[0].style = \"display:block\";',\n 250)\n\n driver.element('p').element('a').click()\n assert ('second' in driver.current_url) is True\n\ndef test_waits_for_inner_presence_in_dom_and_visibility():\n GIVEN_PAGE.opened_with_body(\n '''\n

\n

Heading 2

\n

''')\n WHEN.load_body_with_timeout(\n '''\n

\n go to Heading 2\n

Heading 2

\n

''',\n 250)\n\n driver.element('p').element('a').click()\n assert ('second' in driver.current_url) is True\n\ndef test_waits_first_for_inner_presence_in_dom_then_visibility():\n GIVEN_PAGE.opened_with_body(\n '''\n

\n

Heading 2

\n

''')\n WHEN.load_body_with_timeout(\n '''\n

\n go to Heading 2\n

Heading 2

\n

''',\n 250)\\\n .execute_script_with_timeout(\n 'document.getElementsByTagName(\"a\")[0].style = \"display:block\";',\n 500)\n\n driver.element('p').element('a').click()\n assert ('second' in driver.current_url) is True\n\ndef test_waits_first_for_parent_in_dom_then_inner_in_dom_then_visibility():\n GIVEN_PAGE.opened_empty()\n WHEN.load_body_with_timeout(\n '''\n

\n

Heading 2

\n

''',\n 250)\n WHEN.load_body_with_timeout(\n '''\n

\n go to Heading 2\n

Heading 2

\n

''',\n 500)\\\n .execute_script_with_timeout(\n 'document.getElementsByTagName(\"a\")[0].style = \"display:block\";',\n 750)\n\n driver.element('p').element('a').click()\n assert ('second' in driver.current_url) is True\n\ndef test_waits_first_for_parent_in_dom_then_visible_then_inner_in_dom_then_visibility():\n GIVEN_PAGE.opened_empty()\n WHEN.load_body_with_timeout(\n '''\n

\n

Heading 2

\n

''',\n 250)\\\n .execute_script_with_timeout(\n 'document.getElementsByTagName(\"p\")[0].style = \"display:block\";',\n 500)\n WHEN.load_body_with_timeout(\n '''\n

\n go to Heading 2\n

Heading 2

\n

''',\n 750)\\\n .execute_script_with_timeout(\n 'document.getElementsByTagName(\"a\")[0].style = \"display:block\";',\n 1000)\n\n driver.element('p').element('a').click()\n assert ('second' in driver.current_url) is True\n\n# todo: there should be each such test method for each \"passing\" test from above...\ndef test_fails_on_timeout_during_waiting_for_inner_visibility():\n config.timeout = 0.25\n GIVEN_PAGE\\\n .opened_with_body(\n '''\n

\n go to Heading 2\n

Heading 2

\n

''')\\\n .execute_script_with_timeout(\n 'document.getElementsByTagName(\"a\")[0].style = \"display:block\";',\n 500)\n\n with pytest.raises(TimeoutException):\n driver.element('p').element('a').click()\n assert ('second' in driver.current_url) is False"}]} {"messages": [{"role": "user", "content": "Write Python code that implements filesystem.py from mammique/django (path: django/template/loaders/filesystem.py)."}, {"role": "assistant", "content": "# django/template/loaders/filesystem.py (from mammique/django, license: bsd-3-clause)\n\n\"\"\"\nWrapper for loading templates from the filesystem.\n\"\"\"\n\nfrom django.conf import settings\nfrom django.template.base import TemplateDoesNotExist\nfrom django.template.loader import BaseLoader\nfrom django.utils._os import safe_join\n\nclass Loader(BaseLoader):\n is_usable = True\n\n def get_template_sources(self, template_name, template_dirs=None):\n \"\"\"\n Returns the absolute paths to \"template_name\", when appended to each\n directory in \"template_dirs\". Any paths that don't lie inside one of the\n template dirs are excluded from the result set, for security reasons.\n \"\"\"\n if not template_dirs:\n template_dirs = settings.TEMPLATE_DIRS\n for template_dir in template_dirs:\n try:\n yield safe_join(template_dir, template_name)\n except UnicodeDecodeError:\n # The template dir name was a bytestring that wasn't valid UTF-8.\n raise\n except ValueError:\n # The joined path was located outside of this particular\n # template_dir (it might be inside another one, so this isn't\n # fatal).\n pass\n\n def load_template_source(self, template_name, template_dirs=None):\n tried = []\n for filepath in self.get_template_sources(template_name, template_dirs):\n try:\n with open(filepath, 'rb') as fp:\n return (fp.read().decode(settings.FILE_CHARSET), filepath)\n except IOError:\n tried.append(filepath)\n if tried:\n error_msg = \"Tried %s\" % tried\n else:\n error_msg = \"Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory.\"\n raise TemplateDoesNotExist(error_msg)\n load_template_source.is_usable = True"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_program.py from 40223245/2015cdb_g6-team1 (path: static/Brython3.1.1-20150328-091302/Lib/unittest/test/test_program.py)."}, {"role": "assistant", "content": "# static/Brython3.1.1-20150328-091302/Lib/unittest/test/test_program.py (from 40223245/2015cdb_g6-team1, license: gpl-3.0)\n\nimport io\n\nimport os\nimport sys\nimport unittest\n\nclass Test_TestProgram(unittest.TestCase):\n\n def test_discovery_from_dotted_path(self):\n loader = unittest.TestLoader()\n\n tests = [self]\n expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__))\n\n self.wasRun = False\n def _find_tests(start_dir, pattern):\n self.wasRun = True\n self.assertEqual(start_dir, expectedPath)\n return tests\n loader._find_tests = _find_tests\n suite = loader.discover('unittest.test')\n self.assertTrue(self.wasRun)\n self.assertEqual(suite._tests, tests)\n\n # Horrible white box test\n def testNoExit(self):\n result = object()\n test = object()\n\n class FakeRunner(object):\n def run(self, test):\n self.test = test\n return result\n\n runner = FakeRunner()\n\n oldParseArgs = unittest.TestProgram.parseArgs\n def restoreParseArgs():\n unittest.TestProgram.parseArgs = oldParseArgs\n unittest.TestProgram.parseArgs = lambda *args: None\n self.addCleanup(restoreParseArgs)\n\n def removeTest():\n del unittest.TestProgram.test\n unittest.TestProgram.test = test\n self.addCleanup(removeTest)\n\n program = unittest.TestProgram(testRunner=runner, exit=False, verbosity=2)\n\n self.assertEqual(program.result, result)\n self.assertEqual(runner.test, test)\n self.assertEqual(program.verbosity, 2)\n\n class FooBar(unittest.TestCase):\n def testPass(self):\n assert True\n def testFail(self):\n assert False\n\n class FooBarLoader(unittest.TestLoader):\n \"\"\"Test loader that returns a suite containing FooBar.\"\"\"\n def loadTestsFromModule(self, module):\n return self.suiteClass(\n [self.loadTestsFromTestCase(Test_TestProgram.FooBar)])\n\n def test_NonExit(self):\n program = unittest.main(exit=False,\n argv=[\"foobar\"],\n testRunner=unittest.TextTestRunner(stream=io.StringIO()),\n testLoader=self.FooBarLoader())\n self.assertTrue(hasattr(program, 'result'))\n\n def test_Exit(self):\n self.assertRaises(\n SystemExit,\n unittest.main,\n argv=[\"foobar\"],\n testRunner=unittest.TextTestRunner(stream=io.StringIO()),\n exit=True,\n testLoader=self.FooBarLoader())\n\n def test_ExitAsDefault(self):\n self.assertRaises(\n SystemExit,\n unittest.main,\n argv=[\"foobar\"],\n testRunner=unittest.TextTestRunner(stream=io.StringIO()),\n testLoader=self.FooBarLoader())\n\nclass InitialisableProgram(unittest.TestProgram):\n exit = False\n result = None\n verbosity = 1\n defaultTest = None\n testRunner = None\n testLoader = unittest.defaultTestLoader\n module = '__main__'\n progName = 'test'\n test = 'test'\n def __init__(self, *args):\n pass\n\nRESULT = object()\n\nclass FakeRunner(object):\n initArgs = None\n test = None\n raiseError = False\n\n def __init__(self, **kwargs):\n FakeRunner.initArgs = kwargs\n if FakeRunner.raiseError:\n FakeRunner.raiseError = False\n raise TypeError\n\n def run(self, test):\n FakeRunner.test = test\n return RESULT\n\nclass TestCommandLineArgs(unittest.TestCase):\n\n def setUp(self):\n self.program = InitialisableProgram()\n self.program.createTests = lambda: None\n FakeRunner.initArgs = None\n FakeRunner.test = None\n FakeRunner.raiseError = False\n\n def testVerbosity(self):\n program = self.program\n\n for opt in '-q', '--quiet':\n program.verbosity = 1\n program.parseArgs([None, opt])\n self.assertEqual(program.verbosity, 0)\n\n for opt in '-v', '--verbose':\n program.verbosity = 1\n program.parseArgs([None, opt])\n self.assertEqual(program.verbosity, 2)\n\n def testBufferCatchFailfast(self):\n program = self.program\n for arg, attr in (('buffer', 'buffer'), ('failfast', 'failfast'),\n ('catch', 'catchbreak')):\n if attr == 'catch' and not hasInstallHandler:\n continue\n\n short_opt = '-%s' % arg[0]\n long_opt = '--%s' % arg\n for opt in short_opt, long_opt:\n setattr(program, attr, None)\n\n program.parseArgs([None, opt])\n self.assertTrue(getattr(program, attr))\n\n for opt in short_opt, long_opt:\n not_none = object()\n setattr(program, attr, not_none)\n\n program.parseArgs([None, opt])\n self.assertEqual(getattr(program, attr), not_none)\n\n def testWarning(self):\n \"\"\"Test the warnings argument\"\"\"\n # see #10535\n class FakeTP(unittest.TestProgram):\n def parseArgs(self, *args, **kw): pass\n def runTests(self, *args, **kw): pass\n warnoptions = sys.warnoptions[:]\n try:\n sys.warnoptions[:] = []\n # no warn options, no arg -> default\n self.assertEqual(FakeTP().warnings, 'default')\n # no warn options, w/ arg -> arg value\n self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore')\n sys.warnoptions[:] = ['somevalue']\n # warn options, no arg -> None\n # warn options, w/ arg -> arg value\n self.assertEqual(FakeTP().warnings, None)\n self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore')\n finally:\n sys.warnoptions[:] = warnoptions\n\n def testRunTestsRunnerClass(self):\n program = self.program\n\n program.testRunner = FakeRunner\n program.verbosity = 'verbosity'\n program.failfast = 'failfast'\n program.buffer = 'buffer'\n program.warnings = 'warnings'\n\n program.runTests()\n\n self.assertEqual(FakeRunner.initArgs, {'verbosity': 'verbosity',\n 'failfast': 'failfast',\n 'buffer': 'buffer',\n 'warnings': 'warnings'})\n self.assertEqual(FakeRunner.test, 'test')\n self.assertIs(program.result, RESULT)\n\n def testRunTestsRunnerInstance(self):\n program = self.program\n\n program.testRunner = FakeRunner()\n FakeRunner.initArgs = None\n\n program.runTests()\n\n # A new FakeRunner should not have been instantiated\n self.assertIsNone(FakeRunner.initArgs)\n\n self.assertEqual(FakeRunner.test, 'test')\n self.assertIs(program.result, RESULT)\n\n def testRunTestsOldRunnerClass(self):\n program = self.program\n\n FakeRunner.raiseError = True\n program.testRunner = FakeRunner\n program.verbosity = 'verbosity'\n program.failfast = 'failfast'\n program.buffer = 'buffer'\n program.test = 'test'\n\n program.runTests()\n\n # If initialising raises a type error it should be retried\n # without the new keyword arguments\n self.assertEqual(FakeRunner.initArgs, {})\n self.assertEqual(FakeRunner.test, 'test')\n self.assertIs(program.result, RESULT)\n\n def testCatchBreakInstallsHandler(self):\n module = sys.modules['unittest.main']\n original = module.installHandler\n def restore():\n module.installHandler = original\n self.addCleanup(restore)\n\n self.installed = False\n def fakeInstallHandler():\n self.installed = True\n module.installHandler = fakeInstallHandler\n\n program = self.program\n program.catchbreak = True\n\n program.testRunner = FakeRunner\n\n program.runTests()\n self.assertTrue(self.installed)\n\n def _patch_isfile(self, names, exists=True):\n def isfile(path):\n return path in names\n original = os.path.isfile\n os.path.isfile = isfile\n def restore():\n os.path.isfile = original\n self.addCleanup(restore)\n\n def testParseArgsFileNames(self):\n # running tests with filenames instead of module names\n program = self.program\n argv = ['progname', 'foo.py', 'bar.Py', 'baz.PY', 'wing.txt']\n self._patch_isfile(argv)\n\n program.createTests = lambda: None\n program.parseArgs(argv)\n\n # note that 'wing.txt' is not a Python file so the name should\n # *not* be converted to a module name\n expected = ['foo', 'bar', 'baz', 'wing.txt']\n self.assertEqual(program.testNames, expected)\n\n def testParseArgsFilePaths(self):\n program = self.program\n argv = ['progname', 'foo/bar/baz.py', 'green\\\\red.py']\n self._patch_isfile(argv)\n\n program.createTests = lambda: None\n program.parseArgs(argv)\n\n expected = ['foo.bar.baz', 'green.red']\n self.assertEqual(program.testNames, expected)\n\n def testParseArgsNonExistentFiles(self):\n program = self.program\n argv = ['progname', 'foo/bar/baz.py', 'green\\\\red.py']\n self._patch_isfile([])\n\n program.createTests = lambda: None\n program.parseArgs(argv)\n\n self.assertEqual(program.testNames, argv[1:])\n\n def testParseArgsAbsolutePathsThatCanBeConverted(self):\n cur_dir = os.getcwd()\n program = self.program\n def _join(name):\n return os.path.join(cur_dir, name)\n argv = ['progname', _join('foo/bar/baz.py'), _join('green\\\\red.py')]\n self._patch_isfile(argv)\n\n program.createTests = lambda: None\n program.parseArgs(argv)\n\n expected = ['foo.bar.baz', 'green.red']\n self.assertEqual(program.testNames, expected)\n\n def testParseArgsAbsolutePathsThatCannotBeConverted(self):\n program = self.program\n # even on Windows '/...' is considered absolute by os.path.abspath\n argv = ['progname', '/foo/bar/baz.py', '/green/red.py']\n self._patch_isfile(argv)\n\n program.createTests = lambda: None\n program.parseArgs(argv)\n\n self.assertEqual(program.testNames, argv[1:])\n\n # it may be better to use platform specific functions to normalise paths\n # rather than accepting '.PY' and '\\' as file seprator on Linux / Mac\n # it would also be better to check that a filename is a valid module\n # identifier (we have a regex for this in loader.py)\n # for invalid filenames should we raise a useful error rather than\n # leaving the current error message (import of filename fails) in place?\n\nif __name__ == '__main__':\n unittest.main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements model.py from awatts/boto (path: boto/sdb/db/model.py)."}, {"role": "assistant", "content": "# boto/sdb/db/model.py (from awatts/boto, license: mit)\n\n# Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish, dis-\n# tribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the fol-\n# lowing conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-\n# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n\nfrom boto.sdb.db.property import Property\nfrom boto.sdb.db.key import Key\nfrom boto.sdb.db.query import Query\nimport boto\nfrom boto.compat import filter\n\nclass ModelMeta(type):\n \"Metaclass for all Models\"\n\n def __init__(cls, name, bases, dict):\n super(ModelMeta, cls).__init__(name, bases, dict)\n # Make sure this is a subclass of Model - mainly copied from django ModelBase (thanks!)\n cls.__sub_classes__ = []\n\n # Do a delayed import to prevent possible circular import errors.\n from boto.sdb.db.manager import get_manager\n\n try:\n if filter(lambda b: issubclass(b, Model), bases):\n for base in bases:\n base.__sub_classes__.append(cls)\n cls._manager = get_manager(cls)\n # look for all of the Properties and set their names\n for key in dict.keys():\n if isinstance(dict[key], Property):\n property = dict[key]\n property.__property_config__(cls, key)\n prop_names = []\n props = cls.properties()\n for prop in props:\n if not prop.__class__.__name__.startswith('_'):\n prop_names.append(prop.name)\n setattr(cls, '_prop_names', prop_names)\n except NameError:\n # 'Model' isn't defined yet, meaning we're looking at our own\n # Model class, defined below.\n pass\n\nclass Model(object):\n __metaclass__ = ModelMeta\n __consistent__ = False # Consistent is set off by default\n id = None\n\n @classmethod\n def get_lineage(cls):\n l = [c.__name__ for c in cls.mro()]\n l.reverse()\n return '.'.join(l)\n\n @classmethod\n def kind(cls):\n return cls.__name__\n\n @classmethod\n def _get_by_id(cls, id, manager=None):\n if not manager:\n manager = cls._manager\n return manager.get_object(cls, id)\n\n @classmethod\n def get_by_id(cls, ids=None, parent=None):\n if isinstance(ids, list):\n objs = [cls._get_by_id(id) for id in ids]\n return objs\n else:\n return cls._get_by_id(ids)\n\n get_by_ids = get_by_id\n\n @classmethod\n def get_by_key_name(cls, key_names, parent=None):\n raise NotImplementedError(\"Key Names are not currently supported\")\n\n @classmethod\n def find(cls, limit=None, next_token=None, **params):\n q = Query(cls, limit=limit, next_token=next_token)\n for key, value in params.items():\n q.filter('%s =' % key, value)\n return q\n\n @classmethod\n def all(cls, limit=None, next_token=None):\n return cls.find(limit=limit, next_token=next_token)\n\n @classmethod\n def get_or_insert(key_name, **kw):\n raise NotImplementedError(\"get_or_insert not currently supported\")\n\n @classmethod\n def properties(cls, hidden=True):\n properties = []\n while cls:\n for key in cls.__dict__.keys():\n prop = cls.__dict__[key]\n if isinstance(prop, Property):\n if hidden or not prop.__class__.__name__.startswith('_'):\n properties.append(prop)\n if len(cls.__bases__) > 0:\n cls = cls.__bases__[0]\n else:\n cls = None\n return properties\n\n @classmethod\n def find_property(cls, prop_name):\n property = None\n while cls:\n for key in cls.__dict__.keys():\n prop = cls.__dict__[key]\n if isinstance(prop, Property):\n if not prop.__class__.__name__.startswith('_') and prop_name == prop.name:\n property = prop\n if len(cls.__bases__) > 0:\n cls = cls.__bases__[0]\n else:\n cls = None\n return property\n\n @classmethod\n def get_xmlmanager(cls):\n if not hasattr(cls, '_xmlmanager'):\n from boto.sdb.db.manager.xmlmanager import XMLManager\n cls._xmlmanager = XMLManager(cls, None, None, None,\n None, None, None, None, False)\n return cls._xmlmanager\n\n @classmethod\n def from_xml(cls, fp):\n xmlmanager = cls.get_xmlmanager()\n return xmlmanager.unmarshal_object(fp)\n\n def __init__(self, id=None, **kw):\n self._loaded = False\n # first try to initialize all properties to their default values\n for prop in self.properties(hidden=False):\n try:\n setattr(self, prop.name, prop.default_value())\n except ValueError:\n pass\n if 'manager' in kw:\n self._manager = kw['manager']\n self.id = id\n for key in kw:\n if key != 'manager':\n # We don't want any errors populating up when loading an object,\n # so if it fails we just revert to it's default value\n try:\n setattr(self, key, kw[key])\n except Exception as e:\n boto.log.exception(e)\n\n def __repr__(self):\n return '%s<%s>' % (self.__class__.__name__, self.id)\n\n def __str__(self):\n return str(self.id)\n\n def __eq__(self, other):\n return other and isinstance(other, Model) and self.id == other.id\n\n def _get_raw_item(self):\n return self._manager.get_raw_item(self)\n\n def load(self):\n if self.id and not self._loaded:\n self._manager.load_object(self)\n\n def reload(self):\n if self.id:\n self._loaded = False\n self._manager.load_object(self)\n\n def put(self, expected_value=None):\n \"\"\"\n Save this object as it is, with an optional expected value\n\n :param expected_value: Optional tuple of Attribute, and Value that\n must be the same in order to save this object. If this\n condition is not met, an SDBResponseError will be raised with a\n Confict status code.\n :type expected_value: tuple or list\n :return: This object\n :rtype: :class:`boto.sdb.db.model.Model`\n \"\"\"\n self._manager.save_object(self, expected_value)\n return self\n\n save = put\n\n def put_attributes(self, attrs):\n \"\"\"\n Save just these few attributes, not the whole object\n\n :param attrs: Attributes to save, key->value dict\n :type attrs: dict\n :return: self\n :rtype: :class:`boto.sdb.db.model.Model`\n \"\"\"\n assert(isinstance(attrs, dict)), \"Argument must be a dict of key->values to save\"\n for prop_name in attrs:\n value = attrs[prop_name]\n prop = self.find_property(prop_name)\n assert(prop), \"Property not found: %s\" % prop_name\n self._manager.set_property(prop, self, prop_name, value)\n self.reload()\n return self\n\n def delete_attributes(self, attrs):\n \"\"\"\n Delete just these attributes, not the whole object.\n\n :param attrs: Attributes to save, as a list of string names\n :type attrs: list\n :return: self\n :rtype: :class:`boto.sdb.db.model.Model`\n \"\"\"\n assert(isinstance(attrs, list)), \"Argument must be a list of names of keys to delete.\"\n self._manager.domain.delete_attributes(self.id, attrs)\n self.reload()\n return self\n\n save_attributes = put_attributes\n\n def delete(self):\n self._manager.delete_object(self)\n\n def key(self):\n return Key(obj=self)\n\n def set_manager(self, manager):\n self._manager = manager\n\n def to_dict(self):\n props = {}\n for prop in self.properties(hidden=False):\n props[prop.name] = getattr(self, prop.name)\n obj = {'properties': props,\n 'id': self.id}\n return {self.__class__.__name__: obj}\n\n def to_xml(self, doc=None):\n xmlmanager = self.get_xmlmanager()\n doc = xmlmanager.marshal_object(self, doc)\n return doc\n\n @classmethod\n def find_subclass(cls, name):\n \"\"\"Find a subclass with a given name\"\"\"\n if name == cls.__name__:\n return cls\n for sc in cls.__sub_classes__:\n r = sc.find_subclass(name)\n if r is not None:\n return r\n\nclass Expando(Model):\n\n def __setattr__(self, name, value):\n if name in self._prop_names:\n object.__setattr__(self, name, value)\n elif name.startswith('_'):\n object.__setattr__(self, name, value)\n elif name == 'id':\n object.__setattr__(self, name, value)\n else:\n self._manager.set_key_value(self, name, value)\n object.__setattr__(self, name, value)\n\n def __getattr__(self, name):\n if not name.startswith('_'):\n value = self._manager.get_key_value(self, name)\n if value:\n object.__setattr__(self, name, value)\n return value\n raise AttributeError"}]} {"messages": [{"role": "user", "content": "Write Python code that implements models.py from liberation/django-elasticsearch (path: test_project/test_app/models.py)."}, {"role": "assistant", "content": "# test_project/test_app/models.py (from liberation/django-elasticsearch, license: mit)\n\nfrom datetime import datetime\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nfrom django_elasticsearch.models import EsIndexable\nfrom django_elasticsearch.serializers import EsJsonSerializer\n\nclass TestSerializer(EsJsonSerializer):\n # Note: i want this field to be null instead of u''\n def serialize_email(self, instance, field_name):\n val = getattr(instance, field_name)\n if val == u'':\n return None\n return val\n\n def serialize_date_joined_exp(self, instance, field_name):\n # abstract\n return {'iso': instance.date_joined.isoformat(),\n 'timestamp': instance.date_joined.strftime('%s.%f')}\n\nclass TestModel(User, EsIndexable):\n class Elasticsearch(EsIndexable.Elasticsearch):\n index = 'django-test'\n doc_type = 'test-doc-type'\n mappings = {\n \"username\": {\"index\": \"not_analyzed\"},\n \"date_joined_exp\": {\"type\": \"object\"}\n }\n serializer_class = TestSerializer\n\n class Meta:\n proxy = True\n ordering = ('id',)\n\nclass Dummy(models.Model):\n foo = models.CharField(max_length=256, null=True)\n\nclass Test2Serializer(EsJsonSerializer):\n def serialize_type_datetimefield(self, instance, field_name):\n d = getattr(instance, field_name)\n # a rather typical api output\n return {\n 'iso': d and d.isoformat(),\n 'date': d and d.date().isoformat(),\n 'time': d and d.time().isoformat()[:5]\n }\n\n def deserialize_type_datetimefield(self, instance, field_name):\n return datetime.strptime(instance.get(field_name)['iso'],\n '%Y-%m-%dT%H:%M:%S.%f')\n\n def serialize_abstract_method(self, instance, field_name):\n return 'woot'\n\n def serialize_bigint(self, instance, field_name):\n return 42\n\n def deserialize_bigint(self, source, field_name):\n return 45\n\nclass Test2Model(EsIndexable):\n # string\n char = models.CharField(max_length=256, null=True)\n text = models.TextField(null=True)\n email = models.EmailField(null=True)\n filef = models.FileField(null=True, upload_to='f/')\n # img = models.ImageField(null=True) # would need pillow\n filepf = models.FilePathField(null=True)\n ipaddr = models.IPAddressField(null=True)\n genipaddr = models.GenericIPAddressField(null=True)\n slug = models.SlugField(null=True)\n url = models.URLField(null=True)\n\n # numeric\n intf = models.IntegerField(null=True)\n bigint = models.BigIntegerField(null=True)\n intlist = models.CommaSeparatedIntegerField(max_length=256, null=True)\n floatf = models.FloatField(null=True)\n dec = models.DecimalField(max_digits=5, decimal_places=2, null=True)\n posint = models.PositiveIntegerField(null=True)\n smint = models.SmallIntegerField(null=True)\n possmint = models.PositiveSmallIntegerField(null=True)\n\n # dj1.8\n # binary = models.BinaryField()\n\n # bool\n boolf = models.BooleanField(null=False, default=True)\n nullboolf = models.NullBooleanField(null=True)\n\n # datetime\n datef = models.DateField(null=True)\n datetf = models.DateTimeField(null=True, auto_now_add=True)\n timef = models.TimeField(null=True)\n\n # related\n fk = models.ForeignKey(Dummy, null=True, related_name=\"tofk\")\n oto = models.OneToOneField(Dummy, null=True, related_name=\"toto\")\n fkself = models.ForeignKey('self', null=True, related_name=\"toselffk\") # a bit of a special case\n mtm = models.ManyToManyField(Dummy, related_name=\"tomtm\")\n\n class Elasticsearch(EsIndexable.Elasticsearch):\n index = 'django-test'\n doc_type = 'test-doc-type'\n serializer_class = Test2Serializer\n # Note: we need to specify this field since the value returned\n # by the serializer does not correspond to it's default mapping\n # see: Test2Serializer.serialize_type_datetimefield\n mappings = {'datetf': {'type': 'object'}}\n\n @property\n def abstract_prop(self):\n return 'weez'"}]} {"messages": [{"role": "user", "content": "Write Python code that implements bug606981_test.py from linjk/mysql-5.6 (path: xtrabackup/test/kewpie/percona_tests/xtrabackup_disabled/bug606981_test.py)."}, {"role": "assistant", "content": "# xtrabackup/test/kewpie/percona_tests/xtrabackup_disabled/bug606981_test.py (from linjk/mysql-5.6, license: gpl-2.0)\n\n#! /usr/bin/env python\n# -*- mode: python; indent-tabs-mode: nil; -*-\n# vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n#\n# Copyright (C) 2011 Patrick Crews\n#\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport os\nimport shutil\nimport tarfile\n\nfrom lib.util.mysqlBaseTestCase import mysqlBaseTestCase\n\nserver_requirements = [[]]\nservers = []\nserver_manager = None\ntest_executor = None\n# we explicitly use the --no-timestamp option\n# here. We will be using a generic / vanilla backup dir\nbackup_path = None\n\nclass basicTest(mysqlBaseTestCase):\n\n def setUp(self):\n master_server = servers[0] # assumption that this is 'master'\n backup_path = os.path.join(master_server.vardir, '_xtrabackup')\n # remove backup paths\n for del_path in [backup_path]:\n if os.path.exists(del_path):\n shutil.rmtree(del_path)\n\n def test_ib_stream(self):\n self.servers = servers\n innobackupex = test_executor.system_manager.innobackupex_path\n xtrabackup = test_executor.system_manager.xtrabackup_path\n master_server = servers[0] # assumption that this is 'master'\n backup_path = os.path.join(master_server.vardir, '_xtrabackup')\n tar_file_path = os.path.join(backup_path,'out.tar')\n output_path = os.path.join(master_server.vardir, 'innobackupex.out')\n exec_path = os.path.dirname(innobackupex)\n\n # populate our server with a test bed\n test_cmd = \"./gentest.pl --gendata=conf/percona/percona.zz\"\n retcode, output = self.execute_randgen(test_cmd, test_executor, master_server)\n\n # Add desired option to config file\n config_file = open(master_server.cnf_file,'a')\n config_file.write(\"innodb_flush_method=O_DIRECT\\n\")\n config_file.close()\n \n # take a backup\n try:\n os.mkdir(backup_path)\n except OSError: \n pass\n cmd = [ innobackupex\n , \"--defaults-file=%s\" %master_server.cnf_file\n , \"--stream=tar\"\n , \"--user=root\"\n , \"--port=%d\" %master_server.master_port\n , \"--host=127.0.0.1\"\n , \"--no-timestamp\"\n , \"--ibbackup=%s\" %xtrabackup\n , \"%s > %s\" %(backup_path,tar_file_path)\n ]\n cmd = \" \".join(cmd)\n retcode, output = self.execute_cmd(cmd, output_path, exec_path, True)\n self.assertTrue(retcode==0,output)\n expected_output = \"xtrabackup: using O_DIRECT\"\n self.assertTrue(expected_output in output, msg=output)\n\n # stop the server\n master_server.stop()\n \n # extract our backup tarball\n cmd = \"tar -ivxf %s\" %tar_file_path\n retcode, output = self.execute_cmd(cmd, output_path, backup_path, True)\n self.assertEqual(retcode,0,output) \n # Check for Bug 723318 - seems quicker than separate test case\n self.assertTrue('xtrabackup_binary' in os.listdir(backup_path)\n , msg = \"Bug723318: xtrabackup_binary not included in tar archive when streaming\")\n\n # do prepare on backup\n cmd = [ innobackupex\n , \"--apply-log\"\n , \"--no-timestamp\"\n , \"--use-memory=500M\"\n , \"--ibbackup=%s\" %xtrabackup\n , backup_path\n ]\n cmd = \" \".join(cmd)\n retcode, output = self.execute_cmd(cmd, output_path, exec_path, True)\n self.assertEqual(retcode,0,output)\n\n # remove old datadir\n shutil.rmtree(master_server.datadir)\n os.mkdir(master_server.datadir)\n \n # restore from backup\n cmd = [ innobackupex\n , \"--defaults-file=%s\" %master_server.cnf_file\n , \"--copy-back\"\n , \"--ibbackup=%s\" %(xtrabackup)\n , backup_path\n ]\n cmd = \" \".join(cmd)\n retcode, output = self.execute_cmd(cmd, output_path, exec_path, True)\n self.assertEqual(retcode,0, output)\n\n # restart server (and ensure it doesn't crash)\n master_server.start()\n self.assertEqual(master_server.status,1, 'Server failed restart from restored datadir...')\n \n # Check the server is ok\n query = \"SELECT COUNT(*) FROM test.DD\"\n expected_output = ((100L,),) \n retcode, output = self.execute_query(query, master_server)\n self.assertEqual(output, expected_output, msg = \"%s || %s\" %(output, expected_output))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements gen_settings_html.py from ofanoyi/sumatrapdf (path: scripts/gen_settings_html.py)."}, {"role": "assistant", "content": "# scripts/gen_settings_html.py (from ofanoyi/sumatrapdf, license: gpl-3.0)\n\n#!/usr/bin/env python\n\nimport os, util2, gen_settingsstructs, trans_langs\n\n\"\"\"\nTODO:\n * for gen_langs_html, show languages that don't have enough translations\n in a separate table\n\"\"\"\n\ng_version = util2.get_sumatrapdf_version()\n\nhtml_tmpl = \"\"\"\\\n\n\n\n\n\nCustomizing SumatraPDF\n\n\n\n\n\n
\n\n

Customizing SumatraPDF

\n\n

You can change the look and behavior of\nSumatraPDF\nby editing the file SumatraPDF-settings.txt. The file is stored in\n%APPDATA%\\SumatraPDF directory for the installed version or in the\nsame directory as SumatraPDF.exe executable for the portable version.

\n\n

Use the menu item Settings -> Advanced Settings... to open the settings file\nwith your default text editor.

\n\n

The file is in a simple text format. Below is an explanation of\nwhat the different settings mean and what their default values are.

\n\n

Highlighted settings can't be changed from the UI. Modifying other settings\ndirectly in this file is not recommended.

\n\n

If you add or remove lines with square brackets, make sure to always add/remove\nsquare brackets in pairs! Else you risk losing all the data following them.

\n\n
\n\n
\n%INSIDE%\n
\n\n
\n

Syntax for color values

\n\n

\nThe syntax for colors is: #rrggbb.

\n

The components are hex values (ranging from 00 to FF) and stand for:\n

    \n
  • rr : red component
  • \n
  • gg : green component
  • \n
  • bb : blue component
  • \n
\nFor example #ff0000 means red color. You can use \nColor Picker or Sphere or\nColorScheme Designer to pick a color.\n

\n
\n\n\n\n\"\"\"\n\nlangs_html_tmpl = \"\"\"\\\n\n\n\n\n\nLanguages supported by SumatraPDF\n\n\n\n\n\n

Languages supported by SumatraPDF

\n\n

Languages supported by SumatraPDF. You can use ISO code as a value\nof UiLanguage setting in settings file.\n

\n\n

Note: not all languages are fully translated. Help us translate SumatraPDF.

\n\n\n\n%INSIDE%\n
Language nameISO code
\n\n\n\n\"\"\"\n\n#indent_str = \"  \"\nindent_str = \" \"\n\n# if s in the form: \"foo](bar.html)\", returns [\"foo\", \"bar.html\"].\n# otherwise returns [\"foo\"]\ndef extract_url(s):\n if not s.endswith(\")\"):\n return [s]\n word_end = s.find(\"]\")\n assert word_end != -1\n word = s[:word_end]\n assert s[word_end+1] == \"(\"\n url = s[word_end+2:-1]\n return [word, url]\n\ndef gen_comment(comment, start, first=False):\n line_len = 100\n s = start + ''\n if not first:\n s = \"\\n\" + s\n left = line_len - len(start)\n # [foo](bar.html) is turned into foo\n href_text = None\n for word in comment.split():\n if word[0] == \"[\":\n word_url = extract_url(word[1:])\n if len(word_url) == 2:\n s += '%s' % (word_url[1], word_url[0])\n continue\n href_text = word_url[0]\n continue\n elif href_text != None:\n word_url = extract_url(word)\n href_text = href_text + \" \" + word_url[0]\n if len(word_url) == 2:\n s += '%s ' % (word_url[1], href_text)\n href_text = None\n continue\n\n if left < len(word):\n s += \"\\n\" + start\n left = line_len - len(start)\n word += \" \"\n left -= len(word)\n if word == \"color \":\n word = 'color '\n elif word == \"colors \":\n word = 'colors '\n s += word\n s = s.rstrip()\n s += ''\n return [s]\n\ndef gen_struct(struct, indent=\"\", prerelease=False):\n lines = []\n first = True\n inside_expert = False\n for field in struct.default:\n if field.internal or type(field) is gen_settingsstructs.Comment or not prerelease and field.prerelease:\n continue\n start_idx = len(lines)\n comment = field.docComment\n if field.version != \"2.3\":\n comment += \" (introduced in version %s)\" % field.version\n lines += gen_comment(comment, indent, first)\n if type(field) is gen_settingsstructs.Array and not field.type.name == \"Compact\":\n indent2 = indent + indent_str[:len(indent_str)/2]\n start = \"%s%s [\\n%s[\" % (indent, field.name, indent2)\n end = \"%s]\\n%s]\" % (indent2, indent)\n inside = gen_struct(field, indent + indent_str, prerelease)\n lines += [start, inside, end]\n elif type(field) is gen_settingsstructs.Struct and not field.type.name == \"Compact\":\n start = \"%s%s [\" % (indent, field.name)\n end = \"%s]\" % indent\n inside = gen_struct(field, indent + indent_str, prerelease)\n lines += [start, inside, end]\n else:\n s = field.inidefault(commentChar=\"\").lstrip()\n lines += [indent + s]\n first = False\n if field.expert and not inside_expert:\n lines[start_idx] = '
' + lines[start_idx]\n elif not field.expert and inside_expert:\n lines[start_idx] = '
' + lines[start_idx]\n inside_expert = field.expert\n return \"\\n\".join(lines)\n\nclass Lang(object):\n def __init__(self, name, code):\n self.name = name\n self.code = code\n\ndef blog_dir():\n script_dir = os.path.realpath(os.path.dirname(__file__))\n blog_dir = os.path.realpath(os.path.join(script_dir, \"..\", \"..\", \"web\", \"blog\", \"www\", \"software\", \"sumatrapdf\"))\n if os.path.exists(blog_dir): return blog_dir\n return None\n\ndef gen_langs_html():\n langs = trans_langs.g_langs\n langs = [Lang(el[1], el[0]) for el in langs]\n lines = []\n langs = sorted(langs, key=lambda lang: lang.name)\n for l in langs:\n s = '%s%s' % (l.name, l.code)\n lines += [s]\n inside = \"\\n\".join(lines)\n s = langs_html_tmpl.replace(\"%INSIDE%\", inside)\n file_name = \"langs.html\"\n p = os.path.join(\"scripts\", file_name)\n open(p, \"w\").write(s)\n if blog_dir():\n p = os.path.join(blog_dir(), file_name)\n open(p, \"w\").write(s)\n\ndef gen_html():\n prefs = gen_settingsstructs.GlobalPrefs\n inside = gen_struct(prefs)\n s = html_tmpl.replace(\"%INSIDE%\", inside)\n file_name = \"settings\" + g_version + \".html\"\n p = os.path.join(\"scripts\", file_name)\n open(p, \"w\").write(s)\n if blog_dir():\n p = os.path.join(blog_dir(), file_name)\n open(p, \"w\").write(s)\n # also save the latest version as settings.html so that there is a\n # permament version we can link from from docs that is independent of\n # program version number\n p = os.path.join(blog_dir(), \"settings.html\")\n open(p, \"w\").write(s)\n\nif __name__ == \"__main__\":\n util2.chdir_top()\n gen_langs_html()\n gen_html()\n gen_settingsstructs.main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements __init__.py from narurien/ganeti-ceph (path: lib/__init__.py)."}, {"role": "assistant", "content": "# lib/__init__.py (from narurien/ganeti-ceph, license: gpl-2.0)\n\n#\n#\n\n# Copyright (C) 2006, 2007, 2012 Google Inc.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n# 02110-1301, USA.\n\n# empty file for package definition\n\n\"\"\"Ganeti python modules\"\"\"\n\ntry:\n from ganeti import ganeti\nexcept ImportError:\n pass\nelse:\n raise Exception(\"A module named \\\"ganeti.ganeti\\\" was successfully imported\"\n \" and should be removed as it can lead to importing the\"\n \" wrong module(s) in other parts of the code, consequently\"\n \" leading to failures which are difficult to debug\")"}]} {"messages": [{"role": "user", "content": "Write Python code that implements forms.py from f-enye/Lister (path: Lister/forms.py)."}, {"role": "assistant", "content": "# Lister/forms.py (from f-enye/Lister, license: mit)\n\nfrom flask.ext.wtf import Form\nfrom wtforms import TextField, PasswordField, BooleanField, IntegerField\nfrom wtforms.validators import Required, Email, EqualTo\n\nclass LoginForm(Form):\n\tuser_name = TextField('user_name', validators = [Required(), Email(message=u'Invalid email address')])\n\t#Not an encrypted password\n\tpassword = PasswordField('password', validators = [Required()])\n\nclass SignupForm(Form):\n\tuser_name = TextField('user_name', validators = [Required(), Email(message=u'Invalid email address')])\n\tpassword = PasswordField('password', validators = [Required(), EqualTo('confirm_password', message='Passwords must match')])\n\tconfirm_password = PasswordField('confirm_password', validators = [Required()])\n\nclass ListForm(Form):\n\tlist_name = TextField('list_name', validators = [Required()])\n\nclass ItemForm(Form):\n\titem_name = TextField('item_name', validators = [Required()])\n\tcheck = BooleanField('check')\n\nclass SearchForm(Form):\n\tuser_name = TextField('user_name', validators = [Required()])\n\nclass ShareListForm(Form):\n\tuser_name = TextField('user_name', validators = [Required()])\n\tlist_id = IntegerField('list_id', validators = [Required()])"}]} {"messages": [{"role": "user", "content": "Write Python code that implements junos.py from nerzhul/ansible (path: lib/ansible/utils/module_docs_fragments/junos.py)."}, {"role": "assistant", "content": "# lib/ansible/utils/module_docs_fragments/junos.py (from nerzhul/ansible, license: gpl-3.0)\n\n#\n# (c) 2015, Peter Sprygada \n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\nclass ModuleDocFragment(object):\n\n # Standard files documentation fragment\n DOCUMENTATION = \"\"\"\noptions:\n host:\n description:\n - Specifies the DNS host name or address for connecting to the remote\n device over the specified transport. The value of host is used as\n the destination address for the transport.\n required: true\n port:\n description:\n - Specifies the port to use when building the connection to the remote\n device. The port value will default to the well known SSH port\n of 22 (for C(transport=cli)) or port 830 (for C(transport=netconf))\n device.\n required: false\n default: 22\n username:\n description:\n - Configures the username to use to authenticate the connection to\n the remote device. This value is used to authenticate\n the SSH session. If the value is not specified in the task, the\n value of environment variable C(ANSIBLE_NET_USERNAME) will be used instead.\n required: false\n password:\n description:\n - Specifies the password to use to authenticate the connection to\n the remote device. This value is used to authenticate\n the SSH session. If the value is not specified in the task, the\n value of environment variable C(ANSIBLE_NET_PASSWORD) will be used instead.\n required: false\n default: null\n timeout:\n description:\n - Specifies the timeout in seconds for communicating with the network device\n for either connecting or sending commands. If the timeout is\n exceeded before the operation is completed, the module will error.\n require: false\n default: 10\n ssh_keyfile:\n description:\n - Specifies the SSH key to use to authenticate the connection to\n the remote device. This value is the path to the key\n used to authenticate the SSH session. If the value is not specified in\n the task, the value of environment variable C(ANSIBLE_NET_SSH_KEYFILE)\n will be used instead.\n required: false\n provider:\n description:\n - Convenience method that allows all I(junos) arguments to be passed as\n a dict object. All constraints (required, choices, etc) must be\n met either by individual arguments or values in this dict.\n required: false\n default: null\n\n\"\"\""}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_server_diagnostics.py from SUSE-Cloud/nova (path: nova/tests/api/openstack/compute/plugins/v3/test_server_diagnostics.py)."}, {"role": "assistant", "content": "# nova/tests/api/openstack/compute/plugins/v3/test_server_diagnostics.py (from SUSE-Cloud/nova, license: apache-2.0)\n\n# Copyright 2011 Eldar Nugaev\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom lxml import etree\n\nfrom nova.api.openstack import compute\nfrom nova.api.openstack.compute.plugins.v3 import server_diagnostics\nfrom nova.api.openstack import wsgi\nfrom nova.compute import api as compute_api\nfrom nova import exception\nfrom nova.openstack.common import jsonutils\nfrom nova import test\nfrom nova.tests.api.openstack import fakes\n\nUUID = 'abc'\n\ndef fake_get_diagnostics(self, _context, instance_uuid):\n return {'data': 'Some diagnostic info'}\n\ndef fake_instance_get(self, _context, instance_uuid):\n if instance_uuid != UUID:\n raise Exception(\"Invalid UUID\")\n return {'uuid': instance_uuid}\n\ndef fake_instance_get_instance_not_found(self, _context, instance_uuid):\n raise exception.InstanceNotFound(instance_id=instance_uuid)\n\nclass ServerDiagnosticsTest(test.NoDBTestCase):\n\n def setUp(self):\n super(ServerDiagnosticsTest, self).setUp()\n self.stubs.Set(compute_api.API, 'get_diagnostics',\n fake_get_diagnostics)\n self.stubs.Set(compute_api.API, 'get', fake_instance_get)\n\n self.router = compute.APIRouterV3(init_only=('servers',\n 'os-server-diagnostics'))\n\n def test_get_diagnostics(self):\n req = fakes.HTTPRequestV3.blank(\n '/servers/%s/os-server-diagnostics' % UUID)\n res = req.get_response(self.router)\n output = jsonutils.loads(res.body)\n self.assertEqual(output, {'data': 'Some diagnostic info'})\n\n def test_get_diagnostics_with_non_existed_instance(self):\n req = fakes.HTTPRequestV3.blank(\n '/servers/%s/os-server-diagnostics' % UUID)\n self.stubs.Set(compute_api.API, 'get',\n fake_instance_get_instance_not_found)\n res = req.get_response(self.router)\n self.assertEqual(res.status_int, 404)\n\nclass TestServerDiagnosticsXMLSerializer(test.NoDBTestCase):\n namespace = wsgi.XMLNS_V11\n\n def _tag(self, elem):\n tagname = elem.tag\n self.assertEqual(tagname[0], '{')\n tmp = tagname.partition('}')\n namespace = tmp[0][1:]\n self.assertEqual(namespace, self.namespace)\n return tmp[2]\n\n def test_index_serializer(self):\n serializer = server_diagnostics.ServerDiagnosticsTemplate()\n exemplar = dict(diag1='foo', diag2='bar')\n text = serializer.serialize(exemplar)\n\n tree = etree.fromstring(text)\n\n self.assertEqual('diagnostics', self._tag(tree))\n self.assertEqual(len(tree), len(exemplar))\n for child in tree:\n tag = self._tag(child)\n self.assertTrue(tag in exemplar)\n self.assertEqual(child.text, exemplar[tag])"}]} {"messages": [{"role": "user", "content": "Write Python code that implements package.py from mfherbst/spack (path: var/spack/repos/builtin/packages/deconseq-standalone/package.py)."}, {"role": "assistant", "content": "# var/spack/repos/builtin/packages/deconseq-standalone/package.py (from mfherbst/spack, license: lgpl-2.1)\n\n##############################################################################\n# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.\n# Produced at the Lawrence Livermore National Laboratory.\n#\n# This file is part of Spack.\n# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.\n# LLNL-CODE-647188\n#\n# For details, see https://github.com/spack/spack\n# Please also see the NOTICE and LICENSE files for our notice and the LGPL.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License (as\n# published by the Free Software Foundation) version 2.1, February 1999.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and\n# conditions of the GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n##############################################################################\nfrom spack import *\n\nclass DeconseqStandalone(Package):\n \"\"\"The DeconSeq tool can be used to automatically detect and efficiently\n remove sequence contaminations from genomic and metagenomic datasets.\"\"\"\n\n homepage = \"http://deconseq.sourceforge.net\"\n url = \"https://sourceforge.net/projects/deconseq/files/standalone/deconseq-standalone-0.4.3.tar.gz\"\n\n version('0.4.3', 'cb3fddb90e584d89fd9c2b6b8f2e20a2')\n\n depends_on('perl@5:')\n\n def install(self, spec, prefix):\n\n filter_file(r'#!/usr/bin/perl',\n '#!/usr/bin/env perl', 'deconseq.pl')\n filter_file(r'#!/usr/bin/perl',\n '#!/usr/bin/env perl', 'splitFasta.pl')\n\n mkdirp(prefix.bin)\n install('bwa64', prefix.bin)\n install('bwaMAC', prefix.bin)\n install('deconseq.pl', prefix.bin)\n install('splitFasta.pl', prefix.bin)\n install('DeconSeqConfig.pm', prefix)\n\n chmod = which('chmod')\n chmod('+x', join_path(prefix.bin, 'bwa64'))\n chmod('+x', join_path(prefix.bin, 'bwaMAC'))\n chmod('+x', join_path(prefix.bin, 'deconseq.pl'))\n chmod('+x', join_path(prefix.bin, 'splitFasta.pl'))\n\n def setup_environment(self, spack_env, run_env):\n run_env.prepend_path('PERL5LIB', prefix)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements urls_unittest.py from lseyesl/phantomjs (path: src/qt/qtwebkit/Tools/Scripts/webkitpy/common/config/urls_unittest.py)."}, {"role": "assistant", "content": "# src/qt/qtwebkit/Tools/Scripts/webkitpy/common/config/urls_unittest.py (from lseyesl/phantomjs, license: bsd-3-clause)\n\n# Copyright (C) 2012 Google Inc. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport unittest2 as unittest\n\nfrom .urls import parse_bug_id, parse_attachment_id\n\nclass URLsTest(unittest.TestCase):\n def test_parse_bug_id(self):\n # FIXME: These would be all better as doctests\n self.assertEqual(12345, parse_bug_id(\"http://webkit.org/b/12345\"))\n self.assertEqual(12345, parse_bug_id(\"foo\\n\\nhttp://webkit.org/b/12345\\nbar\\n\\n\"))\n self.assertEqual(12345, parse_bug_id(\"http://bugs.webkit.org/show_bug.cgi?id=12345\"))\n self.assertEqual(12345, parse_bug_id(\"http://bugs.webkit.org/show_bug.cgi?id=12345&ctype=xml\"))\n self.assertEqual(12345, parse_bug_id(\"http://bugs.webkit.org/show_bug.cgi?id=12345&ctype=xml&excludefield=attachmentdata\"))\n self.assertEqual(12345, parse_bug_id(\"http://bugs.webkit.org/show_bug.cgi?id=12345excludefield=attachmentdata&ctype=xml\"))\n\n # Our url parser is super-fragile, but at least we're testing it.\n self.assertIsNone(parse_bug_id(\"http://www.webkit.org/b/12345\"))\n self.assertIsNone(parse_bug_id(\"http://bugs.webkit.org/show_bug.cgi?ctype=xml&id=12345\"))\n self.assertIsNone(parse_bug_id(\"http://bugs.webkit.org/show_bug.cgi?ctype=xml&id=12345&excludefield=attachmentdata\"))\n self.assertIsNone(parse_bug_id(\"http://bugs.webkit.org/show_bug.cgi?ctype=xml&excludefield=attachmentdata&id=12345\"))\n self.assertIsNone(parse_bug_id(\"http://bugs.webkit.org/show_bug.cgi?excludefield=attachmentdata&ctype=xml&id=12345\"))\n self.assertIsNone(parse_bug_id(\"http://bugs.webkit.org/show_bug.cgi?excludefield=attachmentdata&id=12345&ctype=xml\"))\n\n def test_parse_attachment_id(self):\n self.assertEqual(12345, parse_attachment_id(\"https://bugs.webkit.org/attachment.cgi?id=12345&action=review\"))\n self.assertEqual(12345, parse_attachment_id(\"https://bugs.webkit.org/attachment.cgi?id=12345&action=edit\"))\n self.assertEqual(12345, parse_attachment_id(\"https://bugs.webkit.org/attachment.cgi?id=12345&action=prettypatch\"))\n self.assertEqual(12345, parse_attachment_id(\"https://bugs.webkit.org/attachment.cgi?id=12345&action=diff\"))\n\n # Direct attachment links are hosted from per-bug subdomains:\n self.assertEqual(12345, parse_attachment_id(\"https://bug-23456-attachments.webkit.org/attachment.cgi?id=12345\"))\n # Make sure secure attachment URLs work too.\n self.assertEqual(12345, parse_attachment_id(\"https://bug-23456-attachments.webkit.org/attachment.cgi?id=12345&t=Bqnsdkl9fs\"))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_cg_stc_eng_stc.py from oceanobservatories/mi-instrument (path: mi/dataset/parser/test/test_cg_stc_eng_stc.py)."}, {"role": "assistant", "content": "# mi/dataset/parser/test/test_cg_stc_eng_stc.py (from oceanobservatories/mi-instrument, license: bsd-2-clause)\n\n#!/usr/bin/env python\n\n\"\"\"\n@package mi.dataset.parser.test.test_cg_stc_eng_stc\n@file marine-integrations/mi/dataset/parser/test/test_cg_stc_eng_stc.py\n@author Mike Nicoletti\n@brief Test code for a Cg_stc_eng_stc data parser\n\"\"\"\nimport os\nimport re\n\nimport ntplib\nfrom nose.plugins.attrib import attr\n\nfrom mi.core.exceptions import SampleException\nfrom mi.core.instrument.dataset_data_particle import DataParticleKey\nfrom mi.core.log import get_logger\nfrom mi.dataset.dataset_parser import DataSetDriverConfigKeys\nfrom mi.dataset.parser.cg_stc_eng_stc import CgStcEngStcParser, CgStcEngStcParserDataParticle\nfrom mi.dataset.parser.cg_stc_eng_stc import CgStcEngStcParserDataParticleKey\nfrom mi.dataset.test.test_parser import ParserUnitTestCase\nfrom mi.dataset.driver.cg_stc_eng.stc.resource import RESOURCE_PATH\n\nlog = get_logger()\n\n@attr('UNIT', group='mi')\nclass CgParserUnitTestCase(ParserUnitTestCase):\n \"\"\"\n Cg_stc_eng_stc Parser unit test suite\n \"\"\"\n def state_callback(self, state, file_ingested):\n \"\"\" Call back method to watch what comes in via the position callback \"\"\"\n self.state_callback_value = state\n self.file_ingested_value = file_ingested\n\n def pub_callback(self, pub):\n \"\"\" Call back method to watch what comes in via the publish callback \"\"\"\n self.publish_callback_value = pub\n\n def exception_callback(self, exception):\n \"\"\" Callback method to watch what comes in via the exception callback \"\"\"\n self.exception_callback_value = exception\n\n def setUp(self):\n ParserUnitTestCase.setUp(self)\n self.config = {\n DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.cg_stc_eng_stc',\n DataSetDriverConfigKeys.PARTICLE_CLASS: 'CgStcEngStcParserDataParticle'\n }\n # Define test data particles and their associated timestamps which will be \n # compared with returned results\n fid = open(os.path.join(RESOURCE_PATH, 'stc_status.txt'))\n data = fid.read()\n fid.close()\n utime_grp = re.search(r'Platform.utime=(.+?)(\\r\\n?|\\n)', data)\n self.timestamp_a = ntplib.system_to_ntp_time(float(utime_grp.group(1)))\n self.particle_a = CgStcEngStcParserDataParticle(data,\n internal_timestamp=self.timestamp_a,\n preferred_timestamp=DataParticleKey.INTERNAL_TIMESTAMP)\n\n self.comparison_list = [{DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_PLATFORM_TIME,\n DataParticleKey.VALUE: '2013/10/04 16:07:02.253'},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_PLATFORM_UTIME,\n DataParticleKey.VALUE: 1380902822.253},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MSG_CNTS_C_GPS,\n DataParticleKey.VALUE: 83},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MSG_CNTS_C_NTP,\n DataParticleKey.VALUE: 0},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MSG_CNTS_C_PPS,\n DataParticleKey.VALUE: 4},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MSG_CNTS_C_POWER_SYS,\n DataParticleKey.VALUE: 0},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MSG_CNTS_C_SUPERV,\n DataParticleKey.VALUE: 7},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MSG_CNTS_C_TELEM,\n DataParticleKey.VALUE: 0},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_ERR_C_GPS,\n DataParticleKey.VALUE: 1},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_ERR_C_PPS,\n DataParticleKey.VALUE: 1},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_ERR_C_TELEM_SYS,\n DataParticleKey.VALUE: 3},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_ERRMSG_C_GPS,\n DataParticleKey.VALUE: '***Warning, BAD GPS CHECKSUM'},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_ERRMSG_C_PPS,\n DataParticleKey.VALUE: 'C_PPS: Warning: Pulse delta [790] above warning level [500], still within window [900]'},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_ERRMSG_C_TELEM_SYS,\n DataParticleKey.VALUE: ' \"***Error turning on fb1 [ret=No Device]'},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_CPU_UPTIME,\n DataParticleKey.VALUE: '0 days 00:01:22'},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_CPU_LOAD1,\n DataParticleKey.VALUE: 1.03},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_CPU_LOAD5,\n DataParticleKey.VALUE: 0.36},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_CPU_LOAD15,\n DataParticleKey.VALUE: 0.12},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MEMORY_RAM,\n DataParticleKey.VALUE: 127460},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MEMORY_FREE,\n DataParticleKey.VALUE: 93396},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_NPROC,\n DataParticleKey.VALUE: 76},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_EFLAG,\n DataParticleKey.VALUE: 0},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_MAIN_V,\n DataParticleKey.VALUE: 17.90},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_MAIN_C,\n DataParticleKey.VALUE: 379.20},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_BAT_V,\n DataParticleKey.VALUE: 0.0},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_BAT_C,\n DataParticleKey.VALUE: 0.0},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_TEMP1,\n DataParticleKey.VALUE: 25.0},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_TEMP2,\n DataParticleKey.VALUE: 23.3},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_HUMID,\n DataParticleKey.VALUE: 31.6},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_PRESS,\n DataParticleKey.VALUE: 14.7},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_GF_ENA,\n DataParticleKey.VALUE: 15},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_GFLT1,\n DataParticleKey.VALUE: 7.7},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_GFLT2,\n DataParticleKey.VALUE: 5.2},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_GFLT3,\n DataParticleKey.VALUE: 2.8},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_GFLT4,\n DataParticleKey.VALUE: 4.0},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_MPIC_LD_ENA,\n DataParticleKey.VALUE: 3},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_GPS_DATE,\n DataParticleKey.VALUE: 41013},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_GPS_TIME,\n DataParticleKey.VALUE: 160701},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_GPS_LATSTR,\n DataParticleKey.VALUE: '4132.1353 N'},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_GPS_LONSTR,\n DataParticleKey.VALUE: '07038.8306 W'},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_GPS_LAT,\n DataParticleKey.VALUE: 41.535588},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_GPS_LON,\n DataParticleKey.VALUE: -70.647177},\n {DataParticleKey.VALUE_ID: CgStcEngStcParserDataParticleKey.CG_ENG_GPS_SPD,\n DataParticleKey.VALUE: 0.0}]\n # uncomment the following to write the above comparison list in yml format to a file\n # self.write_comparison_to_yml()\n\n self.file_ingested_value = None\n self.state_callback_value = None\n self.publish_callback_value = None\n self.exception_callback_value = None\n\n def write_comparison_to_yml(self):\n \"\"\"\n Helper class to create a yml file for driver tests\n \"\"\"\n fid = open('particle.yml', 'a')\n fid.write('header:\\n')\n fid.write(' particle_object: CgStcEngStcParserDataParticle\\n')\n fid.write(' particle_type: cg_stc_eng_stc\\n')\n fid.write('data:\\n')\n fid.write(' - _index: 1\\n')\n fid.write(' internal_timestamp: 0.0\\n')\n\n for item in self.comparison_list:\n if isinstance(item.get('value'), float):\n fid.write(' %s: %16.20f\\n' % (item.get('value_id'), item.get('value')))\n else:\n fid.write(' %s: %s\\n' % (item.get('value_id'), item.get('value')))\n fid.close()\n\n def assert_result(self, result, particle, ingested):\n if result[0].raw_data == particle.raw_data:\n log.debug(\"raw data match\")\n log.debug(\"comparing result %s, particle %s\", result[0].contents, particle.contents)\n self.assertEqual(result, [particle])\n self.assertEqual(self.file_ingested_value, ingested)\n\n self.assert_(isinstance(self.publish_callback_value, list))\n self.assertEqual(self.publish_callback_value[0], particle)\n\n def test_simple(self):\n \"\"\"\n Read test data and pull out data particles one at a time.\n Assert that the results are those we expected.\n \"\"\"\n stream_handle = open(os.path.join(RESOURCE_PATH, 'stc_status.txt'))\n self.parser = CgStcEngStcParser(self.config, None, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n\n result = self.parser.get_records(1)\n self.assert_result(result, self.particle_a, True)\n\n # no data left, do not move the position\n result = self.parser.get_records(1)\n self.assertEqual(result, [])\n self.assert_(isinstance(self.publish_callback_value, list))\n self.assertEqual(self.publish_callback_value[0], self.particle_a)\n self.assertEqual(self.exception_callback_value, None)\n\n def test_simple_particles(self):\n \"\"\"\n Read test data and pull out data particles one at a time.\n Assert that the results are those we expected.\n \"\"\"\n stream_handle = open(os.path.join(RESOURCE_PATH, 'stc_status2.txt'))\n self.parser = CgStcEngStcParser(self.config, None, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n\n result = self.parser.get_records(1)\n self.assert_particles(result, 'stc_first2.result.yml', RESOURCE_PATH)\n self.assertEqual(self.exception_callback_value, None)\n\n def test_get_many(self):\n \"\"\"\n Read test data and try to pull out multiple data particles at one time,\n but we should only get 1 .\n Assert that the results are those we expected.\n \"\"\"\n stream_handle = open(os.path.join(RESOURCE_PATH, 'stc_status.txt'))\n self.parser = CgStcEngStcParser(self.config, None, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n\n result = self.parser.get_records(4)\n self.assert_result(result, self.particle_a, True)\n self.assertEqual(len(self.publish_callback_value), 1)\n\n # no data left, do not move the position\n result = self.parser.get_records(1)\n self.assertEqual(result, [])\n self.assert_(isinstance(self.publish_callback_value, list))\n self.assertEqual(self.publish_callback_value[0], self.particle_a)\n self.assertEqual(self.exception_callback_value, None)\n\n def test_generate(self):\n \"\"\"\n Ensure we can generate the particle dictionary and compare it to expected ones\n \"\"\"\n stream_handle = open(os.path.join(RESOURCE_PATH, 'stc_status.txt'))\n self.parser = CgStcEngStcParser(self.config, None, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n\n result = self.parser.get_records(1)\n res_dict = result[0].generate_dict()\n # assert two lists of generated dictionaries are the same\n for cdict in self.comparison_list:\n for rdict in res_dict['values']:\n if cdict.get('value_id') == rdict.get('value_id'):\n if cdict.get('value') != rdict.get('value'):\n log.error(\"mismatch for key %s, values '%s' '%s'\", cdict.get('value_id'),\n cdict.get('value'),\n rdict.get('value'))\n self.fail(\"mismatch for key %s, values '%s', '%s'\" % (cdict.get('value_id'),\n cdict.get('value'),\n rdict.get('value')))\n\n def test_bad_data(self):\n \"\"\"\n Ensure that the missing timestamp field causes a sample exception\n \"\"\"\n with self.assertRaises(SampleException):\n stream_handle = open(os.path.join(RESOURCE_PATH, 'stc_status_missing_time.txt'))\n self.parser = CgStcEngStcParser(self.config, None, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n self.parser.get_records(1)\n\n def test_encoding(self):\n \"\"\"\n Create an encoding error in the data and make sure an encoding error shows up\n \"\"\"\n stream_handle = open(os.path.join(RESOURCE_PATH, 'stc_status_bad_encode.txt'))\n self.parser = CgStcEngStcParser(self.config, None, stream_handle,\n self.state_callback, self.pub_callback,\n self.exception_callback)\n result = self.parser.get_records(1)\n errors = result[0].get_encoding_errors()\n log.debug(\"encoding errors: %s\", errors)\n self.assertNotEqual(errors, [])"}]} {"messages": [{"role": "user", "content": "Write Python code that implements glibc.py from ryfeus/lambda-packs (path: Sklearn_scipy_numpy/source/pip/utils/glibc.py)."}, {"role": "assistant", "content": "# Sklearn_scipy_numpy/source/pip/utils/glibc.py (from ryfeus/lambda-packs, license: mit)\n\nfrom __future__ import absolute_import\n\nimport re\nimport ctypes\nimport platform\nimport warnings\n\ndef glibc_version_string():\n \"Returns glibc version string, or None if not using glibc.\"\n\n # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen\n # manpage says, \"If filename is NULL, then the returned handle is for the\n # main program\". This way we can let the linker do the work to figure out\n # which libc our process is actually using.\n process_namespace = ctypes.CDLL(None)\n try:\n gnu_get_libc_version = process_namespace.gnu_get_libc_version\n except AttributeError:\n # Symbol doesn't exist -> therefore, we are not linked to\n # glibc.\n return None\n\n # Call gnu_get_libc_version, which returns a string like \"2.5\"\n gnu_get_libc_version.restype = ctypes.c_char_p\n version_str = gnu_get_libc_version()\n # py2 / py3 compatibility:\n if not isinstance(version_str, str):\n version_str = version_str.decode(\"ascii\")\n\n return version_str\n\n# Separated out from have_compatible_glibc for easier unit testing\ndef check_glibc_version(version_str, required_major, minimum_minor):\n # Parse string and check against requested version.\n #\n # We use a regexp instead of str.split because we want to discard any\n # random junk that might come after the minor version -- this might happen\n # in patched/forked versions of glibc (e.g. Linaro's version of glibc\n # uses version strings like \"2.20-2014.11\"). See gh-3588.\n m = re.match(r\"(?P[0-9]+)\\.(?P[0-9]+)\", version_str)\n if not m:\n warnings.warn(\"Expected glibc version with 2 components major.minor,\"\n \" got: %s\" % version_str, RuntimeWarning)\n return False\n return (int(m.group(\"major\")) == required_major and\n int(m.group(\"minor\")) >= minimum_minor)\n\ndef have_compatible_glibc(required_major, minimum_minor):\n version_str = glibc_version_string()\n if version_str is None:\n return False\n return check_glibc_version(version_str, required_major, minimum_minor)\n\n# platform.libc_ver regularly returns completely nonsensical glibc\n# versions. E.g. on my computer, platform says:\n#\n# ~$ python2.7 -c 'import platform; print(platform.libc_ver())'\n# ('glibc', '2.7')\n# ~$ python3.5 -c 'import platform; print(platform.libc_ver())'\n# ('glibc', '2.9')\n#\n# But the truth is:\n#\n# ~$ ldd --version\n# ldd (Debian GLIBC 2.22-11) 2.22\n#\n# This is unfortunate, because it means that the linehaul data on libc\n# versions that was generated by pip 8.1.2 and earlier is useless and\n# misleading. Solution: instead of using platform, use our code that actually\n# works.\ndef libc_ver():\n glibc_version = glibc_version_string()\n if glibc_version is None:\n # For non-glibc platforms, fall back on platform.libc_ver\n return platform.libc_ver()\n else:\n return (\"glibc\", glibc_version)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements rich_text.py from poojavade/Genomics_Docker (path: Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/ipython-2.2.0-py2.7.egg/IPython/qt/rich_text.py)."}, {"role": "assistant", "content": "# Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/ipython-2.2.0-py2.7.egg/IPython/qt/rich_text.py (from poojavade/Genomics_Docker, license: apache-2.0)\n\n\"\"\" Defines classes and functions for working with Qt's rich text system.\n\"\"\"\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\n# Standard library imports\nimport io\nimport os\nimport re\n\n# System library imports\nfrom IPython.external.qt import QtGui\n\n# IPython imports\nfrom IPython.utils import py3compat\n\n#-----------------------------------------------------------------------------\n# Constants\n#-----------------------------------------------------------------------------\n\n# A regular expression for an HTML paragraph with no content.\nEMPTY_P_RE = re.compile(r']*>\\s*

')\n\n# A regular expression for matching images in rich text HTML.\n# Note that this is overly restrictive, but Qt's output is predictable...\nIMG_RE = re.compile(r'[\\d]+)\" />')\n\n#-----------------------------------------------------------------------------\n# Classes\n#-----------------------------------------------------------------------------\n\nclass HtmlExporter(object):\n \"\"\" A stateful HTML exporter for a Q(Plain)TextEdit.\n\n This class is designed for convenient user interaction.\n \"\"\"\n\n def __init__(self, control):\n \"\"\" Creates an HtmlExporter for the given Q(Plain)TextEdit.\n \"\"\"\n assert isinstance(control, (QtGui.QPlainTextEdit, QtGui.QTextEdit))\n self.control = control\n self.filename = 'ipython.html'\n self.image_tag = None\n self.inline_png = None\n\n def export(self):\n \"\"\" Displays a dialog for exporting HTML generated by Qt's rich text\n system.\n\n Returns\n -------\n The name of the file that was saved, or None if no file was saved.\n \"\"\"\n parent = self.control.window()\n dialog = QtGui.QFileDialog(parent, 'Save as...')\n dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)\n filters = [\n 'HTML with PNG figures (*.html *.htm)',\n 'XHTML with inline SVG figures (*.xhtml *.xml)'\n ]\n dialog.setNameFilters(filters)\n if self.filename:\n dialog.selectFile(self.filename)\n root,ext = os.path.splitext(self.filename)\n if ext.lower() in ('.xml', '.xhtml'):\n dialog.selectNameFilter(filters[-1])\n\n if dialog.exec_():\n self.filename = dialog.selectedFiles()[0]\n choice = dialog.selectedNameFilter()\n html = py3compat.cast_unicode(self.control.document().toHtml())\n\n # Configure the exporter.\n if choice.startswith('XHTML'):\n exporter = export_xhtml\n else:\n # If there are PNGs, decide how to export them.\n inline = self.inline_png\n if inline is None and IMG_RE.search(html):\n dialog = QtGui.QDialog(parent)\n dialog.setWindowTitle('Save as...')\n layout = QtGui.QVBoxLayout(dialog)\n msg = \"Exporting HTML with PNGs\"\n info = \"Would you like inline PNGs (single large html \" \\\n \"file) or external image files?\"\n checkbox = QtGui.QCheckBox(\"&Don't ask again\")\n checkbox.setShortcut('D')\n ib = QtGui.QPushButton(\"&Inline\")\n ib.setShortcut('I')\n eb = QtGui.QPushButton(\"&External\")\n eb.setShortcut('E')\n box = QtGui.QMessageBox(QtGui.QMessageBox.Question,\n dialog.windowTitle(), msg)\n box.setInformativeText(info)\n box.addButton(ib, QtGui.QMessageBox.NoRole)\n box.addButton(eb, QtGui.QMessageBox.YesRole)\n layout.setSpacing(0)\n layout.addWidget(box)\n layout.addWidget(checkbox)\n dialog.setLayout(layout)\n dialog.show()\n reply = box.exec_()\n dialog.hide()\n inline = (reply == 0)\n if checkbox.checkState():\n # Don't ask anymore; always use this choice.\n self.inline_png = inline\n exporter = lambda h, f, i: export_html(h, f, i, inline)\n\n # Perform the export!\n try:\n return exporter(html, self.filename, self.image_tag)\n except Exception as e:\n msg = \"Error exporting HTML to %s\\n\" % self.filename + str(e)\n reply = QtGui.QMessageBox.warning(parent, 'Error', msg,\n QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)\n\n return None\n\n#-----------------------------------------------------------------------------\n# Functions\n#-----------------------------------------------------------------------------\n\ndef export_html(html, filename, image_tag = None, inline = True):\n \"\"\" Export the contents of the ConsoleWidget as HTML.\n\n Parameters\n ----------\n html : unicode,\n A Python unicode string containing the Qt HTML to export.\n\n filename : str\n The file to be saved.\n\n image_tag : callable, optional (default None)\n Used to convert images. See ``default_image_tag()`` for information.\n\n inline : bool, optional [default True]\n If True, include images as inline PNGs. Otherwise, include them as\n links to external PNG files, mimicking web browsers' \"Web Page,\n Complete\" behavior.\n \"\"\"\n if image_tag is None:\n image_tag = default_image_tag\n\n if inline:\n path = None\n else:\n root,ext = os.path.splitext(filename)\n path = root + \"_files\"\n if os.path.isfile(path):\n raise OSError(\"%s exists, but is not a directory.\" % path)\n\n with io.open(filename, 'w', encoding='utf-8') as f:\n html = fix_html(html)\n f.write(IMG_RE.sub(lambda x: image_tag(x, path = path, format = \"png\"),\n html))\n\ndef export_xhtml(html, filename, image_tag=None):\n \"\"\" Export the contents of the ConsoleWidget as XHTML with inline SVGs.\n\n Parameters\n ----------\n html : unicode,\n A Python unicode string containing the Qt HTML to export.\n\n filename : str\n The file to be saved.\n\n image_tag : callable, optional (default None)\n Used to convert images. See ``default_image_tag()`` for information.\n \"\"\"\n if image_tag is None:\n image_tag = default_image_tag\n\n with io.open(filename, 'w', encoding='utf-8') as f:\n # Hack to make xhtml header -- note that we are not doing any check for\n # valid XML.\n offset = html.find(\"\")\n assert offset > -1, 'Invalid HTML string: no tag.'\n html = (u'\\n'+\n html[offset+6:])\n\n html = fix_html(html)\n f.write(IMG_RE.sub(lambda x: image_tag(x, path = None, format = \"svg\"),\n html))\n\ndef default_image_tag(match, path = None, format = \"png\"):\n \"\"\" Return (X)HTML mark-up for the image-tag given by match.\n\n This default implementation merely removes the image, and exists mostly\n for documentation purposes. More information than is present in the Qt\n HTML is required to supply the images.\n\n Parameters\n ----------\n match : re.SRE_Match\n A match to an HTML image tag as exported by Qt, with match.group(\"Name\")\n containing the matched image ID.\n\n path : string|None, optional [default None]\n If not None, specifies a path to which supporting files may be written\n (e.g., for linked images). If None, all images are to be included\n inline.\n\n format : \"png\"|\"svg\", optional [default \"png\"]\n Format for returned or referenced images.\n \"\"\"\n return u''\n\ndef fix_html(html):\n \"\"\" Transforms a Qt-generated HTML string into a standards-compliant one.\n\n Parameters\n ----------\n html : unicode,\n A Python unicode string containing the Qt HTML.\n \"\"\"\n # A UTF-8 declaration is needed for proper rendering of some characters\n # (e.g., indented commands) when viewing exported HTML on a local system\n # (i.e., without seeing an encoding declaration in an HTTP header).\n # C.f. http://www.w3.org/International/O-charset for details.\n offset = html.find('')\n if offset > -1:\n html = (html[:offset+6]+\n '\\n\\n'+\n html[offset+6:])\n\n # Replace empty paragraphs tags with line breaks.\n html = re.sub(EMPTY_P_RE, '
', html)\n\n return html"}]} {"messages": [{"role": "user", "content": "Write Python code that implements __init__.py from rschnapka/odoo (path: addons/document_webdav/__init__.py)."}, {"role": "assistant", "content": "# addons/document_webdav/__init__.py (from rschnapka/odoo, license: agpl-3.0)\n\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nimport logging\n\nimport webdav\nimport webdav_server\nimport document_webdav\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:"}]} {"messages": [{"role": "user", "content": "Write Python code that implements __init__.py from alexteodor/odoo (path: addons/pos_restaurant/__init__.py)."}, {"role": "assistant", "content": "# addons/pos_restaurant/__init__.py (from alexteodor/odoo, license: agpl-3.0)\n\n# -*- coding: utf-8 -*-\n##############################################################################\n# \n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see . \n#\n##############################################################################\n\nimport restaurant\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_settings.py from stamhe/zulip (path: zproject/test_settings.py)."}, {"role": "assistant", "content": "# zproject/test_settings.py (from stamhe/zulip, license: apache-2.0)\n\nfrom settings import *\nimport os\n\nDATABASES[\"default\"] = {\"NAME\": \"zulip_test\",\n \"USER\": \"zulip_test\",\n \"PASSWORD\": LOCAL_DATABASE_PASSWORD,\n \"HOST\": \"localhost\",\n \"SCHEMA\": \"zulip\",\n \"ENGINE\": \"django.db.backends.postgresql_psycopg2\",\n \"TEST_NAME\": \"django_zulip_tests\",\n \"OPTIONS\": {\"connection_factory\": TimeTrackingConnection },}\n\nif \"TORNADO_SERVER\" in os.environ:\n TORNADO_SERVER = os.environ[\"TORNADO_SERVER\"]\nelse:\n TORNADO_SERVER = None\n\n# Decrease the get_updates timeout to 1 second.\n# This allows CasperJS to proceed quickly to the next test step.\nPOLL_TIMEOUT = 1000\n\n# Don't use the real message log for tests\nEVENT_LOG_DIR = '/tmp/zulip-test-event-log'\n\n# Print our emails rather than sending them\nEMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'\n\n# The test suite uses EmailAuthBackend\nAUTHENTICATION_BACKENDS += ('zproject.backends.EmailAuthBackend',)\n\nTEST_SUITE = True\nRATE_LIMITING = False\n# Don't use rabbitmq from the test suite -- the user_profile_ids for\n# any generated queue elements won't match those being used by the\n# real app.\nUSING_RABBITMQ = False\n\n# Disable the tutorial because it confuses the client tests.\nTUTORIAL_ENABLED = False\n\n# Disable use of memcached for caching\nCACHES['database'] = {\n 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',\n 'LOCATION': 'zulip-database-test-cache',\n 'TIMEOUT': 3600,\n 'CONN_MAX_AGE': 600,\n 'OPTIONS': {\n 'MAX_ENTRIES': 100000\n }\n}\n\nLOGGING['loggers']['zulip.requests']['level'] = 'CRITICAL'\nLOGGING['loggers']['zulip.management']['level'] = 'CRITICAL'\n\nCAMO_URI = 'https://external-content.zulipcdn.net/'\nCAMO_KEY = 'dummy'"}]} {"messages": [{"role": "user", "content": "Write Python code that implements errors.py from EdDev/vdsm (path: lib/vdsm/network/errors.py)."}, {"role": "assistant", "content": "# lib/vdsm/network/errors.py (from EdDev/vdsm, license: gpl-2.0)\n\n#\n# Copyright 2011-2014 Red Hat, Inc.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n#\n# Refer to the README and COPYING files for full details of the license\n#\n\nfrom __future__ import absolute_import\n\nimport six\n\nERR_OK = 0\nERR_BAD_PARAMS = 21\nERR_BAD_ADDR = 22\nERR_BAD_NIC = 23\nERR_USED_NIC = 24\nERR_BAD_BONDING = 25\nERR_BAD_VLAN = 26\nERR_BAD_BRIDGE = 27\nERR_USED_BRIDGE = 28\nERR_FAILED_IFUP = 29\nERR_FAILED_IFDOWN = 30\nERR_USED_BOND = 31\nERR_LOST_CONNECTION = 10 # noConPeer\nERR_OVS_CONNECTION = 32\n\nclass ConfigNetworkError(Exception):\n def __init__(self, errCode, message):\n self.errCode = errCode\n self.message = message\n super(ConfigNetworkError, self).__init__(errCode, message)\n\nclass OvsDBConnectionError(ConfigNetworkError):\n def __init__(self, *args):\n message = _get_message(args)\n super(OvsDBConnectionError, self).__init__(errCode=ERR_OVS_CONNECTION,\n message=message)\n\n @staticmethod\n def is_ovs_db_conn_error(err_msg):\n return 'database connection failed' in err_msg[0]\n\nclass RollbackIncomplete(Exception):\n \"\"\"\n This exception is raised in order to signal API.Global that a call to\n setupNetworks has failed and there are leftovers that need to be cleaned\n up.\n Note that it is never raised by the default ifcfg configurator.\n \"\"\"\n pass\n\ndef _get_message(args):\n \"\"\"\n Due to multiprocessing limitation in the way it processes an exception\n serialization and deserialization, a derived exception needs to accept\n all super classes arguments as input, even if it ignores them.\n\n Given the list of arguments and assuming the message is a string type,\n this helper function fetches the message argument.\n \"\"\"\n for arg in args:\n if isinstance(arg, six.string_types):\n return arg"}]} {"messages": [{"role": "user", "content": "Write Python code that implements fastpoetry_plugin.py from shankisg/twisted-intro (path: twisted/plugins/fastpoetry_plugin.py)."}, {"role": "assistant", "content": "# twisted/plugins/fastpoetry_plugin.py (from shankisg/twisted-intro, license: mit)\n\n# This is the Twisted Fast Poetry Server, version 3.0\n\nfrom zope.interface import implements\n\nfrom twisted.python import usage, log\nfrom twisted.plugin import IPlugin\nfrom twisted.internet.protocol import ServerFactory, Protocol\nfrom twisted.application import internet, service\n\n# Normally we would import these classes from another module.\n\nclass PoetryProtocol(Protocol):\n\n def connectionMade(self):\n poem = self.factory.service.poem\n log.msg('sending %d bytes of poetry to %s'\n % (len(poem), self.transport.getPeer()))\n self.transport.write(poem)\n self.transport.loseConnection()\n\nclass PoetryFactory(ServerFactory):\n\n protocol = PoetryProtocol\n\n def __init__(self, service):\n self.service = service\n\nclass PoetryService(service.Service):\n\n def __init__(self, poetry_file):\n self.poetry_file = poetry_file\n\n def startService(self):\n service.Service.startService(self)\n self.poem = open(self.poetry_file).read()\n log.msg('loaded a poem from: %s' % (self.poetry_file,))\n\n# This is the main body of the plugin. First we define\n# our command-line options.\n\nclass Options(usage.Options):\n\n optParameters = [\n ['port', 'p', 10000, 'The port number to listen on.'],\n ['poem', None, None, 'The file containing the poem.'],\n ['iface', None, 'localhost', 'The interface to listen on.'],\n ]\n\n# Now we define our 'service maker', an object which knows\n# how to construct our service.\n\nclass PoetryServiceMaker(object):\n\n implements(service.IServiceMaker, IPlugin)\n\n tapname = \"fastpoetry\"\n description = \"A fast poetry service.\"\n options = Options\n\n def makeService(self, options):\n top_service = service.MultiService()\n\n poetry_service = PoetryService(options['poem'])\n poetry_service.setServiceParent(top_service)\n\n factory = PoetryFactory(poetry_service)\n tcp_service = internet.TCPServer(int(options['port']), factory,\n interface=options['iface'])\n tcp_service.setServiceParent(top_service)\n\n return top_service\n\n# This variable name is irrelevent. What matters is that\n# instances of PoetryServiceMaker implement IServiceMaker\n# and IPlugin.\n\nservice_maker = PoetryServiceMaker()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements font.py from Sinkmanu/auth-system-chronos (path: Chronos Auth System/tools/Chronos Auth System/tools/urwid/font.py)."}, {"role": "assistant", "content": "# Chronos Auth System/tools/Chronos Auth System/tools/urwid/font.py (from Sinkmanu/auth-system-chronos, license: gpl-3.0)\n\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Urwid BigText fonts\n# Copyright (C) 2004-2006 Ian Ward\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n#\n# Urwid web site: http://excess.org/urwid/\n\nfrom __future__ import nested_scopes\n\nimport re\n\nfrom escape import utf8decode, SAFE_ASCII_DEC_SPECIAL_RE\nfrom util import apply_target_encoding, str_util\nfrom canvas import TextCanvas\n\ntry: True # old python?\nexcept: False, True = 0, 1\n\ndef separate_glyphs(gdata, height):\n \"\"\"return (dictionary of glyphs, utf8 required)\"\"\"\n gl = gdata.split(\"\\n\")\n del gl[0]\n del gl[-1]\n for g in gl:\n assert \"\\t\" not in g\n assert len(gl) == height+1, `gdata`\n key_line = gl[0]\n del gl[0]\n c = None # current character\n key_index = 0 # index into character key line\n end_col = 0 # column position at end of glyph\n start_col = 0 # column position at start of glyph\n jl = [0]*height # indexes into lines of gdata (gl)\n dout = {}\n utf8_required = False\n while True:\n if c is None:\n if key_index >= len(key_line):\n break\n c = key_line[key_index]\n if key_index < len(key_line) and key_line[key_index] == c:\n end_col += str_util.get_width(ord(c))\n key_index += 1\n continue\n out = []\n for k in range(height):\n l = gl[k]\n j = jl[k]\n y = 0\n fill = 0\n while y < end_col - start_col:\n if j >= len(l):\n fill = end_col - start_col - y\n break\n y += str_util.get_width(ord(l[j]))\n j += 1\n assert y + fill == end_col - start_col, \\\n `y, fill, end_col`\n \n segment = l[jl[k]:j]\n if not SAFE_ASCII_DEC_SPECIAL_RE.match(segment):\n utf8_required = True\n \n out.append(segment + \" \" * fill)\n jl[k] = j\n\n start_col = end_col\n dout[c] = (y + fill, out)\n c = None\n return dout, utf8_required\n\n_all_fonts = []\ndef get_all_fonts():\n \"\"\"\n Return a list of (font name, font class) tuples.\n \"\"\"\n return _all_fonts[:]\n\ndef add_font(name, cls):\n _all_fonts.append((name, cls))\n\nclass Font(object):\n def __init__(self):\n assert self.height\n assert self.data\n self.char = {}\n self.canvas = {}\n self.utf8_required = False\n for gdata in self.data:\n self.add_glyphs(gdata)\n \n\n def add_glyphs(self, gdata):\n d, utf8_required = separate_glyphs(gdata, self.height)\n self.char.update(d)\n self.utf8_required |= utf8_required\n\n def characters(self):\n l = self.char.keys()\n l.sort()\n return \"\".join(l)\n\n def char_width(self, c):\n if self.char.has_key(c):\n return self.char[c][0]\n return 0\n \n def char_data(self, c):\n return self.char[c][1]\n\n def render(self, c):\n if c in self.canvas:\n return self.canvas[c]\n width, l = self.char[c]\n tl = []\n csl = []\n for d in l:\n t, cs = apply_target_encoding(d)\n tl.append(t)\n csl.append(cs)\n canv = TextCanvas(tl, None, csl, maxcol=width, \n check_width=False)\n self.canvas[c] = canv\n return canv\n \n\n \n#safe_palette = utf8decode(\"┘┐┌└┼─├┤┴┬│\")\n#more_palette = utf8decode(\"═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬○\")\n#block_palette = utf8decode(\"▄#█#▀#▌#▐#▖#▗#▘#▙#▚#▛#▜#▝#▞#▟\")\n\nclass Thin3x3Font(Font):\n height = 3\n data = [utf8decode(\"\"\"\n000111222333444555666777888999 !\n┌─┐ ┐ ┌─┐┌─┐ ┐┌─ ┌─ ┌─┐┌─┐┌─┐ │\n│ │ │ ┌─┘ ─┤└─┼└─┐├─┐ ┼├─┤└─┤ │\n└─┘ ┴ └─ └─┘ ┴ ─┘└─┘ ┴└─┘ ─┘ .\n\"\"\"), utf8decode(r\"\"\"\n\"###$$$%%%'*++,--.///:;==???[[\\\\\\]]^__`\n\" ┼┼┌┼┐O /' /.. _┌─┐┌ \\ ┐^ `\n ┼┼└┼┐ / * ┼ ─ / ., _ ┌┘│ \\ │ \n └┼┘/ O , ./ . └ \\ ┘ ──\n\"\"\")]\nadd_font(\"Thin 3x3\",Thin3x3Font)\n\nclass Thin4x3Font(Font):\n height = 3\n data = Thin3x3Font.data + [utf8decode(\"\"\"\n0000111122223333444455556666777788889999 ####$$$$\n┌──┐ ┐ ┌──┐┌──┐ ┐┌── ┌── ┌──┐┌──┐┌──┐ ┼─┼┌┼┼┐\n│ │ │ ┌──┘ ─┤└──┼└──┐├──┐ ┼├──┤└──┤ ┼─┼└┼┼┐\n└──┘ ┴ └── └──┘ ┴ ──┘└──┘ ┴└──┘ ──┘ └┼┼┘\n\"\"\")]\nadd_font(\"Thin 4x3\",Thin4x3Font)\n\nclass HalfBlock5x4Font(Font):\n height = 4\n data = [utf8decode(\"\"\"\n00000111112222233333444445555566666777778888899999 !!\n▄▀▀▄ ▄█ ▄▀▀▄ ▄▀▀▄ ▄ █ █▀▀▀ ▄▀▀ ▀▀▀█ ▄▀▀▄ ▄▀▀▄ █ \n█ █ █ ▄▀ ▄▀ █▄▄█ █▄▄ █▄▄ ▐▌ ▀▄▄▀ ▀▄▄█ █ \n█ █ █ ▄▀ ▄ █ █ █ █ █ █ █ █ █ ▀ \n ▀▀ ▀▀▀ ▀▀▀▀ ▀▀ ▀ ▀▀▀ ▀▀ ▀ ▀▀ ▀▀ ▀ \n\"\"\"), utf8decode('''\n\"\"\"######$$$$$$%%%%%&&&&&((()))******++++++,,,-----..////:::;;\n█▐▌ █ █ ▄▀█▀▄ ▐▌▐▌ ▄▀▄ █ █ ▄ ▄ ▄ ▐▌ \n ▀█▀█▀ ▀▄█▄ █ ▀▄▀ ▐▌ ▐▌ ▄▄█▄▄ ▄▄█▄▄ ▄▄▄▄ █ ▀ ▀ \n ▀█▀█▀ ▄ █ █ ▐▌▄ █ ▀▄▌▐▌ ▐▌ ▄▀▄ █ ▐▌ ▀ ▄▀ \n ▀ ▀ ▀▀▀ ▀ ▀ ▀▀ ▀ ▀ ▄▀ ▀ ▀ \n'''), utf8decode(r\"\"\"\n<<<<<=====>>>>>?????@@@@@@[[[[\\\\\\\\]]]]^^^^____```{{{{||}}}}~~~~''´´´\n ▄▀ ▀▄ ▄▀▀▄ ▄▀▀▀▄ █▀▀ ▐▌ ▀▀█ ▄▀▄ ▀▄ ▄▀ █ ▀▄ ▄ █ ▄▀ \n▄▀ ▀▀▀▀ ▀▄ ▄▀ █ █▀█ █ █ █ ▄▀ █ ▀▄ ▐▐▌▌ \n ▀▄ ▀▀▀▀ ▄▀ ▀ █ ▀▀▀ █ ▐▌ █ █ █ █ ▀ \n ▀ ▀ ▀ ▀▀▀ ▀▀▀ ▀ ▀▀▀ ▀▀▀▀ ▀ ▀ ▀ \n\"\"\"), utf8decode('''\nAAAAABBBBBCCCCCDDDDDEEEEEFFFFFGGGGGHHHHHIIJJJJJKKKKK\n▄▀▀▄ █▀▀▄ ▄▀▀▄ █▀▀▄ █▀▀▀ █▀▀▀ ▄▀▀▄ █ █ █ █ █ █ \n█▄▄█ █▄▄▀ █ █ █ █▄▄ █▄▄ █ █▄▄█ █ █ █▄▀ \n█ █ █ █ █ ▄ █ █ █ █ █ ▀█ █ █ █ ▄ █ █ ▀▄ \n▀ ▀ ▀▀▀ ▀▀ ▀▀▀ ▀▀▀▀ ▀ ▀▀ ▀ ▀ ▀ ▀▀ ▀ ▀ \n'''), utf8decode('''\nLLLLLMMMMMMNNNNNOOOOOPPPPPQQQQQRRRRRSSSSSTTTTT\n█ █▄ ▄█ ██ █ ▄▀▀▄ █▀▀▄ ▄▀▀▄ █▀▀▄ ▄▀▀▄ ▀▀█▀▀\n█ █ ▀ █ █▐▌█ █ █ █▄▄▀ █ █ █▄▄▀ ▀▄▄ █ \n█ █ █ █ ██ █ █ █ █ ▌█ █ █ ▄ █ █\n▀▀▀▀ ▀ ▀ ▀ ▀ ▀▀ ▀ ▀▀▌ ▀ ▀ ▀▀ ▀\n'''), utf8decode('''\nUUUUUVVVVVVWWWWWWXXXXXXYYYYYYZZZZZ\n█ █ █ █ █ █ █ █ █ █ ▀▀▀█ \n█ █ ▐▌ ▐▌ █ ▄ █ ▀▄▀ ▀▄▀ ▄▀ \n█ █ █ █ ▐▌█▐▌ ▄▀ ▀▄ █ █ \n ▀▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀▀▀▀ \n'''), utf8decode('''\naaaaabbbbbcccccdddddeeeeeffffggggghhhhhiijjjjkkkkk\n █ █ ▄▀▀ █ ▄ ▄ █\n ▀▀▄ █▀▀▄ ▄▀▀▄ ▄▀▀█ ▄▀▀▄ ▀█▀ ▄▀▀▄ █▀▀▄ ▄ ▄ █ ▄▀ \n▄▀▀█ █ █ █ ▄ █ █ █▀▀ █ ▀▄▄█ █ █ █ █ █▀▄ \n ▀▀▀ ▀▀▀ ▀▀ ▀▀▀ ▀▀ ▀ ▄▄▀ ▀ ▀ ▀ ▄▄▀ ▀ ▀ \n'''), utf8decode('''\nllmmmmmmnnnnnooooopppppqqqqqrrrrssssstttt\n█ █ \n█ █▀▄▀▄ █▀▀▄ ▄▀▀▄ █▀▀▄ ▄▀▀█ █▀▀ ▄▀▀▀ ▀█▀ \n█ █ █ █ █ █ █ █ █ █ █ █ █ ▀▀▄ █\n▀ ▀ ▀ ▀ ▀ ▀▀ █▀▀ ▀▀█ ▀ ▀▀▀ ▀\n'''), utf8decode('''\nuuuuuvvvvvwwwwwwxxxxxxyyyyyzzzzz\n \n█ █ █ █ █ ▄ █ ▀▄ ▄▀ █ █ ▀▀█▀\n█ █ ▐▌▐▌ ▐▌█▐▌ ▄▀▄ ▀▄▄█ ▄▀ \n ▀▀ ▀▀ ▀ ▀ ▀ ▀ ▄▄▀ ▀▀▀▀\n''')]\nadd_font(\"Half Block 5x4\",HalfBlock5x4Font)\n\nclass HalfBlock6x5Font(Font):\n height = 5\n data = [utf8decode(\"\"\"\n000000111111222222333333444444555555666666777777888888999999 ..::////\n▄▀▀▀▄ ▄█ ▄▀▀▀▄ ▄▀▀▀▄ ▄ █ █▀▀▀▀ ▄▀▀▀ ▀▀▀▀█ ▄▀▀▀▄ ▄▀▀▀▄ █\n█ █ █ █ █ █ █ █ █ ▐▌ █ █ █ █ ▀ ▐▌\n█ █ █ ▄▀ ▀▀▄ ▀▀▀█▀ ▀▀▀▀▄ █▀▀▀▄ █ ▄▀▀▀▄ ▀▀▀█ ▄ █\n█ █ █ ▄▀ ▄ █ █ █ █ █ ▐▌ █ █ █ ▐▌\n ▀▀▀ ▀▀▀ ▀▀▀▀▀ ▀▀▀ ▀ ▀▀▀▀ ▀▀▀ ▀ ▀▀▀ ▀▀▀ ▀ ▀\n\"\"\")]\nadd_font(\"Half Block 6x5\",HalfBlock6x5Font)\n\nclass HalfBlockHeavy6x5Font(Font):\n height = 5\n data = [utf8decode(\"\"\"\n000000111111222222333333444444555555666666777777888888999999 ..::////\n▄███▄ ▐█▌ ▄███▄ ▄███▄ █▌ █████ ▄███▄ █████ ▄███▄ ▄███▄ █▌\n█▌ ▐█ ▀█▌ ▀ ▐█ ▀ ▐█ █▌ █▌ █▌ █▌ █▌ █▌ ▐█ █▌ ▐█ █▌ ▐█\n█▌ ▐█ █▌ ▄█▀ ██▌ █████ ████▄ ████▄ ▐█ ▐███▌ ▀████ █▌\n█▌ ▐█ █▌ ▄█▀ ▄ ▐█ █▌ ▐█ █▌ ▐█ █▌ █▌ ▐█ ▐█ █▌▐█\n▀███▀ ███▌ █████ ▀███▀ █▌ ████▀ ▀███▀ ▐█ ▀███▀ ▀███▀ █▌ █▌\n\"\"\")]\nadd_font(\"Half Block Heavy 6x5\",HalfBlockHeavy6x5Font)\n\nclass Thin6x6Font(Font):\n height = 6\n data = [utf8decode(\"\"\"\n000000111111222222333333444444555555666666777777888888999999''\n┌───┐ ┐ ┌───┐ ┌───┐ ┐ ┌─── ┌─── ┌───┐ ┌───┐ ┌───┐ │\n│ │ │ │ │ ┌ │ │ │ │ │ │ │ │ \n│ / │ │ ┌───┘ ─┤ └──┼─ └───┐ ├───┐ ┼ ├───┤ └───┤ \n│ │ │ │ │ │ │ │ │ │ │ │ │ \n└───┘ ┴ └─── └───┘ ┴ ───┘ └───┘ ┴ └───┘ ───┘ \n\n\"\"\"),utf8decode(r'''\n!! \"\"\"######$$$$$$%%%%%%&&&&&&((()))******++++++\n│ ││ ┌ ┌ ┌─┼─┐ ┌┐ / ┌─┐ / \\ \n│ ─┼─┼─ │ │ └┘ / │ │ │ │ \\ / │\n│ │ │ └─┼─┐ / ┌─\\┘ │ │ ──X── ──┼── \n│ ─┼─┼─ │ │ / ┌┐ │ \\, │ │ / \\ │\n. ┘ ┘ └─┼─┘ / └┘ └───\\ \\ / \n\n'''),utf8decode(r\"\"\"\n,,-----..//////::;;<<<<=====>>>>??????@@@@@@\n / ┌───┐ ┌───┐\n / . . / ──── \\ │ │┌──┤\n ──── / / \\ ┌─┘ ││ │ \n / . , \\ ──── / │ │└──┘\n, . / \\ / . └───┘\n\n\"\"\"),utf8decode(r\"\"\"\n[[\\\\\\\\\\\\]]^^^____``{{||}}~~~~~~\n┌ \\ ┐ /\\ \\ ┌ │ ┐ \n│ \\ │ │ │ │ ┌─┐\n│ \\ │ ┤ │ ├ └─┘\n│ \\ │ │ │ │ \n└ \\ ┘ ──── └ │ ┘ \n\n\"\"\"),utf8decode(\"\"\"\nAAAAAABBBBBBCCCCCCDDDDDDEEEEEEFFFFFFGGGGGGHHHHHHIIJJJJJJ\n┌───┐ ┬───┐ ┌───┐ ┬───┐ ┬───┐ ┬───┐ ┌───┐ ┬ ┬ ┬ ┬\n│ │ │ │ │ │ │ │ │ │ │ │ │ │\n├───┤ ├───┤ │ │ │ ├── ├── │ ──┬ ├───┤ │ │\n│ │ │ │ │ │ │ │ │ │ │ │ │ │ ┬ │\n┴ ┴ ┴───┘ └───┘ ┴───┘ ┴───┘ ┴ └───┘ ┴ ┴ ┴ └───┘\n\n\"\"\"),utf8decode(\"\"\"\nKKKKKKLLLLLLMMMMMMNNNNNNOOOOOOPPPPPPQQQQQQRRRRRRSSSSSS\n┬ ┬ ┬ ┌─┬─┐ ┬─┐ ┬ ┌───┐ ┬───┐ ┌───┐ ┬───┐ ┌───┐\n│ ┌─┘ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │\n├─┴┐ │ │ │ │ │ │ │ │ │ ├───┘ │ │ ├─┬─┘ └───┐\n│ └┐ │ │ │ │ │ │ │ │ │ │ ┐│ │ └─┐ │\n┴ ┴ ┴───┘ ┴ ┴ ┴ └─┴ └───┘ ┴ └──┼┘ ┴ ┴ └───┘\n └\n\"\"\"),utf8decode(\"\"\"\nTTTTTTUUUUUUVVVVVVWWWWWWXXXXXXYYYYYYZZZZZZ\n┌─┬─┐ ┬ ┬ ┬ ┬ ┬ ┬ ┬ ┬ ┬ ┬ ┌───┐ \n │ │ │ │ │ │ │ └┐ ┌┘ │ │ ┌─┘ \n │ │ │ │ │ │ │ │ ├─┤ └─┬─┘ ┌┘ \n │ │ │ └┐ ┌┘ │ │ │ ┌┘ └┐ │ ┌┘ \n ┴ └───┘ └─┘ └─┴─┘ ┴ ┴ ┴ └───┘ \n \n\"\"\"),utf8decode(\"\"\"\naaaaaabbbbbbccccccddddddeeeeeefffgggggghhhhhhiijjj\n ┌─┐ \n │ │ │ │ . .\n┌───┐ ├───┐ ┌───┐ ┌───┤ ┌───┐ ┼ ┌───┐ ├───┐ ┐ ┐\n┌───┤ │ │ │ │ │ ├───┘ │ │ │ │ │ │ │\n└───┴ └───┘ └───┘ └───┘ └───┘ ┴ └───┤ ┴ ┴ ┴ │\n └───┘ ─┘\n\"\"\"),utf8decode(\"\"\"\nkkkkkkllmmmmmmnnnnnnooooooppppppqqqqqqrrrrrssssss\n \n│ │ \n│ ┌─ │ ┬─┬─┐ ┬───┐ ┌───┐ ┌───┐ ┌───┐ ┬──┐ ┌───┐\n├─┴┐ │ │ │ │ │ │ │ │ │ │ │ │ │ └───┐\n┴ └─ └ ┴ ┴ ┴ ┴ └───┘ ├───┘ └───┤ ┴ └───┘\n │ │ \n\"\"\"),utf8decode(\"\"\"\nttttuuuuuuvvvvvvwwwwwwxxxxxxyyyyyyzzzzzz\n \n │ \n─┼─ ┬ ┬ ┬ ┬ ┬ ┬ ─┐ ┌─ ┬ ┬ ────┬\n │ │ │ └┐ ┌┘ │ │ │ ├─┤ │ │ ┌───┘\n └─ └───┴ └─┘ └─┴─┘ ─┘ └─ └───┤ ┴────\n └───┘\n\"\"\")]\nadd_font(\"Thin 6x6\",Thin6x6Font)\n\nclass HalfBlock7x7Font(Font):\n height = 7\n data = [utf8decode(\"\"\"\n0000000111111122222223333333444444455555556666666777777788888889999999'''\n ▄███▄ ▐█▌ ▄███▄ ▄███▄ █▌ ▐█████▌ ▄███▄ ▐█████▌ ▄███▄ ▄███▄ ▐█\n▐█ █▌ ▀█▌ ▐█ █▌▐█ █▌▐█ █▌ ▐█ ▐█ ▐█ ▐█ █▌▐█ █▌▐█\n▐█ ▐ █▌ █▌ █▌ ▐██ ▐█████▌▐████▄ ▐████▄ █▌ █████ ▀████▌ \n▐█ ▌ █▌ █▌ ▄█▀ █▌ █▌ █▌▐█ █▌ ▐█ ▐█ █▌ █▌ \n▐█ █▌ █▌ ▄█▀ ▐█ █▌ █▌ █▌▐█ █▌ █▌ ▐█ █▌ █▌ \n ▀███▀ ███▌ ▐█████▌ ▀███▀ █▌ ▐████▀ ▀███▀ ▐█ ▀███▀ ▀███▀ \n\n\"\"\"),utf8decode('''\n!!! \"\"\"\"\"#######$$$$$$$%%%%%%%&&&&&&&(((())))*******++++++\n▐█ ▐█ █▌ ▐█ █▌ █ ▄ █▌ ▄█▄ █▌▐█ ▄▄ ▄▄ \n▐█ ▐█ █▌▐█████▌ ▄███▄ ▐█▌▐█ ▐█ █▌ ▐█ █▌ ▀█▄█▀ ▐█\n▐█ ▐█ █▌ ▐█▄█▄▄ ▀ █▌ ███ █▌ ▐█ ▐█████▌ ████▌\n▐█ ▐█████▌ ▀▀█▀█▌ ▐█ ▄ ███▌▄ █▌ ▐█ ▄█▀█▄ ▐█ \n ▐█ █▌ ▀███▀ █▌▐█▌▐█ █▌ ▐█ █▌ ▀▀ ▀▀ \n▐█ █ ▐█ ▀ ▀██▀█▌ █▌▐█ \n \n'''),utf8decode(\"\"\"\n,,,------.../////:::;;;<<<<<<<======>>>>>>>???????@@@@@@@\n █▌ ▄█▌ ▐█▄ ▄███▄ ▄███▄ \n ▐█ ▐█ ▐█ ▄█▀ ▐████▌ ▀█▄ ▐█ █▌▐█ ▄▄█▌ \n ▐████▌ █▌ ▐██ ██▌ █▌ ▐█▐█▀█▌\n ▐█ ▐█ ▐█ ▀█▄ ▐████▌ ▄█▀ █▌ ▐█▐█▄█▌\n █▌ ▀ ▀█▌ ▐█▀ ▐█ ▀▀▀ \n▐█ ▐█ ▐█ █▌ ▀███▀ \n▀ \n\"\"\"),utf8decode(r\"\"\"\n[[[[\\\\\\\\\\]]]]^^^^^^^_____```{{{{{|||}}}}}~~~~~~~´´´\n▐██▌▐█ ▐██▌ ▐█▌ ▐█ █▌▐█ ▐█ █▌ \n▐█ █▌ █▌ ▐█ █▌ █▌ █▌ ▐█ ▐█ ▄▄ ▐█ \n▐█ ▐█ █▌▐█ █▌ ▄█▌ ▐█ ▐█▄ ▐▀▀█▄▄▌\n▐█ █▌ █▌ ▀█▌ ▐█ ▐█▀ ▀▀\n▐█ ▐█ █▌ █▌ ▐█ ▐█ \n▐██▌ █▌▐██▌ █████ █▌▐█ ▐█ \n \n\"\"\"),utf8decode(\"\"\"\nAAAAAAABBBBBBBCCCCCCCDDDDDDDEEEEEEEFFFFFFFGGGGGGGHHHHHHHIIIIJJJJJJJ\n ▄███▄ ▐████▄ ▄███▄ ▐████▄ ▐█████▌▐█████▌ ▄███▄ ▐█ █▌ ██▌ █▌ \n▐█ █▌▐█ █▌▐█ ▐█ █▌▐█ ▐█ ▐█ ▐█ █▌ ▐█ █▌ \n▐█████▌▐█████ ▐█ ▐█ █▌▐████ ▐████ ▐█ ▐█████▌ ▐█ █▌\n▐█ █▌▐█ █▌▐█ ▐█ █▌▐█ ▐█ ▐█ ██▌▐█ █▌ ▐█ █▌\n▐█ █▌▐█ █▌▐█ ▐█ █▌▐█ ▐█ ▐█ █▌▐█ █▌ ▐█ ▐█ █▌\n▐█ █▌▐████▀ ▀███▀ ▐████▀ ▐█████▌▐█ ▀███▀ ▐█ █▌ ██▌ ▀███▀ \n \n\"\"\"),utf8decode(\"\"\"\nKKKKKKKLLLLLLLMMMMMMMMNNNNNNNOOOOOOOPPPPPPPQQQQQQQRRRRRRRSSSSSSS\n▐█ █▌▐█ ▄█▌▐█▄ ▐██ █▌ ▄███▄ ▐████▄ ▄███▄ ▐████▄ ▄███▄ \n▐█ █▌ ▐█ ▐█ ▐▌ █▌▐██▌ █▌▐█ █▌▐█ █▌▐█ █▌▐█ █▌▐█ \n▐█▄█▌ ▐█ ▐█ ▐▌ █▌▐█▐█ █▌▐█ █▌▐████▀ ▐█ █▌▐█████ ▀███▄ \n▐█▀█▌ ▐█ ▐█ █▌▐█ █▌█▌▐█ █▌▐█ ▐█ █▌▐█ █▌ █▌\n▐█ █▌ ▐█ ▐█ █▌▐█ ▐██▌▐█ █▌▐█ ▐█ █▌█▌▐█ █▌ █▌\n▐█ █▌▐█████▌▐█ █▌▐█ ██▌ ▀███▀ ▐█ ▀███▀ ▐█ █▌ ▀███▀ \n ▀▀ \n\"\"\"),utf8decode(\"\"\"\nTTTTTTTUUUUUUUVVVVVVVWWWWWWWWXXXXXXXYYYYYYYZZZZZZZ\n █████▌▐█ █▌▐█ █▌▐█ █▌▐█ █▌ █▌ █▌▐█████▌ \n █▌ ▐█ █▌ █▌ ▐█ ▐█ █▌ ▐█ █▌ ▐█ ▐█ █▌ \n █▌ ▐█ █▌ ▐█ █▌ ▐█ █▌ ▐█▌ ▐██ █▌ \n █▌ ▐█ █▌ ███ ▐█ ▐▌ █▌ ███ █▌ █▌\n █▌ ▐█ █▌ ▐█▌ ▐█ ▐▌ █▌ █▌ ▐█ █▌ █▌\n █▌ ▀███▀ █ ▀█▌▐█▀ ▐█ █▌ █▌ ▐█████▌ \n \n\"\"\"),utf8decode(\"\"\"\naaaaaaabbbbbbbcccccccdddddddeeeeeeefffffggggggghhhhhhhiiijjjj\n ▐█ █▌ ▄█▌ ▐█ █▌ █▌\n ▐█ █▌ ▐█ ▐█ \n ▄███▄ ▐████▄ ▄███▄ ▄████▌ ▄███▄ ▐███ ▄███▄ ▐████▄ ▐█▌ ▐█▌\n ▄▄▄█▌▐█ █▌▐█ ▐█ █▌▐█▄▄▄█▌ ▐█ ▐█ █▌▐█ █▌ █▌ █▌ \n▐█▀▀▀█▌▐█ █▌▐█ ▐█ █▌▐█▀▀▀ ▐█ ▐█▄▄▄█▌▐█ █▌ █▌ █▌\n ▀████▌▐████▀ ▀███▀ ▀████▌ ▀███▀ ▐█ ▀▀▀█▌▐█ █▌ █▌ █▌\n ▀███▀ ▐██ \n\"\"\"),utf8decode(\"\"\"\nkkkkkkkllllmmmmmmmmnnnnnnnooooooopppppppqqqqqqqrrrrrrsssssss\n▐█ ██ \n▐█ ▐█ \n▐█ ▄█▌ ▐█ ▄█▌▐█▄ ▐████▄ ▄███▄ ▐████▄ ▄████▌ ▄███▌ ▄███▄ \n▐█▄█▀ ▐█ ▐█ ▐▌ █▌▐█ █▌▐█ █▌▐█ █▌▐█ █▌▐█ ▐█▄▄▄ \n▐█▀▀█▄ ▐█ ▐█ ▐▌ █▌▐█ █▌▐█ █▌▐█ █▌▐█ █▌▐█ ▀▀▀█▌\n▐█ █▌ ▐█▌▐█ █▌▐█ █▌ ▀███▀ ▐████▀ ▀████▌▐█ ▀███▀ \n ▐█ █▌\n\"\"\"),utf8decode(\"\"\"\ntttttuuuuuuuvvvvvvvwwwwwwwwxxxxxxxyyyyyyyzzzzzzz\n █▌\n █▌\n ███▌▐█ █▌▐█ █▌▐█ █▌▐█ █▌▐█ █▌▐█████▌ \n █▌ ▐█ █▌ █▌ ▐█ ▐█ █▌ ▀█▄█▀ ▐█ █▌ ▄█▀ \n █▌ ▐█ █▌ ███ ▐█ ▐▌ █▌ ▄█▀█▄ ▐█▄▄▄█▌ ▄█▀\n █▌ ▀███▀ ▐█▌ ▀█▌▐█▀ ▐█ █▌ ▀▀▀█▌▐█████▌\n ▀███▀ \n\"\"\")]\nadd_font(\"Half Block 7x7\",HalfBlock7x7Font)\n\nif __name__ == \"__main__\":\n l = get_all_fonts()\n all_ascii = \"\".join([chr(x) for x in range(32, 127)])\n print \"Available Fonts: (U) = UTF-8 required\"\n print \"----------------\"\n for n,cls in l:\n f = cls()\n u = \"\"\n if f.utf8_required:\n u = \"(U)\"\n print (\"%-20s %3s \" % (n,u)),\n c = f.characters()\n if c == all_ascii:\n print \"Full ASCII\"\n elif c.startswith(all_ascii):\n print \"Full ASCII + \" + c[len(all_ascii):]\n else:\n print \"Characters: \" + c"}]} {"messages": [{"role": "user", "content": "Write Python code that implements util_move_ptxt_data_to_mySQL_table.py from annahs/atmos_research (path: util_move_ptxt_data_to_mySQL_table.py)."}, {"role": "assistant", "content": "# util_move_ptxt_data_to_mySQL_table.py (from annahs/atmos_research, license: mit)\n\nimport sys\nimport os\nimport numpy as np\nfrom pprint import pprint\nfrom datetime import datetime\nimport mysql.connector\nimport pickle\nimport math\n\ninstrument = 'UBCSP2' #'UBCSP2' #ECSP2\ninstrument_locn = 'WHI' #'WHI' POLAR6\n\n#this script will run through all the .ptxt files for the WHI data and put the info into the mySQL database\n\n#1. #alter the dates to set limits on data analysis range\nstart_analysis_at = datetime.strptime('20080601','%Y%m%d')\nend_analysis_at = datetime.strptime('20120411','%Y%m%d')\n\n#2. set the data_dir as the parent folder for the data, the program expects the data dir to contain subfolders named by day (eg 20120101) that contain the actual data\n#note that UTC timestamping was used in the ptxt file for 2009 and for <20120412 otherwise timestamps are in PST\ndata_dir = 'D:/2012/WHI_UBCSP2/Binary/' #'D:/2009/WHI_ECSP2/Binary/'#'D:/2012/WHI_UBCSP2/Binary/' # 'D:/2010/WHI_ECSP2/Binary/' #'D:/2012/WHI_UBCSP2/Binary/' \nos.chdir(data_dir)\n\nparameters = {\n#old calib - need this to retreive incand peak heights which I did not oiriginally write to the ptxt files\n#the first three variables are the terms of the calibration fit line which gives mass in fg/count (eg. for the UBC_SP2 in 2012 use 0.20699+0.00246x-1.09254e-7x2) 2010: 0.156 + 0.00606x + 6.3931e-7x2\n\n'BC_calib1': 0.20699 , #0 order term\n'BC_calib2': 0.00246, #1st order term\n'BC_calib3': - 1.09254e-7, #2nd order term\n'BC_density': 1.8, #density of ambient BC in g/cc\n\n#new - AD corrected calib with uncertinaty, 2009:(0.0172(+-0.00037)x + 0.01244(+-0.14983)) 2010:(0.01081(+-0.0002199)x - 0.32619(+-0.16465))\n'BC_calib1_new': 0.24826, #0 order term\n'BC_calib1_new_err': 0.05668, #0 order term +- uncertainty\n'BC_calib2_new': 0.003043, #1st order term\n'BC_calib2_new_err': 0.0002323, #1st order term +- uncertainty\n}\n\n#sample factor list - 2012 only\nsample_factor_list_file = open('D:/2012/WHI_UBCSP2/Binary/sample_rate_changes.srpckl', 'r')\nsample_factor_list = pickle.load(sample_factor_list_file)\nsample_factor_list_file.close()\n\n#database connection\ncnx = mysql.connector.connect(user='root', password='Suresh15', host='localhost', database='black_carbon')\ncursor = cnx.cursor()\n\n#create insert statement variable for database updating\nadd_particle = ('INSERT IGNORE INTO whi_sp2_single_incand_particle_data'\n '(location, instr, particle_collection_start_time,particle_collection_end_time,sample_flow,incand_pk_height,incand_sat_flag,calc_BC_mass,calc_BC_mass_LL,calc_BC_mass_UL)'\n 'VALUES (%(instrument_locn)s,%(instrument)s,%(particle_collection_start_time)s,%(particle_collection_end_time)s,%(sample_flow)s,%(incand_pk_height)s,%(incand_sat_flag)s,%(calc_BC_mass)s,%(calc_BC_mass_LL)s,%(calc_BC_mass_UL)s)')\n\n#this helper method allows conversion of BC mass from a value arrived at via an old calibration to a value arrived at via a new calibration\n#quad eqytn = ax2 + bx + c\ndef PeakHtFromMass(BC_mass,var_C,var_b,var_a):\n C = var_C \n b = var_b \n a = var_a \n\n \n c = C - BC_mass\n d = b**2-4*a*c\n\n if d < 0:\n #This equation has no real solution\"\n return np.nan\n elif d == 0:\n # This equation has one solution\n x = (-b+math.sqrt(b**2-4*a*c))/(2*a)\n return x\n\n else:\n #This equation has two solutions\n x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a)\n x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a)\n if x1 <4000:\n return x1\n if x2 <4000:\n return x2 \n\t\t\t\n\nfor directory in os.listdir(data_dir):\n\tif os.path.isdir(directory) == True and directory.startswith('20'):\n\t\n\t\tfolder_date = datetime.strptime(directory, '%Y%m%d')\n\t\n\t\tif start_analysis_at <= folder_date <= end_analysis_at:\n\t\n\t\t\tcurrent_dir = os.path.abspath(directory)\n\t\t\tos.chdir(current_dir)\n\t\t\t\n\t\t\tfor file in os.listdir('.'):\n\t\t\t\tif file.endswith('.ptxt'):\n\t\t\t\t\tprint file\n\t\t\t\t\tf = open(file, 'r+')\n\t\t\t\t\tf.readline()\n\n\t\t\t\t\tfor line in f:\n\t\t\t\t\t\tnewline = line.split('\\t')\n\t\t\t\t\t\tstart_time = float(newline[0])# + 28800 #+28800 converts to UTC from PST\n\t\t\t\t\t\tend_time = float(newline[1])# + 28800 #+28800 converts to UTC from PST\n\t\t\t\t\t\tincand_flag = float(newline[2])\n\t\t\t\t\t\tincand_sat_flag = int(newline[3])\n\t\t\t\t\t\tBC_mass = float(newline[4])\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif parameters['BC_calib3'] == 0:\n\t\t\t\t\t\t\tpk_ht = (BC_mass - parameters['BC_calib1'])/parameters['BC_calib2']\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tpk_ht = PeakHtFromMass(BC_mass, parameters['BC_calib1'], parameters['BC_calib2'], parameters['BC_calib3'])\n\t\t\t\t\t\t\n\t\t\t\t\t\tBC_mass = parameters['BC_calib2_new']*pk_ht + parameters['BC_calib1_new'] \n\t\t\t\t\t\tBC_mass_LL = (parameters['BC_calib2_new']-parameters['BC_calib2_new_err'])*pk_ht + (parameters['BC_calib1_new'] - parameters['BC_calib1_new_err'])\n\t\t\t\t\t\tBC_mass_UL = (parameters['BC_calib2_new']+parameters['BC_calib2_new_err'])*pk_ht + (parameters['BC_calib1_new'] + parameters['BC_calib1_new_err'])\n\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t##set correct sample factor - all of 2009 and 2010 were run at 1/1 -\n\t\t\t\t\t\t##note these are in UTC\n\t\t\t\t\t\t#if sample_factor_list: \n\t\t\t\t\t\t#\tfirst_sample_factor_time = calendar.timegm(sample_factor_list[0][0].utctimetuple()) #get UNIX timesoatmp for first sample factor time in UTC \n\t\t\t\t\t\t#\t#first_sample_factor_time = first_sample_factor_time - 8*3600# use if ptxt files still not UTC, ie post 20120411\n\t\t\t\t\t\t#\t\n\t\t\t\t\t\t#\tif start_time >= first_sample_factor_time:\n\t\t\t\t\t\t#\t\tsample_factor = float(sample_factor_list[0][1])\n\t\t\t\t\t\t#\t\tsample_factor_list.pop(0)\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tparticle_data = {\n\t\t\t\t\t\t'instrument': instrument,\n\t\t\t\t\t\t'instrument_locn':instrument_locn,\n\t\t\t\t\t\t'particle_collection_start_time': start_time,\n\t\t\t\t\t\t'particle_collection_end_time': end_time,\n\t\t\t\t\t\t'sample_flow': 120.,\n\t\t\t\t\t\t'incand_pk_height': pk_ht,\n\t\t\t\t\t\t'incand_sat_flag': incand_sat_flag,\n\t\t\t\t\t\t'calc_BC_mass': BC_mass,\n\t\t\t\t\t\t'calc_BC_mass_LL': BC_mass_LL,\n\t\t\t\t\t\t'calc_BC_mass_UL': BC_mass_UL,\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\tcursor.execute(add_particle, particle_data)\n\t\t\t\t\t\tcnx.commit()\n\n\t\t\tos.chdir(data_dir)\n\ncnx.close()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements download_actuals_test.py from DARKPOP/external_chromium_org_third_party_skia (path: gm/rebaseline_server/download_actuals_test.py)."}, {"role": "assistant", "content": "# gm/rebaseline_server/download_actuals_test.py (from DARKPOP/external_chromium_org_third_party_skia, license: bsd-3-clause)\n\n#!/usr/bin/python\n\n\"\"\"\nCopyright 2014 Google Inc.\n\nUse of this source code is governed by a BSD-style license that can be\nfound in the LICENSE file.\n\nTest download.py\n\nTODO(epoger): Create a command to update the expected results (in\nself._output_dir_expected) when appropriate. For now, you should:\n1. examine the results in self.output_dir_actual and make sure they are ok\n2. rm -rf self._output_dir_expected\n3. mv self.output_dir_actual self._output_dir_expected\nAlthough, if you're using an SVN checkout, this will blow away .svn directories\nwithin self._output_dir_expected, which wouldn't be good...\n\n\"\"\"\n\n# System-level imports\nimport os\n\n# Must fix up PYTHONPATH before importing from within Skia\nimport rs_fixpypath # pylint: disable=W0611\n\n# Imports from within Skia\nfrom py.utils import url_utils\nimport base_unittest\nimport download_actuals\n\nclass DownloadTest(base_unittest.TestCase):\n\n def test_fetch(self):\n \"\"\"Tests fetch() of GM results from actual-results.json .\"\"\"\n downloader = download_actuals.Download(\n actuals_base_url=url_utils.create_filepath_url(\n os.path.join(self.input_dir, 'gm-actuals')),\n gm_actuals_root_url=url_utils.create_filepath_url(\n os.path.join(self.input_dir, 'fake-gm-imagefiles')))\n downloader.fetch(\n builder_name='Test-Android-GalaxyNexus-SGX540-Arm7-Release',\n dest_dir=self.output_dir_actual)\n\ndef main():\n base_unittest.main(DownloadTest)\n\nif __name__ == '__main__':\n main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements png.py from Bysmyyr/blink-crosswalk (path: Tools/Scripts/webkitpy/style/checkers/png.py)."}, {"role": "assistant", "content": "# Tools/Scripts/webkitpy/style/checkers/png.py (from Bysmyyr/blink-crosswalk, license: bsd-3-clause)\n\n# Copyright (C) 2012 Balazs Ankes (bank@inf.u-szeged.hu) University of Szeged\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Supports checking WebKit style in png files.\"\"\"\n\nimport os\nimport re\n\nfrom webkitpy.common import checksvnconfigfile\nfrom webkitpy.common import read_checksum_from_png\nfrom webkitpy.common.system.systemhost import SystemHost\nfrom webkitpy.common.checkout.scm.detection import SCMDetector\n\nclass PNGChecker(object):\n \"\"\"Check svn:mime-type for checking style\"\"\"\n\n categories = set(['image/png'])\n\n def __init__(self, file_path, handle_style_error, scm=None, host=None):\n self._file_path = file_path\n self._handle_style_error = handle_style_error\n self._host = host or SystemHost()\n self._fs = self._host.filesystem\n self._detector = scm or SCMDetector(self._fs, self._host.executive).detect_scm_system(self._fs.getcwd())\n\n def check(self, inline=None):\n errorstr = \"\"\n config_file_path = \"\"\n detection = self._detector.display_name()\n\n if self._fs.exists(self._file_path) and self._file_path.endswith(\"-expected.png\"):\n with self._fs.open_binary_file_for_reading(self._file_path) as filehandle:\n if not read_checksum_from_png.read_checksum(filehandle):\n self._handle_style_error(0, 'image/png', 5, \"Image lacks a checksum. Generate pngs using run-webkit-tests to ensure they have a checksum.\")\n\n if detection == \"git\":\n (file_missing, autoprop_missing, png_missing) = checksvnconfigfile.check(self._host, self._fs)\n config_file_path = checksvnconfigfile.config_file_path(self._host, self._fs)\n\n if file_missing:\n self._handle_style_error(0, 'image/png', 5, \"There is no SVN config file. (%s)\" % config_file_path)\n elif autoprop_missing and png_missing:\n self._handle_style_error(0, 'image/png', 5, checksvnconfigfile.errorstr_autoprop(config_file_path) + checksvnconfigfile.errorstr_png(config_file_path))\n elif autoprop_missing:\n self._handle_style_error(0, 'image/png', 5, checksvnconfigfile.errorstr_autoprop(config_file_path))\n elif png_missing:\n self._handle_style_error(0, 'image/png', 5, checksvnconfigfile.errorstr_png(config_file_path))\n\n elif detection == \"svn\":\n prop_get = self._detector.propget(\"svn:mime-type\", self._file_path)\n if prop_get != \"image/png\":\n errorstr = \"Set the svn:mime-type property (svn propset svn:mime-type image/png %s).\" % self._file_path\n self._handle_style_error(0, 'image/png', 5, errorstr)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements deriv.py from forrestv/pyderiv (path: deriv.py)."}, {"role": "assistant", "content": "# deriv.py (from forrestv/pyderiv, license: gpl-3.0)\n\n# This file is part of pyderiv. http://forre.st/pyderiv\n#\n# pyderiv is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# at your option) any later version.\n#\n# pyderiv is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with pyderiv. If not, see .\n\nfrom __future__ import division\n\nimport math\nimport itertools\n\nimport _deriv\n\nclass Variable(object):\n def __init__(self, v):\n self.v = v\n \n def __add__(self, other):\n if not isinstance(other, (Variable, int, long, float)): return NotImplemented\n if isinstance(other, Variable): other = other.v\n return Variable(_deriv._add(self.v, other))\n __radd__ = __add__\n \n def __sub__(self, other):\n if not isinstance(other, (Variable, int, long, float)): return NotImplemented\n if isinstance(other, Variable): other = other.v\n return Variable(_deriv._sub(self.v, other))\n def __rsub__(self, other):\n if not isinstance(other, (Variable, int, long, float)): return NotImplemented\n if isinstance(other, Variable): other = other.v\n return Variable(_deriv._sub(other, self.v))\n \n def __mul__(self, other):\n if not isinstance(other, (Variable, int, long, float)): return NotImplemented\n if isinstance(other, Variable): other = other.v\n return Variable(_deriv._mul(self.v, other))\n __rmul__ = __mul__\n \n def __div__(self, other):\n if not isinstance(other, (Variable, int, long, float)): return NotImplemented\n if isinstance(other, Variable): other = other.v\n return Variable(_deriv._div(self.v, other))\n __truediv__ = __div__\n def __rdiv__(self, other):\n if not isinstance(other, (Variable, int, long, float)): return NotImplemented\n if isinstance(other, Variable): other = other.v\n return Variable(_deriv._div(other, self.v))\n __rtruediv__ = __rdiv__\n \n def __pow__(self, other):\n if not isinstance(other, (Variable, int, long, float)): return NotImplemented\n if isinstance(other, Variable): other = other.v\n return Variable(_deriv._pow(self.v, other))\n def __rpow__(self, other):\n if not isinstance(other, (Variable, int, long, float)): return NotImplemented\n if isinstance(other, Variable): other = other.v\n return Variable(_deriv._pow(other, self.v))\n \n def __repr__(self):\n return \"Variable(%r)\" % (self.v,)\n\nid_generator = itertools.count()\n\ndef varying(value, d_count=1, noise=False):\n assert d_count >= 0\n \n if d_count == 0:\n return value\n \n o = id_generator.next()\n if noise:\n o = ~o\n \n v = (value, {o: 1})\n p = v\n for i in xrange(d_count - 1):\n p[1][o] = (p[1][o], {o: 0})\n p = p[1][o]\n \n return Variable(v)\n\ndef sin(self):\n if isinstance(self, Variable):\n return Variable(_deriv._sin(self.v))\n else:\n return math.sin(self)\n\ndef cos(self):\n if isinstance(self, Variable):\n return Variable(_deriv._cos(self.v))\n else:\n return math.cos(self)\n\ndef log(self):\n if isinstance(self, Variable):\n return Variable(_deriv.log(self.v))\n else:\n return math.log(self)\n\ndef v(self):\n if not isinstance(self, Variable):\n return self\n return _deriv._v(self.v)\n\ndef d(self, *others):\n if not isinstance(self, Variable):\n return 0\n \n for other in others:\n assert isinstance(other, Variable)\n assert len(other.v[1]) == 1\n \n self = Variable(_deriv._d(self.v).get(other.v[1].keys()[0], 0))\n \n return self\n\ndef get_matrix(output, input, n=1):\n return [[v(d(y, *(x,)*n)) for x in input] for y in output]\n\ndef matrix_wrapper(n):\n def b(f):\n def a(args, *extra_args, **extra_kwargs):\n args2 = [varying(x) for x in args]\n result2 = f(args2, *extra_args, **extra_kwargs)\n result = result2[0]\n return (([v(x) for x in result], get_matrix(result, args2, n)),) + tuple(result2[1:])\n return a\n return b\n\njacobian_decorator = matrix_wrapper(1)\nhessian_decorator = matrix_wrapper(2)\n\nif __name__ == \"__main__\":\n w, x, y, z = [varying(n) for n in [3, 4, 5, 6]]\n \n #q = w / x + y * z + 1 / w\n \n q = \\\n (w + 4) + (4 + w) + (w + x) + (x + w) + \\\n (w - 4) + (4 - w) + (w - x) + (x - w) + \\\n (w * 4) + (4 * w) + (w * x) + (x * w) + \\\n (w / 4) + (4 / w) + (w / x) + (x / w) + \\\n (w **4) + (4 **w) + (w **x) + (x **w) + \\\n 0\n \n #q = w ** x\n \n print q\n \n print \"q\", v(q)\n \n print \"dq/dw\", v(d(q, w))\n print \"dq/dx\", v(d(q, x))\n print \"dq/dy\", v(d(q, y))\n print \"dq/dz\", v(d(q, z))\n \n print \"ddq/dw\", v(d(q, w, w))\n print \"ddq/dx\", v(d(q, x, x))\n print \"ddq/dy\", v(d(q, y, y))\n print \"ddq/dz\", v(d(q, z, z))\n \n def f((a, b, c)):\n return ((a + b + c, a * b * c, a * b + c, a + b * c, a * a + b * b + c * c), 5)\n \n j = jacobian_decorator(f)\n h = hessian_decorator(f)\n \n print f((1., 2., 3.))\n print j((1., 2., 3.))\n print h((1., 2., 3.))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements Benchmarks.py from nikoonia/gem5v (path: configs/common/Benchmarks.py)."}, {"role": "assistant", "content": "# configs/common/Benchmarks.py (from nikoonia/gem5v, license: bsd-3-clause)\n\n# Copyright (c) 2006-2007 The Regents of The University of Michigan\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met: redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer;\n# redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution;\n# neither the name of the copyright holders nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# Authors: Ali Saidi\n\nfrom SysPaths import script, disk, binary\nfrom os import environ as env\nfrom m5.defines import buildEnv\n\nclass SysConfig:\n def __init__(self, script=None, mem=None, disk=None):\n self.scriptname = script\n self.diskname = disk\n self.memsize = mem\n\n def script(self):\n if self.scriptname:\n return script(self.scriptname)\n else:\n return ''\n\n def mem(self):\n if self.memsize:\n return self.memsize\n else:\n return '128MB'\n\n def disk(self):\n if self.diskname:\n return disk(self.diskname)\n elif buildEnv['TARGET_ISA'] == 'alpha':\n return env.get('LINUX_IMAGE', disk('linux-latest.img'))\n elif buildEnv['TARGET_ISA'] == 'x86':\n return env.get('LINUX_IMAGE', disk('x86root.img'))\n elif buildEnv['TARGET_ISA'] == 'arm':\n return env.get('LINUX_IMAGE', disk('linux-arm-ael.img'))\n else:\n print \"Don't know what default disk image to use for %s ISA\" % \\\n buildEnv['TARGET_ISA']\n exit(1)\n\n# Benchmarks are defined as a key in a dict which is a list of SysConfigs\n# The first defined machine is the test system, the others are driving systems\n\nBenchmarks = {\n 'PovrayBench': [SysConfig('povray-bench.rcS', '512MB', 'povray.img')],\n 'PovrayAutumn': [SysConfig('povray-autumn.rcS', '512MB', 'povray.img')],\n\n 'NetperfStream': [SysConfig('netperf-stream-client.rcS'),\n SysConfig('netperf-server.rcS')],\n 'NetperfStreamUdp': [SysConfig('netperf-stream-udp-client.rcS'),\n SysConfig('netperf-server.rcS')],\n 'NetperfUdpLocal': [SysConfig('netperf-stream-udp-local.rcS')],\n 'NetperfStreamNT': [SysConfig('netperf-stream-nt-client.rcS'),\n SysConfig('netperf-server.rcS')],\n 'NetperfMaerts': [SysConfig('netperf-maerts-client.rcS'),\n SysConfig('netperf-server.rcS')],\n 'SurgeStandard': [SysConfig('surge-server.rcS', '512MB'),\n SysConfig('surge-client.rcS', '256MB')],\n 'SurgeSpecweb': [SysConfig('spec-surge-server.rcS', '512MB'),\n SysConfig('spec-surge-client.rcS', '256MB')],\n 'Nhfsstone': [SysConfig('nfs-server-nhfsstone.rcS', '512MB'),\n SysConfig('nfs-client-nhfsstone.rcS')],\n 'Nfs': [SysConfig('nfs-server.rcS', '900MB'),\n SysConfig('nfs-client-dbench.rcS')],\n 'NfsTcp': [SysConfig('nfs-server.rcS', '900MB'),\n SysConfig('nfs-client-tcp.rcS')],\n 'IScsiInitiator': [SysConfig('iscsi-client.rcS', '512MB'),\n SysConfig('iscsi-server.rcS', '512MB')],\n 'IScsiTarget': [SysConfig('iscsi-server.rcS', '512MB'),\n SysConfig('iscsi-client.rcS', '512MB')],\n 'Validation': [SysConfig('iscsi-server.rcS', '512MB'),\n SysConfig('iscsi-client.rcS', '512MB')],\n 'Ping': [SysConfig('ping-server.rcS',),\n SysConfig('ping-client.rcS')],\n\n 'ValAccDelay': [SysConfig('devtime.rcS', '512MB')],\n 'ValAccDelay2': [SysConfig('devtimewmr.rcS', '512MB')],\n 'ValMemLat': [SysConfig('micro_memlat.rcS', '512MB')],\n 'ValMemLat2MB': [SysConfig('micro_memlat2mb.rcS', '512MB')],\n 'ValMemLat8MB': [SysConfig('micro_memlat8mb.rcS', '512MB')],\n 'ValMemLat': [SysConfig('micro_memlat8.rcS', '512MB')],\n 'ValTlbLat': [SysConfig('micro_tlblat.rcS', '512MB')],\n 'ValSysLat': [SysConfig('micro_syscall.rcS', '512MB')],\n 'ValCtxLat': [SysConfig('micro_ctx.rcS', '512MB')],\n 'ValStream': [SysConfig('micro_stream.rcS', '512MB')],\n 'ValStreamScale': [SysConfig('micro_streamscale.rcS', '512MB')],\n 'ValStreamCopy': [SysConfig('micro_streamcopy.rcS', '512MB')],\n\n 'MutexTest': [SysConfig('mutex-test.rcS', '128MB')],\n 'ArmAndroid-GB': [SysConfig('null.rcS', '256MB',\n 'ARMv7a-Gingerbread-Android.SMP.mouse.nolock.clean.img')],\n 'bbench-gb': [SysConfig('bbench-gb.rcS', '256MB',\n 'ARMv7a-Gingerbread-Android.SMP.mouse.nolock.img')],\n 'ArmAndroid-ICS': [SysConfig('null.rcS', '256MB',\n 'ARMv7a-ICS-Android.SMP.nolock.clean.img')],\n 'bbench-ics': [SysConfig('bbench-ics.rcS', '256MB',\n 'ARMv7a-ICS-Android.SMP.nolock.img')]\n}\n\nbenchs = Benchmarks.keys()\nbenchs.sort()\nDefinedBenchmarks = \", \".join(benchs)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements 0023_attachment_m2m.py from mastizada/kuma (path: kuma/wiki/migrations/0023_attachment_m2m.py)."}, {"role": "assistant", "content": "# kuma/wiki/migrations/0023_attachment_m2m.py (from mastizada/kuma, license: mpl-2.0)\n\n# encoding: utf-8\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n\n # Adding model 'DocumentAttachment'\n db.create_table('wiki_documentattachment', (\n ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('file', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['attachments.Attachment'])),\n ('document', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['wiki.Document'])),\n ('attached_by', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True)),\n ('name', self.gf('django.db.models.fields.TextField')()),\n ))\n db.send_create_signal('attachments', ['DocumentAttachment'])\n\n def backwards(self, orm):\n\n # Deleting model 'DocumentAttachment'\n db.delete_table('wiki_documentattachment')\n\n models = {\n 'auth.group': {\n 'Meta': {'object_name': 'Group'},\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),\n 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['auth.Permission']\", 'symmetrical': 'False', 'blank': 'True'})\n },\n 'auth.permission': {\n 'Meta': {'ordering': \"('content_type__app_label', 'content_type__model', 'codename')\", 'unique_together': \"(('content_type', 'codename'),)\", 'object_name': 'Permission'},\n 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['contenttypes.ContentType']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})\n },\n 'auth.user': {\n 'Meta': {'object_name': 'User'},\n 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),\n 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),\n 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),\n 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['auth.Group']\", 'symmetrical': 'False', 'blank': 'True'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),\n 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),\n 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),\n 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),\n 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['auth.Permission']\", 'symmetrical': 'False', 'blank': 'True'}),\n 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})\n },\n 'contenttypes.contenttype': {\n 'Meta': {'ordering': \"('name',)\", 'unique_together': \"(('app_label', 'model'),)\", 'object_name': 'ContentType', 'db_table': \"'django_content_type'\"},\n 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})\n },\n 'tidings.watch': {\n 'Meta': {'object_name': 'Watch'},\n 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['contenttypes.ContentType']\", 'null': 'True', 'blank': 'True'}),\n 'email': ('django.db.models.fields.EmailField', [], {'db_index': 'True', 'max_length': '75', 'null': 'True', 'blank': 'True'}),\n 'event_type': ('django.db.models.fields.CharField', [], {'max_length': '30', 'db_index': 'True'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),\n 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'db_index': 'True'}),\n 'secret': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}),\n 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['auth.User']\", 'null': 'True', 'blank': 'True'})\n },\n 'attachments.attachment': {\n 'Meta': {'object_name': 'Attachment', 'db_table': \"'wiki_attachment'\"},\n 'current_revision': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'current_rev'\", 'null': 'True', 'to': \"orm['attachments.AttachmentRevision']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'mindtouch_attachment_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'db_index': 'True'}),\n 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}),\n 'slug': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),\n 'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})\n },\n 'attachments.attachmentrevision': {\n 'Meta': {'object_name': 'AttachmentRevision', 'db_table': \"'wiki_attachmentrevision'\"},\n 'attachment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'revisions'\", 'to': \"orm['attachments.Attachment']\"}),\n 'comment': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),\n 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'created_attachment_revisions'\", 'to': \"orm['auth.User']\"}),\n 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),\n 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '500'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'is_approved': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),\n 'is_mindtouch_migration': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),\n 'mime_type': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),\n 'mindtouch_old_id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'null': 'True', 'db_index': 'True'}),\n 'slug': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'db_index': 'True'}),\n 'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'db_index': 'True'})\n },\n 'wiki.document': {\n 'Meta': {'unique_together': \"(('parent', 'locale'), ('slug', 'locale'))\", 'object_name': 'Document'},\n 'category': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),\n 'current_revision': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'current_for+'\", 'null': 'True', 'to': \"orm['wiki.Revision']\"}),\n 'defer_rendering': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),\n 'files': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['attachments.Attachment']\", 'through': \"orm['wiki.DocumentAttachment']\", 'symmetrical': 'False'}),\n 'html': ('django.db.models.fields.TextField', [], {}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'is_localizable': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),\n 'is_template': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),\n 'last_rendered_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),\n 'locale': ('kuma.core.fields.LocaleField', [], {'default': \"'en-US'\", 'max_length': '7', 'db_index': 'True'}),\n 'mindtouch_page_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'db_index': 'True'}),\n 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}),\n 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': \"'translations'\", 'null': 'True', 'to': \"orm['wiki.Document']\"}),\n 'parent_topic': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': \"'children'\", 'null': 'True', 'to': \"orm['wiki.Document']\"}),\n 'related_documents': ('django.db.models.fields.related.ManyToManyField', [], {'to': \"orm['wiki.Document']\", 'through': \"orm['wiki.RelatedDocument']\", 'symmetrical': 'False'}),\n 'render_scheduled_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),\n 'render_started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),\n 'rendered_errors': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),\n 'rendered_html': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),\n 'slug': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),\n 'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})\n },\n 'wiki.documentattachment': {\n 'Meta': {'object_name': 'DocumentAttachment'},\n 'attached_by': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['auth.User']\", 'null': 'True'}),\n 'document': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['wiki.Document']\"}),\n 'file': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['attachments.Attachment']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.TextField', [], {})\n },\n 'wiki.documenttag': {\n 'Meta': {'object_name': 'DocumentTag'},\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'})\n },\n 'wiki.editortoolbar': {\n 'Meta': {'object_name': 'EditorToolbar'},\n 'code': ('django.db.models.fields.TextField', [], {'max_length': '2000'}),\n 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'created_toolbars'\", 'to': \"orm['auth.User']\"}),\n 'default': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})\n },\n 'wiki.firefoxversion': {\n 'Meta': {'unique_together': \"(('item_id', 'document'),)\", 'object_name': 'FirefoxVersion'},\n 'document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'firefox_version_set'\", 'to': \"orm['wiki.Document']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'item_id': ('django.db.models.fields.IntegerField', [], {})\n },\n 'wiki.helpfulvote': {\n 'Meta': {'object_name': 'HelpfulVote'},\n 'anonymous_id': ('django.db.models.fields.CharField', [], {'max_length': '40', 'db_index': 'True'}),\n 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),\n 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'poll_votes'\", 'null': 'True', 'to': \"orm['auth.User']\"}),\n 'document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'poll_votes'\", 'to': \"orm['wiki.Document']\"}),\n 'helpful': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'user_agent': ('django.db.models.fields.CharField', [], {'max_length': '1000'})\n },\n 'wiki.operatingsystem': {\n 'Meta': {'unique_together': \"(('item_id', 'document'),)\", 'object_name': 'OperatingSystem'},\n 'document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'operating_system_set'\", 'to': \"orm['wiki.Document']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'item_id': ('django.db.models.fields.IntegerField', [], {})\n },\n 'wiki.relateddocument': {\n 'Meta': {'ordering': \"['-in_common']\", 'object_name': 'RelatedDocument'},\n 'document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'related_from'\", 'to': \"orm['wiki.Document']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'in_common': ('django.db.models.fields.IntegerField', [], {}),\n 'related': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'related_to'\", 'to': \"orm['wiki.Document']\"})\n },\n 'wiki.reviewtag': {\n 'Meta': {'object_name': 'ReviewTag'},\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'})\n },\n 'wiki.reviewtaggedrevision': {\n 'Meta': {'object_name': 'ReviewTaggedRevision'},\n 'content_object': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['wiki.Revision']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'tag': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['wiki.ReviewTag']\"})\n },\n 'wiki.revision': {\n 'Meta': {'object_name': 'Revision'},\n 'based_on': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['wiki.Revision']\", 'null': 'True', 'blank': 'True'}),\n 'comment': ('django.db.models.fields.CharField', [], {'max_length': '255'}),\n 'content': ('django.db.models.fields.TextField', [], {}),\n 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),\n 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'created_revisions'\", 'to': \"orm['auth.User']\"}),\n 'document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'revisions'\", 'to': \"orm['wiki.Document']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'is_approved': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),\n 'is_mindtouch_migration': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),\n 'keywords': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n 'mindtouch_old_id': ('django.db.models.fields.IntegerField', [], {'unique': 'True', 'null': 'True', 'db_index': 'True'}),\n 'reviewed': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),\n 'reviewer': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"'reviewed_revisions'\", 'null': 'True', 'to': \"orm['auth.User']\"}),\n 'show_toc': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),\n 'significance': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),\n 'slug': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'db_index': 'True'}),\n 'summary': ('django.db.models.fields.TextField', [], {}),\n 'tags': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),\n 'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'db_index': 'True'})\n },\n 'wiki.taggeddocument': {\n 'Meta': {'object_name': 'TaggedDocument'},\n 'content_object': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['wiki.Document']\"}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'tag': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['wiki.DocumentTag']\"})\n }\n }\n\n complete_apps = ['wiki']"}]} {"messages": [{"role": "user", "content": "Write Python code that implements subscribe_test.py from gautam1858/tensorflow (path: tensorflow/python/framework/subscribe_test.py)."}, {"role": "assistant", "content": "# tensorflow/python/framework/subscribe_test.py (from gautam1858/tensorflow, license: apache-2.0)\n\n# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tf.subscribe.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import subscribe\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import script_ops\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import googletest\n\nclass SubscribeTest(test_util.TensorFlowTestCase):\n\n def _ExpectSubscribedIdentities(self, container):\n \"\"\"Convenience function to test a container of subscribed identities.\"\"\"\n self.assertTrue(\n all(subscribe._is_subscribed_identity(x) for x in container))\n\n @test_util.run_deprecated_v1\n def testSideEffect(self):\n a = constant_op.constant(1)\n b = constant_op.constant(1)\n c = math_ops.add(a, b)\n with ops.control_dependencies([c]):\n d = constant_op.constant(42)\n n = math_ops.negative(c)\n\n shared = []\n\n def sub(t):\n shared.append(t)\n return t\n\n c0 = c\n self.assertTrue(c0.op in d.op.control_inputs)\n c = subscribe.subscribe(c,\n lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n # Verify that control dependencies are correctly moved to the subscription.\n self.assertFalse(c0.op in d.op.control_inputs)\n self.assertTrue(c.op in d.op.control_inputs)\n\n with self.cached_session() as sess:\n c_out = self.evaluate([c])\n n_out = self.evaluate([n])\n d_out = self.evaluate([d])\n\n self.assertEqual(n_out, [-2])\n self.assertEqual(c_out, [2])\n self.assertEqual(d_out, [42])\n self.assertEqual(shared, [2, 2, 2])\n\n @test_util.run_deprecated_v1\n def testSupportedTypes(self):\n \"\"\"Confirm that supported types are correctly detected and handled.\"\"\"\n\n a = constant_op.constant(1)\n b = constant_op.constant(1)\n c = math_ops.add(a, b)\n\n def sub(t):\n return t\n\n # Tuples.\n subscribed = subscribe.subscribe(\n (a, b), lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n self.assertIsInstance(subscribed, tuple)\n self._ExpectSubscribedIdentities(subscribed)\n\n # Lists.\n subscribed = subscribe.subscribe(\n [a, b], lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n self.assertIsInstance(subscribed, list)\n self._ExpectSubscribedIdentities(subscribed)\n\n # Dictionaries.\n subscribed = subscribe.subscribe({\n 'first': a,\n 'second': b\n }, lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n self.assertIsInstance(subscribed, dict)\n self._ExpectSubscribedIdentities(subscribed.values())\n\n # Namedtuples.\n # pylint: disable=invalid-name\n TensorPair = collections.namedtuple('TensorPair', ['first', 'second'])\n # pylint: enable=invalid-name\n pair = TensorPair(a, b)\n subscribed = subscribe.subscribe(\n pair, lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n self.assertIsInstance(subscribed, TensorPair)\n self._ExpectSubscribedIdentities(subscribed)\n\n # Expect an exception to be raised for unsupported types.\n with self.assertRaisesRegexp(TypeError, 'has invalid type'):\n subscribe.subscribe(c.name,\n lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n\n @test_util.run_deprecated_v1\n def testCaching(self):\n \"\"\"Confirm caching of control output is recalculated between calls.\"\"\"\n a = constant_op.constant(1)\n b = constant_op.constant(2)\n with ops.control_dependencies([a]):\n c = constant_op.constant(42)\n\n shared = {}\n\n def sub(t):\n shared[t] = shared.get(t, 0) + 1\n return t\n\n a = subscribe.subscribe(a,\n lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n\n with ops.control_dependencies([b]):\n d = constant_op.constant(11)\n\n # If it was using outdated cached control_outputs then\n # evaling would not trigger the new subscription.\n b = subscribe.subscribe(b,\n lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n\n with self.cached_session() as sess:\n c_out = self.evaluate([c])\n d_out = self.evaluate([d])\n\n self.assertEqual(c_out, [42])\n self.assertEqual(d_out, [11])\n self.assertEqual(shared, {2: 1, 1: 1})\n\n @test_util.run_deprecated_v1\n def testIsSubscribedIdentity(self):\n \"\"\"Confirm subscribed identity ops are correctly detected.\"\"\"\n a = constant_op.constant(1)\n b = constant_op.constant(2)\n c = math_ops.add(a, b)\n idop = array_ops.identity(c)\n c_sub = subscribe.subscribe(c, [])\n\n self.assertFalse(subscribe._is_subscribed_identity(a))\n self.assertFalse(subscribe._is_subscribed_identity(c))\n self.assertFalse(subscribe._is_subscribed_identity(idop))\n self.assertTrue(subscribe._is_subscribed_identity(c_sub))\n\n @test_util.run_deprecated_v1\n def testSubscribeExtend(self):\n \"\"\"Confirm side effect are correctly added for different input types.\"\"\"\n a = constant_op.constant(1)\n b = constant_op.constant(2)\n c = math_ops.add(a, b)\n\n shared = {}\n\n def sub(t, name):\n shared[name] = shared.get(name, 0) + 1\n return t\n\n # Subscribe with a first side effect graph, passing an unsubscribed tensor.\n sub_graph1 = lambda t: sub(t, 'graph1')\n c_sub = subscribe.subscribe(\n c, lambda t: script_ops.py_func(sub_graph1, [t], [t.dtype]))\n\n # Add a second side effect graph, passing the tensor returned by the\n # previous call to subscribe().\n sub_graph2 = lambda t: sub(t, 'graph2')\n c_sub2 = subscribe.subscribe(\n c_sub, lambda t: script_ops.py_func(sub_graph2, [t], [t.dtype]))\n\n # Add a third side effect graph, passing the original tensor.\n sub_graph3 = lambda t: sub(t, 'graph3')\n c_sub3 = subscribe.subscribe(\n c, lambda t: script_ops.py_func(sub_graph3, [t], [t.dtype]))\n\n # Make sure there's only one identity op matching the source tensor's name.\n graph_ops = ops.get_default_graph().get_operations()\n name_prefix = c.op.name + '/subscription/Identity'\n identity_ops = [op for op in graph_ops if op.name.startswith(name_prefix)]\n self.assertEqual(1, len(identity_ops))\n\n # Expect the objects returned by subscribe() to reference the same tensor.\n self.assertIs(c_sub, c_sub2)\n self.assertIs(c_sub, c_sub3)\n\n # Expect the three side effect graphs to have been evaluated.\n with self.cached_session() as sess:\n self.evaluate([c_sub])\n self.assertIn('graph1', shared)\n self.assertIn('graph2', shared)\n self.assertIn('graph3', shared)\n\n @test_util.run_v1_only('b/120545219')\n def testSubscribeVariable(self):\n \"\"\"Confirm that variables can be subscribed.\"\"\"\n v1 = variables.VariableV1(0.0)\n v2 = variables.VariableV1(4.0)\n add = math_ops.add(v1, v2)\n assign_v1 = v1.assign(3.0)\n\n shared = []\n\n def sub(t):\n shared.append(t)\n return t\n\n v1_sub = subscribe.subscribe(\n v1, lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n self.assertTrue(subscribe._is_subscribed_identity(v1_sub))\n\n with self.cached_session() as sess:\n # Initialize the variables first.\n self.evaluate([v1.initializer])\n self.evaluate([v2.initializer])\n\n # Expect the side effects to be triggered when evaluating the add op as\n # it will read the value of the variable.\n self.evaluate([add])\n self.assertEqual(1, len(shared))\n\n # Expect the side effect not to be triggered when evaluating the assign\n # op as it will not access the 'read' output of the variable.\n self.evaluate([assign_v1])\n self.assertEqual(1, len(shared))\n\n self.evaluate([add])\n self.assertEqual(2, len(shared))\n\n # Make sure the values read from the variable match the expected ones.\n self.assertEqual([0.0, 3.0], shared)\n\n @test_util.run_v1_only('b/120545219')\n def testResourceType(self):\n \"\"\"Confirm that subscribe correctly handles tensors with 'resource' type.\"\"\"\n tensor_array = tensor_array_ops.TensorArray(\n dtype=dtypes.float32,\n tensor_array_name='test',\n size=3,\n infer_shape=False)\n writer = tensor_array.write(0, [[4.0, 5.0]])\n reader = writer.read(0)\n\n shared = []\n\n def sub(t):\n shared.append(t)\n return t\n\n # TensorArray's handle output tensor has a 'resource' type and cannot be\n # subscribed as it's not 'numpy compatible' (see dtypes.py).\n # Expect that the original tensor is returned when subscribing to it.\n tensor_array_sub = subscribe.subscribe(\n tensor_array.handle, lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n self.assertIs(tensor_array_sub, tensor_array.handle)\n self.assertFalse(subscribe._is_subscribed_identity(tensor_array.handle))\n\n with self.cached_session() as sess:\n self.evaluate([reader])\n self.assertEqual(0, len(shared))\n\n @test_util.run_deprecated_v1\n def testMultipleOutputs(self):\n \"\"\"Handle subscriptions to multiple outputs from the same op.\"\"\"\n sparse_tensor_1 = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])\n sparse_tensor_2 = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]], values=[2, 3], dense_shape=[3, 4])\n\n # This op has three outputs.\n sparse_add = sparse_ops.sparse_add(sparse_tensor_1, sparse_tensor_2)\n\n self.assertEqual(3, len(sparse_add.op.outputs))\n\n c1 = constant_op.constant(1)\n\n with ops.control_dependencies(sparse_add.op.outputs):\n # This op depends on all the three outputs.\n neg = -c1\n\n shared = []\n def sub(t):\n shared.append(t)\n return t\n\n # Subscribe the three outputs at once.\n subscribe.subscribe(sparse_add.op.outputs,\n lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n\n with self.cached_session() as sess:\n self.evaluate([neg])\n\n # All three ops have been processed.\n self.assertEqual(3, len(shared))\n\n @test_util.run_deprecated_v1\n def test_subscribe_tensors_on_different_devices(self):\n \"\"\"Side effect ops are added with the same device of the subscribed op.\"\"\"\n c1 = constant_op.constant(10)\n c2 = constant_op.constant(20)\n\n with ops.device('cpu:0'):\n add = math_ops.add(c1, c2)\n\n with ops.device('cpu:1'):\n mul = math_ops.multiply(c1, c2)\n\n def sub(t):\n return t\n\n add_sub = subscribe.subscribe(\n add, lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n\n mul_sub = subscribe.subscribe(\n mul, lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n\n # Expect the identity tensors injected by subscribe to have been created\n # on the same device as their original tensors.\n self.assertNotEqual(add_sub.device, mul_sub.device)\n self.assertEqual(add.device, add_sub.device)\n self.assertEqual(mul.device, mul_sub.device)\n\n @test_util.run_v1_only('b/120545219')\n def test_subscribe_tensors_within_control_flow_context(self):\n \"\"\"Side effect ops are added with the same control flow context.\"\"\"\n c1 = constant_op.constant(10)\n c2 = constant_op.constant(20)\n x1 = math_ops.add(c1, c2)\n x2 = math_ops.multiply(c1, c2)\n\n cond = control_flow_ops.cond(\n x1 < x2,\n lambda: math_ops.add(c1, c2, name='then'),\n lambda: math_ops.subtract(c1, c2, name='else'),\n name='cond')\n\n branch = ops.get_default_graph().get_tensor_by_name('cond/then:0')\n\n def context(tensor):\n return tensor.op._get_control_flow_context()\n\n self.assertIs(context(x1), context(x2))\n self.assertIsNot(context(x1), context(branch))\n\n results = []\n def sub(tensor):\n results.append(tensor)\n return tensor\n\n tensors = [x1, branch, x2]\n subscriptions = subscribe.subscribe(\n tensors, lambda t: script_ops.py_func(sub, [t], [t.dtype]))\n\n for tensor, subscription in zip(tensors, subscriptions):\n self.assertIs(context(tensor), context(subscription))\n\n # Verify that sub(x1) and sub(x2) are in the same context.\n self.assertIs(context(subscriptions[0]), context(subscriptions[2]))\n\n # Verify that sub(x1) and sub(branch) are not.\n self.assertIsNot(context(subscriptions[0]), context(subscriptions[1]))\n\n with self.cached_session() as sess:\n self.evaluate(cond)\n\n self.assertEqual(3, len(results))\n\nif __name__ == '__main__':\n googletest.main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements __init__.py from abdellatifkarroum/odoo (path: addons/crm_partner_assign/wizard/__init__.py)."}, {"role": "assistant", "content": "# addons/crm_partner_assign/wizard/__init__.py (from abdellatifkarroum/odoo, license: agpl-3.0)\n\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nimport crm_forward_to_partner\nimport crm_channel_interested"}]} {"messages": [{"role": "user", "content": "Write Python code that implements account_analytic_chart.py from ThinkOpen-Solutions/odoo (path: addons/account/project/wizard/account_analytic_chart.py)."}, {"role": "assistant", "content": "# addons/account/project/wizard/account_analytic_chart.py (from ThinkOpen-Solutions/odoo, license: agpl-3.0)\n\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nfrom openerp.osv import fields, osv\n\nclass account_analytic_chart(osv.osv_memory):\n _name = 'account.analytic.chart'\n _description = 'Account Analytic Chart'\n\n _columns = {\n 'from_date': fields.date('From'),\n 'to_date': fields.date('To'),\n }\n\n def analytic_account_chart_open_window(self, cr, uid, ids, context=None):\n mod_obj = self.pool.get('ir.model.data')\n act_obj = self.pool.get('ir.actions.act_window')\n result_context = {}\n if context is None:\n context = {}\n result = mod_obj.get_object_reference(cr, uid, 'account', 'action_account_analytic_account_tree2')\n id = result and result[1] or False\n result = act_obj.read(cr, uid, [id], context=context)[0]\n data = self.read(cr, uid, ids, [])[0]\n if data['from_date']:\n result_context.update({'from_date': data['from_date']})\n if data['to_date']:\n result_context.update({'to_date': data['to_date']})\n result['context'] = str(result_context)\n return result\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_categorizer.py from SEMCOG/synthpop (path: synthpop/test/test_categorizer.py)."}, {"role": "assistant", "content": "# synthpop/test/test_categorizer.py (from SEMCOG/synthpop, license: bsd-3-clause)\n\nimport pytest\nimport numpy as np\nfrom ..census_helpers import Census\nfrom .. import categorizer as cat\n\n@pytest.fixture\ndef c():\n return Census(\"827402c2958dcf515e4480b7b2bb93d1025f9389\")\n\n@pytest.fixture\ndef acs_data(c):\n population = ['B01001_001E']\n sex = ['B01001_002E', 'B01001_026E']\n race = ['B02001_0%02dE' % i for i in range(1, 11)]\n male_age_columns = ['B01001_0%02dE' % i for i in range(3, 26)]\n female_age_columns = ['B01001_0%02dE' % i for i in range(27, 50)]\n all_columns = population + sex + race + male_age_columns + \\\n female_age_columns\n df = c.block_group_query(all_columns, \"06\", \"075\", tract=\"030600\")\n return df\n\n@pytest.fixture\ndef pums_data(c):\n return c.download_population_pums(\"06\", \"07506\")\n\ndef test_categorize(acs_data, pums_data):\n p_acs_cat = cat.categorize(acs_data, {\n (\"population\", \"total\"): \"B01001_001E\",\n (\"age\", \"19 and under\"): \"B01001_003E + B01001_004E + B01001_005E + \"\n \"B01001_006E + B01001_007E + B01001_027E + \"\n \"B01001_028E + B01001_029E + B01001_030E + \"\n \"B01001_031E\",\n (\"age\", \"20 to 35\"): \"B01001_008E + B01001_009E + B01001_010E + \"\n \"B01001_011E + B01001_012E + B01001_032E + \"\n \"B01001_033E + B01001_034E + B01001_035E + \"\n \"B01001_036E\",\n (\"age\", \"35 to 60\"): \"B01001_013E + B01001_014E + B01001_015E + \"\n \"B01001_016E + B01001_017E + B01001_037E + \"\n \"B01001_038E + B01001_039E + B01001_040E + \"\n \"B01001_041E\",\n (\"age\", \"above 60\"): \"B01001_018E + B01001_019E + B01001_020E + \"\n \"B01001_021E + B01001_022E + B01001_023E + \"\n \"B01001_024E + B01001_025E + B01001_042E + \"\n \"B01001_043E + B01001_044E + B01001_045E + \"\n \"B01001_046E + B01001_047E + B01001_048E + \"\n \"B01001_049E\",\n (\"race\", \"white\"): \"B02001_002E\",\n (\"race\", \"black\"): \"B02001_003E\",\n (\"race\", \"asian\"): \"B02001_005E\",\n (\"race\", \"other\"): \"B02001_004E + B02001_006E + B02001_007E + \"\n \"B02001_008E\",\n (\"sex\", \"male\"): \"B01001_002E\",\n (\"sex\", \"female\"): \"B01001_026E\"\n }, index_cols=['NAME'])\n\n assert len(p_acs_cat) == 3\n assert len(p_acs_cat.columns) == 11\n assert len(p_acs_cat.columns.names) == 2\n assert p_acs_cat.columns[0][0] == \"age\"\n\n assert np.all(cat.sum_accross_category(p_acs_cat) < 2)\n\n def age_cat(r):\n if r.AGEP <= 19:\n return \"19 and under\"\n elif r.AGEP <= 35:\n return \"20 to 35\"\n elif r.AGEP <= 60:\n return \"35 to 60\"\n return \"above 60\"\n\n def race_cat(r):\n if r.RAC1P == 1:\n return \"white\"\n elif r.RAC1P == 2:\n return \"black\"\n elif r.RAC1P == 6:\n return \"asian\"\n return \"other\"\n\n def sex_cat(r):\n if r.SEX == 1:\n return \"male\"\n return \"female\"\n\n pums_data, jd_persons = cat.joint_distribution(\n pums_data,\n cat.category_combinations(p_acs_cat.columns),\n {\"age\": age_cat, \"race\": race_cat, \"sex\": sex_cat}\n )"}]} {"messages": [{"role": "user", "content": "Write Python code that implements k8s_raw.py from dharmabumstead/ansible (path: lib/ansible/modules/clustering/k8s/k8s_raw.py)."}, {"role": "assistant", "content": "# lib/ansible/modules/clustering/k8s/k8s_raw.py (from dharmabumstead/ansible, license: gpl-3.0)\n\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# (c) 2018, Chris Houseknecht <@chouseknecht>\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\nDOCUMENTATION = '''\n\nmodule: k8s_raw\n\nshort_description: Manage Kubernetes (K8s) objects\n\nversion_added: \"2.5\"\n\nauthor: \"Chris Houseknecht (@chouseknecht)\"\n\ndescription:\n - Use the OpenShift Python client to perform CRUD operations on K8s objects.\n - Pass the object definition from a source file or inline. See examples for reading\n files and using Jinja templates.\n - Access to the full range of K8s APIs.\n - Authenticate using either a config file, certificates, password or token.\n - Supports check mode.\n\nextends_documentation_fragment:\n - k8s_state_options\n - k8s_name_options\n - k8s_resource_options\n - k8s_auth_options\n\nrequirements:\n - \"python >= 2.7\"\n - \"openshift == 0.4.3\"\n - \"PyYAML >= 3.11\"\n'''\n\nEXAMPLES = '''\n- name: Create a k8s namespace\n k8s_raw:\n name: testing\n api_version: v1\n kind: Namespace\n state: present\n\n- name: Create a Service object from an inline definition\n k8s_raw:\n state: present\n definition:\n apiVersion: v1\n kind: Service\n metadata:\n name: web\n namespace: testing\n labels:\n app: galaxy\n service: web\n spec:\n selector:\n app: galaxy\n service: web\n ports:\n - protocol: TCP\n targetPort: 8000\n name: port-8000-tcp\n port: 8000\n\n- name: Create a Service object by reading the definition from a file\n k8s_raw:\n state: present\n src: /testing/service.yml\n\n- name: Get an existing Service object\n k8s_raw:\n api_version: v1\n kind: Service\n name: web\n namespace: testing\n register: web_service\n\n- name: Get a list of all service objects\n k8s_raw:\n api_version: v1\n kind: ServiceList\n namespace: testing\n register: service_list\n\n- name: Remove an existing Service object\n k8s_raw:\n state: absent\n api_version: v1\n kind: Service\n namespace: testing\n name: web\n\n# Passing the object definition from a file\n\n- name: Create a Deployment by reading the definition from a local file\n k8s_raw:\n state: present\n src: /testing/deployment.yml\n\n- name: Read definition file from the Ansible controller file system\n k8s_raw:\n state: present\n definition: \"{{ lookup('file', '/testing/deployment.yml') | from_yaml }}\"\n\n- name: Read definition file from the Ansible controller file system after Jinja templating\n k8s_raw:\n state: present\n definition: \"{{ lookup('template', '/testing/deployment.yml') | from_yaml }}\"\n'''\n\nRETURN = '''\nresult:\n description:\n - The created, patched, or otherwise present object. Will be empty in the case of a deletion.\n returned: success\n type: complex\n contains:\n api_version:\n description: The versioned schema of this representation of an object.\n returned: success\n type: str\n kind:\n description: Represents the REST resource this object represents.\n returned: success\n type: str\n metadata:\n description: Standard object metadata. Includes name, namespace, annotations, labels, etc.\n returned: success\n type: complex\n spec:\n description: Specific attributes of the object. Will vary based on the I(api_version) and I(kind).\n returned: success\n type: complex\n status:\n description: Current status details for the object.\n returned: success\n type: complex\n items:\n description: Returned only when the I(kind) is a List type resource. Contains a set of objects.\n returned: when resource is a List\n type: list\n'''\n\nfrom ansible.module_utils.k8s.raw import KubernetesRawModule\n\ndef main():\n KubernetesRawModule().execute_module()\n\nif __name__ == '__main__':\n main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements versioning.py from JackDanger/sentry (path: src/sentry/utils/versioning.py)."}, {"role": "assistant", "content": "# src/sentry/utils/versioning.py (from JackDanger/sentry, license: bsd-3-clause)\n\nfrom __future__ import absolute_import\n\nimport six\n\nfrom sentry.exceptions import InvalidConfiguration\nfrom sentry.utils import warnings\n\nclass Version(tuple):\n def __str__(self):\n return '.'.join(map(six.binary_type, self))\n\ndef summarize(sequence, max=3):\n items = sequence[:max]\n remainder = len(sequence) - max\n if remainder == 1:\n items.append('and one other')\n elif remainder > 1:\n items.append('and %s others' % (remainder,))\n return items\n\ndef make_upgrade_message(service, modality, version, hosts):\n return '{service} {modality} be upgraded to {version} on {hosts}.'.format(\n hosts=','.join(map(six.binary_type, summarize(hosts.keys(), 2))),\n modality=modality,\n service=service,\n version=version,\n )\n\ndef check_versions(service, versions, required, recommended=None):\n \"\"\"\n Check that hosts fulfill version requirements.\n\n :param service: service label, such as ``Redis``\n :param versions: mapping of host to ``Version``\n :param required: lowest supported ``Version``. If any host does not fulfill\n this requirement, an ``InvalidConfiguration`` exception is raised.\n :param recommended: recommended version. If any host does not fulfill this\n requirement, a ``PendingDeprecationWarning`` is raised.\n \"\"\"\n # x = (host, version)\n must_upgrade = dict(filter(lambda x: required > x[1], versions.items()))\n if must_upgrade:\n raise InvalidConfiguration(make_upgrade_message(service, 'must', required, must_upgrade))\n\n if recommended:\n # x = (host, version)\n should_upgrade = dict(filter(lambda x: recommended > x[1], versions.items()))\n if should_upgrade:\n warnings.warn(\n make_upgrade_message(service, 'should', recommended, should_upgrade),\n PendingDeprecationWarning,\n )"}]} {"messages": [{"role": "user", "content": "Write Python code that implements alttoolbar_repeat.py from fin-ger/alternative-toolbar (path: alttoolbar_repeat.py)."}, {"role": "assistant", "content": "# alttoolbar_repeat.py (from fin-ger/alternative-toolbar, license: gpl-3.0)\n\n# This is a part of the external Repeat One Song plugin for Rhythmbox\n#\n# Author: Eduardo Mucelli Rezende Oliveira\n# E-mail: edumucelli@gmail.com or eduardom@dcc.ufmg.br\n# Version: 0.4 (Unstable) for Rhythmbox 3.0.1 or later\n#\n#\n# reworked for alternative-toolbar\n# Author: fossfreedom\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n\nfrom gi.repository import GObject\nfrom gi.repository import Gtk\nfrom gi.repository import Gdk\nfrom gi.repository import GLib\nfrom gi.repository import Gio\n\nfrom alttoolbar_rb3compat import gtk_version\nfrom alttoolbar_preferences import GSetting\nfrom alttoolbar_preferences import CoverLocale\n\nclass Repeat(GObject.Object):\n def __init__(self, shell, toggle_button):\n \"\"\"\n\n :param toggle_button: button that controls the repeat functions\n :return:\n \"\"\"\n GObject.Object.__init__(self)\n\n # use this to start the repeat-one-song capability (if True)\n self.repeat_song = False\n self.shell = shell\n self.toggle_button = toggle_button\n\n # self.one_song_stprint (\"adjoining\")\n ate_normal, self.one_song_state_eos = range(2)\n # self.one_song_state = self.one_song_state_normal\n\n player = self.shell.props.shell_player\n # Please refer to the comments above to understand why those\n # two callbacks are not being used currently, Rhytmbox 2.99.1\n # player.connect('playing-song-changed', self.on_song_change)\n # player.props.player.connect('eos', self.on_gst_player_eos)\n player.connect('elapsed-changed', self.on_elapsed_change)\n\n if gtk_version() >= 3.12:\n popover = Gtk.Popover.new(toggle_button)\n\n repeat = RepeatPopContainer(popover, toggle_button)\n popover.add(repeat)\n popover.set_modal(False)\n\n else:\n # use our custom Popover equivalent for Gtk+3.10 folks\n popover = CustomPopover(toggle_button)\n repeat = RepeatPopContainer(popover, toggle_button)\n popover.add(repeat)\n\n toggle_button.connect(\"toggled\", self._on_toggle, popover, repeat)\n repeat.connect('repeat-type-changed', self._on_repeat_type_changed)\n\n self._on_repeat_type_changed(repeat, repeat.get_repeat_type())\n\n def _on_toggle(self, toggle, popover, repeat):\n if toggle.get_active():\n popover.show_all()\n self.repeat_song = \\\n repeat.get_repeat_type() == RepeatPopContainer.ONE_SONG\n else:\n popover.hide()\n self.repeat_song = False\n\n self._set_toggle_tooltip(repeat)\n\n print(\"on toggle\", self.repeat_song)\n\n def _set_toggle_tooltip(self, repeat):\n # locale stuff\n cl = CoverLocale()\n cl.switch_locale(cl.Locale.LOCALE_DOMAIN)\n if self.toggle_button.get_has_tooltip():\n if repeat.get_repeat_type() == RepeatPopContainer.ALL_SONGS:\n message = _(\"Repeat all tracks\")\n else:\n message = _(\"Repeat the current track\")\n self.toggle_button.set_tooltip_text(message)\n cl = CoverLocale()\n cl.switch_locale(cl.Locale.RB)\n\n def _on_repeat_type_changed(self, repeat, repeat_type):\n if self.toggle_button.get_active():\n if repeat_type == RepeatPopContainer.ONE_SONG:\n self.repeat_song = True\n else:\n self.repeat_song = False\n else:\n self.repeat_song = False\n\n self._set_toggle_tooltip(repeat)\n\n print(\"repeat type changed\", self.repeat_song)\n\n # Looks like there is a bug on gstreamer player and a seg fault\n # happens as soon as the 'eos' callback is called.\n # https://bugs.launchpad.net/ubuntu/+source/rhythmbox/+bug/1239218\n # As soon it gets fixed or a code-based workaround gets available,\n # this method in conjunction with on_song_change will be used as\n # the way to control the song repetition. Meanwhile, on_elapsed_change\n # will be the chosen solution\n def on_gst_player_eos(self, gst_player, stream_data, early=0):\n # EOS signal means that the song changed because the song is over.\n # ie. the user did not explicitly change the song.\n # https://developer.gnome.org/rhythmbox/\n # unstable/RBPlayer.html#RBPlayer-eos\n if self.repeat_song:\n self.one_song_state = self.one_song_state_eos\n\n # This is a old method to 'repeat' the current song as soon as it\n # reaches the last second. Will be the used until the bug mentioned on the\n # comments above gets fixed.\n def on_song_change(self, player, time):\n if self.one_song_state == self.one_song_state_eos:\n self.one_song_state = self.one_song_state_normal\n player.do_previous()\n\n # This is a old method to 'repeat' the current song as soon as it\n # reaches the last second. Will be the used until the bug mentioned on the\n # comments above gets fixed.\n # This might be improved keeping a instance variable with the duration and\n # updating it on_song_change. Therefore, it would not be\n # necessary to query the duration every time\n def on_elapsed_change(self, player, time):\n if self.repeat_song:\n duration = player.get_playing_song_duration()\n if duration > 0:\n # Repeat on the last two seconds of the song. Previously the\n # last second was used but RB now seems to use the last second\n # to prepare things for the next song of the list\n if time >= duration - 2:\n player.set_playing_time(0)\n\nclass RepeatPopContainer(Gtk.ButtonBox):\n __gsignals__ = {\n \"repeat-type-changed\": (GObject.SIGNAL_RUN_LAST, None, (int,))\n }\n\n # repeat-type-changed is emitted with one of the following values\n ONE_SONG = 1\n ALL_SONGS = 2\n\n def __init__(self, parent_container, parent_button, *args, **kwargs):\n super(RepeatPopContainer, self).__init__(*args, **kwargs)\n\n self.set_orientation(Gtk.Orientation.HORIZONTAL)\n self.set_layout(Gtk.ButtonBoxStyle.START)\n self.props.margin = 5\n context = self.get_style_context()\n context.add_class('linked')\n\n icon_size = 4\n\n toggle1 = Gtk.RadioButton.new(None)\n toggle1.set_mode(False)\n fallback = 'media-playlist-repeat-symbolic'\n icon = Gio.ThemedIcon.new_with_default_fallbacks(fallback)\n image = Gtk.Image()\n image.set_from_gicon(icon, icon_size)\n image.props.margin = 5\n toggle1.set_image(image)\n toggle1.connect('leave-notify-event', self._on_popover_mouse_over)\n toggle1.connect('enter-notify-event', self._on_popover_mouse_over)\n toggle1.connect('toggled', self._on_popover_button_toggled)\n\n # locale stuff\n cl = CoverLocale()\n cl.switch_locale(cl.Locale.LOCALE_DOMAIN)\n\n if parent_button.get_has_tooltip():\n toggle1.set_tooltip_text(_(\"Repeat all tracks\"))\n\n self._repeat_button = toggle1\n self.add(toggle1)\n self.child_set_property(toggle1, \"non-homogeneous\", True)\n toggle1.show_all()\n\n self._repeat_image = Gtk.Image()\n self._repeat_image.set_from_gicon(icon, icon_size)\n self._repeat_image.props.margin = 5\n\n toggle2 = Gtk.RadioButton.new_from_widget(toggle1)\n toggle2.set_mode(False)\n sym = 'media-playlist-repeat-song-symbolic'\n icon2 = Gio.ThemedIcon.new_with_default_fallbacks(sym)\n image2 = Gtk.Image()\n image2.set_from_gicon(icon2, icon_size)\n image2.props.margin = 5\n toggle2.set_image(image2)\n\n if parent_button.get_has_tooltip():\n toggle2.set_tooltip_text(_(\"Repeat the current track\"))\n\n self._repeat_song_image = Gtk.Image()\n self._repeat_song_image.set_from_gicon(icon2, icon_size)\n self._repeat_song_image.props.margin = 5\n\n toggle2.connect('leave-notify-event', self._on_popover_mouse_over)\n toggle2.connect('enter-notify-event', self._on_popover_mouse_over)\n toggle2.connect('toggled', self._on_popover_button_toggled)\n toggle2.show_all()\n self._repeat_song_button = toggle2\n self.add(toggle2)\n self.child_set_property(toggle2, \"non-homogeneous\", True)\n\n self._popover_inprogress = 0\n parent_container.connect('leave-notify-event',\n self._on_popover_mouse_over)\n parent_container.connect('enter-notify-event',\n self._on_popover_mouse_over)\n parent_button.connect('leave-notify-event',\n self._on_popover_mouse_over)\n parent_button.connect('enter-notify-event',\n self._on_popover_mouse_over)\n\n parent_button.set_image(self._repeat_image)\n\n self._parent_container = parent_container\n self._parent_button = parent_button\n\n # now get the repeat-type saved in gsettings\n # get values from gsettings\n self.gs = GSetting()\n self.plugin_settings = self.gs.get_setting(self.gs.Path.PLUGIN)\n\n repeat_type = self.plugin_settings[self.gs.PluginKey.REPEAT_TYPE]\n\n if repeat_type == RepeatPopContainer.ONE_SONG:\n self._repeat_song_button.set_active(True)\n\n def _on_popover_button_toggled(self, button, *args):\n print(\"popover toggle\")\n if button.get_active():\n if button == self._repeat_button:\n self._parent_button.set_image(self._repeat_image)\n self.emit('repeat-type-changed', RepeatPopContainer.ALL_SONGS)\n self.plugin_settings[self.gs.PluginKey.REPEAT_TYPE] = \\\n RepeatPopContainer.ALL_SONGS\n else:\n self._parent_button.set_image(self._repeat_song_image)\n self.emit('repeat-type-changed', RepeatPopContainer.ONE_SONG)\n self.plugin_settings[self.gs.PluginKey.REPEAT_TYPE] = \\\n RepeatPopContainer.ONE_SONG\n\n def get_repeat_type(self):\n repeat_type = RepeatPopContainer.ALL_SONGS\n if self._repeat_song_button.get_active():\n repeat_type = RepeatPopContainer.ONE_SONG\n\n return repeat_type\n\n def _on_popover_mouse_over(self, widget, eventcrossing):\n if eventcrossing.type == Gdk.EventType.ENTER_NOTIFY:\n if self._popover_inprogress == 0:\n self._popover_inprogress = 1\n print(\"enter1\")\n else:\n self._popover_inprogress = 2\n print(\"enter2\")\n self._popover_inprogress_count = 0\n\n if type(widget) is Gtk.ToggleButton:\n print(\"here\")\n if widget.get_active():\n print(self._parent_container)\n self._parent_container.show_all()\n else:\n print(\"exit\")\n self._popover_inprogress = 3\n\n def delayed(*args):\n if self._popover_inprogress == 3:\n self._popover_inprogress_count += 1\n\n if self._popover_inprogress_count < 5:\n return True\n\n self._parent_container.hide()\n self._popover_inprogress = 0\n print(\"exit timeout\")\n return False\n else:\n return True\n\n if self._popover_inprogress == 1:\n print(\"adding timeout\")\n self._popover_inprogress = 2\n GLib.timeout_add(100, delayed)\n\nclass CustomPopover(Gtk.Window):\n def __init__(self, parent_button, *args, **kwargs):\n super(CustomPopover, self).__init__(type=Gtk.WindowType.POPUP, *args,\n **kwargs)\n\n self.set_decorated(False)\n self.set_resizable(False)\n self.set_type_hint(Gdk.WindowTypeHint.DOCK)\n self.stick()\n self._parent_button = parent_button\n self.connect_after('show', self._on_show)\n # Track movements of the window to move calendar window as well\n self.connect(\"configure-event\", self.on_window_config)\n\n def add(self, widget):\n self._frame = Gtk.Frame()\n self._frame.add(widget)\n\n super(CustomPopover, self).add(self._frame)\n self._frame.show_all()\n\n # Popoverwindow co ordinates without off-screen correction:\n # Window origin (x, y)\n # |\n # V\n # ---------------------------------\n # | Main Window |\n # | |\n # | |\n # |Toggle button's (x, y) |\n # |(relative to parent window) |\n # | | |\n # | V |\n # | ......................... |\n # Popover | | Toggle Button | |\n # window's | | | |\n # (x, y)---+> ......................... |\n # |(window will be here) |\n # | |\n # | |\n # ---------------------------------\n # Popover Window's screen coordinates:\n # x = Window's origin x + Toggle Button's relative x\n # y = Window's origin y + Toggle Button's relative y + Toggle Button's\n # height\n\n def _on_show(self, widget):\n rect = self._parent_button.get_allocation()\n main_window = self._parent_button.get_toplevel()\n [val, win_x, win_y] = main_window.get_window().get_origin()\n cal_x = win_x + rect.x\n cal_y = win_y + rect.y + rect.height\n\n [x, y] = self.apply_screen_coord_correction(cal_x, cal_y)\n self.move(x, y)\n\n # This function \"tries\" to correct calendar window position so that it is\n # not obscured when\n # a portion of main window is off-screen.\n # Known bug: If the main window is partially off-screen before Calendar\n # window\n # has been realized then get_allocation() will return rect of 1x1 in which\n # case\n # the calculations will fail & correction will not be applied\n def apply_screen_coord_correction(self, x, y):\n corrected_y = y\n corrected_x = x\n rect = self.get_allocation()\n screen_w = Gdk.Screen.width()\n screen_h = Gdk.Screen.height()\n\n delta_x = screen_w - (x + rect.width)\n delta_y = screen_h - (y + rect.height)\n if delta_x < 0:\n corrected_x += delta_x\n print(\"at x\")\n if corrected_x < 0:\n corrected_x = 0\n\n button_rect = self._parent_button.get_allocation()\n window_width, window_height = \\\n self._parent_button.get_toplevel().get_size()\n # print (y, button_rect.y, button_rect.height, )\n\n calc = (window_height - (button_rect.y + (button_rect.height * 2)))\n if delta_y < 0 or (calc < 0):\n btn_hgt = self._parent_button.get_allocation().height\n corrected_y = y - rect.height - btn_hgt\n print(\"at y\")\n if corrected_y < 0:\n corrected_y = 0\n return [corrected_x, corrected_y]\n\n # \"configure-event\" callback of main window, try to move calendar window\n # along with main window.\n def on_window_config(self, widget, event):\n # Maybe better way to find the visiblilty\n if self.get_mapped():\n rect = self._parent_button.get_allocation()\n main_window = self._parent_button.get_toplevel()\n [val, win_x, win_y] = main_window.get_window().get_origin()\n cal_x = win_x + rect.x\n cal_y = win_y + rect.y + rect.height\n\n self.show_all()\n [x, y] = self.apply_screen_coord_correction(cal_x, cal_y)\n self.move(x, y)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements setup.py from lubomir/django-rest-framework (path: setup.py)."}, {"role": "assistant", "content": "# setup.py (from lubomir/django-rest-framework, license: bsd-2-clause)\n\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport re\nimport shutil\nimport sys\n\nfrom setuptools import setup\n\ndef get_version(package):\n \"\"\"\n Return package version as listed in `__version__` in `init.py`.\n \"\"\"\n init_py = open(os.path.join(package, '__init__.py')).read()\n return re.search(\"__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py).group(1)\n\ndef get_packages(package):\n \"\"\"\n Return root package and all sub-packages.\n \"\"\"\n return [dirpath\n for dirpath, dirnames, filenames in os.walk(package)\n if os.path.exists(os.path.join(dirpath, '__init__.py'))]\n\ndef get_package_data(package):\n \"\"\"\n Return all files under the root package, that are not in a\n package themselves.\n \"\"\"\n walk = [(dirpath.replace(package + os.sep, '', 1), filenames)\n for dirpath, dirnames, filenames in os.walk(package)\n if not os.path.exists(os.path.join(dirpath, '__init__.py'))]\n\n filepaths = []\n for base, filenames in walk:\n filepaths.extend([os.path.join(base, filename)\n for filename in filenames])\n return {package: filepaths}\n\nversion = get_version('rest_framework')\n\nif sys.argv[-1] == 'publish':\n if os.system(\"pip freeze | grep wheel\"):\n print(\"wheel not installed.\\nUse `pip install wheel`.\\nExiting.\")\n sys.exit()\n if os.system(\"pip freeze | grep twine\"):\n print(\"twine not installed.\\nUse `pip install twine`.\\nExiting.\")\n sys.exit()\n os.system(\"python setup.py sdist bdist_wheel\")\n os.system(\"twine upload dist/*\")\n print(\"You probably want to also tag the version now:\")\n print(\" git tag -a %s -m 'version %s'\" % (version, version))\n print(\" git push --tags\")\n shutil.rmtree('dist')\n shutil.rmtree('build')\n shutil.rmtree('djangorestframework.egg-info')\n sys.exit()\n\nsetup(\n name='djangorestframework',\n version=version,\n url='http://www.django-rest-framework.org',\n license='BSD',\n description='Web APIs for Django, made easy.',\n author='Tom Christie',\n author_email='tom@tomchristie.com', # SEE NOTE BELOW (*)\n packages=get_packages('rest_framework'),\n package_data=get_package_data('rest_framework'),\n install_requires=[],\n zip_safe=False,\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Topic :: Internet :: WWW/HTTP',\n ]\n)\n\n# (*) Please direct queries to the discussion group, rather than to me directly\n# Doing so helps ensure your question is helpful to other users.\n# Queries directly to my email are likely to receive a canned response.\n#\n# Many thanks for your understanding."}]} {"messages": [{"role": "user", "content": "Write Python code that implements base.py from CalHoll/SoundMoose (path: server/project/conf/base.py)."}, {"role": "assistant", "content": "# server/project/conf/base.py (from CalHoll/SoundMoose, license: mit)\n\nimport os\nimport sys\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nROOT_DIR = os.path.dirname(BASE_DIR)\nsys.path.append(\n os.path.join(BASE_DIR, 'apps')\n)\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'a'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\n\nALLOWED_HOSTS = ['*']\n\n# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'core',\n 'rest_framework',\n 'rest_framework_swagger',\n]\n\nMIDDLEWARE_CLASSES = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'core.middleware.corsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n os.path.normpath(os.path.join(BASE_DIR, 'templates')),\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'wsgi.application'\n\n# Database\n# https://docs.djangoproject.com/en/1.9/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': 'soundmoose',\n 'USER': 'postgres',\n 'PASSWORD': 'hrr20soundmoose',\n 'HOST': '127.0.0.1',\n 'PORT': '5432',\n }\n}\n\n# Password validation\n# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.9/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.9/howto/static-files/\n\nSTATIC_URL = '/static/'\n\n# STATIC FILE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root\nSTATIC_ROOT = os.path.join(ROOT_DIR, 'assets')\n\n# See:\n# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n# END STATIC FILE CONFIGURATION\n\n# MEDIA CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root\nMEDIA_ROOT = os.path.normpath(os.path.join(ROOT_DIR, 'media'))\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url\nMEDIA_URL = '/media/'\n# END MEDIA CONFIGURATION\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_true': {\n '()': 'django.utils.log.RequireDebugTrue',\n },\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse',\n },\n },\n 'formatters': {\n 'verbose': {\n 'format': \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\",\n 'datefmt': \"%d/%b/%Y %H:%M:%S\"\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'filters': ['require_debug_true'],\n 'class': 'logging.StreamHandler',\n },\n 'file': {\n 'level': 'ERROR',\n 'class': 'logging.FileHandler',\n 'filters': ['require_debug_false'],\n 'filename': 'log/error.log',\n 'formatter': 'verbose'\n },\n },\n 'loggers': {\n 'django.db.backends': {\n 'level': 'DEBUG',\n 'handlers': ['console'],\n },\n 'django.request': {\n 'handlers': ['file'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\nREST_FRAMEWORK = {\n 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)\n}\nTEMPLATE_LOADERS = [\n'django.template.loaders.eggs.Loader',\n]\n\n# CORS Middleware https://github.com/ottoyiu/django-cors-headers/\n\nCORS_ORIGIN_ALLOW_ALL = True\n\nCORS_ORIGIN_WHITELIST = (\n 'soundmoose.com',\n 'www.soundmoose.com',\n 'localhost:3000',\n)\n\nCORS_ALLOW_METHODS = (\n 'DELETE',\n 'GET',\n 'OPTIONS',\n 'PATCH',\n 'POST',\n 'PUT',\n)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_install_scripts.py from makermade/arm_android-19_arm-linux-androideabi-4.8 (path: lib/python2.7/distutils/tests/test_install_scripts.py)."}, {"role": "assistant", "content": "# lib/python2.7/distutils/tests/test_install_scripts.py (from makermade/arm_android-19_arm-linux-androideabi-4.8, license: gpl-2.0)\n\n\"\"\"Tests for distutils.command.install_scripts.\"\"\"\n\nimport os\nimport unittest\n\nfrom distutils.command.install_scripts import install_scripts\nfrom distutils.core import Distribution\n\nfrom distutils.tests import support\nfrom test.test_support import run_unittest\n\nclass InstallScriptsTestCase(support.TempdirManager,\n support.LoggingSilencer,\n unittest.TestCase):\n\n def test_default_settings(self):\n dist = Distribution()\n dist.command_obj[\"build\"] = support.DummyCommand(\n build_scripts=\"/foo/bar\")\n dist.command_obj[\"install\"] = support.DummyCommand(\n install_scripts=\"/splat/funk\",\n force=1,\n skip_build=1,\n )\n cmd = install_scripts(dist)\n self.assertTrue(not cmd.force)\n self.assertTrue(not cmd.skip_build)\n self.assertTrue(cmd.build_dir is None)\n self.assertTrue(cmd.install_dir is None)\n\n cmd.finalize_options()\n\n self.assertTrue(cmd.force)\n self.assertTrue(cmd.skip_build)\n self.assertEqual(cmd.build_dir, \"/foo/bar\")\n self.assertEqual(cmd.install_dir, \"/splat/funk\")\n\n def test_installation(self):\n source = self.mkdtemp()\n expected = []\n\n def write_script(name, text):\n expected.append(name)\n f = open(os.path.join(source, name), \"w\")\n try:\n f.write(text)\n finally:\n f.close()\n\n write_script(\"script1.py\", (\"#! /usr/bin/env python2.3\\n\"\n \"# bogus script w/ Python sh-bang\\n\"\n \"pass\\n\"))\n write_script(\"script2.py\", (\"#!/usr/bin/python\\n\"\n \"# bogus script w/ Python sh-bang\\n\"\n \"pass\\n\"))\n write_script(\"shell.sh\", (\"#!/bin/sh\\n\"\n \"# bogus shell script w/ sh-bang\\n\"\n \"exit 0\\n\"))\n\n target = self.mkdtemp()\n dist = Distribution()\n dist.command_obj[\"build\"] = support.DummyCommand(build_scripts=source)\n dist.command_obj[\"install\"] = support.DummyCommand(\n install_scripts=target,\n force=1,\n skip_build=1,\n )\n cmd = install_scripts(dist)\n cmd.finalize_options()\n cmd.run()\n\n installed = os.listdir(target)\n for name in expected:\n self.assertTrue(name in installed)\n\ndef test_suite():\n return unittest.makeSuite(InstallScriptsTestCase)\n\nif __name__ == \"__main__\":\n run_unittest(test_suite())"}]} {"messages": [{"role": "user", "content": "Write Python code that implements __init__.py from syndbg/ubuntu-make (path: umake/interactions/__init__.py)."}, {"role": "assistant", "content": "# umake/interactions/__init__.py (from syndbg/ubuntu-make, license: gpl-3.0)\n\n# -*- coding: utf-8 -*-\n# Copyright (C) 2014 Canonical\n#\n# Authors:\n# Didier Roche\n#\n# This program is free software; you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free Software\n# Foundation; version 3.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n# details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n# module gather different types of interactions with the UI\n\nfrom gettext import gettext as _\nimport logging\nfrom umake.tools import InputError\n\nlogger = logging.getLogger(__name__)\n\nclass Choice:\n\n def __init__(self, id, label, callback_fn, txt_shorcut=None, is_default=False):\n \"\"\"Choice element containing label and callback function\"\"\"\n self.id = id\n self.label = label\n self.txt_shorcut = txt_shorcut\n self.callback_fn = callback_fn\n self.is_default = is_default\n\nclass TextWithChoices:\n\n def __init__(self, content, choices=[], newline_before_option=False):\n \"\"\"Content text with a list of multiple Choice elements\"\"\"\n current_ids = []\n default_found = False\n for choice in choices:\n if choice.id in current_ids:\n message = \"{} choice id is already in registered ids. Can't instantiate this \" \\\n \"interaction\".format(choice.id)\n logger.error(message)\n raise BaseException(message)\n current_ids.append(choice.id)\n if choice.is_default:\n if default_found:\n message = \"One default was already registered, can't register a second one in that choices set: {}\"\\\n .format([choice.label for choice in choices])\n logger.error(message)\n raise BaseException(message)\n default_found = True\n self.content = content\n self.choices = choices\n self.newline_before_option = newline_before_option\n\n def choose(self, choice_id=None, answer=None):\n \"\"\"Return associated callback for choice\"\"\"\n for choice in self.choices:\n if (choice_id is not None and choice.id == choice_id) or\\\n (answer is not None and (choice.label.lower() == answer.lower() or\n (choice.txt_shorcut is not None and\n choice.txt_shorcut.lower() == answer.lower()))):\n return choice.callback_fn()\n msg = _(\"No suitable answer provided\")\n if choice_id is not None:\n msg = _(\"Your entry '{}' isn't an acceptable choice. choices are: {}\")\\\n .format(choice_id, [choice.id for choice in self.choices])\n if answer is not None:\n msg = _(\"Your entry '{}' isn't an acceptable choice. choices are: {} and {}\")\\\n .format(answer, [choice.txt_shorcut for choice in self.choices if choice.txt_shorcut is not None],\n [choice.label for choice in self.choices])\n if not choice_id and not answer:\n for choice in self.choices:\n if choice.is_default:\n return choice.callback_fn()\n logger.error(msg)\n raise InputError(msg)\n\n @property\n def prompt(self):\n \"\"\"Text prompt handling if we do have some shortcuts\"\"\"\n possible_answers = []\n for choice in self.choices:\n answer = choice.label\n if choice.txt_shorcut:\n # NOTE: sum of answers\n answer += _(\" ({})\").format((choice.txt_shorcut))\n possible_answers.append(answer)\n if self.newline_before_option:\n # NOTE: first is prompt, newline and then set of answers\n prompt = _(\"{}\\n[{}] \").format(self.content, '/'.join(possible_answers))\n else:\n # NOTE: first is prompt, then set of answers:\n prompt = _(\"{} [{}] \").format(self.content, '/'.join(possible_answers))\n return prompt\n\nclass LicenseAgreement(TextWithChoices):\n\n def __init__(self, content, callback_yes, callback_no):\n \"\"\"License agreement text with accept/decline\"\"\"\n choices = [Choice(0, _(\"I Accept\"), callback_yes, txt_shorcut=_(\"a\")),\n Choice(1, _(\"I don't accept\"), callback_no, txt_shorcut=_(\"N\"), is_default=True)]\n super().__init__(content, choices=choices, newline_before_option=True)\n\n @property\n def input(self):\n \"\"\"Text input prompt handling if we do have some shortcuts\"\"\"\n answers = []\n for choice in self.choices:\n # NOTE: first element is choice, and then shortcut\n _(\"{} ({})\")\n answer = _(\"{} ({})\").format(choice.label, choice.txt_shorcut)\n answers.append(answer)\n # append different possible choices\n return _(\"[{}] \").format('/'.join(answers))\n\nclass InputText:\n\n def __init__(self, content, callback_fn, default_input=\"\"):\n \"\"\"Content text with an line input\"\"\"\n self.content = content\n self._callback_fn = callback_fn\n self.default_input = default_input\n\n def run_callback(self, result):\n self._callback_fn(result)\n\nclass YesNo(TextWithChoices):\n\n def __init__(self, content, callback_yes, callback_no, default_is_yes=False):\n \"\"\"Return a basic Yes No question, default being false or overriden\"\"\"\n super().__init__(content, [Choice(0, _(\"Yes\"), callback_yes, txt_shorcut=_('y'), is_default=default_is_yes),\n Choice(1, _(\"No\"), callback_no, txt_shorcut=_(\"N\"),\n is_default=(not default_is_yes))])\n\nclass DisplayMessage:\n def __init__(self, text):\n self.text = text\n\nclass UnknownProgress:\n def __init__(self, iterator):\n self.bar = None\n self._iterator = iterator"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_textbox16.py from jvrsantacruz/XlsxWriter (path: xlsxwriter/test/comparison/test_textbox16.py)."}, {"role": "assistant", "content": "# xlsxwriter/test/comparison/test_textbox16.py (from jvrsantacruz/XlsxWriter, license: bsd-2-clause)\n\n###############################################################################\n#\n# Tests for XlsxWriter.\n#\n# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org\n#\n\nfrom ..excel_comparsion_test import ExcelComparisonTest\nfrom ...workbook import Workbook\n\nclass TestCompareXLSXFiles(ExcelComparisonTest):\n \"\"\"\n Test file created by XlsxWriter against a file created by Excel.\n\n \"\"\"\n\n def setUp(self):\n self.maxDiff = None\n\n filename = 'textbox16.xlsx'\n\n test_dir = 'xlsxwriter/test/comparison/'\n self.got_filename = test_dir + '_test_' + filename\n self.exp_filename = test_dir + 'xlsx_files/' + filename\n\n self.ignore_files = []\n self.ignore_elements = {}\n\n def test_create_file(self):\n \"\"\"Test the creation of a simple XlsxWriter file with textbox(s).\"\"\"\n\n workbook = Workbook(self.got_filename)\n\n worksheet = workbook.add_worksheet()\n\n worksheet.insert_textbox('E9', 'This is some text',\n {'align': {'vertical': 'middle'}})\n\n workbook.close()\n\n self.assertExcelEqual()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements account_analytic_line.py from xaviercobain88/framework-python (path: openerp/addons/account/account_analytic_line.py)."}, {"role": "assistant", "content": "# openerp/addons/account/account_analytic_line.py (from xaviercobain88/framework-python, license: agpl-3.0)\n\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import fields\nfrom openerp.osv import osv\nfrom openerp.tools.translate import _\n\nclass account_analytic_line(osv.osv):\n _inherit = 'account.analytic.line'\n _description = 'Analytic Line'\n _columns = {\n 'product_uom_id': fields.many2one('product.uom', 'Unit of Measure'),\n 'product_id': fields.many2one('product.product', 'Product'),\n 'general_account_id': fields.many2one('account.account', 'General Account', required=True, ondelete='restrict'),\n 'move_id': fields.many2one('account.move.line', 'Move Line', ondelete='cascade', select=True),\n 'journal_id': fields.many2one('account.analytic.journal', 'Analytic Journal', required=True, ondelete='restrict', select=True),\n 'code': fields.char('Code', size=8),\n 'ref': fields.char('Ref.', size=64),\n 'currency_id': fields.related('move_id', 'currency_id', type='many2one', relation='res.currency', string='Account Currency', store=True, help=\"The related account currency if not equal to the company one.\", readonly=True),\n 'amount_currency': fields.related('move_id', 'amount_currency', type='float', string='Amount Currency', store=True, help=\"The amount expressed in the related account currency if not equal to the company one.\", readonly=True),\n }\n\n _defaults = {\n 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.analytic.line', context=c),\n }\n _order = 'date desc'\n\n def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):\n if context is None:\n context = {}\n if context.get('from_date',False):\n args.append(['date', '>=', context['from_date']])\n if context.get('to_date',False):\n args.append(['date','<=', context['to_date']])\n return super(account_analytic_line, self).search(cr, uid, args, offset, limit,\n order, context=context, count=count)\n\n def _check_company(self, cr, uid, ids, context=None):\n lines = self.browse(cr, uid, ids, context=context)\n for l in lines:\n if l.move_id and not l.account_id.company_id.id == l.move_id.account_id.company_id.id:\n return False\n return True\n\n # Compute the cost based on the price type define into company\n # property_valuation_price_type property\n def on_change_unit_amount(self, cr, uid, id, prod_id, quantity, company_id,\n unit=False, journal_id=False, context=None):\n if context==None:\n context={}\n if not journal_id:\n j_ids = self.pool.get('account.analytic.journal').search(cr, uid, [('type','=','purchase')])\n journal_id = j_ids and j_ids[0] or False\n if not journal_id or not prod_id:\n return {}\n product_obj = self.pool.get('product.product')\n analytic_journal_obj =self.pool.get('account.analytic.journal')\n product_price_type_obj = self.pool.get('product.price.type')\n j_id = analytic_journal_obj.browse(cr, uid, journal_id, context=context)\n prod = product_obj.browse(cr, uid, prod_id, context=context)\n result = 0.0\n if prod_id:\n unit = prod.uom_id.id\n if j_id.type == 'purchase':\n unit = prod.uom_po_id.id\n if j_id.type <> 'sale':\n a = prod.property_account_expense.id\n if not a:\n a = prod.categ_id.property_account_expense_categ.id\n if not a:\n raise osv.except_osv(_('Error!'),\n _('There is no expense account defined ' \\\n 'for this product: \"%s\" (id:%d).') % \\\n (prod.name, prod.id,))\n else:\n a = prod.property_account_income.id\n if not a:\n a = prod.categ_id.property_account_income_categ.id\n if not a:\n raise osv.except_osv(_('Error!'),\n _('There is no income account defined ' \\\n 'for this product: \"%s\" (id:%d).') % \\\n (prod.name, prod_id,))\n\n flag = False\n # Compute based on pricetype\n product_price_type_ids = product_price_type_obj.search(cr, uid, [('field','=','standard_price')], context=context)\n pricetype = product_price_type_obj.browse(cr, uid, product_price_type_ids, context=context)[0]\n if journal_id:\n journal = analytic_journal_obj.browse(cr, uid, journal_id, context=context)\n if journal.type == 'sale':\n product_price_type_ids = product_price_type_obj.search(cr, uid, [('field','=','list_price')], context=context)\n if product_price_type_ids:\n pricetype = product_price_type_obj.browse(cr, uid, product_price_type_ids, context=context)[0]\n # Take the company currency as the reference one\n if pricetype.field == 'list_price':\n flag = True\n ctx = context.copy()\n if unit:\n # price_get() will respect a 'uom' in its context, in order\n # to return a default price for those units\n ctx['uom'] = unit\n amount_unit = prod.price_get(pricetype.field, context=ctx)[prod.id]\n prec = self.pool.get('decimal.precision').precision_get(cr, uid, 'Account')\n amount = amount_unit * quantity or 0.0\n result = round(amount, prec)\n if not flag:\n result *= -1\n return {'value': {\n 'amount': result,\n 'general_account_id': a,\n 'product_uom_id': unit\n }\n }\n\n def view_header_get(self, cr, user, view_id, view_type, context=None):\n if context is None:\n context = {}\n if context.get('account_id', False):\n # account_id in context may also be pointing to an account.account.id\n cr.execute('select name from account_analytic_account where id=%s', (context['account_id'],))\n res = cr.fetchone()\n if res:\n res = _('Entries: ')+ (res[0] or '')\n return res\n return False\n\naccount_analytic_line()\n\nclass res_partner(osv.osv):\n \"\"\" Inherits partner and adds contract information in the partner form \"\"\"\n _inherit = 'res.partner'\n\n _columns = {\n 'contract_ids': fields.one2many('account.analytic.account', \\\n 'partner_id', 'Contracts', readonly=True),\n }\n\nres_partner()\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:"}]} {"messages": [{"role": "user", "content": "Write Python code that implements optimizer_v2.py from girving/tensorflow (path: tensorflow/python/keras/optimizer_v2/optimizer_v2.py)."}, {"role": "assistant", "content": "# tensorflow/python/keras/optimizer_v2/optimizer_v2.py (from girving/tensorflow, license: apache-2.0)\n\n# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Version 2 of class Optimizer.\"\"\"\n# pylint: disable=g-bad-name\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\n\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gradients\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.training import distribute as distribute_lib\nfrom tensorflow.python.training import distribution_strategy_context\nfrom tensorflow.python.training import optimizer as optimizer_v1\nfrom tensorflow.python.training import slot_creator\nfrom tensorflow.python.training.checkpointable import base as checkpointable\nfrom tensorflow.python.util import nest\n\nclass _OptimizableVariable(object):\n \"\"\"Interface for abstracting over variables in the optimizers.\"\"\"\n\n @abc.abstractmethod\n def target(self):\n \"\"\"Returns the optimization target for this variable.\"\"\"\n raise NotImplementedError(\"Calling an abstract method.\")\n\n @abc.abstractmethod\n def update_op(self, optimizer, g, *args):\n \"\"\"Returns the update ops for updating the variable.\"\"\"\n raise NotImplementedError(\"Calling an abstract method.\")\n\nclass _RefVariableProcessor(_OptimizableVariable):\n \"\"\"Processor for Variable.\"\"\"\n\n def __init__(self, v):\n self._v = v\n\n def target(self):\n return self._v._ref() # pylint: disable=protected-access\n\n def update_op(self, optimizer, g, *args):\n if isinstance(g, ops.Tensor):\n update_op = optimizer._apply_dense(g, self._v, *args) # pylint: disable=protected-access\n if self._v.constraint is not None:\n with ops.control_dependencies([update_op]):\n return self._v.assign(self._v.constraint(self._v))\n else:\n return update_op\n else:\n assert isinstance(g, ops.IndexedSlices), (\"Gradient \", g, \" is neither a \"\n \"tensor nor IndexedSlices.\")\n if self._v.constraint is not None:\n raise RuntimeError(\n \"Cannot use a constraint function on a sparse variable.\")\n # pylint: disable=protected-access\n return optimizer._apply_sparse_duplicate_indices(g, self._v, *args)\n\nclass _DenseReadResourceVariableProcessor(_OptimizableVariable):\n \"\"\"Processor for dense ResourceVariables.\"\"\"\n\n def __init__(self, v):\n self._v = v\n\n def target(self):\n return self._v\n\n def update_op(self, optimizer, g, *args):\n # pylint: disable=protected-access\n update_op = optimizer._resource_apply_dense(g, self._v.op.inputs[0], *args)\n if self._v.constraint is not None:\n with ops.control_dependencies([update_op]):\n return self._v.assign(self._v.constraint(self._v))\n else:\n return update_op\n\nclass _DenseResourceVariableProcessor(_OptimizableVariable):\n \"\"\"Processor for dense ResourceVariables.\"\"\"\n\n def __init__(self, v):\n self._v = v\n\n def target(self):\n return self._v\n\n def update_op(self, optimizer, g, *args):\n # pylint: disable=protected-access\n if isinstance(g, ops.IndexedSlices):\n if self._v.constraint is not None:\n raise RuntimeError(\n \"Cannot use a constraint function on a sparse variable.\")\n return optimizer._resource_apply_sparse_duplicate_indices(\n g.values, self._v, g.indices, *args)\n update_op = optimizer._resource_apply_dense(g, self._v, *args)\n if self._v.constraint is not None:\n with ops.control_dependencies([update_op]):\n return self._v.assign(self._v.constraint(self._v))\n else:\n return update_op\n\nclass _TensorProcessor(_OptimizableVariable):\n \"\"\"Processor for ordinary Tensors.\n\n Even though a Tensor can't really be updated, sometimes it is useful to\n compute the gradients with respect to a Tensor using the optimizer. Updating\n the Tensor is, of course, unsupported.\n \"\"\"\n\n def __init__(self, v):\n self._v = v\n\n def target(self):\n return self._v\n\n def update_op(self, optimizer, g, *args):\n raise NotImplementedError(\"Trying to update a Tensor \", self._v)\n\ndef _get_processor(v):\n \"\"\"The processor of v.\"\"\"\n if context.executing_eagerly():\n if isinstance(v, ops.Tensor):\n return _TensorProcessor(v)\n else:\n return _DenseResourceVariableProcessor(v)\n if v.op.type == \"VarHandleOp\":\n return _DenseResourceVariableProcessor(v)\n if isinstance(v, variables.Variable):\n return _RefVariableProcessor(v)\n if isinstance(v, ops.Tensor):\n return _TensorProcessor(v)\n raise NotImplementedError(\"Trying to optimize unsupported type \", v)\n\ndef _var_key_v2(var):\n \"\"\"Key for representing a primary variable, for looking up slots.\"\"\"\n # pylint: disable=protected-access\n if hasattr(var, \"_distributed_container\"):\n distributed_container = var._distributed_container()\n assert distributed_container is not None\n if context.executing_eagerly():\n return distributed_container._unique_id\n return distributed_container._shared_name\n if context.executing_eagerly():\n return var._unique_id\n return var.op.name\n\ndef _resolve(value, name):\n if callable(value):\n value = value()\n return ops.convert_to_tensor(value, name=name)\n\ndef _is_dynamic(value):\n \"\"\"Returns true if __init__ arg `value` should be re-evaluated each step.\"\"\"\n if callable(value): return True\n # Don't need to do anything special in graph mode, since dynamic values\n # will propagate correctly automatically.\n # TODO(josh11b): Add per-device caching across steps using variables for\n # truly static values once we add distributed support.\n if context.executing_eagerly() and isinstance(\n value, resource_variable_ops.ResourceVariable):\n return True\n return False\n\nclass _OptimizerV2State(object):\n \"\"\"Holds per-graph and per-step optimizer state.\n\n Use _init_with_static_hyper() to create the state for a graph, and then\n _copy_with_dynamic_hyper() to convert that to state for a particular step.\n The difference between the two is that the former only has hyper\n parameter values that are static and the latter also has values that\n can change every step (according to _is_dynamic()).\n \"\"\"\n\n def __init__(self, op_name):\n self._op_name = op_name\n\n def _init_with_static_hyper(self, hyper):\n \"\"\"Initialize a fresh state object from hyper dict.\"\"\"\n # self._hyper contains a dict from name to a dict with the Tensor values.\n # This dict starts with a single item with key \"None\" with the hyper\n # parameter value converted to a Tensor. Other items have dtype keys\n # with that Tensor cast to that dtype.\n with ops.init_scope():\n self._hyper = {name: {None: ops.convert_to_tensor(value, name=name)}\n for name, (dynamic, value) in sorted(hyper.items())\n if not dynamic}\n self._slots = {}\n self._non_slot_dict = {}\n # Extra state to help Optimizers implement Checkpointable. Holds information\n # about variables which will be restored as soon as they're created.\n self._deferred_dependencies = {} # Non-slot variables\n self._deferred_slot_restorations = {} # Slot variables\n\n def _copy_with_dynamic_hyper(self, hyper, distribution, non_slot_devices):\n \"\"\"Create a new state object for a particular step.\"\"\"\n ret = _OptimizerV2State(self._op_name)\n # pylint: disable=protected-access\n ret._slots = self._slots\n ret._non_slot_dict = self._non_slot_dict\n ret._deferred_dependencies = self._deferred_dependencies\n ret._deferred_slot_restorations = self._deferred_slot_restorations\n ret._hyper = {name: {None: _resolve(value, name)}\n for name, (dynamic, value) in sorted(hyper.items())\n if dynamic}\n ret._hyper.update(self._hyper)\n ret._non_slot_devices = non_slot_devices\n ret._distribution = distribution\n return ret\n\n def _variables(self):\n \"\"\"Returns a list of all variables held by self.\"\"\"\n optimizer_variables = list(self._non_slot_dict.values())\n for variable_dict in self._slots.values():\n for slot_for_variable in variable_dict.values():\n optimizer_variables.append(slot_for_variable)\n # Sort variables by name so that the return is deterministic.\n return sorted(optimizer_variables, key=lambda v: v.name)\n\n def _slot_dict(self, slot_name):\n \"\"\"Returns a dict for caching slots created under the given name.\n\n Args:\n slot_name: Name for the slot.\n\n Returns:\n A dict that maps primary `Variable` objects to the slot created\n for that variable, under the given slot name.\n \"\"\"\n named_slots = self._slots.get(slot_name, None)\n if named_slots is None:\n named_slots = {}\n self._slots[slot_name] = named_slots\n return named_slots\n\n def create_slot(self, var, val, slot_name, optional_op_name=None):\n \"\"\"Find or create a slot for a variable.\n\n Args:\n var: A `Variable` object.\n val: A `Tensor`. The initial value of the slot.\n slot_name: Name for the slot.\n optional_op_name: Name to use when scoping the Variable that\n needs to be created for the slot.\n\n Returns:\n A `Variable` object.\n \"\"\"\n named_slots = self._slot_dict(slot_name)\n var_key = _var_key_v2(var)\n if var_key not in named_slots:\n new_slot_variable = slot_creator.create_slot(\n var, val, optional_op_name or self._op_name)\n self._restore_slot_variable(\n slot_name=slot_name, variable=var,\n slot_variable=new_slot_variable)\n named_slots[var_key] = new_slot_variable\n return named_slots[var_key]\n\n def create_slot_with_initializer(self, var, initializer, shape, dtype,\n slot_name, optional_op_name=None):\n \"\"\"Find or create a slot for a variable, using an Initializer.\n\n Args:\n var: A `Variable` object.\n initializer: An `Initializer`. The initial value of the slot.\n shape: Shape of the initial value of the slot.\n dtype: Type of the value of the slot.\n slot_name: Name for the slot.\n optional_op_name: Name to use when scoping the Variable that\n needs to be created for the slot.\n\n Returns:\n A `Variable` object.\n \"\"\"\n named_slots = self._slot_dict(slot_name)\n var_key = _var_key_v2(var)\n if var_key not in named_slots:\n new_slot_variable = slot_creator.create_slot_with_initializer(\n var, initializer, shape, dtype, optional_op_name or self._op_name)\n self._restore_slot_variable(\n slot_name=slot_name, variable=var,\n slot_variable=new_slot_variable)\n named_slots[var_key] = new_slot_variable\n return named_slots[var_key]\n\n def zeros_slot(self, var, slot_name, optional_op_name=None):\n \"\"\"Find or create a slot initialized with 0.0.\n\n Args:\n var: A `Variable` object.\n slot_name: Name for the slot.\n optional_op_name: Name to use when scoping the Variable that\n needs to be created for the slot.\n\n Returns:\n A `Variable` object.\n \"\"\"\n named_slots = self._slot_dict(slot_name)\n var_key = _var_key_v2(var)\n if var_key not in named_slots:\n new_slot_variable = slot_creator.create_zeros_slot(\n var, optional_op_name or self._op_name)\n self._restore_slot_variable(\n slot_name=slot_name, variable=var,\n slot_variable=new_slot_variable)\n named_slots[var_key] = new_slot_variable\n return named_slots[var_key]\n\n def _create_or_restore_slot_variable(\n self, slot_variable_position, slot_name, variable,\n optional_op_name=None):\n \"\"\"Restore a slot variable's value, possibly creating it.\n\n Called when a variable which has an associated slot variable is created or\n restored. When executing eagerly, we create the slot variable with a\n restoring initializer.\n\n No new variables are created when graph building. Instead,\n _restore_slot_variable catches these after normal creation and adds restore\n ops to the graph. This method is nonetheless important when graph building\n for the case when a slot variable has already been created but `variable`\n has just been added to a dependency graph (causing us to realize that the\n slot variable needs to be restored).\n\n Args:\n slot_variable_position: A `checkpointable._CheckpointPosition` object\n indicating the slot variable `Checkpointable` object to be restored.\n slot_name: The name of this `Optimizer`'s slot to restore into.\n variable: The variable object this slot is being created for.\n optional_op_name: Name to use when scoping the Variable that\n needs to be created for the slot.\n \"\"\"\n slot_variable = self.get_slot(var=variable, name=slot_name)\n if (slot_variable is None and context.executing_eagerly() and\n slot_variable_position.is_simple_variable()\n # Defer slot variable creation if there is an active variable creator\n # scope. Generally we'd like to eagerly create/restore slot variables\n # when possible, but this may mean that scopes intended to catch\n # `variable` also catch its eagerly created slot variable\n # unintentionally (specifically make_template would add a dependency on\n # a slot variable if not for this case). Deferring is mostly harmless\n # (aside from double initialization), and makes variable creator scopes\n # behave the same way they do when graph building.\n and not ops.get_default_graph()._variable_creator_stack): # pylint: disable=protected-access\n initializer = checkpointable.CheckpointInitialValue(\n checkpoint_position=slot_variable_position)\n slot_variable = self.create_slot(\n var=variable,\n val=initializer,\n slot_name=slot_name,\n optional_op_name=optional_op_name)\n # Optimizers do not have unconditional dependencies on their slot\n # variables (nor do any other objects). They are only saved if the\n # variables they were created for are also saved.\n if slot_variable is not None:\n # If we've either made this slot variable, or if we've pulled out an\n # existing slot variable, we should restore it.\n slot_variable_position.restore(slot_variable)\n else:\n # We didn't make the slot variable. Defer restoring until it gets created\n # normally. We keep a list rather than the one with the highest restore\n # UID in case slot variables have their own dependencies, in which case\n # those could differ between restores.\n variable_key = _var_key_v2(variable)\n self._deferred_slot_restorations.setdefault(\n slot_name, {}).setdefault(variable_key, []).append(\n slot_variable_position)\n\n def get_slot(self, var, name):\n \"\"\"Return a slot named `name` created for `var` by the Optimizer.\n\n Some `Optimizer` subclasses use additional variables. For example\n `Momentum` and `Adagrad` use variables to accumulate updates. This method\n gives access to these `Variable` objects if for some reason you need them.\n\n Use `get_slot_names()` to get the list of slot names created by the\n `Optimizer`.\n\n Args:\n var: A variable passed to `minimize()` or `apply_gradients()`.\n name: A string.\n\n Returns:\n The `Variable` for the slot if it was created, `None` otherwise.\n \"\"\"\n named_slots = self._slots.get(name, None)\n if not named_slots:\n return None\n return named_slots.get(_var_key_v2(var), None)\n\n def get_slot_names(self):\n \"\"\"Return a list of the names of slots created by the `Optimizer`.\n\n See `get_slot()`.\n\n Returns:\n A list of strings.\n \"\"\"\n return sorted(self._slots.keys())\n\n def create_non_slot(self, initial_value, name, colocate_with=None):\n \"\"\"Add an extra variable, not associated with a slot.\"\"\"\n v = self._non_slot_dict.get(name, None)\n if v is None:\n if colocate_with is None: colocate_with = self._non_slot_devices\n with self._distribution.colocate_vars_with(colocate_with):\n # TODO(josh11b): Use get_variable() except for the legacy Adam use case.\n v = variable_scope.variable(initial_value, name=name, trainable=False)\n self._non_slot_dict[name] = v\n deferred_dependencies_list = self._deferred_dependencies.pop(name, ())\n for checkpoint_position in sorted(\n deferred_dependencies_list,\n key=lambda restore: restore.checkpoint.restore_uid,\n reverse=True):\n checkpoint_position.restore(v)\n return v\n\n def _restore_slot_variable(self, slot_name, variable, slot_variable):\n \"\"\"Restore a newly created slot variable's value.\"\"\"\n variable_key = _var_key_v2(variable)\n deferred_restorations = self._deferred_slot_restorations.get(\n slot_name, {}).pop(variable_key, [])\n # Iterate over restores, highest restore UID first to minimize the number\n # of assignments.\n deferred_restorations.sort(key=lambda position: position.restore_uid,\n reverse=True)\n for checkpoint_position in deferred_restorations:\n checkpoint_position.restore(slot_variable)\n\n def get_non_slot(self, name):\n \"\"\"Returns the non-slot variable identified by `name`.\"\"\"\n return self._non_slot_dict.get(name, None)\n\n def get_hyper(self, name, dtype=None):\n \"\"\"Returns the `name` hyper parameter, optionally cast to `dtype`.\"\"\"\n dtype_dict = self._hyper[name]\n # Do we have the value cast to dtype already cached? This should always\n # succeed when dtype is None.\n if dtype in dtype_dict:\n return dtype_dict[dtype]\n # Not cached, cast to dtype and save the result in the cache.\n result = math_ops.cast(dtype_dict[None], dtype)\n dtype_dict[dtype] = result\n return result\n\nclass OptimizerV2(optimizer_v1.Optimizer):\n \"\"\"Updated base class for optimizers.\n\n This class defines the API to add Ops to train a model. You never use this\n class directly, but instead instantiate one of its subclasses such as\n `GradientDescentOptimizer`, `AdagradOptimizer`, or `MomentumOptimizer`.\n\n ### Usage\n\n ```python\n # Create an optimizer with the desired parameters.\n opt = GradientDescentOptimizer(learning_rate=0.1)\n # Add Ops to the graph to minimize a cost by updating a list of variables.\n # \"cost\" is a Tensor, and the list of variables contains tf.Variable\n # objects.\n opt_op = opt.minimize(cost, var_list=)\n ```\n\n In the training program you will just have to run the returned Op.\n\n ```python\n # Execute opt_op to do one step of training:\n opt_op.run()\n ```\n\n ### Processing gradients before applying them.\n\n Calling `minimize()` takes care of both computing the gradients and\n applying them to the variables. If you want to process the gradients\n before applying them you can instead use the optimizer in three steps:\n\n 1. Compute the gradients with `compute_gradients()`.\n 2. Process the gradients as you wish.\n 3. Apply the processed gradients with `apply_gradients()`.\n\n Example:\n\n ```python\n # Create an optimizer.\n opt = GradientDescentOptimizer(learning_rate=0.1)\n\n # Compute the gradients for a list of variables.\n grads_and_vars = opt.compute_gradients(loss, )\n\n # grads_and_vars is a list of tuples (gradient, variable). Do whatever you\n # need to the 'gradient' part, for example cap them, etc.\n capped_grads_and_vars = [(MyCapper(gv[0]), gv[1]) for gv in grads_and_vars]\n\n # Ask the optimizer to apply the capped gradients.\n opt.apply_gradients(capped_grads_and_vars)\n ```\n\n ### Gating Gradients\n\n Both `minimize()` and `compute_gradients()` accept a `gate_gradients`\n argument that controls the degree of parallelism during the application of\n the gradients.\n\n The possible values are: `GATE_NONE`, `GATE_OP`, and `GATE_GRAPH`.\n\n `GATE_NONE`: Compute and apply gradients in parallel. This provides\n the maximum parallelism in execution, at the cost of some non-reproducibility\n in the results. For example the two gradients of `matmul` depend on the input\n values: With `GATE_NONE` one of the gradients could be applied to one of the\n inputs _before_ the other gradient is computed resulting in non-reproducible\n results.\n\n `GATE_OP`: For each Op, make sure all gradients are computed before\n they are used. This prevents race conditions for Ops that generate gradients\n for multiple inputs where the gradients depend on the inputs.\n\n `GATE_GRAPH`: Make sure all gradients for all variables are computed\n before any one of them is used. This provides the least parallelism but can\n be useful if you want to process all gradients before applying any of them.\n\n ### Slots\n\n Some optimizer subclasses, such as `MomentumOptimizer` and `AdagradOptimizer`\n allocate and manage additional variables associated with the variables to\n train. These are called Slots. Slots have names and you can ask the\n optimizer for the names of the slots that it uses. Once you have a slot name\n you can ask the optimizer for the variable it created to hold the slot value.\n\n This can be useful if you want to log debug a training algorithm, report stats\n about the slots, etc.\n\n ### Non-slot variables\n\n Some optimizer subclasses, such as `AdamOptimizer` have variables that\n are not associated with the variables to train, just the step itself.\n\n ### Hyper parameters\n\n These are arguments passed to the optimizer subclass constructor\n (the `__init__` method), and then passed to `self._set_hyper()`.\n They can be either regular Python values (like 1.0), tensors, or\n callables. If they are callable, the callable will be called during\n `apply_gradients()` to get the value for the hyper parameter.\n\n ### State\n\n Internal methods are passed a `state` argument with the correct\n values to use for the slot and non-slot variables, and the hyper\n parameters.\n \"\"\"\n\n # Values for gate_gradients.\n GATE_NONE = 0\n GATE_OP = 1\n GATE_GRAPH = 2\n\n def __init__(self, name):\n \"\"\"Create a new Optimizer.\n\n This must be called by the constructors of subclasses.\n Note that Optimizer instances should not bind to a single graph,\n and so shouldn't keep Tensors as member variables. Generally\n you should be able to use the _set_hyper()/state.get_hyper()\n facility instead.\n\n Args:\n name: A non-empty string. The name to use for accumulators created\n for the optimizer.\n\n Raises:\n ValueError: If name is malformed.\n RuntimeError: If _create_slots has been overridden instead of\n _create_vars.\n \"\"\"\n # Note: We intentionally don't call parent __init__.\n\n # Optimizer._create_slots was replaced by _create_vars in OptimizerV2.\n if (self.__class__._create_slots.__code__ is not # pylint: disable=protected-access\n OptimizerV2._create_slots.__code__):\n raise RuntimeError(\"Override _create_vars instead of _create_slots when \"\n \"descending from OptimizerV2 (class %s)\" %\n self.__class__.__name__)\n if not name:\n raise ValueError(\"Must specify the optimizer name\")\n\n self._use_locking = False\n self._name = name\n # Map from graph_key to state for that graph. We use the graph_key\n # since it works in both eager and graph mode, and gives the outer\n # graph inside functions.\n tower_context = distribution_strategy_context.get_tower_context()\n if tower_context is None:\n # In a cross-tower context for a DistributionStrategy, which means\n # only one Optimizer will be created, not one per tower.\n self._per_graph_state = {}\n else:\n # We use get_tower_context().merge_call() to get a single dict\n # shared across all model replicas when running with a\n # DistributionStrategy.\n self._per_graph_state = tower_context.merge_call(lambda _: {})\n\n # Hyper parameters, and whether they should be re-evaluated every step.\n self._hyper = {}\n\n def _set_hyper(self, name, value):\n self._hyper[name] = (_is_dynamic(value), value)\n\n def minimize(self, loss, global_step=None, var_list=None,\n gate_gradients=GATE_OP, aggregation_method=None,\n colocate_gradients_with_ops=False, name=None,\n grad_loss=None, stop_gradients=None,\n scale_loss_by_num_towers=None):\n \"\"\"Add operations to minimize `loss` by updating `var_list`.\n\n This method simply combines calls `compute_gradients()` and\n `apply_gradients()`. If you want to process the gradient before applying\n them call `compute_gradients()` and `apply_gradients()` explicitly instead\n of using this function.\n\n Args:\n loss: A `Tensor` containing the value to minimize.\n global_step: Optional `Variable` to increment by one after the\n variables have been updated.\n var_list: Optional list or tuple of `Variable` objects to update to\n minimize `loss`. Defaults to the list of variables collected in\n the graph under the key `GraphKeys.TRAINABLE_VARIABLES`.\n gate_gradients: How to gate the computation of gradients. Can be\n `GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`.\n aggregation_method: Specifies the method used to combine gradient terms.\n Valid values are defined in the class `AggregationMethod`.\n colocate_gradients_with_ops: If True, try colocating gradients with\n the corresponding op.\n name: Optional name for the returned operation.\n grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`.\n stop_gradients: Optional. A Tensor or list of tensors not to differentiate\n through.\n scale_loss_by_num_towers: Optional boolean. If true, scale the loss\n down by the number of towers. By default, auto-detects whether this\n is needed.\n\n Returns:\n An Operation that updates the variables in `var_list`. If `global_step`\n was not `None`, that operation also increments `global_step`.\n\n Raises:\n ValueError: If some of the variables are not `Variable` objects.\n\n @compatibility(eager)\n When eager execution is enabled, `loss` should be a Python function that\n takes elements of `var_list` as arguments and computes the value to be\n minimized. If `var_list` is None, `loss` should take no arguments.\n Minimization (and gradient computation) is done with respect to the\n elements of `var_list` if not None, else with respect to any trainable\n variables created during the execution of the `loss` function.\n `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and\n `grad_loss` are ignored when eager execution is enabled.\n @end_compatibility\n \"\"\"\n grads_and_vars = self.compute_gradients(\n loss, var_list=var_list, gate_gradients=gate_gradients,\n aggregation_method=aggregation_method,\n colocate_gradients_with_ops=colocate_gradients_with_ops,\n grad_loss=grad_loss, stop_gradients=stop_gradients,\n scale_loss_by_num_towers=scale_loss_by_num_towers)\n\n vars_with_grad = [v for g, v in grads_and_vars if g is not None]\n if not vars_with_grad:\n raise ValueError(\n \"No gradients provided for any variable, check your graph for ops\"\n \" that do not support gradients, between variables %s and loss %s.\" %\n ([str(v) for _, v in grads_and_vars], loss))\n\n return self.apply_gradients(grads_and_vars, global_step=global_step,\n name=name)\n\n def compute_gradients(self, loss, var_list=None,\n gate_gradients=GATE_OP,\n aggregation_method=None,\n colocate_gradients_with_ops=False,\n grad_loss=None, stop_gradients=None,\n scale_loss_by_num_towers=None):\n \"\"\"Compute gradients of `loss` for the variables in `var_list`.\n\n This is the first part of `minimize()`. It returns a list\n of (gradient, variable) pairs where \"gradient\" is the gradient\n for \"variable\". Note that \"gradient\" can be a `Tensor`, an\n `IndexedSlices`, or `None` if there is no gradient for the\n given variable.\n\n Args:\n loss: A Tensor containing the value to minimize or a callable taking\n no arguments which returns the value to minimize. When eager execution\n is enabled it must be a callable.\n var_list: Optional list or tuple of `tf.Variable` to update to minimize\n `loss`. Defaults to the list of variables collected in the graph\n under the key `GraphKeys.TRAINABLE_VARIABLES`.\n gate_gradients: How to gate the computation of gradients. Can be\n `GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`.\n aggregation_method: Specifies the method used to combine gradient terms.\n Valid values are defined in the class `AggregationMethod`.\n colocate_gradients_with_ops: If True, try colocating gradients with\n the corresponding op.\n grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`.\n stop_gradients: Optional. A Tensor or list of tensors not to differentiate\n through.\n scale_loss_by_num_towers: Optional boolean. If true, scale the loss\n down by the number of towers. By default, auto-detects whether this\n is needed.\n\n Returns:\n A list of (gradient, variable) pairs. Variable is always present, but\n gradient can be `None`.\n\n Raises:\n TypeError: If `var_list` contains anything else than `Variable` objects.\n ValueError: If some arguments are invalid.\n RuntimeError: If called with eager execution enabled and `loss` is\n not callable.\n\n @compatibility(eager)\n When eager execution is enabled, `gate_gradients`, `aggregation_method`,\n and `colocate_gradients_with_ops` are ignored.\n @end_compatibility\n \"\"\"\n # TODO(josh11b): Test that we handle weight decay in a reasonable way.\n if callable(loss):\n with backprop.GradientTape() as tape:\n if var_list is not None:\n tape.watch(var_list)\n loss_value = loss()\n\n # Scale loss for number of towers (callable-loss case). In this case,\n # we have to be careful to call distribute_lib.get_loss_reduction()\n # *after* loss() is evaluated, so we know what loss reduction it uses.\n if scale_loss_by_num_towers is None:\n scale_loss_by_num_towers = (\n distribute_lib.get_loss_reduction() ==\n variable_scope.VariableAggregation.MEAN)\n if scale_loss_by_num_towers:\n num_towers = distribution_strategy_context.get_distribution_strategy(\n ).num_towers\n if num_towers > 1:\n loss_value *= 1. / num_towers\n\n if var_list is None:\n var_list = tape.watched_variables()\n grads = tape.gradient(loss_value, var_list, grad_loss)\n return list(zip(grads, var_list))\n if context.executing_eagerly():\n raise RuntimeError(\n \"`loss` passed to Optimizer.compute_gradients should \"\n \"be a function when eager execution is enabled.\")\n\n # Scale loss for number of towers (non-callable-loss case).\n if scale_loss_by_num_towers is None:\n scale_loss_by_num_towers = (\n distribute_lib.get_loss_reduction() ==\n variable_scope.VariableAggregation.MEAN)\n if scale_loss_by_num_towers:\n num_towers = distribution_strategy_context.get_distribution_strategy(\n ).num_towers\n if num_towers > 1:\n loss *= 1. / num_towers\n\n if gate_gradients not in [optimizer_v1.Optimizer.GATE_NONE,\n optimizer_v1.Optimizer.GATE_OP,\n optimizer_v1.Optimizer.GATE_GRAPH]:\n raise ValueError(\"gate_gradients must be one of: Optimizer.GATE_NONE, \"\n \"Optimizer.GATE_OP, Optimizer.GATE_GRAPH. Not %s\" %\n gate_gradients)\n self._assert_valid_dtypes([loss])\n if grad_loss is not None:\n self._assert_valid_dtypes([grad_loss])\n if var_list is None:\n var_list = (\n variables.trainable_variables() +\n ops.get_collection(ops.GraphKeys.TRAINABLE_RESOURCE_VARIABLES))\n else:\n var_list = nest.flatten(var_list)\n # pylint: disable=protected-access\n var_list += ops.get_collection(ops.GraphKeys._STREAMING_MODEL_PORTS)\n # pylint: enable=protected-access\n processors = [_get_processor(v) for v in var_list]\n if not var_list:\n raise ValueError(\"No variables to optimize.\")\n var_refs = [p.target() for p in processors]\n grads = gradients.gradients(\n loss, var_refs, grad_ys=grad_loss,\n gate_gradients=(gate_gradients == optimizer_v1.Optimizer.GATE_OP),\n aggregation_method=aggregation_method,\n colocate_gradients_with_ops=colocate_gradients_with_ops,\n stop_gradients=stop_gradients)\n if gate_gradients == optimizer_v1.Optimizer.GATE_GRAPH:\n grads = control_flow_ops.tuple(grads)\n grads_and_vars = list(zip(grads, var_list))\n self._assert_valid_dtypes(\n [v for g, v in grads_and_vars\n if g is not None and v.dtype != dtypes.resource])\n return grads_and_vars\n\n def apply_gradients(self, grads_and_vars, global_step=None, name=None):\n \"\"\"Apply gradients to variables.\n\n This is the second part of `minimize()`. It returns an `Operation` that\n applies gradients.\n\n Args:\n grads_and_vars: List of (gradient, variable) pairs as returned by\n `compute_gradients()`.\n global_step: Optional `Variable` to increment by one after the\n variables have been updated.\n name: Optional name for the returned operation. Default to the\n name passed to the `Optimizer` constructor.\n\n Returns:\n An `Operation` that applies the specified gradients. If `global_step`\n was not None, that operation also increments `global_step`.\n\n Raises:\n TypeError: If `grads_and_vars` is malformed.\n ValueError: If none of the variables have gradients.\n \"\"\"\n # This is a default implementation of apply_gradients() that can be shared\n # by most optimizers. It relies on the subclass implementing the following\n # methods: _create_vars(), _prepare(), _apply_dense(), and _apply_sparse().\n\n # Filter out variables with gradients of `None`.\n grads_and_vars = tuple(grads_and_vars) # Make sure repeat iteration works.\n if not grads_and_vars:\n raise ValueError(\"No variables provided.\")\n filtered = tuple((g, v) for (g, v) in grads_and_vars if g is not None)\n if not filtered:\n raise ValueError(\"No gradients provided for any variable: %s.\" %\n ([str(v) for _, v in grads_and_vars],))\n return distribution_strategy_context.get_tower_context().merge_call(\n self._distributed_apply, filtered, global_step=global_step, name=name)\n\n def _get_or_create_state(self, var_list=None):\n \"\"\"Either looks up or creates `_OptimizerV2State`.\n\n If any variables are available, they should be passed via the `var_list`\n argument, and these will be used to determine the graph to create/retrieve\n state for. Otherwise the returned state is for the current default graph.\n\n Args:\n var_list: A list of variables to extract a graph from.\n\n Returns:\n An `_OptimizerV2State` object.\n \"\"\"\n # Determine the graph_key from the current graph.\n eager_execution = context.executing_eagerly()\n if eager_execution or var_list is None:\n graph = ops.get_default_graph()\n else:\n graph = ops._get_graph_from_inputs(var_list) # pylint: disable=protected-access\n assert graph is not None\n graph_key = graph._graph_key # pylint: disable=protected-access\n\n # Get the per graph state by looking up the graph_key.\n if graph_key in self._per_graph_state:\n per_graph_state = self._per_graph_state[graph_key]\n else:\n per_graph_state = _OptimizerV2State(self._name)\n per_graph_state._init_with_static_hyper(self._hyper) # pylint: disable=protected-access\n self._per_graph_state[graph_key] = per_graph_state\n return per_graph_state\n\n def _distributed_apply(self, distribution, grads_and_vars, global_step, name):\n \"\"\"`apply_gradients` for use with a `DistributionStrategy`.\"\"\"\n reduced_grads = distribution.batch_reduce(\n variable_scope.VariableAggregation.SUM, grads_and_vars)\n var_list = [v for _, v in grads_and_vars]\n grads_and_vars = zip(reduced_grads, var_list)\n\n unwrapped_var_list = [x for v in var_list for x in distribution.unwrap(v)]\n eager_execution = context.executing_eagerly()\n if eager_execution:\n # Give a clear error in this case instead of \"name not supported\n # for Eager Tensors\" when we compute non_slot_devices.\n for v in unwrapped_var_list:\n if isinstance(v, ops.Tensor):\n raise NotImplementedError(\"Trying to update a Tensor \", v)\n\n with ops.name_scope(name, self._name) as name:\n per_graph_state = self._get_or_create_state(var_list=unwrapped_var_list)\n # Include the current value of any dynamic hyper parameters in `state`.\n non_slot_devices = distribution.non_slot_devices(var_list)\n state = per_graph_state._copy_with_dynamic_hyper( # pylint: disable=protected-access\n self._hyper, distribution, non_slot_devices)\n\n # Create any slot and non-slot variables we need in `state`.\n with ops.init_scope():\n self._create_vars(var_list, state)\n\n with ops.name_scope(name): # Re-enter name_scope created above\n # Give the child class a chance to do something before we start\n # applying gradients.\n self._prepare(state)\n\n def update(v, g):\n \"\"\"Update variable `v` using gradient `g`.\"\"\"\n assert v is not None\n\n # Convert the grad to Tensor or IndexedSlices if necessary, and\n # look up a processor for each variable's type.\n try:\n g = ops.convert_to_tensor_or_indexed_slices(g)\n except TypeError:\n raise TypeError(\n \"Gradient must be convertible to a Tensor\"\n \" or IndexedSlices, or None: %s\" % g)\n if not isinstance(g, (ops.Tensor, ops.IndexedSlices)):\n raise TypeError(\n \"Gradient must be a Tensor, IndexedSlices, or None: %s\" % g)\n processor = _get_processor(v)\n\n # We colocate all ops created in _apply_dense or _apply_sparse\n # on the same device as the variable.\n # TODO(apassos): figure out how to get the variable name here.\n scope_name = \"\" if eager_execution else v.op.name\n # device_policy is set because non-mirrored tensors will be read in\n # `update_op`.\n # TODO(josh11b): Make different state objects for each device to\n # avoid needing to set the device_policy.\n with ops.name_scope(\"update_\" + scope_name), \\\n context.context().device_policy(context.DEVICE_PLACEMENT_SILENT):\n return processor.update_op(self, g, state)\n\n # Use the processors to update the variables.\n update_ops = []\n for grad, var in grads_and_vars:\n update_ops.extend(distribution.update(var, update, grad, grouped=False))\n\n # Give the child class a chance to do something after applying\n # gradients\n def finish():\n # TODO(josh11b): Make different state objects for each device to\n # avoid needing to set the device_policy.\n with context.context().device_policy(context.DEVICE_PLACEMENT_SILENT):\n return self._finish(state)\n\n update_ops = control_flow_ops.group(update_ops)\n with ops.control_dependencies([update_ops]):\n finish_updates = distribution.update_non_slot(\n non_slot_devices, finish, grouped=False)\n # We said grouped=False, which means finish_updates is always a list.\n # It will be [None] when finish() returns None.\n if finish_updates == [None]:\n finish_updates = [update_ops]\n\n # Update `global_step` (if any).\n if global_step is None:\n apply_updates = distribution.group(finish_updates, name=name)\n else:\n with ops.control_dependencies(finish_updates):\n\n def update_global_step(global_step, name):\n return global_step.assign_add(1, read_value=False, name=name)\n\n apply_updates = distribution.update(global_step, update_global_step,\n name)\n\n # Add the training op to the TRAIN_OP graph collection in graph mode.\n if not eager_execution:\n if isinstance(apply_updates, ops.Tensor):\n apply_updates = apply_updates.op\n train_op = ops.get_collection_ref(ops.GraphKeys.TRAIN_OP)\n if apply_updates not in train_op:\n train_op.append(apply_updates)\n\n return apply_updates\n\n def get_slot(self, var, name):\n \"\"\"Return a slot named `name` created for `var` by the Optimizer.\n\n Some `Optimizer` subclasses use additional variables. For example\n `Momentum` and `Adagrad` use variables to accumulate updates. This method\n gives access to these `Variable` objects if for some reason you need them.\n\n Use `get_slot_names()` to get the list of slot names created by the\n `Optimizer`.\n\n Args:\n var: A variable passed to `minimize()` or `apply_gradients()`.\n name: A string.\n\n Returns:\n The `Variable` for the slot if it was created, `None` otherwise.\n \"\"\"\n state = self._get_state_for_var(var)\n return state.get_slot(var, name) if state is not None else None\n\n def get_slot_names(self):\n \"\"\"Return a list of the names of slots created by the `Optimizer`.\n\n See `get_slot()`.\n\n Returns:\n A list of strings.\n \"\"\"\n state = self._get_per_graph_state()\n return state.get_slot_names() if state is not None else []\n\n def variables(self):\n \"\"\"A list of variables which encode the current state of `Optimizer`.\n\n Includes slot variables and additional global variables created by the\n optimizer in the current default graph.\n\n Returns:\n A list of variables.\n \"\"\"\n state = self._get_per_graph_state()\n return state._variables() if state is not None else [] # pylint: disable=protected-access\n\n # --------------\n # Methods to be implemented by subclasses if they want to use the\n # inherited implementation of apply_gradients() or compute_gradients().\n # --------------\n def _create_vars(self, var_list, state):\n \"\"\"Create all slots needed by the variables and any non-slot variables.\n\n Args:\n var_list: A list of `Variable` objects.\n state: An object with these methods:\n `create_slot(var, val, slot_name, optional_op_name)`,\n `create_slot_with_initializer(`\n `var, initializer, shape, dtype, slot_name, optional_op_name)`,\n `zeros_slot(var, slot_name, optional_op_name)`,\n `create_non_slot_variable(initial_value, name, colocate_with)`,\n `get_hyper(name)`\n \"\"\"\n # No slots needed by default\n pass\n\n def _prepare(self, state):\n \"\"\"Code to execute before applying gradients.\n\n Note that most uses of _prepare() in Optimizer have been subsumed\n by explicit support for hyper parameters in OptimizerV2\n\n Args:\n state: An object with a `get_hyper(name)` method.\n\n Returns:\n Return value will be ignored.\n \"\"\"\n pass\n\n def _apply_dense(self, grad, var, state):\n \"\"\"Add ops to apply dense gradients to `var`.\n\n Args:\n grad: A `Tensor`.\n var: A `Variable` object.\n state: An object with `get_slot(var, name)`, `get_non_slot(self, name)`,\n and `get_hyper(name)` methods.\n\n Returns:\n An `Operation`.\n \"\"\"\n raise NotImplementedError()\n\n def _resource_apply_dense(self, grad, handle, state):\n \"\"\"Add ops to apply dense gradients to the variable `handle`.\n\n Args:\n grad: a `Tensor` representing the gradient.\n handle: a `Tensor` of dtype `resource` which points to the variable\n to be updated.\n state: An object with `get_slot(var, name)`, `get_non_slot(self, name)`,\n and `get_hyper(name)` methods.\n\n Returns:\n An `Operation` which updates the value of the variable.\n \"\"\"\n raise NotImplementedError()\n\n def _resource_apply_sparse_duplicate_indices(\n self, grad, handle, indices, state):\n \"\"\"Add ops to apply sparse gradients to `handle`, with repeated indices.\n\n Optimizers which override this method must deal with repeated indices. See\n the docstring of `_apply_sparse_duplicate_indices` for details. By default\n the correct behavior, to sum non-unique indices and their associated\n gradients, is enforced by first pre-processing `grad` and `indices` and\n passing them on to `_resource_apply_sparse`. Optimizers which deal correctly\n with duplicate indices may instead override this method to avoid the\n overhead of summing.\n\n Args:\n grad: a `Tensor` representing the gradient for the affected indices.\n handle: a `Tensor` of dtype `resource` which points to the variable\n to be updated.\n indices: a `Tensor` of integral type representing the indices for\n which the gradient is nonzero. Indices may be repeated.\n state: An object with `get_slot(var, name)`, `get_non_slot(self, name)`,\n and `get_hyper(name)` methods.\n\n Returns:\n An `Operation` which updates the value of the variable.\n \"\"\"\n # pylint: disable=protected-access\n summed_grad, unique_indices = optimizer_v1._deduplicate_indexed_slices(\n values=grad, indices=indices)\n # pylint: enable=protected-access\n return self._resource_apply_sparse(\n summed_grad, handle, unique_indices, state)\n\n def _resource_apply_sparse(self, grad, handle, indices, state):\n \"\"\"Add ops to apply sparse gradients to the variable `handle`.\n\n Similar to `_apply_sparse`, the `indices` argument to this method has been\n de-duplicated. Optimizers which deal correctly with non-unique indices may\n instead override `_resource_apply_sparse_duplicate_indices` to avoid this\n overhead.\n\n Args:\n grad: a `Tensor` representing the gradient for the affected indices.\n handle: a `Tensor` of dtype `resource` which points to the variable\n to be updated.\n indices: a `Tensor` of integral type representing the indices for\n which the gradient is nonzero. Indices are unique.\n state: An object with `get_slot(var, name)`, `get_non_slot(self, name)`,\n and `get_hyper(name)` methods.\n\n Returns:\n An `Operation` which updates the value of the variable.\n \"\"\"\n raise NotImplementedError()\n\n def _apply_sparse_duplicate_indices(self, grad, var, state):\n \"\"\"Add ops to apply sparse gradients to `var`, with repeated sparse indices.\n\n Optimizers which override this method must deal with IndexedSlices objects\n such as the following:\n\n IndexedSlicesValue(values=[1, 1], indices=[0, 0], dense_shape=[1])\n\n The correct interpretation is:\n\n IndexedSlicesValue(values=[2], indices=[0], dense_shape=[1])\n\n Many optimizers deal incorrectly with repeated indices when updating based\n on sparse gradients (e.g. summing squares rather than squaring the sum, or\n applying momentum terms multiple times). Adding first is always the correct\n behavior, so this is enforced here by reconstructing the IndexedSlices to\n have only unique indices, then calling _apply_sparse.\n\n Optimizers which deal correctly with repeated indices may instead override\n this method to avoid the overhead of summing indices.\n\n Args:\n grad: `IndexedSlices`.\n var: A `Variable` object.\n state: An object with `get_slot(var, name)`, `get_non_slot(self, name)`,\n and `get_hyper(name)` methods.\n\n Returns:\n An `Operation`.\n \"\"\"\n # pylint: disable=protected-access\n summed_values, unique_indices = optimizer_v1._deduplicate_indexed_slices(\n values=grad.values, indices=grad.indices)\n # pylint: enable=protected-access\n gradient_no_duplicate_indices = ops.IndexedSlices(\n indices=unique_indices,\n values=summed_values,\n dense_shape=grad.dense_shape)\n return self._apply_sparse(gradient_no_duplicate_indices, var, state)\n\n def _apply_sparse(self, grad, var, state):\n \"\"\"Add ops to apply sparse gradients to `var`.\n\n The IndexedSlices object passed to `grad` in this function is by default\n pre-processed in `_apply_sparse_duplicate_indices` to remove duplicate\n indices (see its docstring for details). Optimizers which can tolerate or\n have correct special cases for duplicate sparse indices may override\n `_apply_sparse_duplicate_indices` instead of this function, avoiding that\n overhead.\n\n Args:\n grad: `IndexedSlices`, with no repeated indices.\n var: A `Variable` object.\n state: An object with `get_slot(var, name)`, `get_non_slot(self, name)`,\n and `get_hyper(name)` methods.\n\n Returns:\n An `Operation`.\n \"\"\"\n raise NotImplementedError()\n\n def _finish(self, state):\n \"\"\"Do what is needed to finish the update.\n\n This is called inside a scope colocated with any non-slot variables.\n\n Args:\n state: An object with `get_slot(var, name)`, `get_non_slot(self, name)`,\n and `get_hyper(name)` methods.\n\n Returns:\n The operation to apply updates, or None if no updates.\n \"\"\"\n return None\n\n # --------------\n # Utility methods for subclasses.\n # --------------\n def _get_per_graph_state(self):\n # pylint: disable=protected-access\n return self._per_graph_state.get(ops.get_default_graph()._graph_key, None)\n\n def _get_state_for_var(self, var):\n # pylint: disable=protected-access\n return self._per_graph_state.get(var._graph_key, None)\n\n # --------------\n # Overridden methods from Checkpointable.\n # --------------\n\n def _track_checkpointable(self, *args, **kwargs):\n \"\"\"Optimizers may not track dependencies. Raises an error.\"\"\"\n raise NotImplementedError(\n \"Optimizers may not have dependencies. File a feature request if this \"\n \"limitation bothers you.\")\n\n @property\n def _checkpoint_dependencies(self):\n \"\"\"From Checkpointable. Gather graph-specific non-slot variables to save.\"\"\"\n current_graph_non_slot_variables = []\n state = self._get_per_graph_state()\n if state is not None:\n for name, variable_object in sorted(\n state._non_slot_dict.items(), # pylint: disable=protected-access\n # Avoid comparing variables\n key=lambda item: item[0]):\n current_graph_non_slot_variables.append(\n checkpointable.CheckpointableReference(\n name=name, ref=variable_object))\n # Note: ignores super(); Optimizers may not have any dependencies outside of\n # state objects.\n return current_graph_non_slot_variables\n\n def _lookup_dependency(self, name):\n \"\"\"From Checkpointable. Find a non-slot variable in the current graph.\"\"\"\n state = self._get_per_graph_state()\n if state is None:\n return None\n else:\n return state.get_non_slot(name)\n\n @property\n def _deferred_dependencies(self):\n \"\"\"Lets Checkpointable know where non-slot variables are created.\n\n If necessary, creates a new state object for the current default graph.\n Checkpointable will then add entries to that state's deferred dependency\n dictionary. The state object will check that dictionary when creating\n non-slot variables, restoring their value if an entry is found.\n\n Returns:\n A dictionary which holds deferred dependencies for the current default\n graph.\n \"\"\"\n state = self._get_or_create_state()\n return state._deferred_dependencies # pylint: disable=protected-access\n\n def _create_or_restore_slot_variable(\n self, slot_variable_position, slot_name, variable):\n \"\"\"Checkpointable: Restore a slot variable's value, possibly creating it.\n\n Called when a variable which has an associated slot variable is created or\n restored.\n\n Args:\n slot_variable_position: A `checkpointable._CheckpointPosition` object\n indicating the slot variable `Checkpointable` object to be restored.\n slot_name: The name of this `Optimizer`'s slot to restore into.\n variable: The variable object this slot is being created for.\n \"\"\"\n state = self._get_or_create_state(var_list=[variable])\n state._create_or_restore_slot_variable( # pylint: disable=protected-access\n slot_variable_position=slot_variable_position,\n slot_name=slot_name,\n variable=variable,\n optional_op_name=self._name)\n\n def get_config(self):\n \"\"\"Returns the config of the optimimizer.\n\n An optimizer config is a Python dictionary (serializable)\n containing the configuration of an optimizer.\n The same optimizer can be reinstantiated later\n (without any saved state) from this configuration.\n\n Returns:\n Python dictionary.\n \"\"\"\n return {\"name\": self._name}\n\n @classmethod\n def from_config(cls, config, custom_objects=None):\n \"\"\"Creates an optimizer from its config.\n\n This method is the reverse of `get_config`,\n capable of instantiating the same optimizer from the config\n dictionary.\n\n Arguments:\n config: A Python dictionary, typically the output of get_config.\n custom_objects: A Python dictionary mapping names to additional Python\n objects used to create this optimizer, such as a function used for a\n hyperparameter.\n\n Returns:\n An optimizer instance.\n \"\"\"\n return cls(**config)\n\n def _serialize_hyperparameter(self, hyperparameter_name):\n \"\"\"Serialize a hyperparameter that can be a float, callable, or Tensor.\"\"\"\n return self._hyper[hyperparameter_name][1]\n\n # --------------\n # Unsupported parent methods\n # --------------\n def _slot_dict(self, slot_name):\n raise NotImplementedError(\n \"_slot_dict() method unsupported in OptimizerV2\")\n\n def _get_or_make_slot(self, var, val, slot_name, op_name):\n raise NotImplementedError(\n \"_get_or_make_slot() method unsupported in OptimizerV2\")\n\n def _get_or_make_slot_with_initializer(self, var, initializer, shape, dtype,\n slot_name, op_name):\n raise NotImplementedError(\n \"_get_or_make_slot_with_initializer() method unsupported in \"\n \"OptimizerV2\")\n\n def _create_non_slot_variable(self, initial_value, name, colocate_with):\n raise NotImplementedError(\n \"_create_non_slot_variable() method unsupported in OptimizerV2\")\n\n def _get_non_slot_variable(self, name, graph=None):\n raise NotImplementedError(\n \"_get_non_slot_variable() method unsupported in OptimizerV2\")\n\n def _non_slot_variables(self):\n raise NotImplementedError(\n \"_non_slot_variables() method unsupported in OptimizerV2\")"}]} {"messages": [{"role": "user", "content": "Write Python code that implements network_testnode_interchangeability.py from spbguru/repo1 (path: tests/integration/py2/nupic/engine/network_testnode_interchangeability.py)."}, {"role": "assistant", "content": "# tests/integration/py2/nupic/engine/network_testnode_interchangeability.py (from spbguru/repo1, license: gpl-3.0)\n\n#!/usr/bin/env python\n# ----------------------------------------------------------------------\n# Numenta Platform for Intelligent Computing (NuPIC)\n# Copyright (C) 2014, Numenta, Inc. Unless you have an agreement\n# with Numenta, Inc., for a separate license for this software code, the\n# following terms and conditions apply:\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License version 3 as\n# published by the Free Software Foundation.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# See the GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see http://www.gnu.org/licenses.\n#\n# http://numenta.org/licenses/\n# ----------------------------------------------------------------------\n\n\"\"\"This test verifies that the C++ test node and py.TestNode\n\nIt creates the same two node network with all four combinations\nof TestNode and py.TestNode:\n\n1. TestNode, TestNode\n2. TestNode, py.TestNode\n3. py.TestNode, TestNode\n4. py.TestNode, py.TestNode\n\nThen it performs the same tests as the twonode_network demo (except the error\nmessages tests for the three node network):\n\n - Can add regions to network and set dimensions\n - Linking induces dimensions correctly\n - Network computation happens in correct order\n - Direct (zero-copy) access to outputs\n - Linking correctly maps outputs to inputs\n\"\"\"\n\nimport logging\nimport unittest2 as unittest\n\nfrom nupic.engine import Network, Dimensions\n\nLOGGER = logging.getLogger(__name__)\n\nclass NetworkTestNodeInterchangeabilityTest(unittest.TestCase):\n\n def testNodesPyTestNodeAndTestNode(self):\n self.runNodesTest('py.TestNode', 'TestNode')\n\n def testNodesTestNodeAndPyTestNode(self):\n self.runNodesTest('TestNode', 'py.TestNode')\n\n def testNodesTestNodeAndTestNode(self):\n self.runNodesTest('TestNode', 'TestNode')\n\n def testNodesPyTestNodeAndPyTestNode(self):\n self.runNodesTest('py.TestNode', 'py.TestNode')\n\n def runNodesTest(self, nodeType1, nodeType2):\n # =====================================================\n # Build and run the network\n # =====================================================\n LOGGER.info('test(level1: %s, level2: %s)', nodeType1, nodeType2)\n net = Network()\n level1 = net.addRegion(\"level1\", nodeType1, \"{int32Param: 15}\")\n dims = Dimensions([6, 4])\n level1.setDimensions(dims)\n\n level2 = net.addRegion(\"level2\", nodeType2, \"{real64Param: 128.23}\")\n\n net.link(\"level1\", \"level2\", \"TestFanIn2\", \"\")\n\n # Could call initialize here, but not necessary as net.run()\n # initializes implicitly.\n # net.initialize()\n\n net.run(1)\n LOGGER.info(\"Successfully created network and ran for one iteration\")\n\n # =====================================================\n # Check everything\n # =====================================================\n dims = level1.getDimensions()\n self.assertEqual(len(dims), 2)\n self.assertEqual(dims[0], 6)\n self.assertEqual(dims[1], 4)\n\n dims = level2.getDimensions()\n self.assertEqual(len(dims), 2)\n self.assertEqual(dims[0], 3)\n self.assertEqual(dims[1], 2)\n\n # Check L1 output. \"False\" means don't copy, i.e.\n # get a pointer to the actual output\n # Actual output values are determined by the TestNode\n # compute() behavior.\n l1output = level1.getOutputData(\"bottomUpOut\")\n self.assertEqual(len(l1output), 48) # 24 nodes; 2 values per node\n for i in xrange(24):\n self.assertEqual(l1output[2*i], 0) # size of input to each node is 0\n self.assertEqual(l1output[2*i+1], i) # node number\n\n # check L2 output.\n l2output = level2.getOutputData(\"bottomUpOut\")\n self.assertEqual(len(l2output), 12) # 6 nodes; 2 values per node\n # Output val = node number + sum(inputs)\n # Can compute from knowing L1 layout\n #\n # 00 01 | 02 03 | 04 05\n # 06 07 | 08 09 | 10 11\n # ---------------------\n # 12 13 | 14 15 | 16 17\n # 18 19 | 20 21 | 22 23\n outputVals = []\n outputVals.append(0 + (0 + 1 + 6 + 7))\n outputVals.append(1 + (2 + 3 + 8 + 9))\n outputVals.append(2 + (4 + 5 + 10 + 11))\n outputVals.append(3 + (12 + 13 + 18 + 19))\n outputVals.append(4 + (14 + 15 + 20 + 21))\n outputVals.append(5 + (16 + 17 + 22 + 23))\n for i in xrange(6):\n if l2output[2*i] != 8:\n LOGGER.info(l2output[2*i])\n # from dbgp.client import brk; brk(port=9019)\n\n self.assertEqual(l2output[2*i], 8) # size of input for each node is 8\n self.assertEqual(l2output[2*i+1], outputVals[i])\n\n # =====================================================\n # Run for one more iteration\n # =====================================================\n LOGGER.info(\"Running for a second iteration\")\n net.run(1)\n\n # =====================================================\n # Check everything again\n # =====================================================\n\n # Outputs are all the same except that the first output is\n # incremented by the iteration number\n for i in xrange(24):\n self.assertEqual(l1output[2*i], 1)\n self.assertEqual(l1output[2*i+1], i)\n\n for i in xrange(6):\n self.assertEqual(l2output[2*i], 9)\n self.assertEqual(l2output[2*i+1], outputVals[i] + 4)\n\n # =====================================================\n # Demonstrate a few other features\n # =====================================================\n\n #\n # Linking can induce dimensions downward\n #\n\n net = Network()\n level1 = net.addRegion(\"level1\", nodeType1, \"\")\n level2 = net.addRegion(\"level2\", nodeType2, \"\")\n dims = Dimensions([3, 2])\n level2.setDimensions(dims)\n net.link(\"level1\", \"level2\", \"TestFanIn2\", \"\")\n net.initialize()\n\n # Level1 should now have dimensions [6, 4]\n self.assertEqual(level1.getDimensions()[0], 6)\n self.assertEqual(level1.getDimensions()[1], 4)\n\nif __name__ == \"__main__\":\n unittest.main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_textbox02.py from mdeemer/XlsxWriter (path: xlsxwriter/test/comparison/test_textbox02.py)."}, {"role": "assistant", "content": "# xlsxwriter/test/comparison/test_textbox02.py (from mdeemer/XlsxWriter, license: bsd-2-clause)\n\n###############################################################################\n#\n# Tests for XlsxWriter.\n#\n# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org\n#\n\nfrom ..excel_comparsion_test import ExcelComparisonTest\nfrom ...workbook import Workbook\n\nclass TestCompareXLSXFiles(ExcelComparisonTest):\n \"\"\"\n Test file created by XlsxWriter against a file created by Excel.\n\n \"\"\"\n\n def setUp(self):\n self.maxDiff = None\n\n filename = 'textbox02.xlsx'\n\n test_dir = 'xlsxwriter/test/comparison/'\n self.got_filename = test_dir + '_test_' + filename\n self.exp_filename = test_dir + 'xlsx_files/' + filename\n\n self.ignore_files = []\n self.ignore_elements = {}\n\n def test_create_file(self):\n \"\"\"Test the creation of a simple XlsxWriter file with textbox(s).\"\"\"\n\n workbook = Workbook(self.got_filename)\n\n worksheet = workbook.add_worksheet()\n\n worksheet.insert_textbox('E9', 'This is some text')\n\n worksheet.insert_textbox('H18', 'Some more text')\n\n workbook.close()\n\n self.assertExcelEqual()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_insert.py from buntyke/Flask (path: microblog/flask/lib/python2.7/site-packages/sqlalchemy/testing/suite/test_insert.py)."}, {"role": "assistant", "content": "# microblog/flask/lib/python2.7/site-packages/sqlalchemy/testing/suite/test_insert.py (from buntyke/Flask, license: mit)\n\nfrom .. import fixtures, config\nfrom ..config import requirements\nfrom .. import exclusions\nfrom ..assertions import eq_\nfrom .. import engines\n\nfrom sqlalchemy import Integer, String, select, literal_column, literal\n\nfrom ..schema import Table, Column\n\nclass LastrowidTest(fixtures.TablesTest):\n run_deletes = 'each'\n\n __backend__ = True\n\n __requires__ = 'implements_get_lastrowid', 'autoincrement_insert'\n\n __engine_options__ = {\"implicit_returning\": False}\n\n @classmethod\n def define_tables(cls, metadata):\n Table('autoinc_pk', metadata,\n Column('id', Integer, primary_key=True,\n test_needs_autoincrement=True),\n Column('data', String(50))\n )\n\n Table('manual_pk', metadata,\n Column('id', Integer, primary_key=True, autoincrement=False),\n Column('data', String(50))\n )\n\n def _assert_round_trip(self, table, conn):\n row = conn.execute(table.select()).first()\n eq_(\n row,\n (config.db.dialect.default_sequence_base, \"some data\")\n )\n\n def test_autoincrement_on_insert(self):\n\n config.db.execute(\n self.tables.autoinc_pk.insert(),\n data=\"some data\"\n )\n self._assert_round_trip(self.tables.autoinc_pk, config.db)\n\n def test_last_inserted_id(self):\n\n r = config.db.execute(\n self.tables.autoinc_pk.insert(),\n data=\"some data\"\n )\n pk = config.db.scalar(select([self.tables.autoinc_pk.c.id]))\n eq_(\n r.inserted_primary_key,\n [pk]\n )\n\n # failed on pypy1.9 but seems to be OK on pypy 2.1\n # @exclusions.fails_if(lambda: util.pypy,\n # \"lastrowid not maintained after \"\n # \"connection close\")\n @requirements.dbapi_lastrowid\n def test_native_lastrowid_autoinc(self):\n r = config.db.execute(\n self.tables.autoinc_pk.insert(),\n data=\"some data\"\n )\n lastrowid = r.lastrowid\n pk = config.db.scalar(select([self.tables.autoinc_pk.c.id]))\n eq_(\n lastrowid, pk\n )\n\nclass InsertBehaviorTest(fixtures.TablesTest):\n run_deletes = 'each'\n __backend__ = True\n\n @classmethod\n def define_tables(cls, metadata):\n Table('autoinc_pk', metadata,\n Column('id', Integer, primary_key=True,\n test_needs_autoincrement=True),\n Column('data', String(50))\n )\n Table('manual_pk', metadata,\n Column('id', Integer, primary_key=True, autoincrement=False),\n Column('data', String(50))\n )\n Table('includes_defaults', metadata,\n Column('id', Integer, primary_key=True,\n test_needs_autoincrement=True),\n Column('data', String(50)),\n Column('x', Integer, default=5),\n Column('y', Integer,\n default=literal_column(\"2\", type_=Integer) + literal(2)))\n\n def test_autoclose_on_insert(self):\n if requirements.returning.enabled:\n engine = engines.testing_engine(\n options={'implicit_returning': False})\n else:\n engine = config.db\n\n r = engine.execute(\n self.tables.autoinc_pk.insert(),\n data=\"some data\"\n )\n assert r._soft_closed\n assert not r.closed\n assert r.is_insert\n assert not r.returns_rows\n\n @requirements.returning\n def test_autoclose_on_insert_implicit_returning(self):\n r = config.db.execute(\n self.tables.autoinc_pk.insert(),\n data=\"some data\"\n )\n assert r._soft_closed\n assert not r.closed\n assert r.is_insert\n assert not r.returns_rows\n\n @requirements.empty_inserts\n def test_empty_insert(self):\n r = config.db.execute(\n self.tables.autoinc_pk.insert(),\n )\n assert r._soft_closed\n assert not r.closed\n\n r = config.db.execute(\n self.tables.autoinc_pk.select().\n where(self.tables.autoinc_pk.c.id != None)\n )\n\n assert len(r.fetchall())\n\n @requirements.insert_from_select\n def test_insert_from_select(self):\n table = self.tables.manual_pk\n config.db.execute(\n table.insert(),\n [\n dict(id=1, data=\"data1\"),\n dict(id=2, data=\"data2\"),\n dict(id=3, data=\"data3\"),\n ]\n )\n\n config.db.execute(\n table.insert(inline=True).\n from_select((\"id\", \"data\",),\n select([table.c.id + 5, table.c.data]).\n where(table.c.data.in_([\"data2\", \"data3\"]))\n ),\n )\n\n eq_(\n config.db.execute(\n select([table.c.data]).order_by(table.c.data)\n ).fetchall(),\n [(\"data1\", ), (\"data2\", ), (\"data2\", ),\n (\"data3\", ), (\"data3\", )]\n )\n\n @requirements.insert_from_select\n def test_insert_from_select_with_defaults(self):\n table = self.tables.includes_defaults\n config.db.execute(\n table.insert(),\n [\n dict(id=1, data=\"data1\"),\n dict(id=2, data=\"data2\"),\n dict(id=3, data=\"data3\"),\n ]\n )\n\n config.db.execute(\n table.insert(inline=True).\n from_select((\"id\", \"data\",),\n select([table.c.id + 5, table.c.data]).\n where(table.c.data.in_([\"data2\", \"data3\"]))\n ),\n )\n\n eq_(\n config.db.execute(\n select([table]).order_by(table.c.data, table.c.id)\n ).fetchall(),\n [(1, 'data1', 5, 4), (2, 'data2', 5, 4),\n (7, 'data2', 5, 4), (3, 'data3', 5, 4), (8, 'data3', 5, 4)]\n )\n\nclass ReturningTest(fixtures.TablesTest):\n run_create_tables = 'each'\n __requires__ = 'returning', 'autoincrement_insert'\n __backend__ = True\n\n __engine_options__ = {\"implicit_returning\": True}\n\n def _assert_round_trip(self, table, conn):\n row = conn.execute(table.select()).first()\n eq_(\n row,\n (config.db.dialect.default_sequence_base, \"some data\")\n )\n\n @classmethod\n def define_tables(cls, metadata):\n Table('autoinc_pk', metadata,\n Column('id', Integer, primary_key=True,\n test_needs_autoincrement=True),\n Column('data', String(50))\n )\n\n @requirements.fetch_rows_post_commit\n def test_explicit_returning_pk_autocommit(self):\n engine = config.db\n table = self.tables.autoinc_pk\n r = engine.execute(\n table.insert().returning(\n table.c.id),\n data=\"some data\"\n )\n pk = r.first()[0]\n fetched_pk = config.db.scalar(select([table.c.id]))\n eq_(fetched_pk, pk)\n\n def test_explicit_returning_pk_no_autocommit(self):\n engine = config.db\n table = self.tables.autoinc_pk\n with engine.begin() as conn:\n r = conn.execute(\n table.insert().returning(\n table.c.id),\n data=\"some data\"\n )\n pk = r.first()[0]\n fetched_pk = config.db.scalar(select([table.c.id]))\n eq_(fetched_pk, pk)\n\n def test_autoincrement_on_insert_implcit_returning(self):\n\n config.db.execute(\n self.tables.autoinc_pk.insert(),\n data=\"some data\"\n )\n self._assert_round_trip(self.tables.autoinc_pk, config.db)\n\n def test_last_inserted_id_implicit_returning(self):\n\n r = config.db.execute(\n self.tables.autoinc_pk.insert(),\n data=\"some data\"\n )\n pk = config.db.scalar(select([self.tables.autoinc_pk.c.id]))\n eq_(\n r.inserted_primary_key,\n [pk]\n )\n\n__all__ = ('LastrowidTest', 'InsertBehaviorTest', 'ReturningTest')"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_kit2fiff_gui.py from Odingod/mne-python (path: mne/gui/tests/test_kit2fiff_gui.py)."}, {"role": "assistant", "content": "# mne/gui/tests/test_kit2fiff_gui.py (from Odingod/mne-python, license: bsd-3-clause)\n\n# Authors: Christian Brodbeck \n#\n# License: BSD (3-clause)\n\nimport os\nimport warnings\n\nimport numpy as np\nfrom numpy.testing import assert_allclose, assert_array_equal\nfrom nose.tools import assert_true, assert_false, assert_equal\n\nimport mne\nfrom mne.io.kit.tests import data_dir as kit_data_dir\nfrom mne.io import Raw\nfrom mne.utils import _TempDir, requires_traits, run_tests_if_main\n\nmrk_pre_path = os.path.join(kit_data_dir, 'test_mrk_pre.sqd')\nmrk_post_path = os.path.join(kit_data_dir, 'test_mrk_post.sqd')\nsqd_path = os.path.join(kit_data_dir, 'test.sqd')\nhsp_path = os.path.join(kit_data_dir, 'test_hsp.txt')\nfid_path = os.path.join(kit_data_dir, 'test_elp.txt')\nfif_path = os.path.join(kit_data_dir, 'test_bin_raw.fif')\n\nwarnings.simplefilter('always')\n\n@requires_traits\ndef test_kit2fiff_model():\n \"\"\"Test CombineMarkersModel Traits Model\"\"\"\n from mne.gui._kit2fiff_gui import Kit2FiffModel, Kit2FiffPanel\n tempdir = _TempDir()\n tgt_fname = os.path.join(tempdir, 'test-raw.fif')\n\n model = Kit2FiffModel()\n assert_false(model.can_save)\n model.markers.mrk1.file = mrk_pre_path\n model.markers.mrk2.file = mrk_post_path\n model.sqd_file = sqd_path\n model.hsp_file = hsp_path\n assert_false(model.can_save)\n model.fid_file = fid_path\n\n # export raw\n assert_true(model.can_save)\n raw_out = model.get_raw()\n raw_out.save(tgt_fname)\n raw = Raw(tgt_fname)\n\n # Compare exported raw with the original binary conversion\n raw_bin = Raw(fif_path)\n trans_bin = raw.info['dev_head_t']['trans']\n want_keys = list(raw_bin.info.keys())\n assert_equal(sorted(want_keys), sorted(list(raw.info.keys())))\n trans_transform = raw_bin.info['dev_head_t']['trans']\n assert_allclose(trans_transform, trans_bin, 0.1)\n\n # Averaging markers\n model.markers.mrk3.method = \"Average\"\n trans_avg = model.dev_head_trans\n assert_false(np.all(trans_avg == trans_transform))\n assert_allclose(trans_avg, trans_bin, 0.1)\n\n # Test exclusion of one marker\n model.markers.mrk3.method = \"Transform\"\n model.use_mrk = [1, 2, 3, 4]\n assert_false(np.all(model.dev_head_trans == trans_transform))\n assert_false(np.all(model.dev_head_trans == trans_avg))\n assert_false(np.all(model.dev_head_trans == np.eye(4)))\n\n # test setting stim channels\n model.stim_slope = '+'\n events_bin = mne.find_events(raw_bin, stim_channel='STI 014')\n\n model.stim_chs = '<'\n raw = model.get_raw()\n events = mne.find_events(raw, stim_channel='STI 014')\n assert_array_equal(events, events_bin)\n\n events_rev = events_bin.copy()\n events_rev[:, 2] = 1\n model.stim_chs = '>'\n raw = model.get_raw()\n events = mne.find_events(raw, stim_channel='STI 014')\n assert_array_equal(events, events_rev)\n\n model.stim_chs = 'man'\n model.stim_chs_manual = list(range(167, 159, -1))\n raw = model.get_raw()\n events = mne.find_events(raw, stim_channel='STI 014')\n assert_array_equal(events, events_bin)\n\n # test reset\n model.clear_all()\n assert_equal(model.use_mrk, [0, 1, 2, 3, 4])\n assert_equal(model.sqd_file, \"\")\n\n os.environ['_MNE_GUI_TESTING_MODE'] = 'true'\n try:\n with warnings.catch_warnings(record=True): # traits warnings\n warnings.simplefilter('always')\n Kit2FiffPanel()\n finally:\n del os.environ['_MNE_GUI_TESTING_MODE']\n\nrun_tests_if_main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements gtkdoc.py from lostdj/Jaklin-OpenJFX (path: modules/web/src/main/native/Tools/gtk/gtkdoc.py)."}, {"role": "assistant", "content": "# modules/web/src/main/native/Tools/gtk/gtkdoc.py (from lostdj/Jaklin-OpenJFX, license: gpl-2.0)\n\n# Copyright (C) 2011 Igalia S.L.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\nimport errno\nimport logging\nimport os\nimport os.path\nimport subprocess\nimport sys\n\nclass GTKDoc(object):\n\n \"\"\"Class that controls a gtkdoc run.\n\n Each instance of this class represents one gtkdoc configuration\n and set of documentation. The gtkdoc package is a series of tools\n run consecutively which converts inline C/C++ documentation into\n docbook files and then into HTML. This class is suitable for\n generating documentation or simply verifying correctness.\n\n Keyword arguments:\n output_dir -- The path where gtkdoc output should be placed. Generation\n may overwrite file in this directory. Required.\n module_name -- The name of the documentation module. For libraries this\n is typically the library name. Required if not library path\n is given.\n source_dirs -- A list of paths to the source code to be scanned. Required.\n ignored_files -- A list of filenames to ignore in the source directory. It is\n only necessary to provide the basenames of these files.\n Typically it is important to provide an updated list of\n ignored files to prevent warnings about undocumented symbols.\n namespace -- The library namespace.\n decorator -- If a decorator is used to unhide certain symbols in header\n files this parameter is required for successful scanning.\n (default '')\n deprecation_guard -- gtkdoc tries to ensure that symbols marked as deprecated\n are encased in this C preprocessor define. This is required\n to avoid gtkdoc warnings. (default '')\n cflags -- This parameter specifies any preprocessor flags necessary for\n building the scanner binary during gtkdoc-scanobj. Typically\n this includes all absolute include paths necessary to resolve\n all header dependencies. (default '')\n ldflags -- This parameter specifies any linker flags necessary for\n building the scanner binary during gtkdoc-scanobj. Typically\n this includes \"-lyourlibraryname\". (default '')\n library_path -- This parameter specifies the path to the directory where you\n library resides used for building the scanner binary during\n gtkdoc-scanobj. (default '')\n\n doc_dir -- The path to other documentation files necessary to build\n the documentation. This files in this directory as well as\n the files in the 'html' subdirectory will be copied\n recursively into the output directory. (default '')\n main_sgml_file -- The path or name (if a doc_dir is given) of the SGML file\n that is the considered the main page of your documentation.\n (default: -docs.sgml)\n version -- The version number of the module. If this is provided,\n a version.xml file containing the version will be created\n in the output directory during documentation generation.\n\n interactive -- Whether or not errors or warnings should prompt the user\n to continue or not. When this value is false, generation\n will continue despite warnings. (default False)\n\n virtual_root -- A temporary installation directory which is used as the root\n where the actual installation prefix lives; this is mostly\n useful for packagers, and should be set to what is given to\n make install as DESTDIR.\n \"\"\"\n\n def __init__(self, args):\n\n # Parameters specific to scanning.\n self.module_name = ''\n self.source_dirs = []\n self.ignored_files = []\n self.namespace = ''\n self.decorator = ''\n self.deprecation_guard = ''\n\n # Parameters specific to gtkdoc-scanobj.\n self.cflags = ''\n self.ldflags = ''\n self.library_path = ''\n\n # Parameters specific to generation.\n self.output_dir = ''\n self.doc_dir = ''\n self.main_sgml_file = ''\n\n # Parameters specific to gtkdoc-fixxref.\n self.cross_reference_deps = []\n\n self.interactive = False\n\n self.logger = logging.getLogger('gtkdoc')\n\n for key, value in iter(args.items()):\n setattr(self, key, value)\n\n def raise_error_if_not_specified(key):\n if not getattr(self, key):\n raise Exception('%s not specified.' % key)\n\n raise_error_if_not_specified('output_dir')\n raise_error_if_not_specified('source_dirs')\n raise_error_if_not_specified('module_name')\n\n # Make all paths absolute in case we were passed relative paths, since\n # we change the current working directory when executing subcommands.\n self.output_dir = os.path.abspath(self.output_dir)\n self.source_dirs = [os.path.abspath(x) for x in self.source_dirs]\n if self.library_path:\n self.library_path = os.path.abspath(self.library_path)\n\n if not self.main_sgml_file:\n self.main_sgml_file = self.module_name + \"-docs.sgml\"\n\n def generate(self, html=True):\n self.saw_warnings = False\n\n self._copy_doc_files_to_output_dir(html)\n self._write_version_xml()\n self._run_gtkdoc_scan()\n self._run_gtkdoc_scangobj()\n self._run_gtkdoc_mktmpl()\n self._run_gtkdoc_mkdb()\n\n if not html:\n return\n\n self._run_gtkdoc_mkhtml()\n self._run_gtkdoc_fixxref()\n\n def _delete_file_if_exists(self, path):\n if not os.access(path, os.F_OK | os.R_OK):\n return\n self.logger.debug('deleting %s', path)\n os.unlink(path)\n\n def _create_directory_if_nonexistent(self, path):\n try:\n os.makedirs(path)\n except OSError as error:\n if error.errno != errno.EEXIST:\n raise\n\n def _raise_exception_if_file_inaccessible(self, path):\n if not os.path.exists(path) or not os.access(path, os.R_OK):\n raise Exception(\"Could not access file at: %s\" % path)\n\n def _output_has_warnings(self, outputs):\n for output in outputs:\n if output and output.find('warning'):\n return True\n return False\n\n def _ask_yes_or_no_question(self, question):\n if not self.interactive:\n return True\n\n question += ' [y/N] '\n answer = None\n while answer != 'y' and answer != 'n' and answer != '':\n answer = raw_input(question).lower()\n return answer == 'y'\n\n def _run_command(self, args, env=None, cwd=None, print_output=True, ignore_warnings=False):\n if print_output:\n self.logger.info(\"Running %s\", args[0])\n self.logger.debug(\"Full command args: %s\", str(args))\n\n process = subprocess.Popen(args, env=env, cwd=cwd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = [b.decode(\"utf-8\") for b in process.communicate()]\n\n if print_output:\n if stdout:\n sys.stdout.write(stdout)\n if stderr:\n sys.stderr.write(stderr)\n\n if process.returncode != 0:\n raise Exception('%s produced a non-zero return code %i'\n % (args[0], process.returncode))\n\n if not ignore_warnings and ('warning' in stderr or 'warning' in stdout):\n self.saw_warnings = True\n if not self._ask_yes_or_no_question('%s produced warnings, '\n 'try to continue?' % args[0]):\n raise Exception('%s step failed' % args[0])\n\n return stdout.strip()\n\n def _copy_doc_files_to_output_dir(self, html=True):\n if not self.doc_dir:\n self.logger.info('Not copying any files from doc directory,'\n ' because no doc directory given.')\n return\n\n def copy_file_replacing_existing(src, dest):\n if os.path.isdir(src):\n self.logger.debug('skipped directory %s', src)\n return\n if not os.access(src, os.F_OK | os.R_OK):\n self.logger.debug('skipped unreadable %s', src)\n return\n\n self._delete_file_if_exists(dest)\n\n self.logger.debug('created %s', dest)\n try:\n os.link(src, dest)\n except OSError:\n os.symlink(src, dest)\n\n def copy_all_files_in_directory(src, dest):\n for path in os.listdir(src):\n copy_file_replacing_existing(os.path.join(src, path),\n os.path.join(dest, path))\n\n self.logger.info('Copying template files to output directory...')\n self._create_directory_if_nonexistent(self.output_dir)\n copy_all_files_in_directory(self.doc_dir, self.output_dir)\n\n if not html:\n return\n\n self.logger.info('Copying HTML files to output directory...')\n html_src_dir = os.path.join(self.doc_dir, 'html')\n html_dest_dir = os.path.join(self.output_dir, 'html')\n self._create_directory_if_nonexistent(html_dest_dir)\n\n if os.path.exists(html_src_dir):\n copy_all_files_in_directory(html_src_dir, html_dest_dir)\n\n def _write_version_xml(self):\n if not self.version:\n self.logger.info('No version specified, so not writing version.xml')\n return\n\n version_xml_path = os.path.join(self.output_dir, 'version.xml')\n src_version_xml_path = os.path.join(self.doc_dir, 'version.xml')\n\n # Don't overwrite version.xml if it was in the doc directory.\n if os.path.exists(version_xml_path) and \\\n os.path.exists(src_version_xml_path):\n return\n\n output_file = open(version_xml_path, 'w')\n output_file.write(self.version)\n output_file.close()\n\n def _ignored_files_basenames(self):\n return ' '.join([os.path.basename(x) for x in self.ignored_files])\n\n def _run_gtkdoc_scan(self):\n args = ['gtkdoc-scan',\n '--module=%s' % self.module_name,\n '--rebuild-types']\n\n # Each source directory should be have its own \"--source-dir=\" prefix.\n args.extend(['--source-dir=%s' % path for path in self.source_dirs])\n\n if self.decorator:\n args.append('--ignore-decorators=%s' % self.decorator)\n if self.deprecation_guard:\n args.append('--deprecated-guards=%s' % self.deprecation_guard)\n if self.output_dir:\n args.append('--output-dir=%s' % self.output_dir)\n\n # gtkdoc-scan wants the basenames of ignored headers, so strip the\n # dirname. Different from \"--source-dir\", the headers should be\n # specified as one long string.\n ignored_files_basenames = self._ignored_files_basenames()\n if ignored_files_basenames:\n args.append('--ignore-headers=%s' % ignored_files_basenames)\n\n self._run_command(args)\n\n def _run_gtkdoc_scangobj(self):\n env = os.environ\n ldflags = self.ldflags\n if self.library_path:\n ldflags = ' \"-L%s\" ' % self.library_path + ldflags\n current_ld_library_path = env.get('LD_LIBRARY_PATH')\n if current_ld_library_path:\n env['RUN'] = 'LD_LIBRARY_PATH=\"%s:%s\" ' % (self.library_path, current_ld_library_path)\n else:\n env['RUN'] = 'LD_LIBRARY_PATH=\"%s\" ' % self.library_path\n\n if ldflags:\n env['LDFLAGS'] = '%s %s' % (ldflags, env.get('LDFLAGS', ''))\n if self.cflags:\n env['CFLAGS'] = '%s %s' % (self.cflags, env.get('CFLAGS', ''))\n\n if 'CFLAGS' in env:\n self.logger.debug('CFLAGS=%s', env['CFLAGS'])\n if 'LDFLAGS' in env:\n self.logger.debug('LDFLAGS %s', env['LDFLAGS'])\n if 'RUN' in env:\n self.logger.debug('RUN=%s', env['RUN'])\n self._run_command(['gtkdoc-scangobj', '--module=%s' % self.module_name],\n env=env, cwd=self.output_dir)\n\n def _run_gtkdoc_mktmpl(self):\n args = ['gtkdoc-mktmpl', '--module=%s' % self.module_name]\n self._run_command(args, cwd=self.output_dir)\n\n def _run_gtkdoc_mkdb(self):\n sgml_file = os.path.join(self.output_dir, self.main_sgml_file)\n self._raise_exception_if_file_inaccessible(sgml_file)\n\n args = ['gtkdoc-mkdb',\n '--module=%s' % self.module_name,\n '--main-sgml-file=%s' % sgml_file,\n '--source-suffixes=h,c,cpp,cc',\n '--output-format=xml',\n '--sgml-mode']\n\n if self.namespace:\n args.append('--name-space=%s' % self.namespace)\n\n ignored_files_basenames = self._ignored_files_basenames()\n if ignored_files_basenames:\n args.append('--ignore-files=%s' % ignored_files_basenames)\n\n # Each directory should be have its own \"--source-dir=\" prefix.\n args.extend(['--source-dir=%s' % path for path in self.source_dirs])\n self._run_command(args, cwd=self.output_dir)\n\n def _run_gtkdoc_mkhtml(self):\n html_dest_dir = os.path.join(self.output_dir, 'html')\n if not os.path.isdir(html_dest_dir):\n raise Exception(\"%s is not a directory, could not generate HTML\"\n % html_dest_dir)\n elif not os.access(html_dest_dir, os.X_OK | os.R_OK | os.W_OK):\n raise Exception(\"Could not access %s to generate HTML\"\n % html_dest_dir)\n\n # gtkdoc-mkhtml expects the SGML path to be absolute.\n sgml_file = os.path.join(os.path.abspath(self.output_dir),\n self.main_sgml_file)\n self._raise_exception_if_file_inaccessible(sgml_file)\n\n self._run_command(['gtkdoc-mkhtml', self.module_name, sgml_file],\n cwd=html_dest_dir)\n\n def _run_gtkdoc_fixxref(self):\n args = ['gtkdoc-fixxref',\n '--module-dir=html',\n '--html-dir=html']\n args.extend(['--extra-dir=%s' % extra_dir for extra_dir in self.cross_reference_deps])\n self._run_command(args, cwd=self.output_dir, ignore_warnings=True)\n\n def rebase_installed_docs(self):\n if not os.path.isdir(self.output_dir):\n raise Exception(\"Tried to rebase documentation before generating it.\")\n html_dir = os.path.join(self.virtual_root + self.prefix, 'share', 'gtk-doc', 'html', self.module_name)\n if not os.path.isdir(html_dir):\n return\n args = ['gtkdoc-rebase',\n '--relative',\n '--html-dir=%s' % html_dir]\n args.extend(['--other-dir=%s' % extra_dir for extra_dir in self.cross_reference_deps])\n if self.virtual_root:\n args.extend(['--dest-dir=%s' % self.virtual_root])\n self._run_command(args, cwd=self.output_dir)\n\n def api_missing_documentation(self):\n unused_doc_file = os.path.join(self.output_dir, self.module_name + \"-unused.txt\")\n if not os.path.exists(unused_doc_file) or not os.access(unused_doc_file, os.R_OK):\n return []\n return open(unused_doc_file).read().splitlines()\n\nclass PkgConfigGTKDoc(GTKDoc):\n\n \"\"\"Class reads a library's pkgconfig file to guess gtkdoc parameters.\n\n Some gtkdoc parameters can be guessed by reading a library's pkgconfig\n file, including the cflags, ldflags and version parameters. If you\n provide these parameters as well, they will be appended to the ones\n guessed via the pkgconfig file.\n\n Keyword arguments:\n pkg_config_path -- Path to the pkgconfig file for the library. Required.\n \"\"\"\n\n def __init__(self, pkg_config_path, args):\n super(PkgConfigGTKDoc, self).__init__(args)\n\n pkg_config = os.environ.get('PKG_CONFIG', 'pkg-config')\n\n if not os.path.exists(pkg_config_path):\n raise Exception('Could not find pkg-config file at: %s'\n % pkg_config_path)\n\n self.cflags += \" \" + self._run_command([pkg_config,\n pkg_config_path,\n '--cflags'], print_output=False)\n self.ldflags += \" \" + self._run_command([pkg_config,\n pkg_config_path,\n '--libs'], print_output=False)\n self.version = self._run_command([pkg_config,\n pkg_config_path,\n '--modversion'], print_output=False)\n self.prefix = self._run_command([pkg_config,\n pkg_config_path,\n '--variable=prefix'], print_output=False)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements item.py from CapOM/ChromiumGStreamerBackend (path: tools/telemetry/third_party/gsutilz/third_party/boto/boto/sdb/item.py)."}, {"role": "assistant", "content": "# tools/telemetry/third_party/gsutilz/third_party/boto/boto/sdb/item.py (from CapOM/ChromiumGStreamerBackend, license: bsd-3-clause)\n\n# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish, dis-\n# tribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the fol-\n# lowing conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-\n# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, \n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n\nimport base64\n\nclass Item(dict):\n \"\"\"\n A ``dict`` sub-class that serves as an object representation of a\n SimpleDB item. An item in SDB is similar to a row in a relational\n database. Items belong to a :py:class:`Domain `,\n which is similar to a table in a relational database.\n\n The keys on instances of this object correspond to attributes that are\n stored on the SDB item.\n\n .. tip:: While it is possible to instantiate this class directly, you may\n want to use the convenience methods on :py:class:`boto.sdb.domain.Domain`\n for that purpose. For example, :py:meth:`boto.sdb.domain.Domain.get_item`.\n \"\"\"\n def __init__(self, domain, name='', active=False):\n \"\"\"\n :type domain: :py:class:`boto.sdb.domain.Domain`\n :param domain: The domain that this item belongs to.\n\n :param str name: The name of this item. This name will be used when\n querying for items using methods like\n :py:meth:`boto.sdb.domain.Domain.get_item`\n \"\"\"\n dict.__init__(self)\n self.domain = domain\n self.name = name\n self.active = active\n self.request_id = None\n self.encoding = None\n self.in_attribute = False\n self.converter = self.domain.connection.converter\n\n def startElement(self, name, attrs, connection):\n if name == 'Attribute':\n self.in_attribute = True\n self.encoding = attrs.get('encoding', None)\n return None\n\n def decode_value(self, value):\n if self.encoding == 'base64':\n self.encoding = None\n return base64.decodestring(value)\n else:\n return value\n\n def endElement(self, name, value, connection):\n if name == 'ItemName':\n self.name = self.decode_value(value)\n elif name == 'Name':\n if self.in_attribute:\n self.last_key = self.decode_value(value)\n else:\n self.name = self.decode_value(value)\n elif name == 'Value':\n if self.last_key in self:\n if not isinstance(self[self.last_key], list):\n self[self.last_key] = [self[self.last_key]]\n value = self.decode_value(value)\n if self.converter:\n value = self.converter.decode(value)\n self[self.last_key].append(value)\n else:\n value = self.decode_value(value)\n if self.converter:\n value = self.converter.decode(value)\n self[self.last_key] = value\n elif name == 'BoxUsage':\n try:\n connection.box_usage += float(value)\n except:\n pass\n elif name == 'RequestId':\n self.request_id = value\n elif name == 'Attribute':\n self.in_attribute = False\n else:\n setattr(self, name, value)\n\n def load(self):\n \"\"\"\n Loads or re-loads this item's attributes from SDB.\n\n .. warning::\n If you have changed attribute values on an Item instance,\n this method will over-write the values if they are different in\n SDB. For any local attributes that don't yet exist in SDB,\n they will be safe.\n \"\"\"\n self.domain.get_attributes(self.name, item=self)\n\n def save(self, replace=True):\n \"\"\"\n Saves this item to SDB.\n\n :param bool replace: If ``True``, delete any attributes on the remote\n SDB item that have a ``None`` value on this object.\n \"\"\"\n self.domain.put_attributes(self.name, self, replace)\n # Delete any attributes set to \"None\"\n if replace:\n del_attrs = []\n for name in self:\n if self[name] is None:\n del_attrs.append(name)\n if len(del_attrs) > 0:\n self.domain.delete_attributes(self.name, del_attrs)\n\n def add_value(self, key, value):\n \"\"\"\n Helps set or add to attributes on this item. If you are adding a new\n attribute that has yet to be set, it will simply create an attribute\n named ``key`` with your given ``value`` as its value. If you are\n adding a value to an existing attribute, this method will convert the\n attribute to a list (if it isn't already) and append your new value\n to said list.\n\n For clarification, consider the following interactive session:\n\n .. code-block:: python\n\n >>> item = some_domain.get_item('some_item')\n >>> item.has_key('some_attr')\n False\n >>> item.add_value('some_attr', 1)\n >>> item['some_attr']\n 1\n >>> item.add_value('some_attr', 2)\n >>> item['some_attr']\n [1, 2]\n\n :param str key: The attribute to add a value to.\n :param object value: The value to set or append to the attribute.\n \"\"\"\n if key in self:\n # We already have this key on the item.\n if not isinstance(self[key], list):\n # The key isn't already a list, take its current value and\n # convert it to a list with the only member being the\n # current value.\n self[key] = [self[key]]\n # Add the new value to the list.\n self[key].append(value)\n else:\n # This is a new attribute, just set it.\n self[key] = value\n\n def delete(self):\n \"\"\"\n Deletes this item in SDB.\n\n .. note:: This local Python object remains in its current state\n after deletion, this only deletes the remote item in SDB.\n \"\"\"\n self.domain.delete_item(self)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements enhance.py from cebrusfs/217gdb (path: pwndbg/color/enhance.py)."}, {"role": "assistant", "content": "# pwndbg/color/enhance.py (from cebrusfs/217gdb, license: mit)\n\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport pwndbg.color.theme as theme\nimport pwndbg.config as config\nfrom pwndbg.color import generateColorFunction\n\nconfig_integer_color = theme.ColoredParameter('enhance-integer-value-color', 'none', 'color of value enhance (integer)')\nconfig_string_color = theme.ColoredParameter('enhance-string-value-color', 'none', 'color of value enhance (string)')\nconfig_comment_color = theme.ColoredParameter('enhance-comment-color', 'none', 'color of value enhance (comment)')\nconfig_unknown_color = theme.ColoredParameter('enhance-unknown-color', 'none', 'color of value enhance (unknown value)')\n\ndef integer(x):\n return generateColorFunction(config.enhance_integer_value_color)(x)\n\ndef string(x):\n return generateColorFunction(config.enhance_string_value_color)(x)\n\ndef comment(x):\n return generateColorFunction(config.enhance_comment_color)(x)\n\ndef unknown(x):\n return generateColorFunction(config.enhance_unknown_color)(x)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements include_vars.py from ahamilton55/ansible (path: lib/ansible/plugins/action/include_vars.py)."}, {"role": "assistant", "content": "# lib/ansible/plugins/action/include_vars.py (from ahamilton55/ansible, license: gpl-3.0)\n\n# (c) 2016, Allen Sanabria \n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nfrom os import path, walk\nimport re\n\nfrom ansible.errors import AnsibleError\nfrom ansible.module_utils.six import string_types\nfrom ansible.module_utils._text import to_native, to_text\nfrom ansible.plugins.action import ActionBase\n\nclass ActionModule(ActionBase):\n\n TRANSFERS_FILES = False\n\n VALID_FILE_EXTENSIONS = ['yaml', 'yml', 'json']\n VALID_DIR_ARGUMENTS = ['dir', 'depth', 'files_matching', 'ignore_files', 'extensions']\n VALID_FILE_ARGUMENTS = ['file', '_raw_params']\n VALID_ALL = ['name']\n\n def _set_dir_defaults(self):\n if not self.depth:\n self.depth = 0\n\n if self.files_matching:\n self.matcher = re.compile(r'{0}'.format(self.files_matching))\n else:\n self.matcher = None\n\n if not self.ignore_files:\n self.ignore_files = list()\n\n if isinstance(self.ignore_files, str):\n self.ignore_files = self.ignore_files.split()\n\n elif isinstance(self.ignore_files, dict):\n return {\n 'failed': True,\n 'message': '{0} must be a list'.format(self.ignore_files)\n }\n\n def _set_args(self):\n \"\"\" Set instance variables based on the arguments that were passed \"\"\"\n\n self.return_results_as_name = self._task.args.get('name', None)\n self.source_dir = self._task.args.get('dir', None)\n self.source_file = self._task.args.get('file', None)\n if not self.source_dir and not self.source_file:\n self.source_file = self._task.args.get('_raw_params')\n\n self.depth = self._task.args.get('depth', None)\n self.files_matching = self._task.args.get('files_matching', None)\n self.ignore_files = self._task.args.get('ignore_files', None)\n self.valid_extensions = self._task.args.get('extensions', self.VALID_FILE_EXTENSIONS)\n\n # convert/validate extensions list\n if isinstance(self.valid_extensions, string_types):\n self.valid_extensions = list(self.valid_extensions)\n if not isinstance(self.valid_extensions, list):\n raise AnsibleError('Invalid type for \"extensions\" option, it must be a list')\n\n def run(self, tmp=None, task_vars=None):\n \"\"\" Load yml files recursively from a directory.\n \"\"\"\n if task_vars is None:\n task_vars = dict()\n\n self.show_content = True\n\n # Validate arguments\n dirs = 0\n files = 0\n for arg in self._task.args:\n if arg in self.VALID_DIR_ARGUMENTS:\n dirs += 1\n elif arg in self.VALID_FILE_ARGUMENTS:\n files += 1\n elif arg in self.VALID_ALL:\n pass\n else:\n raise AnsibleError('{0} is not a valid option in debug'.format(arg))\n\n if dirs and files:\n raise AnsibleError(\"Your are mixing file only and dir only arguments, these are incompatible\")\n\n # set internal vars from args\n self._set_args()\n\n results = dict()\n if self.source_dir:\n self._set_dir_defaults()\n self._set_root_dir()\n if path.exists(self.source_dir):\n for root_dir, filenames in self._traverse_dir_depth():\n failed, err_msg, updated_results = (self._load_files_in_dir(root_dir, filenames))\n if failed:\n break\n results.update(updated_results)\n else:\n failed = True\n err_msg = ('{0} directory does not exist'.format(self.source_dir))\n else:\n try:\n self.source_file = self._find_needle('vars', self.source_file)\n failed, err_msg, updated_results = (\n self._load_files(self.source_file)\n )\n if not failed:\n results.update(updated_results)\n\n except AnsibleError as e:\n failed = True\n err_msg = to_native(e)\n\n if self.return_results_as_name:\n scope = dict()\n scope[self.return_results_as_name] = results\n results = scope\n\n result = super(ActionModule, self).run(tmp, task_vars)\n\n if failed:\n result['failed'] = failed\n result['message'] = err_msg\n\n result['ansible_facts'] = results\n result['_ansible_no_log'] = not self.show_content\n\n return result\n\n def _set_root_dir(self):\n if self._task._role:\n if self.source_dir.split('/')[0] == 'vars':\n path_to_use = (\n path.join(self._task._role._role_path, self.source_dir)\n )\n if path.exists(path_to_use):\n self.source_dir = path_to_use\n else:\n path_to_use = (\n path.join(\n self._task._role._role_path, 'vars', self.source_dir\n )\n )\n self.source_dir = path_to_use\n else:\n current_dir = (\n \"/\".join(self._task._ds._data_source.split('/')[:-1])\n )\n self.source_dir = path.join(current_dir, self.source_dir)\n\n def _traverse_dir_depth(self):\n \"\"\" Recursively iterate over a directory and sort the files in\n alphabetical order. Do not iterate pass the set depth.\n The default depth is unlimited.\n \"\"\"\n current_depth = 0\n sorted_walk = list(walk(self.source_dir))\n sorted_walk.sort(key=lambda x: x[0])\n for current_root, current_dir, current_files in sorted_walk:\n current_depth += 1\n if current_depth <= self.depth or self.depth == 0:\n current_files.sort()\n yield (current_root, current_files)\n else:\n break\n\n def _ignore_file(self, filename):\n \"\"\" Return True if a file matches the list of ignore_files.\n Args:\n filename (str): The filename that is being matched against.\n\n Returns:\n Boolean\n \"\"\"\n for file_type in self.ignore_files:\n try:\n if re.search(r'{0}$'.format(file_type), filename):\n return True\n except Exception:\n err_msg = 'Invalid regular expression: {0}'.format(file_type)\n raise AnsibleError(err_msg)\n return False\n\n def _is_valid_file_ext(self, source_file):\n \"\"\" Verify if source file has a valid extension\n Args:\n source_file (str): The full path of source file or source file.\n Returns:\n Bool\n \"\"\"\n file_ext = path.splitext(source_file)\n print(file_ext[-1][2:])\n return bool(len(file_ext) > 1 and file_ext[-1][1:] in self.valid_extensions)\n\n def _load_files(self, filename, validate_extensions=False):\n \"\"\" Loads a file and converts the output into a valid Python dict.\n Args:\n filename (str): The source file.\n\n Returns:\n Tuple (bool, str, dict)\n \"\"\"\n results = dict()\n failed = False\n err_msg = ''\n if validate_extensions and not self._is_valid_file_ext(filename):\n failed = True\n err_msg = ('{0} does not have a valid extension: {1}' .format(filename, ', '.join(self.valid_extensions)))\n else:\n b_data, show_content = self._loader._get_file_contents(filename)\n data = to_text(b_data, errors='surrogate_or_strict')\n\n self.show_content = show_content\n data = self._loader.load(data, show_content)\n if not data:\n data = dict()\n if not isinstance(data, dict):\n failed = True\n err_msg = ('{0} must be stored as a dictionary/hash' .format(filename))\n else:\n results.update(data)\n\n return failed, err_msg, results\n\n def _load_files_in_dir(self, root_dir, var_files):\n \"\"\" Load the found yml files and update/overwrite the dictionary.\n Args:\n root_dir (str): The base directory of the list of files that is being passed.\n var_files: (list): List of files to iterate over and load into a dictionary.\n\n Returns:\n Tuple (bool, str, dict)\n \"\"\"\n results = dict()\n failed = False\n err_msg = ''\n for filename in var_files:\n stop_iter = False\n # Never include main.yml from a role, as that is the default included by the role\n if self._task._role:\n if filename == 'main.yml':\n stop_iter = True\n continue\n\n filepath = path.join(root_dir, filename)\n if self.files_matching:\n if not self.matcher.search(filename):\n stop_iter = True\n\n if not stop_iter and not failed:\n if path.exists(filepath) and not self._ignore_file(filename):\n failed, err_msg, loaded_data = self._load_files(filepath, validate_extensions=True)\n if not failed:\n results.update(loaded_data)\n\n return failed, err_msg, results"}]} {"messages": [{"role": "user", "content": "Write Python code that implements rest.py from data-exp-lab/girder (path: plugins/oauth/server/rest.py)."}, {"role": "assistant", "content": "# plugins/oauth/server/rest.py (from data-exp-lab/girder, license: apache-2.0)\n\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n###############################################################################\n# Copyright Kitware Inc.\n#\n# Licensed under the Apache License, Version 2.0 ( the \"License\" );\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n###############################################################################\n\nimport cherrypy\nimport datetime\nimport six\n\nfrom girder import events\nfrom girder.constants import AccessType\nfrom girder.exceptions import RestException\nfrom girder.api.describe import Description, autoDescribeRoute\nfrom girder.api.rest import Resource\nfrom girder.api import access\nfrom girder.models.setting import Setting\nfrom girder.models.token import Token\nfrom . import constants, providers\n\nclass OAuth(Resource):\n def __init__(self):\n super(OAuth, self).__init__()\n self.resourceName = 'oauth'\n\n self.route('GET', ('provider',), self.listProviders)\n self.route('GET', (':provider', 'callback'), self.callback)\n\n def _createStateToken(self, redirect):\n csrfToken = Token().createToken(days=0.25)\n\n # The delimiter is arbitrary, but a dot doesn't need to be URL-encoded\n state = '%s.%s' % (csrfToken['_id'], redirect)\n return state\n\n def _validateCsrfToken(self, state):\n \"\"\"\n Tests the CSRF token value in the cookie to authenticate the user as\n the originator of the OAuth2 login. Raises a RestException if the token\n is invalid.\n \"\"\"\n csrfTokenId, _, redirect = state.partition('.')\n\n token = Token().load(csrfTokenId, objectId=False, level=AccessType.READ)\n if token is None:\n raise RestException('Invalid CSRF token (state=\"%s\").' % state, code=403)\n\n Token().remove(token)\n\n if token['expires'] < datetime.datetime.utcnow():\n raise RestException('Expired CSRF token (state=\"%s\").' % state,\n code=403)\n\n if not redirect:\n raise RestException('No redirect location (state=\"%s\").' % state)\n\n return redirect\n\n @access.public\n @autoDescribeRoute(\n Description('Get the list of enabled OAuth2 providers and their URLs.')\n .notes('By default, returns an object mapping names of providers to '\n 'the appropriate URL.')\n .param('redirect', 'Where the user should be redirected upon completion'\n ' of the OAuth2 flow.')\n .param('list', 'Whether to return the providers as an ordered list.',\n required=False, dataType='boolean', default=False)\n )\n def listProviders(self, redirect, list):\n enabledNames = Setting().get(constants.PluginSettings.PROVIDERS_ENABLED)\n\n enabledProviders = [\n provider\n for providerName, provider in six.viewitems(providers.idMap)\n if providerName in enabledNames\n ]\n if enabledProviders:\n state = self._createStateToken(redirect)\n else:\n state = None\n\n if list:\n return [\n {\n 'id': provider.getProviderName(external=False),\n 'name': provider.getProviderName(external=True),\n 'url': provider.getUrl(state)\n }\n for provider in enabledProviders\n ]\n else:\n return {\n provider.getProviderName(external=True): provider.getUrl(state)\n for provider in enabledProviders\n }\n\n @access.public\n @autoDescribeRoute(\n Description('Callback called by OAuth providers.')\n .param('provider', 'The provider name.', paramType='path')\n .param('state', 'Opaque state string.', required=False)\n .param('code', 'Authorization code from provider.', required=False)\n .param('error', 'Error message from provider.', required=False),\n hide=True\n )\n def callback(self, provider, state, code, error):\n if error is not None:\n raise RestException(\"Provider returned error: '%s'.\" % error, code=502)\n\n self.requireParams({'state': state, 'code': code})\n\n providerName = provider\n provider = providers.idMap.get(providerName)\n if not provider:\n raise RestException('Unknown provider \"%s\".' % providerName)\n\n redirect = self._validateCsrfToken(state)\n\n providerObj = provider(cherrypy.url())\n token = providerObj.getToken(code)\n\n events.trigger('oauth.auth_callback.before', {\n 'provider': provider,\n 'token': token\n })\n\n user = providerObj.getUser(token)\n\n events.trigger('oauth.auth_callback.after', {\n 'provider': provider,\n 'token': token,\n 'user': user\n })\n\n girderToken = self.sendAuthTokenCookie(user)\n try:\n redirect = redirect.format(girderToken=str(girderToken['_id']))\n except KeyError:\n pass # in case there's another {} that's not handled by format\n\n raise cherrypy.HTTPRedirect(redirect)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements sourcecommand.py from buildbot/buildbot (path: worker/buildbot_worker/test/util/sourcecommand.py)."}, {"role": "assistant", "content": "# worker/buildbot_worker/test/util/sourcecommand.py (from buildbot/buildbot, license: gpl-2.0)\n\n# This file is part of Buildbot. Buildbot is free software: you can\n# redistribute it and/or modify it under the terms of the GNU General Public\n# License as published by the Free Software Foundation, version 2.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n# details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program; if not, write to the Free Software Foundation, Inc., 51\n# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n#\n# Copyright Buildbot Team Members\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nfrom buildbot_worker import runprocess\nfrom buildbot_worker.test.util import command\n\nclass SourceCommandTestMixin(command.CommandTestMixin):\n\n \"\"\"\n Support for testing Source Commands; an extension of CommandTestMixin\n \"\"\"\n\n def make_command(self, cmdclass, args, makedirs=False, initial_sourcedata=''):\n \"\"\"\n Same as the parent class method, but this also adds some source-specific\n patches:\n\n * writeSourcedata - writes to self.sourcedata (self is the TestCase)\n * readSourcedata - reads from self.sourcedata\n * doClobber - invokes RunProcess(['clobber', DIRECTORY])\n * doCopy - invokes RunProcess(['copy', cmd.srcdir, cmd.workdir])\n \"\"\"\n\n cmd = command.CommandTestMixin.make_command(self, cmdclass, args, makedirs)\n\n # note that these patches are to an *instance*, not a class, so there\n # is no need to use self.patch() to reverse them\n\n self.sourcedata = initial_sourcedata\n\n def readSourcedata():\n if self.sourcedata is None:\n raise IOError(\"File not found\")\n return self.sourcedata\n cmd.readSourcedata = readSourcedata\n\n def writeSourcedata(res):\n self.sourcedata = cmd.sourcedata\n return res\n cmd.writeSourcedata = writeSourcedata\n\n # patch out a bunch of actions with invocations of RunProcess that will\n # end up being Expect-able by the tests.\n\n def doClobber(_, dirname):\n r = runprocess.RunProcess(self.builder,\n ['clobber', dirname],\n self.builder.basedir)\n return r.start()\n cmd.doClobber = doClobber\n\n def doCopy(_):\n r = runprocess.RunProcess(self.builder,\n ['copy', cmd.srcdir, cmd.workdir],\n self.builder.basedir)\n return r.start()\n cmd.doCopy = doCopy\n\n def setFileContents(filename, contents):\n r = runprocess.RunProcess(self.builder,\n ['setFileContents', filename, contents],\n self.builder.basedir)\n return r.start()\n cmd.setFileContents = setFileContents\n\n def check_sourcedata(self, _, expected_sourcedata):\n \"\"\"\n Assert that the sourcedata (from the patched functions - see\n make_command) is correct. Use this as a deferred callback.\n \"\"\"\n self.assertEqual(self.sourcedata, expected_sourcedata)\n return _"}]} {"messages": [{"role": "user", "content": "Write Python code that implements flasktasks.py from milkey-mouse/SongRater (path: flasktasks.py)."}, {"role": "assistant", "content": "# flasktasks.py (from milkey-mouse/SongRater, license: mit)\n\n# -*- coding: cp1252 -*-\n#Copyright Milkey Mouse 2015\nfrom HTMLParser import HTMLParser\nimport simplejson as json\nimport celery\nfrom celery import Celery\nfrom flask import render_template\nfrom flask.ext.gzip import Gzip\nfrom celery import task\nfrom flask import Flask\nimport datetime\nimport urllib2\nimport string\nimport math\nimport sys\nimport os\n\ncelery = Celery(\"flasktasks\")\n\n@celery.task(bind=True)\ndef rate(self, name):\n address = \"http://www.songlyrics.com/index.php?section=search&searchW=\"\n address = address + name\n response = urllib2.urlopen(address)\n html = response.read()\n done = False\n html = html[html.find('
'):]\n html = html[html.find('http://'):]\n html = html[:html.find('\"')]\n #try:\n response = urllib2.urlopen(html)\n html = response.read()\n html = html[html.find('

') + 1:]\n html = html[:html.find('

')]\n html = html.replace(\"
\", \"\\n\")\n html = html.replace(\"
\", \"\\n\")\n score = 0.00\n last_word = \"\"\n h = HTMLParser()\n words = html.replace(\"\\n\", \" \").split(\" \")\n wc = len(words)\n wd = 0\n for word2 in words:\n try:\n word = h.unescape(word2.lower())\n try:\n word = word.replace(\"’\", \"'\")\n except:\n pass\n try:\n word = word.translate(string.maketrans(\"\",\"\"), string.punctuation);\n except:\n pass\n wd += 1\n if(word != word.strip()):\n continue\n if(word == \"\"):\n continue\n if(os.path.exists(\"./cache/word/\" + word + \".txt\")):\n text = open(\"./cache/word/\" + word + \".txt\", 'r')\n score = score + int(float(text.read()))\n text.close()\n else:\n lastscore = score\n if word == 'I':\n #print \"STUPID WORD:\" + word\n score = score + 1\n if word == 'baby':\n #print \"STUPID WORD:\" + word\n score = score + 1\n if word == 'butt':\n #print \"STUPID WORD:\" + word\n score = score + 2\n if word == 'no':\n #print \"STUPID WORD:\" + word\n score = score + 1\n if word == 'oh':\n #print \"STUPID WORD:\" + word\n score = score + 0.5\n if word == 'back':\n #print \"STUPID WORD:\" + word\n score = score + 1\n if word == 'gone':\n #print \"STUPID WORD:\" + word\n score = score + 0.5\n if word == 'yeah':\n #print \"STUPID WORD:\" + word\n score = score + 1\n if word == 'mine':\n #print \"STUPID WORD:\" + word\n score = score + 1\n if word == 'fat':\n #print \"STUPID WORD:\" + word\n score = score + 2\n if word == 'love':\n #print \"STUPID WORD:\" + word\n score = score + 1.5\n if word == 'curves':\n #print \"STUPID WORD:\" + word\n score = score + 2.5\n if(lastscore != score):\n continue\n isword = False\n try:\n response2 = urllib2.urlopen(\"http://dictionary.reference.com/browse/\" + word).read()\n if not '
' in response2:\n isword = False\n else:\n isword = True\n except:\n isword = True\n if isword == False:\n #print \"NOT A WORD:\" + word\n score = score + 2\n if(word == \"nah\"):\n #print \"CHANT REPEATED: \" + word\n last_word = word\n pass\n elif(word == \"na\"):\n #print \"CHANT REPEATED: \" + word\n last_word = word\n pass\n elif(word == last_word):\n score = score + 1\n #print \"WORD REPEATED: \" + word\n pass\n last_word = word\n text = open(\"./cache/word/\" + word + \".txt\", 'w')\n text.write(str(score - lastscore))\n text.close()\n self.update_state(state='PROGRESS', meta=str(wd / words.count * 100) + \"%\")\n score += 100\n #print \"CACHED: \" + word\n except:\n pass\n score = score / (len(html) - 1)\n score = score * 750\n return score"}]} {"messages": [{"role": "user", "content": "Write Python code that implements wheel.py from paran0ids0ul/infernal-twin (path: build/pip/build/lib.linux-i686-2.7/pip/commands/wheel.py)."}, {"role": "assistant", "content": "# build/pip/build/lib.linux-i686-2.7/pip/commands/wheel.py (from paran0ids0ul/infernal-twin, license: gpl-3.0)\n\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nimport logging\nimport os\nimport warnings\n\nfrom pip.basecommand import RequirementCommand\nfrom pip.index import PackageFinder\nfrom pip.exceptions import CommandError, PreviousBuildDirError\nfrom pip.req import RequirementSet\nfrom pip.utils import import_or_raise, normalize_path\nfrom pip.utils.build import BuildDirectory\nfrom pip.utils.deprecation import RemovedInPip8Warning\nfrom pip.wheel import WheelCache, WheelBuilder\nfrom pip import cmdoptions\n\nDEFAULT_WHEEL_DIR = os.path.join(normalize_path(os.curdir), 'wheelhouse')\n\nlogger = logging.getLogger(__name__)\n\nclass WheelCommand(RequirementCommand):\n \"\"\"\n Build Wheel archives for your requirements and dependencies.\n\n Wheel is a built-package format, and offers the advantage of not\n recompiling your software during every install. For more details, see the\n wheel docs: http://wheel.readthedocs.org/en/latest.\n\n Requirements: setuptools>=0.8, and wheel.\n\n 'pip wheel' uses the bdist_wheel setuptools extension from the wheel\n package to build individual wheels.\n\n \"\"\"\n\n name = 'wheel'\n usage = \"\"\"\n %prog [options] ...\n %prog [options] -r ...\n %prog [options] [-e] ...\n %prog [options] [-e] ...\n %prog [options] ...\"\"\"\n\n summary = 'Build wheels from your requirements.'\n\n def __init__(self, *args, **kw):\n super(WheelCommand, self).__init__(*args, **kw)\n\n cmd_opts = self.cmd_opts\n\n cmd_opts.add_option(\n '-w', '--wheel-dir',\n dest='wheel_dir',\n metavar='dir',\n default=DEFAULT_WHEEL_DIR,\n help=(\"Build wheels into , where the default is \"\n \"'/wheelhouse'.\"),\n )\n cmd_opts.add_option(cmdoptions.use_wheel())\n cmd_opts.add_option(cmdoptions.no_use_wheel())\n cmd_opts.add_option(cmdoptions.no_binary())\n cmd_opts.add_option(cmdoptions.only_binary())\n cmd_opts.add_option(\n '--build-option',\n dest='build_options',\n metavar='options',\n action='append',\n help=\"Extra arguments to be supplied to 'setup.py bdist_wheel'.\")\n cmd_opts.add_option(cmdoptions.constraints())\n cmd_opts.add_option(cmdoptions.editable())\n cmd_opts.add_option(cmdoptions.requirements())\n cmd_opts.add_option(cmdoptions.download_cache())\n cmd_opts.add_option(cmdoptions.src())\n cmd_opts.add_option(cmdoptions.no_deps())\n cmd_opts.add_option(cmdoptions.build_dir())\n\n cmd_opts.add_option(\n '--global-option',\n dest='global_options',\n action='append',\n metavar='options',\n help=\"Extra global options to be supplied to the setup.py \"\n \"call before the 'bdist_wheel' command.\")\n\n cmd_opts.add_option(\n '--pre',\n action='store_true',\n default=False,\n help=(\"Include pre-release and development versions. By default, \"\n \"pip only finds stable versions.\"),\n )\n\n cmd_opts.add_option(cmdoptions.no_clean())\n\n index_opts = cmdoptions.make_option_group(\n cmdoptions.index_group,\n self.parser,\n )\n\n self.parser.insert_option_group(0, index_opts)\n self.parser.insert_option_group(0, cmd_opts)\n\n def check_required_packages(self):\n import_or_raise(\n 'wheel.bdist_wheel',\n CommandError,\n \"'pip wheel' requires the 'wheel' package. To fix this, run: \"\n \"pip install wheel\"\n )\n pkg_resources = import_or_raise(\n 'pkg_resources',\n CommandError,\n \"'pip wheel' requires setuptools >= 0.8 for dist-info support.\"\n \" To fix this, run: pip install --upgrade setuptools\"\n )\n if not hasattr(pkg_resources, 'DistInfoDistribution'):\n raise CommandError(\n \"'pip wheel' requires setuptools >= 0.8 for dist-info \"\n \"support. To fix this, run: pip install --upgrade \"\n \"setuptools\"\n )\n\n def run(self, options, args):\n self.check_required_packages()\n cmdoptions.resolve_wheel_no_use_binary(options)\n cmdoptions.check_install_build_global(options)\n\n index_urls = [options.index_url] + options.extra_index_urls\n if options.no_index:\n logger.info('Ignoring indexes: %s', ','.join(index_urls))\n index_urls = []\n\n if options.download_cache:\n warnings.warn(\n \"--download-cache has been deprecated and will be removed in \"\n \"the future. Pip now automatically uses and configures its \"\n \"cache.\",\n RemovedInPip8Warning,\n )\n\n if options.build_dir:\n options.build_dir = os.path.abspath(options.build_dir)\n\n with self._build_session(options) as session:\n\n finder = PackageFinder(\n find_links=options.find_links,\n format_control=options.format_control,\n index_urls=index_urls,\n allow_external=options.allow_external,\n allow_unverified=options.allow_unverified,\n allow_all_external=options.allow_all_external,\n allow_all_prereleases=options.pre,\n trusted_hosts=options.trusted_hosts,\n process_dependency_links=options.process_dependency_links,\n session=session,\n )\n\n build_delete = (not (options.no_clean or options.build_dir))\n wheel_cache = WheelCache(options.cache_dir, options.format_control)\n with BuildDirectory(options.build_dir,\n delete=build_delete) as build_dir:\n requirement_set = RequirementSet(\n build_dir=build_dir,\n src_dir=options.src_dir,\n download_dir=None,\n ignore_dependencies=options.ignore_dependencies,\n ignore_installed=True,\n isolated=options.isolated_mode,\n session=session,\n wheel_cache=wheel_cache,\n wheel_download_dir=options.wheel_dir\n )\n\n self.populate_requirement_set(\n requirement_set, args, options, finder, session, self.name,\n wheel_cache\n )\n\n if not requirement_set.has_requirements:\n return\n\n try:\n # build wheels\n wb = WheelBuilder(\n requirement_set,\n finder,\n build_options=options.build_options or [],\n global_options=options.global_options or [],\n )\n if not wb.build():\n raise CommandError(\n \"Failed to build one or more wheels\"\n )\n except PreviousBuildDirError:\n options.no_clean = True\n raise\n finally:\n if not options.no_clean:\n requirement_set.cleanup_files()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements dirac-dms-show-se-status.py from coberger/DIRAC (path: DataManagementSystem/scripts/dirac-dms-show-se-status.py)."}, {"role": "assistant", "content": "# DataManagementSystem/scripts/dirac-dms-show-se-status.py (from coberger/DIRAC, license: gpl-3.0)\n\n#!/usr/bin/env python\n\nfrom DIRAC.Core.Base import Script\n\nScript.setUsageMessage( \"\"\"\nGet status of the available Storage Elements\n\nUsage:\n %s []\n\"\"\" % Script.scriptName )\n\nScript.parseCommandLine()\n\nimport DIRAC\nfrom DIRAC import gConfig,gLogger\nfrom DIRAC.ResourceStatusSystem.Client.ResourceStatus import ResourceStatus\nfrom DIRAC.Core.Utilities.List import sortList\nfrom DIRAC.ConfigurationSystem.Client.Helpers.Resources import Resources\nfrom DIRAC.Core.Security.ProxyInfo import getVOfromProxyGroup\n\nif __name__ == \"__main__\":\n \n result = getVOfromProxyGroup()\n if not result['OK']:\n gLogger.notice( 'Error:', result['Message'] )\n DIRAC.exit( 1 )\n vo = result['Value'] \n resources = Resources( vo = vo )\n result = resources.getEligibleStorageElements()\n if not result['OK']:\n gLogger.notice( 'Error:', result['Message'] )\n DIRAC.exit( 2 )\n seList = sortList( result[ 'Value' ] )\n\n resourceStatus = ResourceStatus()\n \n result = resourceStatus.getStorageStatus( seList )\n if not result['OK']:\n gLogger.notice( 'Error:', result['Message'] )\n DIRAC.exit( 3 )\n\n for k,v in result[ 'Value' ].items():\n \n readState, writeState = 'Active', 'Active'\n \n if v.has_key( 'ReadAccess' ):\n readState = v[ 'ReadAccess' ] \n \n if v.has_key( 'WriteAccess' ):\n writeState = v[ 'WriteAccess']\n gLogger.notice(\"%s %s %s\" % ( k.ljust(25),readState.rjust(15),writeState.rjust(15)) )\n\n DIRAC.exit(0)\n\n################################################################################\n# EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF"}]} {"messages": [{"role": "user", "content": "Write Python code that implements gyptest-rules.py from erikge/watch_gyp (path: test/generator-output/gyptest-rules.py)."}, {"role": "assistant", "content": "# test/generator-output/gyptest-rules.py (from erikge/watch_gyp, license: bsd-3-clause)\n\n#!/usr/bin/env python\n\n# Copyright (c) 2012 Google Inc. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"\nVerifies --generator-output= behavior when using rules.\n\"\"\"\n\nimport TestGyp\n\n# Android doesn't support --generator-output.\ntest = TestGyp.TestGyp(formats=['!android'])\n\ntest.writable(test.workpath('rules'), False)\n\ntest.run_gyp('rules.gyp',\n '--generator-output=' + test.workpath('gypfiles'),\n '-G', 'xcode_ninja_target_pattern=^pull_in_all_actions$',\n chdir='rules')\n\ntest.writable(test.workpath('rules'), True)\n\ntest.relocate('rules', 'relocate/rules')\ntest.relocate('gypfiles', 'relocate/gypfiles')\n\ntest.writable(test.workpath('relocate/rules'), False)\n\ntest.writable(test.workpath('relocate/rules/build'), True)\ntest.writable(test.workpath('relocate/rules/subdir1/build'), True)\ntest.writable(test.workpath('relocate/rules/subdir2/build'), True)\ntest.writable(test.workpath('relocate/rules/subdir2/rules-out'), True)\n\ntest.build('rules.gyp', test.ALL, chdir='relocate/gypfiles')\n\nexpect = \"\"\"\\\nHello from program.c\nHello from function1.in1\nHello from function2.in1\nHello from define3.in0\nHello from define4.in0\n\"\"\"\n\nif test.format == 'xcode':\n chdir = 'relocate/rules/subdir1'\nelse:\n chdir = 'relocate/gypfiles'\ntest.run_built_executable('program', chdir=chdir, stdout=expect)\n\ntest.must_match('relocate/rules/subdir2/rules-out/file1.out',\n \"Hello from file1.in0\\n\")\ntest.must_match('relocate/rules/subdir2/rules-out/file2.out',\n \"Hello from file2.in0\\n\")\ntest.must_match('relocate/rules/subdir2/rules-out/file3.out',\n \"Hello from file3.in1\\n\")\ntest.must_match('relocate/rules/subdir2/rules-out/file4.out',\n \"Hello from file4.in1\\n\")\n\ntest.pass_test()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements ec2_key.py from krdlab/ansible-modules-core (path: cloud/amazon/ec2_key.py)."}, {"role": "assistant", "content": "# cloud/amazon/ec2_key.py (from krdlab/ansible-modules-core, license: gpl-3.0)\n\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\nDOCUMENTATION = '''\n---\nmodule: ec2_key\nversion_added: \"1.5\"\nshort_description: maintain an ec2 key pair.\ndescription:\n - maintains ec2 key pairs. This module has a dependency on python-boto >= 2.5\noptions:\n name:\n description:\n - Name of the key pair.\n required: true\n key_material:\n description:\n - Public key material.\n required: false\n state:\n description:\n - create or delete keypair\n required: false\n default: 'present'\n aliases: []\n wait:\n description:\n - Wait for the specified action to complete before returning.\n required: false\n default: false\n aliases: []\n version_added: \"1.6\"\n wait_timeout:\n description:\n - How long before wait gives up, in seconds\n required: false\n default: 300\n aliases: []\n version_added: \"1.6\"\n\nextends_documentation_fragment:\n - aws\n - ec2\nauthor: \"Vincent Viallet (@zbal)\"\n'''\n\nEXAMPLES = '''\n# Note: None of these examples set aws_access_key, aws_secret_key, or region.\n# It is assumed that their matching environment variables are set.\n\n# Creates a new ec2 key pair named `example` if not present, returns generated\n# private key\n- name: example ec2 key\n ec2_key:\n name: example\n\n# Creates a new ec2 key pair named `example` if not present using provided key\n# material. This could use the 'file' lookup plugin to pull this off disk.\n- name: example2 ec2 key\n ec2_key:\n name: example2\n key_material: 'ssh-rsa AAAAxyz...== me@example.com'\n state: present\n\n# Creates a new ec2 key pair named `example` if not present using provided key\n# material\n- name: example3 ec2 key\n ec2_key:\n name: example3\n key_material: \"{{ item }}\"\n with_file: /path/to/public_key.id_rsa.pub\n\n# Removes ec2 key pair by name\n- name: remove example key\n ec2_key:\n name: example\n state: absent\n'''\n\ntry:\n import boto.ec2\n HAS_BOTO = True\nexcept ImportError:\n HAS_BOTO = False\n\nimport random\nimport string\n\ndef main():\n argument_spec = ec2_argument_spec()\n argument_spec.update(dict(\n name=dict(required=True),\n key_material=dict(required=False),\n state = dict(default='present', choices=['present', 'absent']),\n wait = dict(type='bool', default=False),\n wait_timeout = dict(default=300),\n )\n )\n module = AnsibleModule(\n argument_spec=argument_spec,\n supports_check_mode=True,\n )\n\n if not HAS_BOTO:\n module.fail_json(msg='boto required for this module')\n\n name = module.params['name']\n state = module.params.get('state')\n key_material = module.params.get('key_material')\n wait = module.params.get('wait')\n wait_timeout = int(module.params.get('wait_timeout'))\n\n changed = False\n\n ec2 = ec2_connect(module)\n\n # find the key if present\n key = ec2.get_key_pair(name)\n\n # Ensure requested key is absent\n if state == 'absent':\n if key:\n '''found a match, delete it'''\n if not module.check_mode:\n try:\n key.delete()\n if wait:\n start = time.time()\n action_complete = False\n while (time.time() - start) < wait_timeout:\n if not ec2.get_key_pair(name):\n action_complete = True\n break\n time.sleep(1)\n if not action_complete:\n module.fail_json(msg=\"timed out while waiting for the key to be removed\")\n except Exception, e:\n module.fail_json(msg=\"Unable to delete key pair '%s' - %s\" % (key, e))\n key = None\n changed = True\n\n # Ensure requested key is present\n elif state == 'present':\n if key:\n # existing key found\n if key_material:\n # EC2's fingerprints are non-trivial to generate, so push this key \n # to a temporary name and make ec2 calculate the fingerprint for us.\n #\n # http://blog.jbrowne.com/?p=23\n # https://forums.aws.amazon.com/thread.jspa?messageID=352828\n\n # find an unused name\n test = 'empty'\n while test:\n randomchars = [random.choice(string.ascii_letters + string.digits) for x in range(0,10)]\n tmpkeyname = \"ansible-\" + ''.join(randomchars)\n test = ec2.get_key_pair(tmpkeyname)\n\n # create tmp key\n tmpkey = ec2.import_key_pair(tmpkeyname, key_material)\n # get tmp key fingerprint\n tmpfingerprint = tmpkey.fingerprint\n # delete tmp key\n tmpkey.delete()\n\n if key.fingerprint != tmpfingerprint:\n if not module.check_mode:\n key.delete()\n key = ec2.import_key_pair(name, key_material) \n\n if wait:\n start = time.time()\n action_complete = False\n while (time.time() - start) < wait_timeout:\n if ec2.get_key_pair(name):\n action_complete = True\n break\n time.sleep(1)\n if not action_complete:\n module.fail_json(msg=\"timed out while waiting for the key to be re-created\")\n\n changed = True\n pass\n\n # if the key doesn't exist, create it now\n else:\n '''no match found, create it'''\n if not module.check_mode:\n if key_material:\n '''We are providing the key, need to import'''\n key = ec2.import_key_pair(name, key_material)\n else:\n '''\n No material provided, let AWS handle the key creation and \n retrieve the private key\n '''\n key = ec2.create_key_pair(name)\n\n if wait:\n start = time.time()\n action_complete = False\n while (time.time() - start) < wait_timeout:\n if ec2.get_key_pair(name):\n action_complete = True\n break\n time.sleep(1)\n if not action_complete:\n module.fail_json(msg=\"timed out while waiting for the key to be created\")\n\n changed = True\n\n if key:\n data = {\n 'name': key.name,\n 'fingerprint': key.fingerprint\n }\n if key.material:\n data.update({'private_key': key.material})\n\n module.exit_json(changed=changed, key=data)\n else:\n module.exit_json(changed=changed, key=None)\n\n# import module snippets\nfrom ansible.module_utils.basic import *\nfrom ansible.module_utils.ec2 import *\n\nmain()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements config.py from foodsnag/foodsnag-web (path: config.py)."}, {"role": "assistant", "content": "# config.py (from foodsnag/foodsnag-web, license: mit)\n\nimport os\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nclass Config:\n APP_NAME = 'FoodSnag'\n MAILER_NAME = 'Snagger'\n MAILER_EMAIL = 'snagger@foodsnag.com'\n MG_KEY = os.environ.get('MG_KEY')\n MG_URL = 'https://api.mailgun.net/v3/sandbox86fa708b0be84193924a6900094a11cf.mailgun.org'\n\n SECRET_KEY = os.environ.get('SECRET_KEY') or 'G00DB33F'\n SQLALCHEMY_COMMIT_ON_TEARDOWN = True\n\n @staticmethod\n def init_app(app):\n pass\n\nclass DevelopmentConfig(Config):\n DEBUG = True\n TESTING = True\n SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \\\n 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')\n\nclass TestingConfig(Config):\n DEBUG = True\n TESTING = True\n SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \\\n 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')\n\nclass ProductionConfig(Config):\n MG_URL = 'https://api.mailgun.net/v3/mg.foodsnag.com'\n SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \\\n 'sqlite:///' + os.path.join(basedir, 'data.sqlite')\n\nconfig = {\n 'development': DevelopmentConfig,\n 'testing': TestingConfig,\n 'production': ProductionConfig,\n\n 'default': DevelopmentConfig\n}"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_compat.py from DGrady/pandas (path: pandas/tests/computation/test_compat.py)."}, {"role": "assistant", "content": "# pandas/tests/computation/test_compat.py (from DGrady/pandas, license: bsd-3-clause)\n\nimport pytest\nfrom distutils.version import LooseVersion\n\nimport pandas as pd\n\nfrom pandas.core.computation.engines import _engines\nimport pandas.core.computation.expr as expr\nfrom pandas.core.computation import _MIN_NUMEXPR_VERSION\n\ndef test_compat():\n # test we have compat with our version of nu\n\n from pandas.core.computation import _NUMEXPR_INSTALLED\n try:\n import numexpr as ne\n ver = ne.__version__\n if ver < LooseVersion(_MIN_NUMEXPR_VERSION):\n assert not _NUMEXPR_INSTALLED\n else:\n assert _NUMEXPR_INSTALLED\n except ImportError:\n pytest.skip(\"not testing numexpr version compat\")\n\n@pytest.mark.parametrize('engine', _engines)\n@pytest.mark.parametrize('parser', expr._parsers)\ndef test_invalid_numexpr_version(engine, parser):\n def testit():\n a, b = 1, 2 # noqa\n res = pd.eval('a + b', engine=engine, parser=parser)\n assert res == 3\n\n if engine == 'numexpr':\n try:\n import numexpr as ne\n except ImportError:\n pytest.skip(\"no numexpr\")\n else:\n if ne.__version__ < LooseVersion(_MIN_NUMEXPR_VERSION):\n with pytest.raises(ImportError):\n testit()\n else:\n testit()\n else:\n testit()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements plot_feature_selection.py from zhenv5/scikit-learn (path: examples/feature_selection/plot_feature_selection.py)."}, {"role": "assistant", "content": "# examples/feature_selection/plot_feature_selection.py (from zhenv5/scikit-learn, license: bsd-3-clause)\n\n\"\"\"\n===============================\nUnivariate Feature Selection\n===============================\n\nAn example showing univariate feature selection.\n\nNoisy (non informative) features are added to the iris data and\nunivariate feature selection is applied. For each feature, we plot the\np-values for the univariate feature selection and the corresponding\nweights of an SVM. We can see that univariate feature selection\nselects the informative features and that these have larger SVM weights.\n\nIn the total set of features, only the 4 first ones are significant. We\ncan see that they have the highest score with univariate feature\nselection. The SVM assigns a large weight to one of these features, but also\nSelects many of the non-informative features.\nApplying univariate feature selection before the SVM\nincreases the SVM weight attributed to the significant features, and will\nthus improve classification.\n\"\"\"\nprint(__doc__)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn import datasets, svm\nfrom sklearn.feature_selection import SelectPercentile, f_classif\n\n###############################################################################\n# import some data to play with\n\n# The iris dataset\niris = datasets.load_iris()\n\n# Some noisy data not correlated\nE = np.random.uniform(0, 0.1, size=(len(iris.data), 20))\n\n# Add the noisy data to the informative features\nX = np.hstack((iris.data, E))\ny = iris.target\n\n###############################################################################\nplt.figure(1)\nplt.clf()\n\nX_indices = np.arange(X.shape[-1])\n\n###############################################################################\n# Univariate feature selection with F-test for feature scoring\n# We use the default selection function: the 10% most significant features\nselector = SelectPercentile(f_classif, percentile=10)\nselector.fit(X, y)\nscores = -np.log10(selector.pvalues_)\nscores /= scores.max()\nplt.bar(X_indices - .45, scores, width=.2,\n label=r'Univariate score ($-Log(p_{value})$)', color='g')\n\n###############################################################################\n# Compare to the weights of an SVM\nclf = svm.SVC(kernel='linear')\nclf.fit(X, y)\n\nsvm_weights = (clf.coef_ ** 2).sum(axis=0)\nsvm_weights /= svm_weights.max()\n\nplt.bar(X_indices - .25, svm_weights, width=.2, label='SVM weight', color='r')\n\nclf_selected = svm.SVC(kernel='linear')\nclf_selected.fit(selector.transform(X), y)\n\nsvm_weights_selected = (clf_selected.coef_ ** 2).sum(axis=0)\nsvm_weights_selected /= svm_weights_selected.max()\n\nplt.bar(X_indices[selector.get_support()] - .05, svm_weights_selected,\n width=.2, label='SVM weights after selection', color='b')\n\nplt.title(\"Comparing feature selection\")\nplt.xlabel('Feature number')\nplt.yticks(())\nplt.axis('tight')\nplt.legend(loc='upper right')\nplt.show()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements urls.py from mozilla/verbatim (path: local_apps/pootle_project/urls.py)."}, {"role": "assistant", "content": "# local_apps/pootle_project/urls.py (from mozilla/verbatim, license: gpl-2.0)\n\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2008 Zuza Software Foundation\n#\n# This file is part of translate.\n#\n# translate is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# translate is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with translate; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\nfrom django.conf.urls.defaults import *\n\nurlpatterns = patterns('pootle_project.views',\n (r'^$|^index.html$', 'projects_index'),\n (r'^(?P[^/]*)/admin.html$', 'project_admin'),\n (r'^(?P[^/]*)/permissions.html$', 'project_admin_permissions'),\n (r'^(?P[^/]*)(/|/index.html)?$', 'project_language_index'),\n)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements __init__.py from aequitas/home-assistant (path: homeassistant/components/conversation/__init__.py)."}, {"role": "assistant", "content": "# homeassistant/components/conversation/__init__.py (from aequitas/home-assistant, license: apache-2.0)\n\n\"\"\"Support for functionality to have conversations with Home Assistant.\"\"\"\nimport logging\nimport re\n\nimport voluptuous as vol\n\nfrom homeassistant import core\nfrom homeassistant.components import http\nfrom homeassistant.components.cover import (\n INTENT_CLOSE_COVER, INTENT_OPEN_COVER)\nfrom homeassistant.components.http.data_validator import RequestDataValidator\nfrom homeassistant.const import EVENT_COMPONENT_LOADED\nfrom homeassistant.core import callback\nfrom homeassistant.helpers import config_validation as cv, intent\nfrom homeassistant.loader import bind_hass\nfrom homeassistant.setup import ATTR_COMPONENT\n\nfrom .util import create_matcher\n\n_LOGGER = logging.getLogger(__name__)\n\nATTR_TEXT = 'text'\n\nDOMAIN = 'conversation'\n\nREGEX_TURN_COMMAND = re.compile(r'turn (?P(?: |\\w)+) (?P\\w+)')\nREGEX_TYPE = type(re.compile(''))\n\nUTTERANCES = {\n 'cover': {\n INTENT_OPEN_COVER: ['Open [the] [a] [an] {name}[s]'],\n INTENT_CLOSE_COVER: ['Close [the] [a] [an] {name}[s]']\n }\n}\n\nSERVICE_PROCESS = 'process'\n\nSERVICE_PROCESS_SCHEMA = vol.Schema({\n vol.Required(ATTR_TEXT): cv.string,\n})\n\nCONFIG_SCHEMA = vol.Schema({DOMAIN: vol.Schema({\n vol.Optional('intents'): vol.Schema({\n cv.string: vol.All(cv.ensure_list, [cv.string])\n })\n})}, extra=vol.ALLOW_EXTRA)\n\n@core.callback\n@bind_hass\ndef async_register(hass, intent_type, utterances):\n \"\"\"Register utterances and any custom intents.\n\n Registrations don't require conversations to be loaded. They will become\n active once the conversation component is loaded.\n \"\"\"\n intents = hass.data.get(DOMAIN)\n\n if intents is None:\n intents = hass.data[DOMAIN] = {}\n\n conf = intents.get(intent_type)\n\n if conf is None:\n conf = intents[intent_type] = []\n\n for utterance in utterances:\n if isinstance(utterance, REGEX_TYPE):\n conf.append(utterance)\n else:\n conf.append(create_matcher(utterance))\n\nasync def async_setup(hass, config):\n \"\"\"Register the process service.\"\"\"\n config = config.get(DOMAIN, {})\n intents = hass.data.get(DOMAIN)\n\n if intents is None:\n intents = hass.data[DOMAIN] = {}\n\n for intent_type, utterances in config.get('intents', {}).items():\n conf = intents.get(intent_type)\n\n if conf is None:\n conf = intents[intent_type] = []\n\n conf.extend(create_matcher(utterance) for utterance in utterances)\n\n async def process(service):\n \"\"\"Parse text into commands.\"\"\"\n text = service.data[ATTR_TEXT]\n _LOGGER.debug('Processing: <%s>', text)\n try:\n await _process(hass, text)\n except intent.IntentHandleError as err:\n _LOGGER.error('Error processing %s: %s', text, err)\n\n hass.services.async_register(\n DOMAIN, SERVICE_PROCESS, process, schema=SERVICE_PROCESS_SCHEMA)\n\n hass.http.register_view(ConversationProcessView)\n\n # We strip trailing 's' from name because our state matcher will fail\n # if a letter is not there. By removing 's' we can match singular and\n # plural names.\n\n async_register(hass, intent.INTENT_TURN_ON, [\n 'Turn [the] [a] {name}[s] on',\n 'Turn on [the] [a] [an] {name}[s]',\n ])\n async_register(hass, intent.INTENT_TURN_OFF, [\n 'Turn [the] [a] [an] {name}[s] off',\n 'Turn off [the] [a] [an] {name}[s]',\n ])\n async_register(hass, intent.INTENT_TOGGLE, [\n 'Toggle [the] [a] [an] {name}[s]',\n '[the] [a] [an] {name}[s] toggle',\n ])\n\n @callback\n def register_utterances(component):\n \"\"\"Register utterances for a component.\"\"\"\n if component not in UTTERANCES:\n return\n for intent_type, sentences in UTTERANCES[component].items():\n async_register(hass, intent_type, sentences)\n\n @callback\n def component_loaded(event):\n \"\"\"Handle a new component loaded.\"\"\"\n register_utterances(event.data[ATTR_COMPONENT])\n\n hass.bus.async_listen(EVENT_COMPONENT_LOADED, component_loaded)\n\n # Check already loaded components.\n for component in hass.config.components:\n register_utterances(component)\n\n return True\n\nasync def _process(hass, text):\n \"\"\"Process a line of text.\"\"\"\n intents = hass.data.get(DOMAIN, {})\n\n for intent_type, matchers in intents.items():\n for matcher in matchers:\n match = matcher.match(text)\n\n if not match:\n continue\n\n response = await hass.helpers.intent.async_handle(\n DOMAIN, intent_type,\n {key: {'value': value} for key, value\n in match.groupdict().items()}, text)\n return response\n\nclass ConversationProcessView(http.HomeAssistantView):\n \"\"\"View to retrieve shopping list content.\"\"\"\n\n url = '/api/conversation/process'\n name = \"api:conversation:process\"\n\n @RequestDataValidator(vol.Schema({\n vol.Required('text'): str,\n }))\n async def post(self, request, data):\n \"\"\"Send a request for processing.\"\"\"\n hass = request.app['hass']\n\n try:\n intent_result = await _process(hass, data['text'])\n except intent.IntentHandleError as err:\n intent_result = intent.IntentResponse()\n intent_result.async_set_speech(str(err))\n\n if intent_result is None:\n intent_result = intent.IntentResponse()\n intent_result.async_set_speech(\"Sorry, I didn't understand that\")\n\n return self.json(intent_result)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements evaluation.py from dssg/cincinnati2015-public (path: evaluation/webapp/evaluation.py)."}, {"role": "assistant", "content": "# evaluation/webapp/evaluation.py (from dssg/cincinnati2015-public, license: mit)\n\nfrom datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\n\nfrom webapp import config\n\ndef weighted_f1(scores):\n f1_0 = scores[\"f1\"][0] * scores[\"support\"][0]\n f1_1 = scores[\"f1\"][1] * scores[\"support\"][1]\n return (f1_0 + f1_1) / (scores[\"support\"][0] + scores[\"support\"][1])\n\ndef plot_normalized_confusion_matrix(labels, predictions):\n cutoff = 0.5\n predictions_binary = np.copy(predictions)\n predictions_binary[predictions_binary >= cutoff] = 1\n predictions_binary[predictions_binary < cutoff] = 0\n\n cm = metrics.confusion_matrix(labels, predictions_binary)\n np.set_printoptions(precision=2)\n fig = plt.figure()\n cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n target_names = [\"No violation\", \"Violation\"]\n plt.imshow(cm_normalized, interpolation='nearest', cmap=plt.cm.Blues)\n plt.title(\"Normalized Confusion Matrix\")\n plt.colorbar()\n tick_marks = np.arange(len(target_names))\n plt.xticks(tick_marks, target_names, rotation=45)\n plt.yticks(tick_marks, target_names)\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n return fig\n\ndef plot_feature_importances(feature_names, feature_importances):\n importances = list(zip(feature_names, list(feature_importances)))\n importances = pd.DataFrame(importances, columns=[\"Feature\", \"Importance\"])\n importances = importances.set_index(\"Feature\")\n importances = importances.sort(columns=\"Importance\", ascending=False)\n importances = importances[0:20]\n with plt.style.context(('ggplot')):\n fig, ax = plt.subplots()\n importances.plot(kind=\"barh\", legend=False, ax=ax)\n plt.tight_layout()\n plt.title(\"Feature importances (Top 20)\")\n return fig\n\ndef plot_growth(results):\n results = pd.DataFrame(results, columns=[\"date\", \"score\"])\n results = results.set_index(\"date\")\n results[\"score\"] = results[\"score\"].astype(float)\n results = results.reindex(pd.date_range(datetime(2015, 7, 28), datetime(2015, 8, 27)))\n results[\"random\"] = pd.Series(3409/float(6124), index=results.index)\n with plt.style.context(('ggplot')):\n fig, ax = plt.subplots(figsize=(8, 3))\n results[\"score\"].plot(legend=False, ax=ax, marker=\"x\")\n results[\"random\"].plot(legend=False, ax=ax, style='--')\n\n ax.set_ylabel(config.score_name)\n plt.tight_layout()\n ax.set_ylim(0.5, 1.0)\n return fig\n\ndef precision_at_x_percent(test_labels, test_predictions, x_percent=0.01, return_cutoff=False):\n\n cutoff_index = int(len(test_predictions) * x_percent)\n cutoff_index = min(cutoff_index, len(test_predictions) -1)\n\n sorted_by_probability = np.sort(test_predictions)[::-1]\n cutoff_probability = sorted_by_probability[cutoff_index]\n\n test_predictions_binary = np.copy(test_predictions)\n test_predictions_binary[test_predictions_binary >= cutoff_probability] = 1\n test_predictions_binary[test_predictions_binary < cutoff_probability] = 0\n\n precision, _, _, _ = metrics.precision_recall_fscore_support(test_labels, test_predictions_binary)\n precision = precision[1] # only interested in precision for label 1\n\n if return_cutoff:\n return precision, cutoff_probability\n else:\n return precision\n\ndef plot_precision_recall_n(test_labels, test_predictions):\n y_score = test_predictions\n precision_curve, recall_curve, pr_thresholds = metrics.precision_recall_curve(test_labels, y_score)\n precision_curve = precision_curve[:-1]\n recall_curve = recall_curve[:-1]\n pct_above_per_thresh = []\n number_scored = len(y_score)\n for value in pr_thresholds:\n num_above_thresh = len(y_score[y_score>=value])\n pct_above_thresh = num_above_thresh / float(number_scored)\n pct_above_per_thresh.append(pct_above_thresh)\n pct_above_per_thresh = np.array(pct_above_per_thresh)\n\n with plt.style.context(('ggplot')):\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.plot(pct_above_per_thresh, precision_curve, \"#000099\")\n ax1.set_xlabel('percent of population')\n ax1.set_ylabel('precision', color=\"#000099\")\n plt.ylim([0.0, 1.0])\n ax2 = ax1.twinx()\n ax2.plot(pct_above_per_thresh, recall_curve, \"#CC0000\")\n ax2.set_ylabel('recall', color=\"#CC0000\")\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.0])\n plt.title(\"Precision-recall for top x%\")\n return fig\n\ndef plot_precision_cutoff(test_labels, test_predictions):\n percent_range = [0.001* i for i in range(1, 10)] + [0.01 * i for i in range(1, 101)]\n precisions_and_cutoffs = [precision_at_x_percent(test_labels, test_predictions, x_percent=p, return_cutoff=True)\n for p in percent_range]\n precisions, cutoffs = zip(*precisions_and_cutoffs)\n\n with plt.style.context(('ggplot')):\n fig, ax = plt.subplots()\n ax.plot(percent_range, precisions, \"#000099\")\n ax.set_xlabel('percent of population')\n ax.set_ylabel('precision', color=\"#000099\")\n plt.ylim([0.0, 1.0])\n ax2 = ax.twinx()\n ax2.plot(percent_range, cutoffs, \"#CC0000\")\n ax2.set_ylabel('cutoff at', color=\"#CC0000\")\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.0])\n plt.title(\"Precision at x%\")\n return fig\n\ndef plot_ROC(test_labels, test_predictions):\n fpr, tpr, thresholds = metrics.roc_curve(test_labels, test_predictions, pos_label=1)\n with plt.style.context(('ggplot')):\n fig, ax = plt.subplots()\n ax.plot(fpr[2], tpr[2])\n #ax.plot([0, 1], [0, 1], 'k--')\n #plt.xlim([0.0, 1.0])\n #plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic')\n return fig"}]} {"messages": [{"role": "user", "content": "Write Python code that implements rfe.py from mfjb/scikit-learn (path: sklearn/feature_selection/rfe.py)."}, {"role": "assistant", "content": "# sklearn/feature_selection/rfe.py (from mfjb/scikit-learn, license: bsd-3-clause)\n\n# Authors: Alexandre Gramfort \n# Vincent Michel \n# Gilles Louppe \n#\n# License: BSD 3 clause\n\n\"\"\"Recursive feature elimination for feature ranking\"\"\"\n\nimport warnings\nimport numpy as np\nfrom ..utils import check_X_y, safe_sqr\nfrom ..utils.metaestimators import if_delegate_has_method\nfrom ..base import BaseEstimator\nfrom ..base import MetaEstimatorMixin\nfrom ..base import clone\nfrom ..base import is_classifier\nfrom ..cross_validation import check_cv\nfrom ..cross_validation import _safe_split, _score\nfrom ..metrics.scorer import check_scoring\nfrom .base import SelectorMixin\n\nclass RFE(BaseEstimator, MetaEstimatorMixin, SelectorMixin):\n \"\"\"Feature ranking with recursive feature elimination.\n\n Given an external estimator that assigns weights to features (e.g., the\n coefficients of a linear model), the goal of recursive feature elimination\n (RFE) is to select features by recursively considering smaller and smaller\n sets of features. First, the estimator is trained on the initial set of\n features and weights are assigned to each one of them. Then, features whose\n absolute weights are the smallest are pruned from the current set features.\n That procedure is recursively repeated on the pruned set until the desired\n number of features to select is eventually reached.\n\n Read more in the :ref:`User Guide `.\n\n Parameters\n ----------\n estimator : object\n A supervised learning estimator with a `fit` method that updates a\n `coef_` attribute that holds the fitted parameters. Important features\n must correspond to high absolute values in the `coef_` array.\n\n For instance, this is the case for most supervised learning\n algorithms such as Support Vector Classifiers and Generalized\n Linear Models from the `svm` and `linear_model` modules.\n\n n_features_to_select : int or None (default=None)\n The number of features to select. If `None`, half of the features\n are selected.\n\n step : int or float, optional (default=1)\n If greater than or equal to 1, then `step` corresponds to the (integer)\n number of features to remove at each iteration.\n If within (0.0, 1.0), then `step` corresponds to the percentage\n (rounded down) of features to remove at each iteration.\n\n estimator_params : dict\n Parameters for the external estimator.\n This attribute is deprecated as of version 0.16 and will be removed in\n 0.18. Use estimator initialisation or set_params method instead.\n\n verbose : int, default=0\n Controls verbosity of output.\n\n Attributes\n ----------\n n_features_ : int\n The number of selected features.\n\n support_ : array of shape [n_features]\n The mask of selected features.\n\n ranking_ : array of shape [n_features]\n The feature ranking, such that ``ranking_[i]`` corresponds to the\n ranking position of the i-th feature. Selected (i.e., estimated\n best) features are assigned rank 1.\n\n estimator_ : object\n The external estimator fit on the reduced dataset.\n\n Examples\n --------\n The following example shows how to retrieve the 5 right informative\n features in the Friedman #1 dataset.\n\n >>> from sklearn.datasets import make_friedman1\n >>> from sklearn.feature_selection import RFE\n >>> from sklearn.svm import SVR\n >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)\n >>> estimator = SVR(kernel=\"linear\")\n >>> selector = RFE(estimator, 5, step=1)\n >>> selector = selector.fit(X, y)\n >>> selector.support_ # doctest: +NORMALIZE_WHITESPACE\n array([ True, True, True, True, True,\n False, False, False, False, False], dtype=bool)\n >>> selector.ranking_\n array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5])\n\n References\n ----------\n\n .. [1] Guyon, I., Weston, J., Barnhill, S., & Vapnik, V., \"Gene selection\n for cancer classification using support vector machines\",\n Mach. Learn., 46(1-3), 389--422, 2002.\n \"\"\"\n def __init__(self, estimator, n_features_to_select=None, step=1,\n estimator_params=None, verbose=0):\n self.estimator = estimator\n self.n_features_to_select = n_features_to_select\n self.step = step\n self.estimator_params = estimator_params\n self.verbose = verbose\n\n @property\n def _estimator_type(self):\n return self.estimator._estimator_type\n\n def fit(self, X, y):\n \"\"\"Fit the RFE model and then the underlying estimator on the selected\n features.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = [n_samples, n_features]\n The training input samples.\n\n y : array-like, shape = [n_samples]\n The target values.\n \"\"\"\n return self._fit(X, y)\n\n def _fit(self, X, y, step_score=None):\n X, y = check_X_y(X, y, \"csc\")\n # Initialization\n n_features = X.shape[1]\n if self.n_features_to_select is None:\n n_features_to_select = n_features / 2\n else:\n n_features_to_select = self.n_features_to_select\n\n if 0.0 < self.step < 1.0:\n step = int(max(1, self.step * n_features))\n else:\n step = int(self.step)\n if step <= 0:\n raise ValueError(\"Step must be >0\")\n\n if self.estimator_params is not None:\n warnings.warn(\"The parameter 'estimator_params' is deprecated as \"\n \"of version 0.16 and will be removed in 0.18. The \"\n \"parameter is no longer necessary because the value \"\n \"is set via the estimator initialisation or \"\n \"set_params method.\", DeprecationWarning)\n\n support_ = np.ones(n_features, dtype=np.bool)\n ranking_ = np.ones(n_features, dtype=np.int)\n\n if step_score:\n self.scores_ = []\n\n # Elimination\n while np.sum(support_) > n_features_to_select:\n # Remaining features\n features = np.arange(n_features)[support_]\n\n # Rank the remaining features\n estimator = clone(self.estimator)\n if self.estimator_params:\n estimator.set_params(**self.estimator_params)\n if self.verbose > 0:\n print(\"Fitting estimator with %d features.\" % np.sum(support_))\n\n estimator.fit(X[:, features], y)\n\n # Get coefs\n if hasattr(estimator, 'coef_'):\n coefs = estimator.coef_\n elif hasattr(estimator, 'feature_importances_'):\n coefs = estimator.feature_importances_\n else:\n raise RuntimeError('The classifier does not expose '\n '\"coef_\" or \"feature_importances_\" '\n 'attributes')\n\n # Get ranks\n if coefs.ndim > 1:\n ranks = np.argsort(safe_sqr(coefs).sum(axis=0))\n else:\n ranks = np.argsort(safe_sqr(coefs))\n\n # for sparse case ranks is matrix\n ranks = np.ravel(ranks)\n\n # Eliminate the worse features\n threshold = min(step, np.sum(support_) - n_features_to_select)\n\n # Compute step score on the previous selection iteration\n # because 'estimator' must use features\n # that have not been eliminated yet\n if step_score:\n self.scores_.append(step_score(estimator, features))\n support_[features[ranks][:threshold]] = False\n ranking_[np.logical_not(support_)] += 1\n\n # Set final attributes\n features = np.arange(n_features)[support_]\n self.estimator_ = clone(self.estimator)\n if self.estimator_params:\n self.estimator_.set_params(**self.estimator_params)\n self.estimator_.fit(X[:, features], y)\n\n # Compute step score when only n_features_to_select features left\n if step_score:\n self.scores_.append(step_score(self.estimator_, features))\n self.n_features_ = support_.sum()\n self.support_ = support_\n self.ranking_ = ranking_\n\n return self\n\n @if_delegate_has_method(delegate='estimator')\n def predict(self, X):\n \"\"\"Reduce X to the selected features and then predict using the\n underlying estimator.\n\n Parameters\n ----------\n X : array of shape [n_samples, n_features]\n The input samples.\n\n Returns\n -------\n y : array of shape [n_samples]\n The predicted target values.\n \"\"\"\n return self.estimator_.predict(self.transform(X))\n\n @if_delegate_has_method(delegate='estimator')\n def score(self, X, y):\n \"\"\"Reduce X to the selected features and then return the score of the\n underlying estimator.\n\n Parameters\n ----------\n X : array of shape [n_samples, n_features]\n The input samples.\n\n y : array of shape [n_samples]\n The target values.\n \"\"\"\n return self.estimator_.score(self.transform(X), y)\n\n def _get_support_mask(self):\n return self.support_\n\n @if_delegate_has_method(delegate='estimator')\n def decision_function(self, X):\n return self.estimator_.decision_function(self.transform(X))\n\n @if_delegate_has_method(delegate='estimator')\n def predict_proba(self, X):\n return self.estimator_.predict_proba(self.transform(X))\n\n @if_delegate_has_method(delegate='estimator')\n def predict_log_proba(self, X):\n return self.estimator_.predict_log_proba(self.transform(X))\n\nclass RFECV(RFE, MetaEstimatorMixin):\n \"\"\"Feature ranking with recursive feature elimination and cross-validated\n selection of the best number of features.\n\n Read more in the :ref:`User Guide `.\n\n Parameters\n ----------\n estimator : object\n A supervised learning estimator with a `fit` method that updates a\n `coef_` attribute that holds the fitted parameters. Important features\n must correspond to high absolute values in the `coef_` array.\n\n For instance, this is the case for most supervised learning\n algorithms such as Support Vector Classifiers and Generalized\n Linear Models from the `svm` and `linear_model` modules.\n\n step : int or float, optional (default=1)\n If greater than or equal to 1, then `step` corresponds to the (integer)\n number of features to remove at each iteration.\n If within (0.0, 1.0), then `step` corresponds to the percentage\n (rounded down) of features to remove at each iteration.\n\n cv : int or cross-validation generator, optional (default=None)\n If int, it is the number of folds.\n If None, 3-fold cross-validation is performed by default.\n Specific cross-validation objects can also be passed, see\n `sklearn.cross_validation module` for details.\n\n scoring : string, callable or None, optional, default: None\n A string (see model evaluation documentation) or\n a scorer callable object / function with signature\n ``scorer(estimator, X, y)``.\n\n estimator_params : dict\n Parameters for the external estimator.\n This attribute is deprecated as of version 0.16 and will be removed in\n 0.18. Use estimator initialisation or set_params method instead.\n\n verbose : int, default=0\n Controls verbosity of output.\n\n Attributes\n ----------\n n_features_ : int\n The number of selected features with cross-validation.\n\n support_ : array of shape [n_features]\n The mask of selected features.\n\n ranking_ : array of shape [n_features]\n The feature ranking, such that `ranking_[i]`\n corresponds to the ranking\n position of the i-th feature.\n Selected (i.e., estimated best)\n features are assigned rank 1.\n\n grid_scores_ : array of shape [n_subsets_of_features]\n The cross-validation scores such that\n ``grid_scores_[i]`` corresponds to\n the CV score of the i-th subset of features.\n\n estimator_ : object\n The external estimator fit on the reduced dataset.\n\n Notes\n -----\n The size of ``grid_scores_`` is equal to ceil((n_features - 1) / step) + 1,\n where step is the number of features removed at each iteration.\n\n Examples\n --------\n The following example shows how to retrieve the a-priori not known 5\n informative features in the Friedman #1 dataset.\n\n >>> from sklearn.datasets import make_friedman1\n >>> from sklearn.feature_selection import RFECV\n >>> from sklearn.svm import SVR\n >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)\n >>> estimator = SVR(kernel=\"linear\")\n >>> selector = RFECV(estimator, step=1, cv=5)\n >>> selector = selector.fit(X, y)\n >>> selector.support_ # doctest: +NORMALIZE_WHITESPACE\n array([ True, True, True, True, True,\n False, False, False, False, False], dtype=bool)\n >>> selector.ranking_\n array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5])\n\n References\n ----------\n\n .. [1] Guyon, I., Weston, J., Barnhill, S., & Vapnik, V., \"Gene selection\n for cancer classification using support vector machines\",\n Mach. Learn., 46(1-3), 389--422, 2002.\n \"\"\"\n def __init__(self, estimator, step=1, cv=None, scoring=None,\n estimator_params=None, verbose=0):\n self.estimator = estimator\n self.step = step\n self.cv = cv\n self.scoring = scoring\n self.estimator_params = estimator_params\n self.verbose = verbose\n\n def fit(self, X, y):\n \"\"\"Fit the RFE model and automatically tune the number of selected\n features.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = [n_samples, n_features]\n Training vector, where `n_samples` is the number of samples and\n `n_features` is the total number of features.\n\n y : array-like, shape = [n_samples]\n Target values (integers for classification, real numbers for\n regression).\n \"\"\"\n X, y = check_X_y(X, y, \"csr\")\n if self.estimator_params is not None:\n warnings.warn(\"The parameter 'estimator_params' is deprecated as \"\n \"of version 0.16 and will be removed in 0.18. \"\n \"The parameter is no longer necessary because the \"\n \"value is set via the estimator initialisation or \"\n \"set_params method.\", DeprecationWarning)\n # Initialization\n cv = check_cv(self.cv, X, y, is_classifier(self.estimator))\n scorer = check_scoring(self.estimator, scoring=self.scoring)\n n_features = X.shape[1]\n n_features_to_select = 1\n\n # Determine the number of subsets of features\n scores = []\n\n # Cross-validation\n for n, (train, test) in enumerate(cv):\n X_train, y_train = _safe_split(self.estimator, X, y, train)\n X_test, y_test = _safe_split(self.estimator, X, y, test, train)\n\n rfe = RFE(estimator=self.estimator,\n n_features_to_select=n_features_to_select,\n step=self.step, estimator_params=self.estimator_params,\n verbose=self.verbose - 1)\n\n rfe._fit(X_train, y_train, lambda estimator, features:\n _score(estimator, X_test[:, features], y_test, scorer))\n scores.append(np.array(rfe.scores_[::-1]).reshape(1, -1))\n scores = np.sum(np.concatenate(scores, 0), 0)\n # The index in 'scores' when 'n_features' features are selected\n n_feature_index = np.ceil((n_features - n_features_to_select) /\n float(self.step))\n n_features_to_select = max(n_features_to_select,\n n_features - ((n_feature_index -\n np.argmax(scores)) *\n self.step))\n # Re-execute an elimination with best_k over the whole set\n rfe = RFE(estimator=self.estimator,\n n_features_to_select=n_features_to_select,\n step=self.step, estimator_params=self.estimator_params)\n\n rfe.fit(X, y)\n\n # Set final attributes\n self.support_ = rfe.support_\n self.n_features_ = rfe.n_features_\n self.ranking_ = rfe.ranking_\n self.estimator_ = clone(self.estimator)\n if self.estimator_params:\n self.estimator_.set_params(**self.estimator_params)\n self.estimator_.fit(self.transform(X), y)\n\n # Fixing a normalization error, n is equal to len(cv) - 1\n # here, the scores are normalized by len(cv)\n self.grid_scores_ = scores / len(cv)\n return self"}]} {"messages": [{"role": "user", "content": "Write Python code that implements feature_logging.py from untrustbank/litecoin (path: test/functional/feature_logging.py)."}, {"role": "assistant", "content": "# test/functional/feature_logging.py (from untrustbank/litecoin, license: mit)\n\n#!/usr/bin/env python3\n# Copyright (c) 2017 The Bitcoin Core developers\n# Distributed under the MIT software license, see the accompanying\n# file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\"\"\"Test debug logging.\"\"\"\n\nimport os\n\nfrom test_framework.test_framework import BitcoinTestFramework\n\nclass LoggingTest(BitcoinTestFramework):\n def set_test_params(self):\n self.num_nodes = 1\n self.setup_clean_chain = True\n\n def run_test(self):\n # test default log file name\n assert os.path.isfile(os.path.join(self.nodes[0].datadir, \"regtest\", \"debug.log\"))\n\n # test alternative log file name in datadir\n self.restart_node(0, [\"-debuglogfile=foo.log\"])\n assert os.path.isfile(os.path.join(self.nodes[0].datadir, \"regtest\", \"foo.log\"))\n\n # test alternative log file name outside datadir\n tempname = os.path.join(self.options.tmpdir, \"foo.log\")\n self.restart_node(0, [\"-debuglogfile=%s\" % tempname])\n assert os.path.isfile(tempname)\n\n # check that invalid log (relative) will cause error\n invdir = os.path.join(self.nodes[0].datadir, \"regtest\", \"foo\")\n invalidname = os.path.join(\"foo\", \"foo.log\")\n self.stop_node(0)\n self.assert_start_raises_init_error(0, [\"-debuglogfile=%s\" % (invalidname)],\n \"Error: Could not open debug log file\")\n assert not os.path.isfile(os.path.join(invdir, \"foo.log\"))\n\n # check that invalid log (relative) works after path exists\n self.stop_node(0)\n os.mkdir(invdir)\n self.start_node(0, [\"-debuglogfile=%s\" % (invalidname)])\n assert os.path.isfile(os.path.join(invdir, \"foo.log\"))\n\n # check that invalid log (absolute) will cause error\n self.stop_node(0)\n invdir = os.path.join(self.options.tmpdir, \"foo\")\n invalidname = os.path.join(invdir, \"foo.log\")\n self.assert_start_raises_init_error(0, [\"-debuglogfile=%s\" % invalidname],\n \"Error: Could not open debug log file\")\n assert not os.path.isfile(os.path.join(invdir, \"foo.log\"))\n\n # check that invalid log (absolute) works after path exists\n self.stop_node(0)\n os.mkdir(invdir)\n self.start_node(0, [\"-debuglogfile=%s\" % (invalidname)])\n assert os.path.isfile(os.path.join(invdir, \"foo.log\"))\n\nif __name__ == '__main__':\n LoggingTest().main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements __init__.py from ingadhoc/odoo (path: addons/l10n_be_coda/wizard/__init__.py)."}, {"role": "assistant", "content": "# addons/l10n_be_coda/wizard/__init__.py (from ingadhoc/odoo, license: agpl-3.0)\n\n# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# \n# Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved.\n# \n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nimport account_coda_import\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:"}]} {"messages": [{"role": "user", "content": "Write Python code that implements model_ops.py from yufengg/tensorflow (path: tensorflow/contrib/boosted_trees/python/ops/model_ops.py)."}, {"role": "assistant", "content": "# tensorflow/contrib/boosted_trees/python/ops/model_ops.py (from yufengg/tensorflow, license: apache-2.0)\n\n# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Model ops python wrappers.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.boosted_trees.python.ops import gen_model_ops\nfrom tensorflow.contrib.boosted_trees.python.ops.gen_model_ops import tree_ensemble_deserialize\nfrom tensorflow.contrib.boosted_trees.python.ops.gen_model_ops import tree_ensemble_serialize\n# pylint: disable=unused-import\nfrom tensorflow.contrib.boosted_trees.python.ops.gen_model_ops import tree_ensemble_stamp_token\n# pylint: enable=unused-import\n\nfrom tensorflow.contrib.util import loader\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import resources\nfrom tensorflow.python.platform import resource_loader\nfrom tensorflow.python.training import saver\n\nops.NotDifferentiable(\"TreeEnsembleVariable\")\nops.NotDifferentiable(\"TreeEnsembleSerialize\")\nops.NotDifferentiable(\"TreeEnsembleDeserialize\")\n\nclass TreeEnsembleVariableSavable(saver.BaseSaverBuilder.SaveableObject):\n \"\"\"SaveableObject implementation for TreeEnsembleVariable.\"\"\"\n\n def __init__(self, tree_ensemble_handle, create_op, name):\n \"\"\"Creates a TreeEnsembleVariableSavable object.\n\n Args:\n tree_ensemble_handle: handle to the tree ensemble variable.\n create_op: the op to initialize the variable.\n name: the name to save the tree ensemble variable under.\n \"\"\"\n stamp_token, ensemble_config = tree_ensemble_serialize(tree_ensemble_handle)\n # slice_spec is useful for saving a slice from a variable.\n # It's not meaningful the tree ensemble variable. So we just pass an empty\n # value.\n slice_spec = \"\"\n specs = [\n saver.BaseSaverBuilder.SaveSpec(stamp_token, slice_spec,\n name + \"_stamp\"),\n saver.BaseSaverBuilder.SaveSpec(ensemble_config, slice_spec,\n name + \"_config\"),\n ]\n super(TreeEnsembleVariableSavable,\n self).__init__(tree_ensemble_handle, specs, name)\n self._tree_ensemble_handle = tree_ensemble_handle\n self._create_op = create_op\n\n def restore(self, restored_tensors, unused_restored_shapes):\n \"\"\"Restores the associated tree ensemble from 'restored_tensors'.\n\n Args:\n restored_tensors: the tensors that were loaded from a checkpoint.\n unused_restored_shapes: the shapes this object should conform to after\n restore. Not meaningful for trees.\n\n Returns:\n The operation that restores the state of the tree ensemble variable.\n \"\"\"\n with ops.control_dependencies([self._create_op]):\n return tree_ensemble_deserialize(\n self._tree_ensemble_handle,\n stamp_token=restored_tensors[0],\n tree_ensemble_config=restored_tensors[1])\n\ndef tree_ensemble_variable(stamp_token,\n tree_ensemble_config,\n name,\n container=None):\n r\"\"\"Creates a tree ensemble model and returns a handle to it.\n\n Args:\n stamp_token: The initial stamp token value for the ensemble resource.\n tree_ensemble_config: A `Tensor` of type `string`.\n Serialized proto of the tree ensemble.\n name: A name for the ensemble variable.\n container: An optional `string`. Defaults to `\"\"`.\n\n Returns:\n A `Tensor` of type mutable `string`. The handle to the tree ensemble.\n \"\"\"\n with ops.name_scope(name, \"TreeEnsembleVariable\") as name:\n resource_handle = gen_model_ops.decision_tree_ensemble_resource_handle_op(\n container, shared_name=name, name=name)\n create_op = gen_model_ops.create_tree_ensemble_variable(\n resource_handle, stamp_token, tree_ensemble_config)\n is_initialized_op = gen_model_ops.tree_ensemble_is_initialized_op(\n resource_handle)\n # Adds the variable to the savable list.\n saveable = TreeEnsembleVariableSavable(resource_handle, create_op,\n resource_handle.name)\n ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, saveable)\n resources.register_resource(resource_handle, create_op, is_initialized_op)\n return resource_handle\n\n# Conditionally load ops, they might already be statically linked in.\ntry:\n _model_ops = loader.load_op_library(\n resource_loader.get_path_to_datafile(\"_model_ops.so\"))\nexcept (errors.NotFoundError, IOError):\n print(\"Error loading _model_ops.so\")"}]} {"messages": [{"role": "user", "content": "Write Python code that implements V1beta3_ServiceStatus.py from ramielrowe/magnum (path: magnum/common/pythonk8sclient/client/models/V1beta3_ServiceStatus.py)."}, {"role": "assistant", "content": "# magnum/common/pythonk8sclient/client/models/V1beta3_ServiceStatus.py (from ramielrowe/magnum, license: apache-2.0)\n\n#!/usr/bin/env python\n\"\"\"\nCopyright 2015 Reverb Technologies, Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nclass V1beta3_ServiceStatus(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\"\"\"\n\n def __init__(self):\n \"\"\"\n Attributes:\n swaggerTypes (dict): The key is attribute name and the value is attribute type.\n attributeMap (dict): The key is attribute name and the value is json key in definition.\n \"\"\"\n self.swaggerTypes = {\n \n }\n\n self.attributeMap = {\n \n }"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_employee_display_own_info.py from OCA/hr (path: hr_employee_display_own_info/tests/test_employee_display_own_info.py)."}, {"role": "assistant", "content": "# hr_employee_display_own_info/tests/test_employee_display_own_info.py (from OCA/hr, license: agpl-3.0)\n\n# Copyright 2017-2019 Onestein ()\n# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).\n\nfrom odoo.tests.common import TransactionCase\n\nclass TestEmployeeDisplayOwnInfo(TransactionCase):\n\n def setUp(self):\n super(TestEmployeeDisplayOwnInfo, self).setUp()\n\n self.user_test = self.env.ref('base.user_demo')\n self.employee = self.env['hr.employee'].create({\n 'name': 'Employee',\n })\n\n def test_01(self):\n self.assertFalse(self.user_test.has_group('hr.group_hr_user'))\n self.assertFalse(\n self.employee.sudo(self.user_test).employee_display_personal_data)\n\n def test_02(self):\n self.assertTrue(self.env.user.has_group('hr.group_hr_user'))\n self.assertTrue(self.employee.employee_display_personal_data)\n\n def test_03(self):\n self.employee.write({'user_id': self.user_test.id})\n self.assertFalse(self.user_test.has_group('hr.group_hr_user'))\n self.assertTrue(\n self.employee.sudo(self.user_test).employee_display_personal_data)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements utils.py from sbt9uc/osf.io (path: framework/mongo/utils.py)."}, {"role": "assistant", "content": "# framework/mongo/utils.py (from sbt9uc/osf.io, license: apache-2.0)\n\n# -*- coding: utf-8 -*-\n\nimport re\nimport httplib as http\n\nimport pymongo\nfrom modularodm.exceptions import ValidationValueError\n\nfrom framework.exceptions import HTTPError\n\n# MongoDB forbids field names that begin with \"$\" or contain \".\". These\n# utilities map to and from Mongo field names.\n\nmongo_map = {\n '.': '__!dot!__',\n '$': '__!dollar!__',\n}\n\ndef to_mongo(item):\n for key, value in mongo_map.items():\n item = item.replace(key, value)\n return item\n\ndef to_mongo_key(item):\n return to_mongo(item).strip().lower()\n\ndef from_mongo(item):\n for key, value in mongo_map.items():\n item = item.replace(value, key)\n return item\n\nsanitize_pattern = re.compile(r'<\\/?[^>]+>')\ndef sanitized(value):\n if value != sanitize_pattern.sub('', value):\n raise ValidationValueError('Unsanitary string')\n\ndef unique_on(*groups):\n \"\"\"Decorator for subclasses of `StoredObject`. Add a unique index on each\n group of keys provided.\n\n :param *groups: List of lists of keys to be indexed\n \"\"\"\n def wrapper(cls):\n cls.__indices__ = getattr(cls, '__indices__', [])\n cls.__indices__.extend([\n {\n 'key_or_list': [\n (key, pymongo.ASCENDING)\n for key in group\n ],\n 'unique': True,\n }\n for group in groups\n ])\n return cls\n return wrapper\n\ndef get_or_http_error(Model, pk, allow_deleted=False):\n instance = Model.load(pk)\n if not allow_deleted and getattr(instance, 'is_deleted', False):\n raise HTTPError(http.GONE, data=dict(\n message_long=\"This resource has been deleted\"\n ))\n if not instance:\n raise HTTPError(http.NOT_FOUND, data=dict(\n message_long=\"No resource with that primary key could be found\"\n ))\n else:\n return instance"}]} {"messages": [{"role": "user", "content": "Write Python code that implements account.py from skarra/CalDAVClientLibrary (path: caldavclientlibrary/client/account.py)."}, {"role": "assistant", "content": "# caldavclientlibrary/client/account.py (from skarra/CalDAVClientLibrary, license: apache-2.0)\n\n##\n# Copyright (c) 2006-2013 Apple Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##\n\nfrom caldavclientlibrary.client.clientsession import CalDAVSession\nfrom caldavclientlibrary.client.principal import principalCache\n\nclass CalDAVAccount(object):\n\n def __init__(self, server, port=None, ssl=False, user=\"\", pswd=\"\", principal=None, root=None, logging=False):\n self.session = CalDAVSession(server, port, ssl, user, pswd, principal, root, logging)\n self.principal = principalCache.getPrincipal(self.session, self.session.principalPath)\n\n def setUserPswd(self, user, pswd):\n\n self.session.setUserPswd(user, pswd)\n self.principal = principalCache.getPrincipal(self.session, self.session.principalPath)\n\n def getPrincipal(self, path=None, refresh=False):\n if path:\n return principalCache.getPrincipal(self.session, path, refresh=refresh)\n elif refresh:\n self.principal = principalCache.getPrincipal(self.session, self.session.principalPath, refresh=refresh)\n\n return self.principal"}]} {"messages": [{"role": "user", "content": "Write Python code that implements macurl2path.py from googleinterns/learnbase (path: learnbase/src/main/webapp/WEB-INF/Lib/macurl2path.py)."}, {"role": "assistant", "content": "# learnbase/src/main/webapp/WEB-INF/Lib/macurl2path.py (from googleinterns/learnbase, license: apache-2.0)\n\n\"\"\"Macintosh-specific module for conversion between pathnames and URLs.\n\nDo not import directly; use urllib instead.\"\"\"\n\nimport urllib\nimport os\n\n__all__ = [\"url2pathname\",\"pathname2url\"]\n\ndef url2pathname(pathname):\n \"\"\"OS-specific conversion from a relative URL of the 'file' scheme\n to a file system path; not recommended for general use.\"\"\"\n #\n # XXXX The .. handling should be fixed...\n #\n tp = urllib.splittype(pathname)[0]\n if tp and tp != 'file':\n raise RuntimeError, 'Cannot convert non-local URL to pathname'\n # Turn starting /// into /, an empty hostname means current host\n if pathname[:3] == '///':\n pathname = pathname[2:]\n elif pathname[:2] == '//':\n raise RuntimeError, 'Cannot convert non-local URL to pathname'\n components = pathname.split('/')\n # Remove . and embedded ..\n i = 0\n while i < len(components):\n if components[i] == '.':\n del components[i]\n elif components[i] == '..' and i > 0 and \\\n components[i-1] not in ('', '..'):\n del components[i-1:i+1]\n i = i-1\n elif components[i] == '' and i > 0 and components[i-1] != '':\n del components[i]\n else:\n i = i+1\n if not components[0]:\n # Absolute unix path, don't start with colon\n rv = ':'.join(components[1:])\n else:\n # relative unix path, start with colon. First replace\n # leading .. by empty strings (giving ::file)\n i = 0\n while i < len(components) and components[i] == '..':\n components[i] = ''\n i = i + 1\n rv = ':' + ':'.join(components)\n # and finally unquote slashes and other funny characters\n return urllib.unquote(rv)\n\ndef pathname2url(pathname):\n \"\"\"OS-specific conversion from a file system path to a relative URL\n of the 'file' scheme; not recommended for general use.\"\"\"\n if '/' in pathname:\n raise RuntimeError, \"Cannot convert pathname containing slashes\"\n components = pathname.split(':')\n # Remove empty first and/or last component\n if components[0] == '':\n del components[0]\n if components[-1] == '':\n del components[-1]\n # Replace empty string ('::') by .. (will result in '/../' later)\n for i in range(len(components)):\n if components[i] == '':\n components[i] = '..'\n # Truncate names longer than 31 bytes\n components = map(_pncomp2url, components)\n\n if os.path.isabs(pathname):\n return '/' + '/'.join(components)\n else:\n return '/'.join(components)\n\ndef _pncomp2url(component):\n component = urllib.quote(component[:31], safe='') # We want to quote slashes\n return component\n\ndef test():\n for url in [\"index.html\",\n \"bar/index.html\",\n \"/foo/bar/index.html\",\n \"/foo/bar/\",\n \"/\"]:\n print '%r -> %r' % (url, url2pathname(url))\n for path in [\"drive:\",\n \"drive:dir:\",\n \"drive:dir:file\",\n \"drive:file\",\n \"file\",\n \":file\",\n \":dir:\",\n \":dir:file\"]:\n print '%r -> %r' % (path, pathname2url(path))\n\nif __name__ == '__main__':\n test()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements ec2_vpc_vgw.py from PriceChild/ansible (path: lib/ansible/modules/cloud/amazon/ec2_vpc_vgw.py)."}, {"role": "assistant", "content": "# lib/ansible/modules/cloud/amazon/ec2_vpc_vgw.py (from PriceChild/ansible, license: gpl-3.0)\n\n#!/usr/bin/python\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\nANSIBLE_METADATA = {'metadata_version': '1.0',\n 'status': ['stableinterface'],\n 'supported_by': 'curated'}\n\nDOCUMENTATION = '''\nmodule: ec2_vpc_vgw\nshort_description: Create and delete AWS VPN Virtual Gateways.\ndescription:\n - Creates AWS VPN Virtual Gateways\n - Deletes AWS VPN Virtual Gateways\n - Attaches Virtual Gateways to VPCs\n - Detaches Virtual Gateways from VPCs\nversion_added: \"2.2\"\nrequirements: [ boto3 ]\noptions:\n state:\n description:\n - present to ensure resource is created.\n - absent to remove resource\n required: false\n default: present\n choices: [ \"present\", \"absent\"]\n name:\n description:\n - name of the vgw to be created or deleted\n required: false\n type:\n description:\n - type of the virtual gateway to be created\n required: false\n choices: [ \"ipsec.1\" ]\n vpn_gateway_id:\n description:\n - vpn gateway id of an existing virtual gateway\n required: false\n vpc_id:\n description:\n - the vpc-id of a vpc to attach or detach\n required: false\n wait_timeout:\n description:\n - number of seconds to wait for status during vpc attach and detach\n required: false\n default: 320\n tags:\n description:\n - dictionary of resource tags\n required: false\n default: null\n aliases: [ \"resource_tags\" ]\nauthor: Nick Aslanidis (@naslanidis)\nextends_documentation_fragment:\n - aws\n - ec2\n'''\n\nEXAMPLES = '''\n- name: Create a new vgw attached to a specific VPC\n ec2_vpc_vgw:\n state: present\n region: ap-southeast-2\n profile: personal\n vpc_id: vpc-12345678\n name: personal-testing\n type: ipsec.1\n register: created_vgw\n\n- name: Create a new unattached vgw\n ec2_vpc_vgw:\n state: present\n region: ap-southeast-2\n profile: personal\n name: personal-testing\n type: ipsec.1\n tags:\n environment: production\n owner: ABC\n register: created_vgw\n\n- name: Remove a new vgw using the name\n ec2_vpc_vgw:\n state: absent\n region: ap-southeast-2\n profile: personal\n name: personal-testing\n type: ipsec.1\n register: deleted_vgw\n\n- name: Remove a new vgw using the vpn_gateway_id\n ec2_vpc_vgw:\n state: absent\n region: ap-southeast-2\n profile: personal\n vpn_gateway_id: vgw-3a9aa123\n register: deleted_vgw\n'''\n\nRETURN = '''\nresult:\n description: The result of the create, or delete action.\n returned: success\n type: dictionary\n'''\n\ntry:\n import json\n import time\n import botocore\n import boto3\n HAS_BOTO3 = True\nexcept ImportError:\n HAS_BOTO3 = False\n\ndef get_vgw_info(vgws):\n if not isinstance(vgws, list):\n return\n\n for vgw in vgws:\n vgw_info = {\n 'id': vgw['VpnGatewayId'],\n 'type': vgw['Type'],\n 'state': vgw['State'],\n 'vpc_id': None,\n 'tags': dict()\n }\n\n for tag in vgw['Tags']:\n vgw_info['tags'][tag['Key']] = tag['Value']\n\n if len(vgw['VpcAttachments']) != 0 and vgw['VpcAttachments'][0]['State'] == 'attached':\n vgw_info['vpc_id'] = vgw['VpcAttachments'][0]['VpcId']\n\n return vgw_info\n\ndef wait_for_status(client, module, vpn_gateway_id, status):\n polling_increment_secs = 15\n max_retries = (module.params.get('wait_timeout') / polling_increment_secs)\n status_achieved = False\n\n for x in range(0, max_retries):\n try:\n response = find_vgw(client, module, vpn_gateway_id)\n if response[0]['VpcAttachments'][0]['State'] == status:\n status_achieved = True\n break\n else:\n time.sleep(polling_increment_secs)\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n result = response\n return status_achieved, result\n\ndef attach_vgw(client, module, vpn_gateway_id):\n params = dict()\n params['VpcId'] = module.params.get('vpc_id')\n\n try:\n response = client.attach_vpn_gateway(VpnGatewayId=vpn_gateway_id, VpcId=params['VpcId'])\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n status_achieved, vgw = wait_for_status(client, module, [vpn_gateway_id], 'attached')\n if not status_achieved:\n module.fail_json(msg='Error waiting for vpc to attach to vgw - please check the AWS console')\n\n result = response\n return result\n\ndef detach_vgw(client, module, vpn_gateway_id, vpc_id=None):\n params = dict()\n params['VpcId'] = module.params.get('vpc_id')\n\n if vpc_id:\n try:\n response = client.detach_vpn_gateway(VpnGatewayId=vpn_gateway_id, VpcId=vpc_id)\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n else:\n try:\n response = client.detach_vpn_gateway(VpnGatewayId=vpn_gateway_id, VpcId=params['VpcId'])\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n status_achieved, vgw = wait_for_status(client, module, [vpn_gateway_id], 'detached')\n if not status_achieved:\n module.fail_json(msg='Error waiting for vpc to detach from vgw - please check the AWS console')\n\n result = response\n return result\n\ndef create_vgw(client, module):\n params = dict()\n params['Type'] = module.params.get('type')\n\n try:\n response = client.create_vpn_gateway(Type=params['Type'])\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n result = response\n return result\n\ndef delete_vgw(client, module, vpn_gateway_id):\n\n try:\n response = client.delete_vpn_gateway(VpnGatewayId=vpn_gateway_id)\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n #return the deleted VpnGatewayId as this is not included in the above response\n result = vpn_gateway_id\n return result\n\ndef create_tags(client, module, vpn_gateway_id):\n params = dict()\n\n try:\n response = client.create_tags(Resources=[vpn_gateway_id],Tags=load_tags(module))\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n result = response\n return result\n\ndef delete_tags(client, module, vpn_gateway_id, tags_to_delete=None):\n params = dict()\n\n if tags_to_delete:\n try:\n response = client.delete_tags(Resources=[vpn_gateway_id], Tags=tags_to_delete)\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n else:\n try:\n response = client.delete_tags(Resources=[vpn_gateway_id])\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n result = response\n return result\n\ndef load_tags(module):\n tags = []\n\n if module.params.get('tags'):\n for name, value in module.params.get('tags').items():\n tags.append({'Key': name, 'Value': str(value)})\n tags.append({'Key': \"Name\", 'Value': module.params.get('name')})\n else:\n tags.append({'Key': \"Name\", 'Value': module.params.get('name')})\n return tags\n\ndef find_tags(client, module, resource_id=None):\n\n if resource_id:\n try:\n response = client.describe_tags(Filters=[\n {'Name': 'resource-id', 'Values': [resource_id]}\n ])\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n result = response\n return result\n\ndef check_tags(client, module, existing_vgw, vpn_gateway_id):\n params = dict()\n params['Tags'] = module.params.get('tags')\n vgw = existing_vgw\n changed = False\n tags_list = {}\n\n #format tags for comparison\n for tags in existing_vgw[0]['Tags']:\n if tags['Key'] != 'Name':\n tags_list[tags['Key']] = tags['Value']\n\n # if existing tags don't match the tags arg, delete existing and recreate with new list\n if params['Tags'] is not None and tags_list != params['Tags']:\n delete_tags(client, module, vpn_gateway_id)\n create_tags(client, module, vpn_gateway_id)\n vgw = find_vgw(client, module)\n changed = True\n\n #if no tag args are supplied, delete any existing tags with the exception of the name tag\n if params['Tags'] is None and tags_list != {}:\n tags_to_delete = []\n for tags in existing_vgw[0]['Tags']:\n if tags['Key'] != 'Name':\n tags_to_delete.append(tags)\n\n delete_tags(client, module, vpn_gateway_id, tags_to_delete)\n vgw = find_vgw(client, module)\n changed = True\n\n return vgw, changed\n\ndef find_vpc(client, module):\n params = dict()\n params['vpc_id'] = module.params.get('vpc_id')\n\n if params['vpc_id']:\n try:\n response = client.describe_vpcs(VpcIds=[params['vpc_id']])\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n result = response\n return result\n\ndef find_vgw(client, module, vpn_gateway_id=None):\n params = dict()\n params['Name'] = module.params.get('name')\n params['Type'] = module.params.get('type')\n params['State'] = module.params.get('state')\n\n if params['State'] == 'present':\n try:\n response = client.describe_vpn_gateways(Filters=[\n {'Name': 'type', 'Values': [params['Type']]},\n {'Name': 'tag:Name', 'Values': [params['Name']]}\n ])\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n else:\n if vpn_gateway_id:\n try:\n response = client.describe_vpn_gateways(VpnGatewayIds=vpn_gateway_id)\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n else:\n try:\n response = client.describe_vpn_gateways(Filters=[\n {'Name': 'type', 'Values': [params['Type']]},\n {'Name': 'tag:Name', 'Values': [params['Name']]}\n ])\n except botocore.exceptions.ClientError:\n e = get_exception()\n module.fail_json(msg=str(e))\n\n result = response['VpnGateways']\n return result\n\ndef ensure_vgw_present(client, module):\n\n # If an existing vgw name and type matches our args, then a match is considered to have been\n # found and we will not create another vgw.\n\n changed = False\n params = dict()\n result = dict()\n params['Name'] = module.params.get('name')\n params['VpcId'] = module.params.get('vpc_id')\n params['Type'] = module.params.get('type')\n params['Tags'] = module.params.get('tags')\n params['VpnGatewayIds'] = module.params.get('vpn_gateway_id')\n\n # Check that a name argument has been supplied.\n if not module.params.get('name'):\n module.fail_json(msg='A name is required when a status of \\'present\\' is suppled')\n\n # check if a gateway matching our module args already exists\n existing_vgw = find_vgw(client, module)\n\n if existing_vgw != [] and existing_vgw[0]['State'] != 'deleted':\n vpn_gateway_id = existing_vgw[0]['VpnGatewayId']\n vgw, changed = check_tags(client, module, existing_vgw, vpn_gateway_id)\n\n # if a vpc_id was provided, check if it exists and if it's attached\n if params['VpcId']:\n\n # check that the vpc_id exists. If not, an exception is thrown\n vpc = find_vpc(client, module)\n current_vpc_attachments = existing_vgw[0]['VpcAttachments']\n\n if current_vpc_attachments != [] and current_vpc_attachments[0]['State'] == 'attached':\n if current_vpc_attachments[0]['VpcId'] == params['VpcId'] and current_vpc_attachments[0]['State'] == 'attached':\n changed = False\n else:\n\n # detach the existing vpc from the virtual gateway\n vpc_to_detach = current_vpc_attachments[0]['VpcId']\n detach_vgw(client, module, vpn_gateway_id, vpc_to_detach)\n time.sleep(5)\n attached_vgw = attach_vgw(client, module, vpn_gateway_id)\n vgw = find_vgw(client, module, [vpn_gateway_id])\n changed = True\n else:\n # attach the vgw to the supplied vpc\n attached_vgw = attach_vgw(client, module, vpn_gateway_id)\n vgw = find_vgw(client, module, [vpn_gateway_id])\n changed = True\n\n # if params['VpcId'] is not provided, check the vgw is attached to a vpc. if so, detach it.\n else:\n existing_vgw = find_vgw(client, module, [vpn_gateway_id])\n\n if existing_vgw[0]['VpcAttachments'] != []:\n if existing_vgw[0]['VpcAttachments'][0]['State'] == 'attached':\n # detach the vpc from the vgw\n vpc_to_detach = existing_vgw[0]['VpcAttachments'][0]['VpcId']\n detach_vgw(client, module, vpn_gateway_id, vpc_to_detach)\n changed = True\n\n vgw = find_vgw(client, module, [vpn_gateway_id])\n\n else:\n # create a new vgw\n new_vgw = create_vgw(client, module)\n changed = True\n vpn_gateway_id = new_vgw['VpnGateway']['VpnGatewayId']\n\n # tag the new virtual gateway\n create_tags(client, module, vpn_gateway_id)\n\n # return current state of the vgw\n vgw = find_vgw(client, module, [vpn_gateway_id])\n\n # if a vpc-id was supplied, attempt to attach it to the vgw\n if params['VpcId']:\n attached_vgw = attach_vgw(client, module, vpn_gateway_id)\n changed = True\n vgw = find_vgw(client, module, [vpn_gateway_id])\n\n result = get_vgw_info(vgw)\n return changed, result\n\ndef ensure_vgw_absent(client, module):\n\n # If an existing vgw name and type matches our args, then a match is considered to have been\n # found and we will take steps to delete it.\n\n changed = False\n params = dict()\n result = dict()\n params['Name'] = module.params.get('name')\n params['VpcId'] = module.params.get('vpc_id')\n params['Type'] = module.params.get('type')\n params['Tags'] = module.params.get('tags')\n params['VpnGatewayIds'] = module.params.get('vpn_gateway_id')\n\n # check if a gateway matching our module args already exists\n if params['VpnGatewayIds']:\n existing_vgw_with_id = find_vgw(client, module, [params['VpnGatewayIds']])\n if existing_vgw_with_id != [] and existing_vgw_with_id[0]['State'] != 'deleted':\n existing_vgw = existing_vgw_with_id\n if existing_vgw[0]['VpcAttachments'] != [] and existing_vgw[0]['VpcAttachments'][0]['State'] == 'attached':\n if params['VpcId']:\n if params['VpcId'] != existing_vgw[0]['VpcAttachments'][0]['VpcId']:\n module.fail_json(msg='The vpc-id provided does not match the vpc-id currently attached - please check the AWS console')\n\n else:\n # detach the vpc from the vgw\n detach_vgw(client, module, params['VpnGatewayIds'], params['VpcId'])\n deleted_vgw = delete_vgw(client, module, params['VpnGatewayIds'])\n changed = True\n\n else:\n # attempt to detach any attached vpcs\n vpc_to_detach = existing_vgw[0]['VpcAttachments'][0]['VpcId']\n detach_vgw(client, module, params['VpnGatewayIds'], vpc_to_detach)\n deleted_vgw = delete_vgw(client, module, params['VpnGatewayIds'])\n changed = True\n\n else:\n # no vpc's are attached so attempt to delete the vgw\n deleted_vgw = delete_vgw(client, module, params['VpnGatewayIds'])\n changed = True\n\n else:\n changed = False\n deleted_vgw = \"Nothing to do\"\n\n else:\n #Check that a name and type argument has been supplied if no vgw-id\n if not module.params.get('name') or not module.params.get('type'):\n module.fail_json(msg='A name and type is required when no vgw-id and a status of \\'absent\\' is suppled')\n\n existing_vgw = find_vgw(client, module)\n if existing_vgw != [] and existing_vgw[0]['State'] != 'deleted':\n vpn_gateway_id = existing_vgw[0]['VpnGatewayId']\n if existing_vgw[0]['VpcAttachments'] != [] and existing_vgw[0]['VpcAttachments'][0]['State'] == 'attached':\n if params['VpcId']:\n if params['VpcId'] != existing_vgw[0]['VpcAttachments'][0]['VpcId']:\n module.fail_json(msg='The vpc-id provided does not match the vpc-id currently attached - please check the AWS console')\n\n else:\n # detach the vpc from the vgw\n detach_vgw(client, module, vpn_gateway_id, params['VpcId'])\n\n #now that the vpc has been detached, delete the vgw\n deleted_vgw = delete_vgw(client, module, vpn_gateway_id)\n changed = True\n\n else:\n # attempt to detach any attached vpcs\n vpc_to_detach = existing_vgw[0]['VpcAttachments'][0]['VpcId']\n detach_vgw(client, module, vpn_gateway_id, vpc_to_detach)\n changed = True\n\n #now that the vpc has been detached, delete the vgw\n deleted_vgw = delete_vgw(client, module, vpn_gateway_id)\n\n else:\n # no vpc's are attached so attempt to delete the vgw\n deleted_vgw = delete_vgw(client, module, vpn_gateway_id)\n changed = True\n\n else:\n changed = False\n deleted_vgw = None\n\n result = deleted_vgw\n return changed, result\n\ndef main():\n argument_spec = ec2_argument_spec()\n argument_spec.update(dict(\n state=dict(default='present', choices=['present', 'absent']),\n region=dict(required=True),\n name=dict(),\n vpn_gateway_id=dict(),\n vpc_id=dict(),\n wait_timeout=dict(type='int', default=320),\n type=dict(default='ipsec.1', choices=['ipsec.1']),\n tags=dict(default=None, required=False, type='dict', aliases=['resource_tags']),\n )\n )\n module = AnsibleModule(argument_spec=argument_spec)\n\n if not HAS_BOTO3:\n module.fail_json(msg='json and boto3 is required.')\n\n state = module.params.get('state').lower()\n\n try:\n region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)\n client = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs)\n except botocore.exceptions.NoCredentialsError:\n e = get_exception()\n module.fail_json(msg=\"Can't authorize connection - \"+str(e))\n\n if state == 'present':\n (changed, results) = ensure_vgw_present(client, module)\n else:\n (changed, results) = ensure_vgw_absent(client, module)\n module.exit_json(changed=changed, vgw=results)\n\n# import module snippets\nfrom ansible.module_utils.basic import *\nfrom ansible.module_utils.ec2 import *\n\nif __name__ == '__main__':\n main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements answer_template.py from noelevans/sandpit (path: interview_challenges/koans/answer_template.py)."}, {"role": "assistant", "content": "# interview_challenges/koans/answer_template.py (from noelevans/sandpit, license: mit)\n\n'''\nPython questions to work on. To invoke with pytest use\n\n $ python3 answer_template.py\nor\n $ python3 -m pytest answer_template.py\n\n'''\n\nimport pytest\n\ndef inclusive_range(n):\n # For n = 5, return [1, 2, 3, 4, 5]\n return [1, 2, 3, 4, 5]\n\ndef test_inclusive_range():\n assert list(inclusive_range(5)) == [1, 2, 3, 4, 5]\n\ndef average(ol):\n # The mean for a series of numbers\n pass\n\n# def test_average():\n# assert average([2, 2, 2, 3, 4]) == 2.6\n\ndef no_whitespace(t):\n # Remove all whitespace from the start and end of the string\n pass\n\n# def test_no_whitespace():\n# assert no_whitespace(' hello ') == 'hello'\n\ndef minus_to_plus(t):\n # Replace all - symbols with + characters\n pass\n\n# def test_minus_to_plus():\n# assert minus_to_plus('hello-world') == 'hello+world'\n\ndef sum_bar_last(a, b, c):\n # a + b - c and then do it generically for arbitrary arguments\n pass\n\n# def test_sum_bar_last():\n# assert sum_bar_last(4, 5, 6) == 3\n# assert sum_bar_last(4, 5, 1, 6) == 4\n\ndef mirror(s):\n # Turn a string around so 1st char is the last, 2nd becomes penultimate\n pass\n\n# def test_mirror():\n# assert mirror('smart') == 'trams'\n\ndef odd_idxs(ol):\n # For ol = [4, 5, 6, 7, 8, 9] return [5, 7, 9] the odd indicies of ol\n pass\n\n# def test_odd_idxs():\n# assert odd_idxs([1, 2, 3, 4]) == [2, 4]\n\ndef pairs(ol):\n # For a list, return a list of the items in pairs\n # Eg [2, 3, 4, 5, 6, 7, 8, 9] -> [[2, 3], [4, 5], [6, 7], [8, 9]]\n pass\n\n# def test_pairs():\n# assert list(pairs([0, 1, 2, 3, 4, 5])) == [[0, 1], [2, 3], [4, 5]]\n# # Bonus\n# assert list(pairs([0, 1, 2, 3, 4])) == [[0, 1], [2, 3], [4]]\n\ndef blank_count(ol):\n # Count the amount of not True elements in ol\n pass\n\n# def test_blank_count():\n# assert blank_count([7, 0, None, 1, 'hi', '', 88, 0]) == 4\n\ndef flatten(ol_of_ol):\n # For [[1, 2, 3], [4, 5, 6], [7, 8]] -> [1, 2, 3, 4, 5, 6, 7, 8]\n pass\n\n# def test_flatten():\n# assert flatten([[1, 2, 3], [4, 5], [6, 7]]) == [1, 2, 3, 4, 5, 6, 7]\n\ndef element_divisible_by_3(ol):\n # Is there 1 or more elements divisible by 3 in the input\n pass\n\n# def test_element_divisible_by_3():\n# assert element_divisible_by_3([1, 2, 4, 5]) == False\n# assert element_divisible_by_3([1, 2, 6, 5]) == True\n\ndef most_common(ol):\n # Return the most common element in the input list\n pass\n\n# def test_most_common():\n# assert most_common([3, 3, 4, 4, 4, 4, 2]) == 4\n\ndef dict_reverse(d):\n # For {'a': 3, 'b': 4, 'c': 9} -> {3: 'a', 4: 'b', 9: 'c'}\n pass\n\n# def test_dict_reverse():\n# assert dict_reverse({'a': 3, 'b': 4, 'c': 9}) == {3: 'a', 4: 'b', 9: 'c'}\n\ndef atomic_weight(formula):\n\n def weight(element='Na'):\n import mendeleev\n return getattr(mendeleev, element).atomic_weight\n\n pass\n\n# def test_atomic_weight():\n# assert atomic_weight('NaCl') == pytest.approx(58.4, 0.01)\n# assert atomic_weight('CCl4') == pytest.approx(153.8, 0.01)\n# assert atomic_weight('H2O') == pytest.approx(18.0, 0.01)\n# assert atomic_weight('H2SO4') == pytest.approx(98.1, 0.01)\n# assert atomic_weight('C6H12COH') == pytest.approx(113.2, 0.01)\n\ndef sequences(max_len):\n '''\n For a given max_len return all combinations of ACGT, first of\n length 1, then 2, until max_len is reached\n eg.\n 3 -> ['A', 'C', 'G', 'T', 'AC', 'AG', 'AT', 'CG', 'CT', 'GT', 'ACG',\n 'ACT', 'AGT', 'CGT']\n '''\n pass\n\n# def test_sequences():\n# assert list(sequences(3)) == ['A', 'C', 'G', 'T', 'AC', 'AG', 'AT', 'CG',\n# 'CT', 'GT', 'ACG', 'ACT', 'AGT', 'CGT']\n\ndef stock_prices(ticker):\n prices = {\n '2019-02-14': {\n 'MSFT': 106,\n 'GOOG': 1120,\n },\n '2019-02-15': {\n 'MSFT': 108,\n 'NFLX': 351,\n },\n '2019-02-18': {\n 'MSFT': 108,\n 'GOOG': 1119,\n 'NFLX': 352,\n },\n '2019-02-19': {\n 'MSFT': 109,\n 'GOOG': 1122,\n 'NFLX': 107,\n },\n }\n\n# def test_stock_prices():\n# assert set(stock_prices('MSFT')) == set([ 106, 108, 108, 109])\n# assert list(stock_prices('MSFT')) == [ 106, 108, 108, 109]\n# assert list(stock_prices('NFLX')) == [None, 351, 352, 107]\n# assert list(stock_prices('GOOG')) == [1120, 1120, 1119, 1122]\n\ndef main():\n import os\n filename = os.path.basename(__file__)\n pytest.main([filename])\n\nif __name__ == '__main__':\n main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements tests.py from deployed/django (path: tests/dates/tests.py)."}, {"role": "assistant", "content": "# tests/dates/tests.py (from deployed/django, license: bsd-3-clause)\n\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.test import TestCase\n\nfrom .models import Article, Comment, Category\n\nclass DatesTests(TestCase):\n def test_related_model_traverse(self):\n a1 = Article.objects.create(\n title=\"First one\",\n pub_date=datetime.date(2005, 7, 28),\n )\n a2 = Article.objects.create(\n title=\"Another one\",\n pub_date=datetime.date(2010, 7, 28),\n )\n a3 = Article.objects.create(\n title=\"Third one, in the first day\",\n pub_date=datetime.date(2005, 7, 28),\n )\n\n a1.comments.create(\n text=\"Im the HULK!\",\n pub_date=datetime.date(2005, 7, 28),\n )\n a1.comments.create(\n text=\"HULK SMASH!\",\n pub_date=datetime.date(2005, 7, 29),\n )\n a2.comments.create(\n text=\"LMAO\",\n pub_date=datetime.date(2010, 7, 28),\n )\n a3.comments.create(\n text=\"+1\",\n pub_date=datetime.date(2005, 8, 29),\n )\n\n c = Category.objects.create(name=\"serious-news\")\n c.articles.add(a1, a3)\n\n self.assertQuerysetEqual(\n Comment.objects.dates(\"article__pub_date\", \"year\"), [\n datetime.date(2005, 1, 1),\n datetime.date(2010, 1, 1),\n ],\n lambda d: d,\n )\n self.assertQuerysetEqual(\n Comment.objects.dates(\"article__pub_date\", \"month\"), [\n datetime.date(2005, 7, 1),\n datetime.date(2010, 7, 1),\n ],\n lambda d: d\n )\n self.assertQuerysetEqual(\n Comment.objects.dates(\"article__pub_date\", \"day\"), [\n datetime.date(2005, 7, 28),\n datetime.date(2010, 7, 28),\n ],\n lambda d: d\n )\n self.assertQuerysetEqual(\n Article.objects.dates(\"comments__pub_date\", \"day\"), [\n datetime.date(2005, 7, 28),\n datetime.date(2005, 7, 29),\n datetime.date(2005, 8, 29),\n datetime.date(2010, 7, 28),\n ],\n lambda d: d\n )\n self.assertQuerysetEqual(\n Article.objects.dates(\"comments__approval_date\", \"day\"), []\n )\n self.assertQuerysetEqual(\n Category.objects.dates(\"articles__pub_date\", \"day\"), [\n datetime.date(2005, 7, 28),\n ],\n lambda d: d,\n )"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_bitfields.py from vFense/vFenseAgent-nix (path: agent/deps/rpm6/Python-2.7.5/lib/python2.7/ctypes/test/test_bitfields.py)."}, {"role": "assistant", "content": "# agent/deps/rpm6/Python-2.7.5/lib/python2.7/ctypes/test/test_bitfields.py (from vFense/vFenseAgent-nix, license: lgpl-3.0)\n\nfrom ctypes import *\nimport unittest\nimport os\n\nimport ctypes\nimport _ctypes_test\n\nclass BITS(Structure):\n _fields_ = [(\"A\", c_int, 1),\n (\"B\", c_int, 2),\n (\"C\", c_int, 3),\n (\"D\", c_int, 4),\n (\"E\", c_int, 5),\n (\"F\", c_int, 6),\n (\"G\", c_int, 7),\n (\"H\", c_int, 8),\n (\"I\", c_int, 9),\n\n (\"M\", c_short, 1),\n (\"N\", c_short, 2),\n (\"O\", c_short, 3),\n (\"P\", c_short, 4),\n (\"Q\", c_short, 5),\n (\"R\", c_short, 6),\n (\"S\", c_short, 7)]\n\nfunc = CDLL(_ctypes_test.__file__).unpack_bitfields\nfunc.argtypes = POINTER(BITS), c_char\n\n##for n in \"ABCDEFGHIMNOPQRS\":\n## print n, hex(getattr(BITS, n).size), getattr(BITS, n).offset\n\nclass C_Test(unittest.TestCase):\n\n def test_ints(self):\n for i in range(512):\n for name in \"ABCDEFGHI\":\n b = BITS()\n setattr(b, name, i)\n self.assertEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name)))\n\n def test_shorts(self):\n for i in range(256):\n for name in \"MNOPQRS\":\n b = BITS()\n setattr(b, name, i)\n self.assertEqual((name, i, getattr(b, name)), (name, i, func(byref(b), name)))\n\nsigned_int_types = (c_byte, c_short, c_int, c_long, c_longlong)\nunsigned_int_types = (c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong)\nint_types = unsigned_int_types + signed_int_types\n\nclass BitFieldTest(unittest.TestCase):\n\n def test_longlong(self):\n class X(Structure):\n _fields_ = [(\"a\", c_longlong, 1),\n (\"b\", c_longlong, 62),\n (\"c\", c_longlong, 1)]\n\n self.assertEqual(sizeof(X), sizeof(c_longlong))\n x = X()\n x.a, x.b, x.c = -1, 7, -1\n self.assertEqual((x.a, x.b, x.c), (-1, 7, -1))\n\n def test_ulonglong(self):\n class X(Structure):\n _fields_ = [(\"a\", c_ulonglong, 1),\n (\"b\", c_ulonglong, 62),\n (\"c\", c_ulonglong, 1)]\n\n self.assertEqual(sizeof(X), sizeof(c_longlong))\n x = X()\n self.assertEqual((x.a, x.b, x.c), (0, 0, 0))\n x.a, x.b, x.c = 7, 7, 7\n self.assertEqual((x.a, x.b, x.c), (1, 7, 1))\n\n def test_signed(self):\n for c_typ in signed_int_types:\n class X(Structure):\n _fields_ = [(\"dummy\", c_typ),\n (\"a\", c_typ, 3),\n (\"b\", c_typ, 3),\n (\"c\", c_typ, 1)]\n self.assertEqual(sizeof(X), sizeof(c_typ)*2)\n\n x = X()\n self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 0, 0))\n x.a = -1\n self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, -1, 0, 0))\n x.a, x.b = 0, -1\n self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, -1, 0))\n\n def test_unsigned(self):\n for c_typ in unsigned_int_types:\n class X(Structure):\n _fields_ = [(\"a\", c_typ, 3),\n (\"b\", c_typ, 3),\n (\"c\", c_typ, 1)]\n self.assertEqual(sizeof(X), sizeof(c_typ))\n\n x = X()\n self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 0, 0))\n x.a = -1\n self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 7, 0, 0))\n x.a, x.b = 0, -1\n self.assertEqual((c_typ, x.a, x.b, x.c), (c_typ, 0, 7, 0))\n\n def fail_fields(self, *fields):\n return self.get_except(type(Structure), \"X\", (),\n {\"_fields_\": fields})\n\n def test_nonint_types(self):\n # bit fields are not allowed on non-integer types.\n result = self.fail_fields((\"a\", c_char_p, 1))\n self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_char_p'))\n\n result = self.fail_fields((\"a\", c_void_p, 1))\n self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_void_p'))\n\n if c_int != c_long:\n result = self.fail_fields((\"a\", POINTER(c_int), 1))\n self.assertEqual(result, (TypeError, 'bit fields not allowed for type LP_c_int'))\n\n result = self.fail_fields((\"a\", c_char, 1))\n self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_char'))\n\n try:\n c_wchar\n except NameError:\n pass\n else:\n result = self.fail_fields((\"a\", c_wchar, 1))\n self.assertEqual(result, (TypeError, 'bit fields not allowed for type c_wchar'))\n\n class Dummy(Structure):\n _fields_ = []\n\n result = self.fail_fields((\"a\", Dummy, 1))\n self.assertEqual(result, (TypeError, 'bit fields not allowed for type Dummy'))\n\n def test_single_bitfield_size(self):\n for c_typ in int_types:\n result = self.fail_fields((\"a\", c_typ, -1))\n self.assertEqual(result, (ValueError, 'number of bits invalid for bit field'))\n\n result = self.fail_fields((\"a\", c_typ, 0))\n self.assertEqual(result, (ValueError, 'number of bits invalid for bit field'))\n\n class X(Structure):\n _fields_ = [(\"a\", c_typ, 1)]\n self.assertEqual(sizeof(X), sizeof(c_typ))\n\n class X(Structure):\n _fields_ = [(\"a\", c_typ, sizeof(c_typ)*8)]\n self.assertEqual(sizeof(X), sizeof(c_typ))\n\n result = self.fail_fields((\"a\", c_typ, sizeof(c_typ)*8 + 1))\n self.assertEqual(result, (ValueError, 'number of bits invalid for bit field'))\n\n def test_multi_bitfields_size(self):\n class X(Structure):\n _fields_ = [(\"a\", c_short, 1),\n (\"b\", c_short, 14),\n (\"c\", c_short, 1)]\n self.assertEqual(sizeof(X), sizeof(c_short))\n\n class X(Structure):\n _fields_ = [(\"a\", c_short, 1),\n (\"a1\", c_short),\n (\"b\", c_short, 14),\n (\"c\", c_short, 1)]\n self.assertEqual(sizeof(X), sizeof(c_short)*3)\n self.assertEqual(X.a.offset, 0)\n self.assertEqual(X.a1.offset, sizeof(c_short))\n self.assertEqual(X.b.offset, sizeof(c_short)*2)\n self.assertEqual(X.c.offset, sizeof(c_short)*2)\n\n class X(Structure):\n _fields_ = [(\"a\", c_short, 3),\n (\"b\", c_short, 14),\n (\"c\", c_short, 14)]\n self.assertEqual(sizeof(X), sizeof(c_short)*3)\n self.assertEqual(X.a.offset, sizeof(c_short)*0)\n self.assertEqual(X.b.offset, sizeof(c_short)*1)\n self.assertEqual(X.c.offset, sizeof(c_short)*2)\n\n def get_except(self, func, *args, **kw):\n try:\n func(*args, **kw)\n except Exception, detail:\n return detail.__class__, str(detail)\n\n def test_mixed_1(self):\n class X(Structure):\n _fields_ = [(\"a\", c_byte, 4),\n (\"b\", c_int, 4)]\n if os.name in (\"nt\", \"ce\"):\n self.assertEqual(sizeof(X), sizeof(c_int)*2)\n else:\n self.assertEqual(sizeof(X), sizeof(c_int))\n\n def test_mixed_2(self):\n class X(Structure):\n _fields_ = [(\"a\", c_byte, 4),\n (\"b\", c_int, 32)]\n self.assertEqual(sizeof(X), sizeof(c_int)*2)\n\n def test_mixed_3(self):\n class X(Structure):\n _fields_ = [(\"a\", c_byte, 4),\n (\"b\", c_ubyte, 4)]\n self.assertEqual(sizeof(X), sizeof(c_byte))\n\n def test_mixed_4(self):\n class X(Structure):\n _fields_ = [(\"a\", c_short, 4),\n (\"b\", c_short, 4),\n (\"c\", c_int, 24),\n (\"d\", c_short, 4),\n (\"e\", c_short, 4),\n (\"f\", c_int, 24)]\n # MSVC does NOT combine c_short and c_int into one field, GCC\n # does (unless GCC is run with '-mms-bitfields' which\n # produces code compatible with MSVC).\n if os.name in (\"nt\", \"ce\"):\n self.assertEqual(sizeof(X), sizeof(c_int) * 4)\n else:\n self.assertEqual(sizeof(X), sizeof(c_int) * 2)\n\n def test_anon_bitfields(self):\n # anonymous bit-fields gave a strange error message\n class X(Structure):\n _fields_ = [(\"a\", c_byte, 4),\n (\"b\", c_ubyte, 4)]\n class Y(Structure):\n _anonymous_ = [\"_\"]\n _fields_ = [(\"_\", X)]\n\n @unittest.skipUnless(hasattr(ctypes, \"c_uint32\"), \"c_int32 is required\")\n def test_uint32(self):\n class X(Structure):\n _fields_ = [(\"a\", c_uint32, 32)]\n x = X()\n x.a = 10\n self.assertEqual(x.a, 10)\n x.a = 0xFDCBA987\n self.assertEqual(x.a, 0xFDCBA987)\n\n @unittest.skipUnless(hasattr(ctypes, \"c_uint64\"), \"c_int64 is required\")\n def test_uint64(self):\n class X(Structure):\n _fields_ = [(\"a\", c_uint64, 64)]\n x = X()\n x.a = 10\n self.assertEqual(x.a, 10)\n x.a = 0xFEDCBA9876543211\n self.assertEqual(x.a, 0xFEDCBA9876543211)\n\nif __name__ == \"__main__\":\n unittest.main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements RegRestoreKey.py from Mj258/weiboapi (path: srapyDemo/envs/Lib/site-packages/win32/Demos/RegRestoreKey.py)."}, {"role": "assistant", "content": "# srapyDemo/envs/Lib/site-packages/win32/Demos/RegRestoreKey.py (from Mj258/weiboapi, license: mit)\n\nimport win32api, win32security\nimport win32con, ntsecuritycon, winnt\nimport os\n\ntemp_dir=win32api.GetTempPath()\nfname=win32api.GetTempFileName(temp_dir,'rsk')[0]\nprint fname\n## file can't exist\nos.remove(fname)\n\n## enable backup and restore privs\nrequired_privs = ((win32security.LookupPrivilegeValue('',ntsecuritycon.SE_BACKUP_NAME),win32con.SE_PRIVILEGE_ENABLED),\n (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_RESTORE_NAME),win32con.SE_PRIVILEGE_ENABLED)\n )\nph = win32api.GetCurrentProcess()\nth = win32security.OpenProcessToken(ph, win32con.TOKEN_READ|win32con.TOKEN_ADJUST_PRIVILEGES)\nadjusted_privs=win32security.AdjustTokenPrivileges(th,0,required_privs)\n\ntry:\n sa=win32security.SECURITY_ATTRIBUTES()\n my_sid = win32security.GetTokenInformation(th,ntsecuritycon.TokenUser)[0]\n sa.SECURITY_DESCRIPTOR.SetSecurityDescriptorOwner(my_sid,0)\n\n k, disp=win32api.RegCreateKeyEx(win32con.HKEY_CURRENT_USER, 'Python test key', SecurityAttributes=sa,\n samDesired=win32con.KEY_ALL_ACCESS, Class='some class', Options=0)\n win32api.RegSetValue(k, None, win32con.REG_SZ, 'Default value for python test key')\n\n subk, disp=win32api.RegCreateKeyEx(k, 'python test subkey', SecurityAttributes=sa,\n samDesired=win32con.KEY_ALL_ACCESS, Class='some other class', Options=0)\n win32api.RegSetValue(subk, None, win32con.REG_SZ, 'Default value for subkey')\n\n win32api.RegSaveKeyEx(k, fname, Flags=winnt.REG_STANDARD_FORMAT, SecurityAttributes=sa)\n\n restored_key, disp=win32api.RegCreateKeyEx(win32con.HKEY_CURRENT_USER, 'Python test key(restored)', SecurityAttributes=sa,\n samDesired=win32con.KEY_ALL_ACCESS, Class='restored class', Options=0)\n win32api.RegRestoreKey(restored_key, fname)\nfinally:\n win32security.AdjustTokenPrivileges(th, 0, adjusted_privs)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements sinkhorn_unbalanced_test.py from google-research/ott (path: tests/core/sinkhorn_unbalanced_test.py)."}, {"role": "assistant", "content": "# tests/core/sinkhorn_unbalanced_test.py (from google-research/ott, license: apache-2.0)\n\n# coding=utf-8\n# Copyright 2021 Google LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Tests for the Policy.\"\"\"\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport jax\nimport jax.numpy as jnp\nimport jax.test_util\n\nfrom ott.core import sinkhorn\nfrom ott.geometry import pointcloud\n\nclass SinkhornUnbalancedTest(jax.test_util.JaxTestCase):\n\n def setUp(self):\n super().setUp()\n self.rng = jax.random.PRNGKey(0)\n self.dim = 4\n self.n = 68\n self.m = 123\n self.rng, *rngs = jax.random.split(self.rng, 5)\n self.x = jax.random.uniform(rngs[0], (self.n, self.dim))\n self.y = jax.random.uniform(rngs[1], (self.m, self.dim))\n a = jax.random.uniform(rngs[2], (self.n,))\n b = jax.random.uniform(rngs[3], (self.m,))\n self.a = a / jnp.sum(a)\n self.b = b / jnp.sum(b)\n\n @parameterized.named_parameters(\n dict(\n testcase_name='lse-no-mom',\n lse_mode=True,\n momentum=1.0,\n inner_iterations=10,\n norm_error=1,\n tau_a=0.8,\n tau_b=0.9\n ),\n dict(\n testcase_name='lse-high-mom',\n lse_mode=True,\n momentum=1.5,\n inner_iterations=10,\n norm_error=1,\n tau_a=0.8,\n tau_b=0.9\n ),\n dict(\n testcase_name='scal-no-mom',\n lse_mode=False,\n momentum=1.0,\n inner_iterations=10,\n norm_error=1,\n tau_a=0.8,\n tau_b=0.9\n ),\n dict(\n testcase_name='scal-high-mom',\n lse_mode=False,\n momentum=1.5,\n inner_iterations=10,\n norm_error=1,\n tau_a=0.8,\n tau_b=0.9\n ))\n def test_euclidean_point_cloud(self, lse_mode, momentum,\n inner_iterations, norm_error, tau_a, tau_b):\n \"\"\"Two point clouds, tested with various parameters.\"\"\"\n threshold = 1e-3\n geom = pointcloud.PointCloud(self.x, self.y, epsilon=0.1)\n errors = sinkhorn.sinkhorn(\n geom,\n a=self.a,\n b=self.b,\n threshold=threshold,\n momentum=momentum,\n inner_iterations=inner_iterations,\n norm_error=norm_error,\n lse_mode=lse_mode,\n tau_a=tau_a,\n tau_b=tau_b).errors\n err = errors[errors > -1][-1]\n self.assertGreater(threshold, err)\n self.assertGreater(err, 0)\n\nif __name__ == '__main__':\n absltest.main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements handler.py from Xowap/ansible (path: lib/ansible/playbook/handler.py)."}, {"role": "assistant", "content": "# lib/ansible/playbook/handler.py (from Xowap/ansible, license: gpl-3.0)\n\n# (c) 2012-2014, Michael DeHaan \n#\n# This file is part of Ansible\n#\n# Ansible is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n\n# Make coding more python3-ish\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nfrom ansible.errors import AnsibleError\n#from ansible.inventory.host import Host\nfrom ansible.playbook.task import Task\n\nclass Handler(Task):\n\n def __init__(self, block=None, role=None, task_include=None):\n self._flagged_hosts = []\n\n super(Handler, self).__init__(block=block, role=role, task_include=task_include)\n\n def __repr__(self):\n ''' returns a human readable representation of the handler '''\n return \"HANDLER: %s\" % self.get_name()\n\n @staticmethod\n def load(data, block=None, role=None, task_include=None, variable_manager=None, loader=None):\n t = Handler(block=block, role=role, task_include=task_include)\n return t.load_data(data, variable_manager=variable_manager, loader=loader)\n\n def flag_for_host(self, host):\n #assert instanceof(host, Host)\n if host not in self._flagged_hosts:\n self._flagged_hosts.append(host)\n\n def has_triggered(self, host):\n return host in self._flagged_hosts\n\n def serialize(self):\n result = super(Handler, self).serialize()\n result['is_handler'] = True\n return result"}]} {"messages": [{"role": "user", "content": "Write Python code that implements SearchDialogBase.py from MattsFleaMarket/python-for-android (path: python3-alpha/python3-src/Lib/idlelib/SearchDialogBase.py)."}, {"role": "assistant", "content": "# python3-alpha/python3-src/Lib/idlelib/SearchDialogBase.py (from MattsFleaMarket/python-for-android, license: apache-2.0)\n\nfrom tkinter import *\n\nclass SearchDialogBase:\n\n title = \"Search Dialog\"\n icon = \"Search\"\n needwrapbutton = 1\n\n def __init__(self, root, engine):\n self.root = root\n self.engine = engine\n self.top = None\n\n def open(self, text, searchphrase=None):\n self.text = text\n if not self.top:\n self.create_widgets()\n else:\n self.top.deiconify()\n self.top.tkraise()\n if searchphrase:\n self.ent.delete(0,\"end\")\n self.ent.insert(\"end\",searchphrase)\n self.ent.focus_set()\n self.ent.selection_range(0, \"end\")\n self.ent.icursor(0)\n self.top.grab_set()\n\n def close(self, event=None):\n if self.top:\n self.top.grab_release()\n self.top.withdraw()\n\n def create_widgets(self):\n top = Toplevel(self.root)\n top.bind(\"\", self.default_command)\n top.bind(\"\", self.close)\n top.protocol(\"WM_DELETE_WINDOW\", self.close)\n top.wm_title(self.title)\n top.wm_iconname(self.icon)\n self.top = top\n\n self.row = 0\n self.top.grid_columnconfigure(0, pad=2, weight=0)\n self.top.grid_columnconfigure(1, pad=2, minsize=100, weight=100)\n\n self.create_entries()\n self.create_option_buttons()\n self.create_other_buttons()\n return self.create_command_buttons()\n\n def make_entry(self, label, var):\n l = Label(self.top, text=label)\n l.grid(row=self.row, column=0, sticky=\"nw\")\n e = Entry(self.top, textvariable=var, exportselection=0)\n e.grid(row=self.row, column=1, sticky=\"nwe\")\n self.row = self.row + 1\n return e\n\n def make_frame(self,labeltext=None):\n if labeltext:\n l = Label(self.top, text=labeltext)\n l.grid(row=self.row, column=0, sticky=\"nw\")\n f = Frame(self.top)\n f.grid(row=self.row, column=1, columnspan=1, sticky=\"nwe\")\n self.row = self.row + 1\n return f\n\n def make_button(self, label, command, isdef=0):\n b = Button(self.buttonframe,\n text=label, command=command,\n default=isdef and \"active\" or \"normal\")\n cols,rows=self.buttonframe.grid_size()\n b.grid(pady=1,row=rows,column=0,sticky=\"ew\")\n self.buttonframe.grid(rowspan=rows+1)\n return b\n\n def create_entries(self):\n self.ent = self.make_entry(\"Find:\", self.engine.patvar)\n\n def create_option_buttons(self):\n f = self.make_frame(\"Options\")\n\n btn = Checkbutton(f, anchor=\"w\",\n variable=self.engine.revar,\n text=\"Regular expression\")\n btn.pack(side=\"left\", fill=\"both\")\n if self.engine.isre():\n btn.select()\n\n btn = Checkbutton(f, anchor=\"w\",\n variable=self.engine.casevar,\n text=\"Match case\")\n btn.pack(side=\"left\", fill=\"both\")\n if self.engine.iscase():\n btn.select()\n\n btn = Checkbutton(f, anchor=\"w\",\n variable=self.engine.wordvar,\n text=\"Whole word\")\n btn.pack(side=\"left\", fill=\"both\")\n if self.engine.isword():\n btn.select()\n\n if self.needwrapbutton:\n btn = Checkbutton(f, anchor=\"w\",\n variable=self.engine.wrapvar,\n text=\"Wrap around\")\n btn.pack(side=\"left\", fill=\"both\")\n if self.engine.iswrap():\n btn.select()\n\n def create_other_buttons(self):\n f = self.make_frame(\"Direction\")\n\n #lbl = Label(f, text=\"Direction: \")\n #lbl.pack(side=\"left\")\n\n btn = Radiobutton(f, anchor=\"w\",\n variable=self.engine.backvar, value=1,\n text=\"Up\")\n btn.pack(side=\"left\", fill=\"both\")\n if self.engine.isback():\n btn.select()\n\n btn = Radiobutton(f, anchor=\"w\",\n variable=self.engine.backvar, value=0,\n text=\"Down\")\n btn.pack(side=\"left\", fill=\"both\")\n if not self.engine.isback():\n btn.select()\n\n def create_command_buttons(self):\n #\n # place button frame on the right\n f = self.buttonframe = Frame(self.top)\n f.grid(row=0,column=2,padx=2,pady=2,ipadx=2,ipady=2)\n\n b = self.make_button(\"close\", self.close)\n b.lower()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements package_update_checker.py from kevlar1818/dotfiles (path: bspwm/.config/polybar/package_update_checker.py)."}, {"role": "assistant", "content": "# bspwm/.config/polybar/package_update_checker.py (from kevlar1818/dotfiles, license: mit)\n\n#!/usr/bin/env python\nimport sys\nfrom subprocess import run\n\ndef colorize_text(text, color):\n return f'%{{F{color}}}{text}%{{F-}}'\n\nif __name__ == '__main__':\n xrdb = run('xrdb -query', shell=True, capture_output=True, text=True, check=True)\n\n raw_colors = (\n line.replace('*', '').split(':')\n for line in xrdb.stdout.split('\\n')\n if line.startswith('*')\n )\n\n x_colors = {\n name: color.strip()\n for name, color in raw_colors\n }\n\n checkupdates = run('checkupdates', capture_output=True, text=True)\n\n # checkupdates returns non-zero with no output if there's no packages to\n # upgrade\n if checkupdates.returncode != 0 and checkupdates.stderr:\n print(colorize_text('ERR', x_colors['color1']))\n sys.exit(0)\n\n stripped_lines = (\n line.strip()\n for line in checkupdates.stdout.split('\\n')\n )\n packages = [\n line.split(' ')[0]\n for line in stripped_lines\n if line\n ]\n\n if 'linux' in packages:\n color = x_colors['color3']\n\n elif packages:\n color = x_colors['foreground']\n\n else:\n color = x_colors['color8']\n\n print(colorize_text(len(packages), color))"}]} {"messages": [{"role": "user", "content": "Write Python code that implements tcp.py from proxysh/Safejumper-for-Desktop (path: buildlinux/env64/lib/python2.7/site-packages/twisted/internet/iocpreactor/tcp.py)."}, {"role": "assistant", "content": "# buildlinux/env64/lib/python2.7/site-packages/twisted/internet/iocpreactor/tcp.py (from proxysh/Safejumper-for-Desktop, license: gpl-2.0)\n\n# Copyright (c) Twisted Matrix Laboratories.\n# See LICENSE for details.\n\n\"\"\"\nTCP support for IOCP reactor\n\"\"\"\n\nimport socket, operator, errno, struct\n\nfrom zope.interface import implementer, classImplements\n\nfrom twisted.internet import interfaces, error, address, main, defer\nfrom twisted.internet.protocol import Protocol\nfrom twisted.internet.abstract import _LogOwner, isIPv6Address\nfrom twisted.internet.tcp import _SocketCloser, Connector as TCPConnector\nfrom twisted.internet.tcp import _AbortingMixin, _BaseBaseClient, _BaseTCPClient\nfrom twisted.python import log, failure, reflect\nfrom twisted.python.compat import _PY3, nativeString\n\nfrom twisted.internet.iocpreactor import iocpsupport as _iocp, abstract\nfrom twisted.internet.iocpreactor.interfaces import IReadWriteHandle\nfrom twisted.internet.iocpreactor.const import ERROR_IO_PENDING\nfrom twisted.internet.iocpreactor.const import SO_UPDATE_CONNECT_CONTEXT\nfrom twisted.internet.iocpreactor.const import SO_UPDATE_ACCEPT_CONTEXT\nfrom twisted.internet.iocpreactor.const import ERROR_CONNECTION_REFUSED\nfrom twisted.internet.iocpreactor.const import ERROR_NETWORK_UNREACHABLE\n\ntry:\n from twisted.internet._newtls import startTLS as _startTLS\nexcept ImportError:\n _startTLS = None\n\n# ConnectEx returns these. XXX: find out what it does for timeout\nconnectExErrors = {\n ERROR_CONNECTION_REFUSED: errno.WSAECONNREFUSED,\n ERROR_NETWORK_UNREACHABLE: errno.WSAENETUNREACH,\n }\n\n@implementer(IReadWriteHandle, interfaces.ITCPTransport,\n interfaces.ISystemHandle)\nclass Connection(abstract.FileHandle, _SocketCloser, _AbortingMixin):\n \"\"\"\n @ivar TLS: C{False} to indicate the connection is in normal TCP mode,\n C{True} to indicate that TLS has been started and that operations must\n be routed through the L{TLSMemoryBIOProtocol} instance.\n \"\"\"\n TLS = False\n\n def __init__(self, sock, proto, reactor=None):\n abstract.FileHandle.__init__(self, reactor)\n self.socket = sock\n self.getFileHandle = sock.fileno\n self.protocol = proto\n\n def getHandle(self):\n return self.socket\n\n def dataReceived(self, rbuffer):\n \"\"\"\n @param rbuffer: Data received.\n @type rbuffer: L{bytes} or L{bytearray}\n \"\"\"\n if isinstance(rbuffer, bytes):\n pass\n elif isinstance(rbuffer, bytearray):\n # XXX: some day, we'll have protocols that can handle raw buffers\n rbuffer = bytes(rbuffer)\n else:\n raise TypeError(\"data must be bytes or bytearray, not \" +\n type(rbuffer))\n\n self.protocol.dataReceived(rbuffer)\n\n def readFromHandle(self, bufflist, evt):\n return _iocp.recv(self.getFileHandle(), bufflist, evt)\n\n def writeToHandle(self, buff, evt):\n \"\"\"\n Send C{buff} to current file handle using C{_iocp.send}. The buffer\n sent is limited to a size of C{self.SEND_LIMIT}.\n \"\"\"\n writeView = memoryview(buff)\n return _iocp.send(self.getFileHandle(),\n writeView[0:self.SEND_LIMIT].tobytes(), evt)\n\n def _closeWriteConnection(self):\n try:\n self.socket.shutdown(1)\n except socket.error:\n pass\n p = interfaces.IHalfCloseableProtocol(self.protocol, None)\n if p:\n try:\n p.writeConnectionLost()\n except:\n f = failure.Failure()\n log.err()\n self.connectionLost(f)\n\n def readConnectionLost(self, reason):\n p = interfaces.IHalfCloseableProtocol(self.protocol, None)\n if p:\n try:\n p.readConnectionLost()\n except:\n log.err()\n self.connectionLost(failure.Failure())\n else:\n self.connectionLost(reason)\n\n def connectionLost(self, reason):\n if self.disconnected:\n return\n abstract.FileHandle.connectionLost(self, reason)\n isClean = (reason is None or\n not reason.check(error.ConnectionAborted))\n self._closeSocket(isClean)\n protocol = self.protocol\n del self.protocol\n del self.socket\n del self.getFileHandle\n protocol.connectionLost(reason)\n\n def logPrefix(self):\n \"\"\"\n Return the prefix to log with when I own the logging thread.\n \"\"\"\n return self.logstr\n\n def getTcpNoDelay(self):\n return operator.truth(self.socket.getsockopt(socket.IPPROTO_TCP,\n socket.TCP_NODELAY))\n\n def setTcpNoDelay(self, enabled):\n self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, enabled)\n\n def getTcpKeepAlive(self):\n return operator.truth(self.socket.getsockopt(socket.SOL_SOCKET,\n socket.SO_KEEPALIVE))\n\n def setTcpKeepAlive(self, enabled):\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, enabled)\n\n if _startTLS is not None:\n def startTLS(self, contextFactory, normal=True):\n \"\"\"\n @see: L{ITLSTransport.startTLS}\n \"\"\"\n _startTLS(self, contextFactory, normal, abstract.FileHandle)\n\n def write(self, data):\n \"\"\"\n Write some data, either directly to the underlying handle or, if TLS\n has been started, to the L{TLSMemoryBIOProtocol} for it to encrypt and\n send.\n\n @see: L{twisted.internet.interfaces.ITransport.write}\n \"\"\"\n if self.disconnected:\n return\n if self.TLS:\n self.protocol.write(data)\n else:\n abstract.FileHandle.write(self, data)\n\n def writeSequence(self, iovec):\n \"\"\"\n Write some data, either directly to the underlying handle or, if TLS\n has been started, to the L{TLSMemoryBIOProtocol} for it to encrypt and\n send.\n\n @see: L{twisted.internet.interfaces.ITransport.writeSequence}\n \"\"\"\n if self.disconnected:\n return\n if self.TLS:\n self.protocol.writeSequence(iovec)\n else:\n abstract.FileHandle.writeSequence(self, iovec)\n\n def loseConnection(self, reason=None):\n \"\"\"\n Close the underlying handle or, if TLS has been started, first shut it\n down.\n\n @see: L{twisted.internet.interfaces.ITransport.loseConnection}\n \"\"\"\n if self.TLS:\n if self.connected and not self.disconnecting:\n self.protocol.loseConnection()\n else:\n abstract.FileHandle.loseConnection(self, reason)\n\n def registerProducer(self, producer, streaming):\n \"\"\"\n Register a producer.\n\n If TLS is enabled, the TLS connection handles this.\n \"\"\"\n if self.TLS:\n # Registering a producer before we're connected shouldn't be a\n # problem. If we end up with a write(), that's already handled in\n # the write() code above, and there are no other potential\n # side-effects.\n self.protocol.registerProducer(producer, streaming)\n else:\n abstract.FileHandle.registerProducer(self, producer, streaming)\n\n def unregisterProducer(self):\n \"\"\"\n Unregister a producer.\n\n If TLS is enabled, the TLS connection handles this.\n \"\"\"\n if self.TLS:\n self.protocol.unregisterProducer()\n else:\n abstract.FileHandle.unregisterProducer(self)\n\nif _startTLS is not None:\n classImplements(Connection, interfaces.ITLSTransport)\n\nclass Client(_BaseBaseClient, _BaseTCPClient, Connection):\n \"\"\"\n @ivar _tlsClientDefault: Always C{True}, indicating that this is a client\n connection, and by default when TLS is negotiated this class will act as\n a TLS client.\n \"\"\"\n addressFamily = socket.AF_INET\n socketType = socket.SOCK_STREAM\n\n _tlsClientDefault = True\n _commonConnection = Connection\n\n def __init__(self, host, port, bindAddress, connector, reactor):\n # ConnectEx documentation says socket _has_ to be bound\n if bindAddress is None:\n bindAddress = ('', 0)\n self.reactor = reactor # createInternetSocket needs this\n _BaseTCPClient.__init__(self, host, port, bindAddress, connector,\n reactor)\n\n def createInternetSocket(self):\n \"\"\"\n Create a socket registered with the IOCP reactor.\n\n @see: L{_BaseTCPClient}\n \"\"\"\n return self.reactor.createSocket(self.addressFamily, self.socketType)\n\n def _collectSocketDetails(self):\n \"\"\"\n Clean up potentially circular references to the socket and to its\n C{getFileHandle} method.\n\n @see: L{_BaseBaseClient}\n \"\"\"\n del self.socket, self.getFileHandle\n\n def _stopReadingAndWriting(self):\n \"\"\"\n Remove the active handle from the reactor.\n\n @see: L{_BaseBaseClient}\n \"\"\"\n self.reactor.removeActiveHandle(self)\n\n def cbConnect(self, rc, data, evt):\n if rc:\n rc = connectExErrors.get(rc, rc)\n self.failIfNotConnected(error.getConnectError((rc,\n errno.errorcode.get(rc, 'Unknown error'))))\n else:\n self.socket.setsockopt(\n socket.SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT,\n struct.pack('P', self.socket.fileno()))\n self.protocol = self.connector.buildProtocol(self.getPeer())\n self.connected = True\n logPrefix = self._getLogPrefix(self.protocol)\n self.logstr = logPrefix + \",client\"\n if self.protocol is None:\n # Factory.buildProtocol is allowed to return None. In that\n # case, make up a protocol to satisfy the rest of the\n # implementation; connectionLost is going to be called on\n # something, for example. This is easier than adding special\n # case support for a None protocol throughout the rest of the\n # transport implementation.\n self.protocol = Protocol()\n # But dispose of the connection quickly.\n self.loseConnection()\n else:\n self.protocol.makeConnection(self)\n self.startReading()\n\n def doConnect(self):\n if not hasattr(self, \"connector\"):\n # this happens if we connector.stopConnecting in\n # factory.startedConnecting\n return\n assert _iocp.have_connectex\n self.reactor.addActiveHandle(self)\n evt = _iocp.Event(self.cbConnect, self)\n\n rc = _iocp.connect(self.socket.fileno(), self.realAddress, evt)\n if rc and rc != ERROR_IO_PENDING:\n self.cbConnect(rc, 0, evt)\n\nclass Server(Connection):\n \"\"\"\n Serverside socket-stream connection class.\n\n I am a serverside network connection transport; a socket which came from an\n accept() on a server.\n\n @ivar _tlsClientDefault: Always C{False}, indicating that this is a server\n connection, and by default when TLS is negotiated this class will act as\n a TLS server.\n \"\"\"\n\n _tlsClientDefault = False\n\n def __init__(self, sock, protocol, clientAddr, serverAddr, sessionno, reactor):\n \"\"\"\n Server(sock, protocol, client, server, sessionno)\n\n Initialize me with a socket, a protocol, a descriptor for my peer (a\n tuple of host, port describing the other end of the connection), an\n instance of Port, and a session number.\n \"\"\"\n Connection.__init__(self, sock, protocol, reactor)\n self.serverAddr = serverAddr\n self.clientAddr = clientAddr\n self.sessionno = sessionno\n logPrefix = self._getLogPrefix(self.protocol)\n self.logstr = \"%s,%s,%s\" % (logPrefix, sessionno, self.clientAddr.host)\n self.repstr = \"<%s #%s on %s>\" % (self.protocol.__class__.__name__,\n self.sessionno, self.serverAddr.port)\n self.connected = True\n self.startReading()\n\n def __repr__(self):\n \"\"\"\n A string representation of this connection.\n \"\"\"\n return self.repstr\n\n def getHost(self):\n \"\"\"\n Returns an IPv4Address.\n\n This indicates the server's address.\n \"\"\"\n return self.serverAddr\n\n def getPeer(self):\n \"\"\"\n Returns an IPv4Address.\n\n This indicates the client's address.\n \"\"\"\n return self.clientAddr\n\nclass Connector(TCPConnector):\n def _makeTransport(self):\n return Client(self.host, self.port, self.bindAddress, self,\n self.reactor)\n\n@implementer(interfaces.IListeningPort)\nclass Port(_SocketCloser, _LogOwner):\n\n connected = False\n disconnected = False\n disconnecting = False\n addressFamily = socket.AF_INET\n socketType = socket.SOCK_STREAM\n _addressType = address.IPv4Address\n sessionno = 0\n\n # Actual port number being listened on, only set to a non-None\n # value when we are actually listening.\n _realPortNumber = None\n\n # A string describing the connections which will be created by this port.\n # Normally this is C{\"TCP\"}, since this is a TCP port, but when the TLS\n # implementation re-uses this class it overrides the value with C{\"TLS\"}.\n # Only used for logging.\n _type = 'TCP'\n\n def __init__(self, port, factory, backlog=50, interface='', reactor=None):\n self.port = port\n self.factory = factory\n self.backlog = backlog\n self.interface = interface\n self.reactor = reactor\n if isIPv6Address(interface):\n self.addressFamily = socket.AF_INET6\n self._addressType = address.IPv6Address\n\n def __repr__(self):\n if self._realPortNumber is not None:\n return \"<%s of %s on %s>\" % (self.__class__,\n self.factory.__class__,\n self._realPortNumber)\n else:\n return \"<%s of %s (not listening)>\" % (self.__class__,\n self.factory.__class__)\n\n def startListening(self):\n try:\n skt = self.reactor.createSocket(self.addressFamily,\n self.socketType)\n # TODO: resolve self.interface if necessary\n if self.addressFamily == socket.AF_INET6:\n addr = socket.getaddrinfo(self.interface, self.port)[0][4]\n else:\n addr = (self.interface, self.port)\n skt.bind(addr)\n except socket.error as le:\n raise error.CannotListenError(self.interface, self.port, le)\n\n self.addrLen = _iocp.maxAddrLen(skt.fileno())\n\n # Make sure that if we listened on port 0, we update that to\n # reflect what the OS actually assigned us.\n self._realPortNumber = skt.getsockname()[1]\n\n log.msg(\"%s starting on %s\" % (self._getLogPrefix(self.factory),\n self._realPortNumber))\n\n self.factory.doStart()\n skt.listen(self.backlog)\n self.connected = True\n self.disconnected = False\n self.reactor.addActiveHandle(self)\n self.socket = skt\n self.getFileHandle = self.socket.fileno\n self.doAccept()\n\n def loseConnection(self, connDone=failure.Failure(main.CONNECTION_DONE)):\n \"\"\"\n Stop accepting connections on this port.\n\n This will shut down my socket and call self.connectionLost().\n It returns a deferred which will fire successfully when the\n port is actually closed.\n \"\"\"\n self.disconnecting = True\n if self.connected:\n self.deferred = defer.Deferred()\n self.reactor.callLater(0, self.connectionLost, connDone)\n return self.deferred\n\n stopListening = loseConnection\n\n def _logConnectionLostMsg(self):\n \"\"\"\n Log message for closing port\n \"\"\"\n log.msg('(%s Port %s Closed)' % (self._type, self._realPortNumber))\n\n def connectionLost(self, reason):\n \"\"\"\n Cleans up the socket.\n \"\"\"\n self._logConnectionLostMsg()\n self._realPortNumber = None\n d = None\n if hasattr(self, \"deferred\"):\n d = self.deferred\n del self.deferred\n\n self.disconnected = True\n self.reactor.removeActiveHandle(self)\n self.connected = False\n self._closeSocket(True)\n del self.socket\n del self.getFileHandle\n\n try:\n self.factory.doStop()\n except:\n self.disconnecting = False\n if d is not None:\n d.errback(failure.Failure())\n else:\n raise\n else:\n self.disconnecting = False\n if d is not None:\n d.callback(None)\n\n def logPrefix(self):\n \"\"\"\n Returns the name of my class, to prefix log entries with.\n \"\"\"\n return reflect.qual(self.factory.__class__)\n\n def getHost(self):\n \"\"\"\n Returns an IPv4Address.\n\n This indicates the server's address.\n \"\"\"\n host, port = self.socket.getsockname()[:2]\n return self._addressType('TCP', host, port)\n\n def cbAccept(self, rc, data, evt):\n self.handleAccept(rc, evt)\n if not (self.disconnecting or self.disconnected):\n self.doAccept()\n\n def handleAccept(self, rc, evt):\n if self.disconnecting or self.disconnected:\n return False\n\n # possible errors:\n # (WSAEMFILE, WSAENOBUFS, WSAENFILE, WSAENOMEM, WSAECONNABORTED)\n if rc:\n log.msg(\"Could not accept new connection -- %s (%s)\" %\n (errno.errorcode.get(rc, 'unknown error'), rc))\n return False\n else:\n evt.newskt.setsockopt(\n socket.SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,\n struct.pack('P', self.socket.fileno()))\n family, lAddr, rAddr = _iocp.get_accept_addrs(evt.newskt.fileno(),\n evt.buff)\n if not _PY3:\n # In _makesockaddr(), we use the Win32 API which\n # gives us an address of the form: (unicode host, port).\n # Only on Python 2 do we need to convert it to a\n # non-unicode str.\n # On Python 3, we leave it alone as unicode.\n lAddr = (nativeString(lAddr[0]), lAddr[1])\n rAddr = (nativeString(rAddr[0]), rAddr[1])\n assert family == self.addressFamily\n\n protocol = self.factory.buildProtocol(\n self._addressType('TCP', rAddr[0], rAddr[1]))\n if protocol is None:\n evt.newskt.close()\n else:\n s = self.sessionno\n self.sessionno = s+1\n transport = Server(evt.newskt, protocol,\n self._addressType('TCP', rAddr[0], rAddr[1]),\n self._addressType('TCP', lAddr[0], lAddr[1]),\n s, self.reactor)\n protocol.makeConnection(transport)\n return True\n\n def doAccept(self):\n evt = _iocp.Event(self.cbAccept, self)\n\n # see AcceptEx documentation\n evt.buff = buff = bytearray(2 * (self.addrLen + 16))\n\n evt.newskt = newskt = self.reactor.createSocket(self.addressFamily,\n self.socketType)\n rc = _iocp.accept(self.socket.fileno(), newskt.fileno(), buff, evt)\n\n if rc and rc != ERROR_IO_PENDING:\n self.handleAccept(rc, evt)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements component_editor.py from playm2mboy/edx-platform (path: common/test/acceptance/pages/studio/component_editor.py)."}, {"role": "assistant", "content": "# common/test/acceptance/pages/studio/component_editor.py (from playm2mboy/edx-platform, license: agpl-3.0)\n\nfrom bok_choy.page_object import PageObject\nfrom selenium.webdriver.common.keys import Keys\nfrom ..common.utils import click_css\nfrom selenium.webdriver.support.ui import Select\n\nclass BaseComponentEditorView(PageObject):\n \"\"\"\n A base :class:`.PageObject` for the component and visibility editors.\n\n This class assumes that the editor is our default editor as displayed for xmodules.\n \"\"\"\n BODY_SELECTOR = '.xblock-editor'\n\n def __init__(self, browser, locator):\n \"\"\"\n Args:\n browser (selenium.webdriver): The Selenium-controlled browser that this page is loaded in.\n locator (str): The locator that identifies which xblock this :class:`.xblock-editor` relates to.\n \"\"\"\n super(BaseComponentEditorView, self).__init__(browser)\n self.locator = locator\n\n def is_browser_on_page(self):\n return self.q(css='{}[data-locator=\"{}\"]'.format(self.BODY_SELECTOR, self.locator)).present\n\n def _bounded_selector(self, selector):\n \"\"\"\n Return `selector`, but limited to this particular `ComponentEditorView` context\n \"\"\"\n return '{}[data-locator=\"{}\"] {}'.format(\n self.BODY_SELECTOR,\n self.locator,\n selector\n )\n\n def url(self):\n \"\"\"\n Returns None because this is not directly accessible via URL.\n \"\"\"\n return None\n\n def save(self):\n \"\"\"\n Clicks save button.\n \"\"\"\n click_css(self, 'a.action-save')\n\n def cancel(self):\n \"\"\"\n Clicks cancel button.\n \"\"\"\n click_css(self, 'a.action-cancel', require_notification=False)\n\nclass ComponentEditorView(BaseComponentEditorView):\n \"\"\"\n A :class:`.PageObject` representing the rendered view of a component editor.\n \"\"\"\n def get_setting_element(self, label):\n \"\"\"\n Returns the index of the setting entry with given label (display name) within the Settings modal.\n \"\"\"\n settings_button = self.q(css='.edit-xblock-modal .editor-modes .settings-button')\n if settings_button.is_present():\n settings_button.click()\n setting_labels = self.q(css=self._bounded_selector('.metadata_edit .wrapper-comp-setting .setting-label'))\n for index, setting in enumerate(setting_labels):\n if setting.text == label:\n return self.q(css=self._bounded_selector('.metadata_edit div.wrapper-comp-setting .setting-input'))[index]\n return None\n\n def set_field_value_and_save(self, label, value):\n \"\"\"\n Sets the text field with given label (display name) to the specified value, and presses Save.\n \"\"\"\n elem = self.get_setting_element(label)\n\n # Clear the current value, set the new one, then\n # Tab to move to the next field (so change event is triggered).\n elem.clear()\n elem.send_keys(value)\n elem.send_keys(Keys.TAB)\n self.save()\n\n def set_select_value_and_save(self, label, value):\n \"\"\"\n Sets the select with given label (display name) to the specified value, and presses Save.\n \"\"\"\n elem = self.get_setting_element(label)\n select = Select(elem)\n select.select_by_value(value)\n self.save()\n\n def get_selected_option_text(self, label):\n \"\"\"\n Returns the text of the first selected option for the select with given label (display name).\n \"\"\"\n elem = self.get_setting_element(label)\n if elem:\n select = Select(elem)\n return select.first_selected_option.text\n else:\n return None\n\nclass ComponentVisibilityEditorView(BaseComponentEditorView):\n \"\"\"\n A :class:`.PageObject` representing the rendered view of a component visibility editor.\n \"\"\"\n OPTION_SELECTOR = '.modal-section-content .field'\n\n @property\n def all_options(self):\n \"\"\"\n Return all visibility options.\n \"\"\"\n return self.q(css=self._bounded_selector(self.OPTION_SELECTOR)).results\n\n @property\n def selected_options(self):\n \"\"\"\n Return all selected visibility options.\n \"\"\"\n results = []\n for option in self.all_options:\n button = option.find_element_by_css_selector('input.input')\n if button.is_selected():\n results.append(option)\n return results\n\n def select_option(self, label_text, save=True):\n \"\"\"\n Click the first option which has a label matching `label_text`.\n\n Arguments:\n label_text (str): Text of a label accompanying the input\n which should be clicked.\n save (boolean): Whether the \"save\" button should be clicked\n afterwards.\n Returns:\n bool: Whether the label was found and clicked.\n \"\"\"\n for option in self.all_options:\n if label_text in option.text:\n option.click()\n if save:\n self.save()\n return True\n return False"}]} {"messages": [{"role": "user", "content": "Write Python code that implements borgish.py from maiome-development/malibu (path: src/malibu/design/borgish.py)."}, {"role": "assistant", "content": "# src/malibu/design/borgish.py (from maiome-development/malibu, license: unlicense)\n\n# -*- coding: utf-8 -*-\n\n__doc__ = \"\"\"\nmalibu.design.borgish\n---------------------\n\nBorgish was designed as a more extended implementation of Alex Martelli's\nBorg design pattern, which aims to provide state consistency similar to\na singleton design, but without the terribleness of singletons.\n\"\"\"\n\nclass SharedState(object):\n \"\"\" This class is for meta-class use as a state machine for\n persistence so we don't use any singleton design.\n\n The module is \"Borg-ish\", as this implementation is loosely\n based on the Borg design pattern by Alex Martelli.\n \"\"\"\n\n @classmethod\n def __initialize_states(cls):\n \"\"\" Initializes a class-scoped states dictionary to store named\n states.\n \"\"\"\n\n if not hasattr(cls, \"_SharedState__states\"):\n cls.__states = {}\n\n def __init__(self, *args, **kw):\n \"\"\" Calls the classes state dict initializer and loads initial\n state, if provided.\n \"\"\"\n\n self.__initialize_states()\n\n if \"state\" in kw:\n self.load_state(kw.get(\"state\"))\n\n def load_state(self, state):\n \"\"\" Loads state into the class, overwriting all data that was\n previously stored.\n\n :param str state: Name of state to load.\n :rtype: None\n :returns: None\n :raises NameError: If the named state does not exist.\n \"\"\"\n\n if state in self.__states:\n self.__dict__ = self.__states[state]\n else:\n raise NameError(\"Can't load non-existent state '%s'.\" % (state))\n\n def save_state(self, state):\n \"\"\" Saves class state into a namespace on the class' shared state\n dict.\n\n :param str state: Name of state to save.\n :rtype: None\n :returns: None\n :raises NameError: If the named state already exists.\n \"\"\"\n\n if state in self.__states:\n raise NameError(\"Can't overwrite stored state '%s'.\" % (state))\n self.__states.update({state: self.__dict__})\n\n def drop_state(self, state):\n \"\"\" Drops the state specified from the class' shared state dictionary.\n\n :param str state: Name of state to drop.\n :rtype: bool\n :returns: True if state was dropped, False otherwise.\n \"\"\"\n\n if state not in self.__states:\n return False\n\n state_dict = self.__states.pop(state, None)\n if not state_dict:\n return False\n\n return True"}]} {"messages": [{"role": "user", "content": "Write Python code that implements test_init.py from joopert/home-assistant (path: tests/components/fan/test_init.py)."}, {"role": "assistant", "content": "# tests/components/fan/test_init.py (from joopert/home-assistant, license: apache-2.0)\n\n\"\"\"Tests for fan platforms.\"\"\"\n\nimport unittest\n\nfrom homeassistant.components.fan import FanEntity\nimport pytest\n\nclass BaseFan(FanEntity):\n \"\"\"Implementation of the abstract FanEntity.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the fan.\"\"\"\n pass\n\nclass TestFanEntity(unittest.TestCase):\n \"\"\"Test coverage for base fan entity class.\"\"\"\n\n def setUp(self):\n \"\"\"Set up test data.\"\"\"\n self.fan = BaseFan()\n\n def tearDown(self):\n \"\"\"Tear down unit test data.\"\"\"\n self.fan = None\n\n def test_fanentity(self):\n \"\"\"Test fan entity methods.\"\"\"\n assert \"off\" == self.fan.state\n assert 0 == len(self.fan.speed_list)\n assert 0 == self.fan.supported_features\n assert {\"speed_list\": []} == self.fan.state_attributes\n # Test set_speed not required\n self.fan.oscillate(True)\n with pytest.raises(NotImplementedError):\n self.fan.set_speed(\"slow\")\n with pytest.raises(NotImplementedError):\n self.fan.turn_on()\n with pytest.raises(NotImplementedError):\n self.fan.turn_off()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements conv_net_SSIM.py from michaelneuder/image_quality_analysis (path: bin/nets/old/conv_net_SSIM.py)."}, {"role": "assistant", "content": "# bin/nets/old/conv_net_SSIM.py (from michaelneuder/image_quality_analysis, license: mit)\n\n#!/usr/bin/env python3\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\nimport numpy as np\nnp.set_printoptions(threshold=np.nan)\nimport tensorflow as tf\nimport time\nfrom PIL import Image as im\n\ndef convolve_inner_layers(x, W, b):\n y = tf.nn.conv2d(x, W, strides = [1,1,1,1], padding='SAME')\n y = tf.nn.bias_add(y, b)\n return tf.nn.tanh(y)\n\ndef convolve_ouput_layer(x, W, b):\n y = tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')\n y = tf.nn.bias_add(y, b)\n return y\n\ndef conv_net(x, W, b):\n conv1 = convolve_inner_layers(x, W['weights1'], b['bias1'])\n conv2 = convolve_inner_layers(conv1, W['weights2'], b['bias2'])\n conv3 = convolve_inner_layers(conv2, W['weights3'], b['bias3'])\n output = convolve_ouput_layer(conv3, W['weights_out'], b['bias_out'])\n return output\n\ndef get_epoch(x, y, n):\n input_size = x.shape[0]\n number_batches = int(input_size / n)\n extra_examples = input_size % n\n batches = {}\n batch_indices = np.arange(input_size)\n np.random.shuffle(batch_indices)\n for i in range(number_batches):\n temp_indices = batch_indices[n*i:n*(i+1)]\n temp_x = []\n temp_y = []\n for j in temp_indices:\n temp_x.append(x[j])\n temp_y.append(y[j])\n batches[i] = [np.asarray(temp_x), np.asarray(temp_y)]\n if extra_examples != 0:\n extra_indices = batch_indices[input_size-extra_examples:input_size]\n temp_x = []\n temp_y = []\n for k in extra_indices:\n temp_x.append(x[k])\n temp_y.append(y[k])\n batches[i+1] = [np.asarray(temp_x), np.asarray(temp_y)]\n return batches\n\ndef main():\n # a bit of ascii fun\n print(' _ _ _ ')\n print(' ___ ___ _ ____ _____ | |_ _| |_(_) ___ _ __ ')\n print(' / __/ _ \\| \\'_ \\ \\ / / _ \\| | | | | __| |/ _ \\| \\'_ \\ ')\n print(' | (_| (_) | | | \\ V / (_) | | |_| | |_| | (_) | | | |')\n print(' \\___\\___/|_| |_|\\_/ \\___/|_|\\__,_|\\__|_|\\___/|_| |_|')\n print('=======================================================')\n print(\"initializing variables ...\")\n\n filter_dim = 11\n\n weights = {\n 'weights1': tf.Variable((1/(filter_dim*filter_dim*2))*tf.random_normal([filter_dim,filter_dim,2,30])),\n 'weights2': tf.Variable((1/(30*filter_dim*filter_dim))*tf.random_normal([filter_dim,filter_dim,30,20])),\n 'weights3': tf.Variable((1/(20*filter_dim*filter_dim))*tf.random_normal([filter_dim,filter_dim,20,10])),\n 'weights_out': tf.Variable((1/(10*filter_dim*filter_dim))*tf.random_normal([filter_dim,filter_dim,10,1]))\n }\n biases = {\n 'bias1': tf.Variable((1/(filter_dim*filter_dim*2))*tf.random_normal([30])),\n 'bias2': tf.Variable((1/(30*filter_dim*filter_dim))*tf.random_normal([20])),\n 'bias3': tf.Variable((1/(20*filter_dim*filter_dim))*tf.random_normal([10])),\n 'bias_out': tf.Variable((1/(10*filter_dim*filter_dim))*tf.random_normal([1]))\n }\n\n # tf Graph input\n x = tf.placeholder(tf.float32, [None, 96, 96, 2])\n y = tf.placeholder(tf.float32, [None, 96, 96, 1])\n\n # data\n print(\"loading data ...\")\n original_images_train = np.loadtxt('../../../data/sample_data/orig_500.txt')\n reconstructed_images_train = np.loadtxt('../../../data/sample_data/recon_500.txt')\n comparison_images_train = np.loadtxt('../../../data/sample_data/comp_500.txt')\n original_images_test = np.loadtxt('../../../data/sample_data/orig_140.txt')\n reconstructed_images_test = np.loadtxt('../../../data/sample_data/recon_140.txt')\n comparison_images_test = np.loadtxt('../../../data/sample_data/comp_140.txt')\n\n # get size of training and testing set\n train_size = original_images_train.shape[0]\n test_size = original_images_test.shape[0]\n\n # reshaping the result data to --- (num pics), 96, 96, 1\n comparison_images_train = np.reshape(comparison_images_train, [train_size, 96, 96, 1])\n comparison_images_test = np.reshape(comparison_images_test, [test_size, 96, 96, 1])\n\n # zipping data\n combined_data_train = np.reshape(np.dstack((original_images_train, reconstructed_images_train)), [train_size,96,96,2])\n combined_data_test = np.reshape(np.dstack((original_images_test, reconstructed_images_test)), [test_size,96,96,2])\n\n #### temporary edit --- don't forget to remove\n for i in range(96,192):\n print(original_images_train[0][i], reconstructed_images_train[0][i], combined_data_train[0][1][i-96])\n exit()\n\n # paramaters\n learning_rate = .0001\n epochs = 100\n\n # model\n prediction = conv_net(x, weights, biases)\n\n # saving state\n saver = tf.train.Saver()\n\n # loss and optimization\n cost = tf.reduce_mean(tf.square(tf.subtract(prediction, y)))\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n\n # session\n init = tf.global_variables_initializer()\n with tf.Session() as sess:\n sess.run(init)\n global_step = 0\n epoch_count = 0\n start_time = time.time()\n print(\"starting training ... \")\n while epoch_count < epochs:\n epoch_time = time.time()\n print('-------------------------------------------------------')\n print('beginning epoch {} ...'.format(epoch_count))\n epoch = get_epoch(combined_data_train, comparison_images_train, 50)\n for i in epoch:\n x_data_train, y_data_train = np.asarray(epoch[i][0]), np.asarray(epoch[i][1])\n sess.run(optimizer, feed_dict={x : x_data_train, y : y_data_train})\n loss = sess.run(cost, feed_dict={x : x_data_train, y : y_data_train})\n print(\" - training global_step {}. current error: {}. \".format(global_step, loss))\n global_step+=1\n print('epoch {} completed in {} seconds. current error = {}'.format(epoch_count, time.time()-epoch_time, loss))\n print('-------------------------------------------------------')\n epoch_count+=1\n print('optimization finished!')\n\n prediction = np.asarray(sess.run(prediction, feed_dict={x : [combined_data_train[0]]}))\n target = np.asarray([comparison_images_test[0]])\n print(prediction.shape, target.shape)\n with open('post_training.csv', mode = 'w') as write_file:\n write_file.write('target, prediction\\n')\n for i in range(96):\n for j in range(96):\n write_file.write(str(float(target[0][i][j][0])) + ', ' + str(float(prediction[0][i][j][0])) + '\\n')\n write_file.close()\n\nif __name__ == '__main__':\n main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements diffsettings.py from bbenko/shinkicker (path: django/core/management/commands/diffsettings.py)."}, {"role": "assistant", "content": "# django/core/management/commands/diffsettings.py (from bbenko/shinkicker, license: bsd-3-clause)\n\nfrom django.core.management.base import NoArgsCommand\n\ndef module_to_dict(module, omittable=lambda k: k.startswith('_')):\n \"Converts a module namespace to a Python dictionary. Used by get_settings_diff.\"\n return dict([(k, repr(v)) for k, v in module.__dict__.items() if not omittable(k)])\n\nclass Command(NoArgsCommand):\n help = \"\"\"Displays differences between the current settings.py and Django's\n default settings. Settings that don't appear in the defaults are\n followed by \"###\".\"\"\"\n\n requires_model_validation = False\n\n def handle_noargs(self, **options):\n # Inspired by Postfix's \"postconf -n\".\n from django.conf import settings, global_settings\n\n # Because settings are imported lazily, we need to explicitly load them.\n settings._setup()\n\n user_settings = module_to_dict(settings._wrapped)\n default_settings = module_to_dict(global_settings)\n\n output = []\n keys = user_settings.keys()\n keys.sort()\n for key in keys:\n if key not in default_settings:\n output.append(\"%s = %s ###\" % (key, user_settings[key]))\n elif user_settings[key] != default_settings[key]:\n output.append(\"%s = %s\" % (key, user_settings[key]))\n return '\\n'.join(output)"}]} {"messages": [{"role": "user", "content": "Write Python code that implements __openerp__.py from CopeX/odoo (path: addons/hw_scale/__openerp__.py)."}, {"role": "assistant", "content": "# addons/hw_scale/__openerp__.py (from CopeX/odoo, license: agpl-3.0)\n\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n{\n 'name': 'Weighting Scale Hardware Driver',\n 'version': '1.0',\n 'category': 'Hardware Drivers',\n 'sequence': 6,\n 'summary': 'Hardware Driver for Weighting Scales',\n 'website': 'https://www.odoo.com/page/point-of-sale',\n 'description': \"\"\"\nBarcode Scanner Hardware Driver\n================================\n\nThis module allows the point of sale to connect to a scale using a USB HSM Serial Scale Interface,\nsuch as the Mettler Toledo Ariva.\n\n\"\"\",\n 'author': 'OpenERP SA',\n 'depends': ['hw_proxy'],\n 'external_dependencies': {'python': ['serial']},\n 'test': [\n ],\n 'installable': True,\n 'auto_install': False,\n}\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:"}]} {"messages": [{"role": "user", "content": "Write Python code that implements 0001_initial.py from aksh1/wagtail-cookiecutter-foundation (path: {{cookiecutter.repo_name}}/pages/migrations/0001_initial.py)."}, {"role": "assistant", "content": "# {{cookiecutter.repo_name}}/pages/migrations/0001_initial.py (from aksh1/wagtail-cookiecutter-foundation, license: mit)\n\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.db.models.deletion\nimport modelcluster.fields\nimport wagtail.wagtailcore.fields\nimport wagtail.wagtailcore.blocks\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('wagtailimages', '0006_add_verbose_names'),\n ('wagtaildocs', '0003_add_verbose_names'),\n ('wagtailcore', '0001_squashed_0016_change_page_url_path_to_text_field'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ContentBlock',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('link_external', models.URLField(verbose_name=b'External link', blank=True)),\n ('title', models.CharField(max_length=255)),\n ('body', wagtail.wagtailcore.fields.RichTextField()),\n ('summary', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ('slug', models.SlugField()),\n ('link_document', models.ForeignKey(related_name='+', blank=True, to='wagtaildocs.Document', null=True)),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='FaqsPage',\n fields=[\n ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),\n ('body', wagtail.wagtailcore.fields.StreamField([(b'faq_question', wagtail.wagtailcore.blocks.CharBlock(classname=b'full title')), (b'faq_answer', wagtail.wagtailcore.blocks.RichTextBlock())])),\n ],\n options={\n 'abstract': False,\n },\n bases=('wagtailcore.page',),\n ),\n migrations.CreateModel(\n name='HomePage',\n fields=[\n ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),\n ('title_text', wagtail.wagtailcore.fields.RichTextField(null=True, blank=True)),\n ('body', wagtail.wagtailcore.fields.RichTextField(null=True, blank=True)),\n ],\n options={\n 'verbose_name': 'Homepage',\n },\n bases=('wagtailcore.page',),\n ),\n migrations.CreateModel(\n name='HomePageCarouselItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('sort_order', models.IntegerField(null=True, editable=False, blank=True)),\n ('link_external', models.URLField(verbose_name=b'External link', blank=True)),\n ('embed_url', models.URLField(verbose_name=b'Embed URL', blank=True)),\n ('caption', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ('image', models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', null=True)),\n ('link_document', models.ForeignKey(related_name='+', blank=True, to='wagtaildocs.Document', null=True)),\n ],\n options={\n 'ordering': ['sort_order'],\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='HomePageContentItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('sort_order', models.IntegerField(null=True, editable=False, blank=True)),\n ('link_external', models.URLField(verbose_name=b'External link', blank=True)),\n ('title', models.CharField(max_length=100)),\n ('content', wagtail.wagtailcore.fields.RichTextField(null=True, blank=True)),\n ('summary', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ('slug', models.SlugField()),\n ('image', models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', null=True)),\n ('link_document', models.ForeignKey(related_name='+', blank=True, to='wagtaildocs.Document', null=True)),\n ],\n options={\n 'ordering': ['sort_order'],\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='HomePageRelatedLink',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('sort_order', models.IntegerField(null=True, editable=False, blank=True)),\n ('link_external', models.URLField(verbose_name=b'External link', blank=True)),\n ('title', models.CharField(help_text=b'Link title', max_length=255)),\n ('link_document', models.ForeignKey(related_name='+', blank=True, to='wagtaildocs.Document', null=True)),\n ],\n options={\n 'ordering': ['sort_order'],\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='StandardIndexPage',\n fields=[\n ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),\n ('subtitle', models.CharField(max_length=255, blank=True)),\n ('intro', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ('feed_image', models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', help_text=b'An optional image to represent the page', null=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=('wagtailcore.page',),\n ),\n migrations.CreateModel(\n name='StandardIndexPageRelatedLink',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('sort_order', models.IntegerField(null=True, editable=False, blank=True)),\n ('link_external', models.URLField(verbose_name=b'External link', blank=True)),\n ('title', models.CharField(help_text=b'Link title', max_length=255)),\n ('link_document', models.ForeignKey(related_name='+', blank=True, to='wagtaildocs.Document', null=True)),\n ],\n options={\n 'ordering': ['sort_order'],\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='StandardPage',\n fields=[\n ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='wagtailcore.Page')),\n ('subtitle', models.CharField(max_length=255, blank=True)),\n ('intro', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ('body', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ('feed_image', models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', null=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=('wagtailcore.page',),\n ),\n migrations.CreateModel(\n name='StandardPageCarouselItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('sort_order', models.IntegerField(null=True, editable=False, blank=True)),\n ('link_external', models.URLField(verbose_name=b'External link', blank=True)),\n ('embed_url', models.URLField(verbose_name=b'Embed URL', blank=True)),\n ('caption', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ('image', models.ForeignKey(related_name='+', on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', null=True)),\n ('link_document', models.ForeignKey(related_name='+', blank=True, to='wagtaildocs.Document', null=True)),\n ('link_page', models.ForeignKey(related_name='+', blank=True, to='wagtailcore.Page', null=True)),\n ('page', modelcluster.fields.ParentalKey(related_name='carousel_items', to='pages.StandardPage')),\n ],\n options={\n 'ordering': ['sort_order'],\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='StandardPageRelatedLink',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('sort_order', models.IntegerField(null=True, editable=False, blank=True)),\n ('link_external', models.URLField(verbose_name=b'External link', blank=True)),\n ('title', models.CharField(help_text=b'Link title', max_length=255)),\n ('link_document', models.ForeignKey(related_name='+', blank=True, to='wagtaildocs.Document', null=True)),\n ('link_page', models.ForeignKey(related_name='+', blank=True, to='wagtailcore.Page', null=True)),\n ('page', modelcluster.fields.ParentalKey(related_name='related_links', to='pages.StandardPage')),\n ],\n options={\n 'ordering': ['sort_order'],\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='Testimonial',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('link_external', models.URLField(verbose_name=b'External link', blank=True)),\n ('name', models.CharField(max_length=150)),\n ('text', models.CharField(max_length=255)),\n ('link_document', models.ForeignKey(related_name='+', blank=True, to='wagtaildocs.Document', null=True)),\n ('link_page', models.ForeignKey(related_name='+', blank=True, to='wagtailcore.Page', null=True)),\n ('page', models.ForeignKey(related_name='testimonials', blank=True, to='wagtailcore.Page', null=True)),\n ('photo', models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, blank=True, to='wagtailimages.Image', null=True)),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.AddField(\n model_name='standardindexpagerelatedlink',\n name='link_page',\n field=models.ForeignKey(related_name='+', blank=True, to='wagtailcore.Page', null=True),\n ),\n migrations.AddField(\n model_name='standardindexpagerelatedlink',\n name='page',\n field=modelcluster.fields.ParentalKey(related_name='related_links', to='pages.StandardIndexPage'),\n ),\n migrations.AddField(\n model_name='homepagerelatedlink',\n name='link_page',\n field=models.ForeignKey(related_name='+', blank=True, to='wagtailcore.Page', null=True),\n ),\n migrations.AddField(\n model_name='homepagerelatedlink',\n name='page',\n field=modelcluster.fields.ParentalKey(related_name='related_links', to='pages.HomePage'),\n ),\n migrations.AddField(\n model_name='homepagecontentitem',\n name='link_page',\n field=models.ForeignKey(related_name='+', blank=True, to='wagtailcore.Page', null=True),\n ),\n migrations.AddField(\n model_name='homepagecontentitem',\n name='page',\n field=modelcluster.fields.ParentalKey(related_name='content_items', to='pages.HomePage'),\n ),\n migrations.AddField(\n model_name='homepagecarouselitem',\n name='link_page',\n field=models.ForeignKey(related_name='+', blank=True, to='wagtailcore.Page', null=True),\n ),\n migrations.AddField(\n model_name='homepagecarouselitem',\n name='page',\n field=modelcluster.fields.ParentalKey(related_name='carousel_items', to='pages.HomePage'),\n ),\n migrations.AddField(\n model_name='contentblock',\n name='link_page',\n field=models.ForeignKey(related_name='+', blank=True, to='wagtailcore.Page', null=True),\n ),\n migrations.AddField(\n model_name='contentblock',\n name='page',\n field=models.ForeignKey(related_name='contentblocks', blank=True, to='wagtailcore.Page', null=True),\n ),\n ]"}]} {"messages": [{"role": "user", "content": "Write Python code that implements VIEW_SUBWINDOW.py from jpaalasm/pyglet (path: contrib/scene2d/tests/scene2d/VIEW_SUBWINDOW.py)."}, {"role": "assistant", "content": "# contrib/scene2d/tests/scene2d/VIEW_SUBWINDOW.py (from jpaalasm/pyglet, license: bsd-3-clause)\n\n#!/usr/bin/env python\n\n'''Testing flat map allow_oob enforcement.\n\nPress 0-9 to set the size of the view in the window (1=10%, 0=100%)\n\nPress arrow keys to move view focal point (little ball) around map.\nPress \"o\" to turn allow_oob on and off.\n\nYou should see no black border with allow_oob=False.\n\nPress escape or close the window to finish the test.\n'''\n\n__docformat__ = 'restructuredtext'\n__version__ = '$Id$'\n\nimport unittest\nfrom render_base import RenderBase\nimport scene2d\nfrom pyglet.event import *\nfrom pyglet.window.event import *\nfrom pyglet.window import key\nfrom scene2d.debug import gen_rect_map\n\nclass OOBTest(RenderBase):\n def test_main(self):\n self.init_window(256, 256)\n self.set_map(gen_rect_map([[{}]*10]*10, 32, 32))\n\n @event(self.w)\n def on_text(text):\n if text == 'o':\n self.view.allow_oob = not self.view.allow_oob\n print 'NOTE: allow_oob =', self.view.allow_oob\n return\n try:\n size = int(25.6 * float(text))\n if size == 0: size = 256\n c = self.view.camera\n c.width = c.height = size\n c.x = c.y = (256-size)/2\n except:\n return EVENT_UNHANDLED\n print 'NOTE: allow_oob =', self.view.allow_oob\n\n self.show_focus()\n\n self.run_test()\nif __name__ == '__main__':\n unittest.main()"}]} {"messages": [{"role": "user", "content": "Write Python code that implements request.py from erkanay/django (path: django/http/request.py)."}, {"role": "assistant", "content": "# django/http/request.py (from erkanay/django, license: bsd-3-clause)\n\nfrom __future__ import unicode_literals\n\nimport copy\nimport os\nimport re\nimport sys\nfrom io import BytesIO\nfrom itertools import chain\nfrom pprint import pformat\n\nfrom django.conf import settings\nfrom django.core import signing\nfrom django.core.exceptions import DisallowedHost, ImproperlyConfigured\nfrom django.core.files import uploadhandler\nfrom django.http.multipartparser import MultiPartParser, MultiPartParserError\nfrom django.utils import six\nfrom django.utils.datastructures import MultiValueDict, ImmutableList\nfrom django.utils.encoding import force_bytes, force_text, force_str, iri_to_uri\nfrom django.utils.six.moves.urllib.parse import parse_qsl, urlencode, quote, urljoin, urlsplit\n\nRAISE_ERROR = object()\nabsolute_http_url_re = re.compile(r\"^https?://\", re.I)\nhost_validation_re = re.compile(r\"^([a-z0-9.-]+|\\[[a-f0-9]*:[a-f0-9:]+\\])(:\\d+)?$\")\n\nclass UnreadablePostError(IOError):\n pass\n\nclass RawPostDataException(Exception):\n \"\"\"\n You cannot access raw_post_data from a request that has\n multipart/* POST data if it has been accessed via POST,\n FILES, etc..\n \"\"\"\n pass\n\nclass HttpRequest(object):\n \"\"\"A basic HTTP request.\"\"\"\n\n # The encoding used in GET/POST dicts. None means use default setting.\n _encoding = None\n _upload_handlers = []\n\n def __init__(self):\n # WARNING: The `WSGIRequest` subclass doesn't call `super`.\n # Any variable assignment made here should also happen in\n # `WSGIRequest.__init__()`.\n\n self.GET = QueryDict(mutable=True)\n self.POST = QueryDict(mutable=True)\n self.COOKIES = {}\n self.META = {}\n self.FILES = MultiValueDict()\n\n self.path = ''\n self.path_info = ''\n self.method = None\n self.resolver_match = None\n self._post_parse_error = False\n\n def __repr__(self):\n return build_request_repr(self)\n\n def get_host(self):\n \"\"\"Returns the HTTP host using the environment or request headers.\"\"\"\n # We try three options, in order of decreasing preference.\n if settings.USE_X_FORWARDED_HOST and (\n 'HTTP_X_FORWARDED_HOST' in self.META):\n host = self.META['HTTP_X_FORWARDED_HOST']\n elif 'HTTP_HOST' in self.META:\n host = self.META['HTTP_HOST']\n else:\n # Reconstruct the host using the algorithm from PEP 333.\n host = self.META['SERVER_NAME']\n server_port = str(self.META['SERVER_PORT'])\n if server_port != ('443' if self.is_secure() else '80'):\n host = '%s:%s' % (host, server_port)\n\n # There is no hostname validation when DEBUG=True\n if settings.DEBUG:\n return host\n\n domain, port = split_domain_port(host)\n if domain and validate_host(domain, settings.ALLOWED_HOSTS):\n return host\n else:\n msg = \"Invalid HTTP_HOST header: %r.\" % host\n if domain:\n msg += \" You may need to add %r to ALLOWED_HOSTS.\" % domain\n else:\n msg += \" The domain name provided is not valid according to RFC 1034/1035.\"\n raise DisallowedHost(msg)\n\n def get_full_path(self):\n # RFC 3986 requires query string arguments to be in the ASCII range.\n # Rather than crash if this doesn't happen, we encode defensively.\n return '%s%s' % (\n self.path,\n ('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) if self.META.get('QUERY_STRING', '') else ''\n )\n\n def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):\n \"\"\"\n Attempts to return a signed cookie. If the signature fails or the\n cookie has expired, raises an exception... unless you provide the\n default argument in which case that value will be returned instead.\n \"\"\"\n try:\n cookie_value = self.COOKIES[key]\n except KeyError:\n if default is not RAISE_ERROR:\n return default\n else:\n raise\n try:\n value = signing.get_cookie_signer(salt=key + salt).unsign(\n cookie_value, max_age=max_age)\n except signing.BadSignature:\n if default is not RAISE_ERROR:\n return default\n else:\n raise\n return value\n\n def build_absolute_uri(self, location=None):\n \"\"\"\n Builds an absolute URI from the location and the variables available in\n this request. If no ``location`` is specified, the absolute URI is\n built on ``request.get_full_path()``. Anyway, if the location is\n absolute, it is simply converted to an RFC 3987 compliant URI and\n returned and if location is relative or is scheme-relative (i.e.,\n ``//example.com/``), it is urljoined to a base URL constructed from the\n request variables.\n \"\"\"\n if location is None:\n # Make it an absolute url (but schemeless and domainless) for the\n # edge case that the path starts with '//'.\n location = '//%s' % self.get_full_path()\n bits = urlsplit(location)\n if not (bits.scheme and bits.netloc):\n current_uri = '{scheme}://{host}{path}'.format(scheme=self.scheme,\n host=self.get_host(),\n path=self.path)\n # Join the constructed URL with the provided location, which will\n # allow the provided ``location`` to apply query strings to the\n # base path as well as override the host, if it begins with //\n location = urljoin(current_uri, location)\n return iri_to_uri(location)\n\n def _get_scheme(self):\n return 'https' if os.environ.get(\"HTTPS\") == \"on\" else 'http'\n\n @property\n def scheme(self):\n # First, check the SECURE_PROXY_SSL_HEADER setting.\n if settings.SECURE_PROXY_SSL_HEADER:\n try:\n header, value = settings.SECURE_PROXY_SSL_HEADER\n except ValueError:\n raise ImproperlyConfigured(\n 'The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values.'\n )\n if self.META.get(header, None) == value:\n return 'https'\n # Failing that, fall back to _get_scheme(), which is a hook for\n # subclasses to implement.\n return self._get_scheme()\n\n def is_secure(self):\n return self.scheme == 'https'\n\n def is_ajax(self):\n return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'\n\n @property\n def encoding(self):\n return self._encoding\n\n @encoding.setter\n def encoding(self, val):\n \"\"\"\n Sets the encoding used for GET/POST accesses. If the GET or POST\n dictionary has already been created, it is removed and recreated on the\n next access (so that it is decoded correctly).\n \"\"\"\n self._encoding = val\n if hasattr(self, '_get'):\n del self._get\n if hasattr(self, '_post'):\n del self._post\n\n def _initialize_handlers(self):\n self._upload_handlers = [uploadhandler.load_handler(handler, self)\n for handler in settings.FILE_UPLOAD_HANDLERS]\n\n @property\n def upload_handlers(self):\n if not self._upload_handlers:\n # If there are no upload handlers defined, initialize them from settings.\n self._initialize_handlers()\n return self._upload_handlers\n\n @upload_handlers.setter\n def upload_handlers(self, upload_handlers):\n if hasattr(self, '_files'):\n raise AttributeError(\"You cannot set the upload handlers after the upload has been processed.\")\n self._upload_handlers = upload_handlers\n\n def parse_file_upload(self, META, post_data):\n \"\"\"Returns a tuple of (POST QueryDict, FILES MultiValueDict).\"\"\"\n self.upload_handlers = ImmutableList(\n self.upload_handlers,\n warning=\"You cannot alter upload handlers after the upload has been processed.\"\n )\n parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)\n return parser.parse()\n\n @property\n def body(self):\n if not hasattr(self, '_body'):\n if self._read_started:\n raise RawPostDataException(\"You cannot access body after reading from request's data stream\")\n try:\n self._body = self.read()\n except IOError as e:\n six.reraise(UnreadablePostError, UnreadablePostError(*e.args), sys.exc_info()[2])\n self._stream = BytesIO(self._body)\n return self._body\n\n def _mark_post_parse_error(self):\n self._post = QueryDict('')\n self._files = MultiValueDict()\n self._post_parse_error = True\n\n def _load_post_and_files(self):\n \"\"\"Populate self._post and self._files if the content-type is a form type\"\"\"\n if self.method != 'POST':\n self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict()\n return\n if self._read_started and not hasattr(self, '_body'):\n self._mark_post_parse_error()\n return\n\n if self.META.get('CONTENT_TYPE', '').startswith('multipart/form-data'):\n if hasattr(self, '_body'):\n # Use already read data\n data = BytesIO(self._body)\n else:\n data = self\n try:\n self._post, self._files = self.parse_file_upload(self.META, data)\n except MultiPartParserError:\n # An error occurred while parsing POST data. Since when\n # formatting the error the request handler might access\n # self.POST, set self._post and self._file to prevent\n # attempts to parse POST data again.\n # Mark that an error occurred. This allows self.__repr__ to\n # be explicit about it instead of simply representing an\n # empty POST\n self._mark_post_parse_error()\n raise\n elif self.META.get('CONTENT_TYPE', '').startswith('application/x-www-form-urlencoded'):\n self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()\n else:\n self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict()\n\n def close(self):\n if hasattr(self, '_files'):\n for f in chain.from_iterable(l[1] for l in self._files.lists()):\n f.close()\n\n # File-like and iterator interface.\n #\n # Expects self._stream to be set to an appropriate source of bytes by\n # a corresponding request subclass (e.g. WSGIRequest).\n # Also when request data has already been read by request.POST or\n # request.body, self._stream points to a BytesIO instance\n # containing that data.\n\n def read(self, *args, **kwargs):\n self._read_started = True\n try:\n return self._stream.read(*args, **kwargs)\n except IOError as e:\n six.reraise(UnreadablePostError, UnreadablePostError(*e.args), sys.exc_info()[2])\n\n def readline(self, *args, **kwargs):\n self._read_started = True\n try:\n return self._stream.readline(*args, **kwargs)\n except IOError as e:\n six.reraise(UnreadablePostError, UnreadablePostError(*e.args), sys.exc_info()[2])\n\n def xreadlines(self):\n while True:\n buf = self.readline()\n if not buf:\n break\n yield buf\n\n __iter__ = xreadlines\n\n def readlines(self):\n return list(iter(self))\n\nclass QueryDict(MultiValueDict):\n \"\"\"\n A specialized MultiValueDict which represents a query string.\n\n A QueryDict can be used to represent GET or POST data. It subclasses\n MultiValueDict since keys in such data can be repeated, for instance\n in the data from a form with a `` form element.\"\"\"\n\n def __init__(self, *args, **attrs):\n super(Select, self).__init__(*args, **attrs)\n self.options = []\n # Undetermined yet:\n self.selectedIndex = None\n # we have no forced value\n self._forced_value = NoValue\n\n def force_value(self, value):\n \"\"\"Like setting a value, except forces it (even for, say, hidden\n fields).\n \"\"\"\n self._forced_value = value\n\n def value__set(self, value):\n if self._forced_value is not NoValue:\n self._forced_value = NoValue\n for i, (option, checked) in enumerate(self.options):\n if option == utils.stringify(value):\n self.selectedIndex = i\n break\n else:\n raise ValueError(\n \"Option %r not found (from %s)\"\n % (value, ', '.join(\n [repr(o) for o, c in self.options])))\n\n def value__get(self):\n if self._forced_value is not NoValue:\n return self._forced_value\n elif self.selectedIndex is not None:\n return self.options[self.selectedIndex][0]\n else:\n for option, checked in self.options:\n if checked:\n return option\n else:\n if self.options:\n return self.options[0][0]\n\n value = property(value__get, value__set)\n\nclass MultipleSelect(Field):\n \"\"\"Field representing ````\"\"\"\n\n def value__get(self):\n if self.selectedIndex is not None:\n return self.options[self.selectedIndex][0]\n else:\n for option, checked in self.options:\n if checked:\n return option\n else:\n return None\n\n value = property(value__get, Select.value__set)\n\nclass Checkbox(Field):\n \"\"\"Field representing ````\n\n .. attribute:: checked\n\n Returns True if checkbox is checked.\n\n \"\"\"\n\n def __init__(self, *args, **attrs):\n super(Checkbox, self).__init__(*args, **attrs)\n self._checked = 'checked' in attrs\n\n def value__set(self, value):\n self._checked = not not value\n\n def value__get(self):\n if self._checked:\n if self._value is None:\n return 'on'\n else:\n return self._value\n else:\n return None\n\n value = property(value__get, value__set)\n\n def checked__get(self):\n return bool(self._checked)\n\n def checked__set(self, value):\n self._checked = not not value\n\n checked = property(checked__get, checked__set)\n\nclass Text(Field):\n \"\"\"Field representing ````\"\"\"\n\nclass File(Field):\n \"\"\"Field representing ````\"\"\"\n\n # TODO: This doesn't actually handle file uploads and enctype\n def value__get(self):\n if self._value is None:\n return ''\n else:\n return self._value\n\n value = property(value__get, Field.value__set)\n\nclass Textarea(Text):\n \"\"\"Field representing ``