<commit_before>"""
Support for KNX/IP sensors.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.knx/
"""

import voluptuous as vol

from custom_components.xknx import ATTR_DISCOVER_DEVICES, DATA_XKNX
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
    CONF_NAME, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE,
    DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_PRESSURE)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity

CONF_ADDRESS = 'address'
CONF_TYPE = 'type'

DEFAULT_NAME = 'XKNX Sensor'
DEPENDENCIES = ['xknx']

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_ADDRESS): cv.string,
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Optional(CONF_TYPE): cv.string,
})

async def async_setup_platform(hass, config, async_add_entities,
                               discovery_info=None):
    """Set up sensor(s) for KNX platform."""
    if discovery_info is not None:
        async_add_entities_discovery(hass, discovery_info, async_add_entities)
    else:
        async_add_entities_config(hass, config, async_add_entities)

@callback
def async_add_entities_discovery(hass, discovery_info, async_add_entities):
    """Set up sensors for KNX platform configured via xknx.yaml."""
    entities = []
    for device_name in discovery_info[ATTR_DISCOVER_DEVICES]:
        device = hass.data[DATA_XKNX].xknx.devices[device_name]
        entities.append(KNXSensor(device))
    async_add_entities(entities)

@callback
def async_add_entities_config(hass, config, async_add_entities):
    """Set up sensor for KNX platform configured within platform."""
    import xknx
    sensor = xknx.devices.Sensor(
        hass.data[DATA_XKNX].xknx,
        name=config.get(CONF_NAME),
        group_address=config.get(CONF_ADDRESS),
        value_type=config.get(CONF_TYPE))
    hass.data[DATA_XKNX].xknx.devices.add(sensor)
    async_add_entities([KNXSensor(sensor)])

class KNXSensor(Entity):
    """Representation of a KNX sensor."""

    def __init__(self, device):
        """Initialize of a KNX sensor."""
        self.device = device

    @callback
    def async_register_callbacks(self):
        """Register callbacks to update hass after device was changed."""
        async def after_update_callback(device):
            """Call after device was updated."""
            await self.async_update_ha_state()
        self.device.register_device_updated_cb(after_update_callback)

    async def async_added_to_hass(self):
        """Store register state change callback."""
        self.async_register_callbacks()

    @property
    def name(self):
        """Return the name of the KNX device."""
        return self.device.name

    @property
    def available(self):
        """Return True if entity is available."""
        return self.hass.data[DATA_XKNX].connected

    @property
    def should_poll(self):
        """No polling needed within KNX."""
        return False

    @property
    def state(self):
        """Return the state of the sensor."""
        return self.device.resolve_state()

    @property
    def unit_of_measurement(self):
        """Return the unit this state is expressed in."""
        return self.device.unit_of_measurement()

    @property
    def device_class(self):
        """Return the device class of the sensor."""
        if self.device.sensor_value.value_type == "humidity":
            return DEVICE_CLASS_HUMIDITY
        if self.device.sensor_value.value_type in \
                ("illuminance", 'luminous_flux'):
            return DEVICE_CLASS_ILLUMINANCE
        if self.device.sensor_value.value_type == "pressure":
            return DEVICE_CLASS_PRESSURE
        if self.device.sensor_value.value_type == "temperature":
            return DEVICE_CLASS_TEMPERATURE
        return None

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        return None
<commit_msg>added DEVICE_CLASS_POWER<commit_after>"""
Support for KNX/IP sensors.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.knx/
"""

import voluptuous as vol

from custom_components.xknx import ATTR_DISCOVER_DEVICES, DATA_XKNX
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
    CONF_NAME, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_ILLUMINANCE,
    DEVICE_CLASS_POWER, DEVICE_CLASS_PRESSURE, DEVICE_CLASS_TEMPERATURE)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity

CONF_ADDRESS = 'address'
CONF_TYPE = 'type'

DEFAULT_NAME = 'XKNX Sensor'
DEPENDENCIES = ['xknx']

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_ADDRESS): cv.string,
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Optional(CONF_TYPE): cv.string,
})

async def async_setup_platform(hass, config, async_add_entities,
                               discovery_info=None):
    """Set up sensor(s) for KNX platform."""
    if discovery_info is not None:
        async_add_entities_discovery(hass, discovery_info, async_add_entities)
    else:
        async_add_entities_config(hass, config, async_add_entities)

@callback
def async_add_entities_discovery(hass, discovery_info, async_add_entities):
    """Set up sensors for KNX platform configured via xknx.yaml."""
    entities = []
    for device_name in discovery_info[ATTR_DISCOVER_DEVICES]:
        device = hass.data[DATA_XKNX].xknx.devices[device_name]
        entities.append(KNXSensor(device))
    async_add_entities(entities)

@callback
def async_add_entities_config(hass, config, async_add_entities):
    """Set up sensor for KNX platform configured within platform."""
    import xknx
    sensor = xknx.devices.Sensor(
        hass.data[DATA_XKNX].xknx,
        name=config.get(CONF_NAME),
        group_address=config.get(CONF_ADDRESS),
        value_type=config.get(CONF_TYPE))
    hass.data[DATA_XKNX].xknx.devices.add(sensor)
    async_add_entities([KNXSensor(sensor)])

class KNXSensor(Entity):
    """Representation of a KNX sensor."""

    def __init__(self, device):
        """Initialize of a KNX sensor."""
        self.device = device

    @callback
    def async_register_callbacks(self):
        """Register callbacks to update hass after device was changed."""
        async def after_update_callback(device):
            """Call after device was updated."""
            await self.async_update_ha_state()
        self.device.register_device_updated_cb(after_update_callback)

    async def async_added_to_hass(self):
        """Store register state change callback."""
        self.async_register_callbacks()

    @property
    def name(self):
        """Return the name of the KNX device."""
        return self.device.name

    @property
    def available(self):
        """Return True if entity is available."""
        return self.hass.data[DATA_XKNX].connected

    @property
    def should_poll(self):
        """No polling needed within KNX."""
        return False

    @property
    def state(self):
        """Return the state of the sensor."""
        return self.device.resolve_state()

    @property
    def unit_of_measurement(self):
        """Return the unit this state is expressed in."""
        return self.device.unit_of_measurement()

    @property
    def device_class(self):
        """Return the device class of the sensor."""
        if self.device.sensor_value.value_type == "humidity":
            return DEVICE_CLASS_HUMIDITY
        if self.device.sensor_value.value_type in \
                ("illuminance", 'luminous_flux'):
            return DEVICE_CLASS_ILLUMINANCE
        if self.device.sensor_value.value_type == "power":
            return DEVICE_CLASS_POWER
        if self.device.sensor_value.value_type == "pressure":
            return DEVICE_CLASS_PRESSURE
        if self.device.sensor_value.value_type == "temperature":
            return DEVICE_CLASS_TEMPERATURE
        return None

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        return None
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import social.apps.django_app.default.fields
from django.conf import settings
import social.storage.django_orm

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Association',
            fields=[
                ('id', models.AutoField(
                    verbose_name='ID', serialize=False, auto_created=True,
                    primary_key=True)),
                ('server_url', models.CharField(max_length=255)),
                ('handle', models.CharField(max_length=255)),
                ('secret', models.CharField(max_length=255)),
                ('issued', models.IntegerField()),
                ('lifetime', models.IntegerField()),
                ('assoc_type', models.CharField(max_length=64)),
            ],
            options={
                'db_table': 'social_auth_association',
            },
            bases=(
                models.Model, social.storage.django_orm.DjangoAssociationMixin
            ),
        ),
        migrations.CreateModel(
            name='Code',
            fields=[
                ('id', models.AutoField(
                    verbose_name='ID', serialize=False, auto_created=True,
                    primary_key=True)),
                ('email', models.EmailField(max_length=75)),
                ('code', models.CharField(max_length=32, db_index=True)),
                ('verified', models.BooleanField(default=False)),
            ],
            options={
                'db_table': 'social_auth_code',
            },
            bases=(models.Model, social.storage.django_orm.DjangoCodeMixin),
        ),
        migrations.CreateModel(
            name='Nonce',
            fields=[
                ('id', models.AutoField(
                    verbose_name='ID', serialize=False, auto_created=True,
                    primary_key=True)),
                ('server_url', models.CharField(max_length=255)),
                ('timestamp', models.IntegerField()),
                ('salt', models.CharField(max_length=65)),
            ],
            options={
                'db_table': 'social_auth_nonce',
            },
            bases=(models.Model, social.storage.django_orm.DjangoNonceMixin),
        ),
        migrations.CreateModel(
            name='UserSocialAuth',
            fields=[
                ('id', models.AutoField(
                    verbose_name='ID', serialize=False, auto_created=True,
                    primary_key=True)),
                ('provider', models.CharField(max_length=32)),
                ('uid', models.CharField(max_length=255)),
                ('extra_data', social.apps.django_app.default.fields.JSONField(
                    default=b'{}')),
                ('user', models.ForeignKey(
                    related_name='social_auth', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'db_table': 'social_auth_usersocialauth',
            },
            bases=(models.Model, social.storage.django_orm.DjangoUserMixin),
        ),
        migrations.AlterUniqueTogether(
            name='usersocialauth',
            unique_together=set([('provider', 'uid')]),
        ),
        migrations.AlterUniqueTogether(
            name='code',
            unique_together=set([('email', 'code')]),
        ),
    ]
<commit_msg>Fix custom user model migrations for Django 1.7<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import social.apps.django_app.default.fields
from django.conf import settings
import social.storage.django_orm
from social.utils import setting_name

user_model = getattr(settings, setting_name('USER_MODEL'), None) or \
             getattr(settings, 'AUTH_USER_MODE', None) or \
             'auth.User'

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(user_model),
    ]

    operations = [
        migrations.CreateModel(
            name='Association',
            fields=[
                ('id', models.AutoField(
                    verbose_name='ID', serialize=False, auto_created=True,
                    primary_key=True)),
                ('server_url', models.CharField(max_length=255)),
                ('handle', models.CharField(max_length=255)),
                ('secret', models.CharField(max_length=255)),
                ('issued', models.IntegerField()),
                ('lifetime', models.IntegerField()),
                ('assoc_type', models.CharField(max_length=64)),
            ],
            options={
                'db_table': 'social_auth_association',
            },
            bases=(
                models.Model, social.storage.django_orm.DjangoAssociationMixin
            ),
        ),
        migrations.CreateModel(
            name='Code',
            fields=[
                ('id', models.AutoField(
                    verbose_name='ID', serialize=False, auto_created=True,
                    primary_key=True)),
                ('email', models.EmailField(max_length=75)),
                ('code', models.CharField(max_length=32, db_index=True)),
                ('verified', models.BooleanField(default=False)),
            ],
            options={
                'db_table': 'social_auth_code',
            },
            bases=(models.Model, social.storage.django_orm.DjangoCodeMixin),
        ),
        migrations.CreateModel(
            name='Nonce',
            fields=[
                ('id', models.AutoField(
                    verbose_name='ID', serialize=False, auto_created=True,
                    primary_key=True)),
                ('server_url', models.CharField(max_length=255)),
                ('timestamp', models.IntegerField()),
                ('salt', models.CharField(max_length=65)),
            ],
            options={
                'db_table': 'social_auth_nonce',
            },
            bases=(models.Model, social.storage.django_orm.DjangoNonceMixin),
        ),
        migrations.CreateModel(
            name='UserSocialAuth',
            fields=[
                ('id', models.AutoField(
                    verbose_name='ID', serialize=False, auto_created=True,
                    primary_key=True)),
                ('provider', models.CharField(max_length=32)),
                ('uid', models.CharField(max_length=255)),
                ('extra_data', social.apps.django_app.default.fields.JSONField(
                    default=b'{}')),
                ('user', models.ForeignKey(
                    related_name='social_auth', to=user_model)),
            ],
            options={
                'db_table': 'social_auth_usersocialauth',
            },
            bases=(models.Model, social.storage.django_orm.DjangoUserMixin),
        ),
        migrations.AlterUniqueTogether(
            name='usersocialauth',
            unique_together=set([('provider', 'uid')]),
        ),
        migrations.AlterUniqueTogether(
            name='code',
            unique_together=set([('email', 'code')]),
        ),
    ]
<|endoftext|>


<commit_before>from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from .geom_point import geom_point

class geom_jitter(geom_point):
    def __init__(self, *args, **kwargs):
        # jitter is just a special case of geom_point, so we'll just use
        # geom_point and then enforce jitter
        super(geom_point, self).__init__()
        self.manual_aes['position'] = "jitter"

<commit_msg>Fixes #286<commit_after>from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from .geom_point import geom_point

class geom_jitter(geom_point):
    def __init__(self, *args, **kwargs):
        # jitter is just a special case of geom_point, so we'll just use
        # geom_point and then enforce jitter
        super(geom_point, self).__init__(*args, **kwargs)
        self.manual_aes['position'] = "jitter"
<|endoftext|>


<commit_before>from django.conf import settings

from ..exceptions import InvalidProfileError
from .base import BaseAuthProvider

class GoogleAuthProvider(BaseAuthProvider):
    client_id = settings.SOCIAL_AUTH_GOOGLE_CLIENT_ID
    client_secret = settings.SOCIAL_AUTH_GOOGLE_SECRET
    scope = [
        'https://www.googleapis.com/auth/plus.me',
        'https://www.googleapis.com/auth/userinfo.email',
        'https://www.googleapis.com/auth/userinfo.profile'
    ]
    auth_uri = 'https://accounts.google.com/o/oauth2/v2/auth'
    token_uri = 'https://www.googleapis.com/oauth2/v4/token'
    jwks_uri = 'https://www.googleapis.com/oauth2/v3/certs'

    def parse_profile(self, session, token):
        id_token = token['id_token']

        email = id_token.get('email', '')
        if not email or not id_token.get('email_verified', False):
            raise InvalidProfileError()

        picture = self.get_picture(session=session, url=id_token.get('picture', ''))
        language = self.get_language(id_token.get('locale', ''))

        return {
            'email': email,
            'picture': picture,
            'first_name': id_token.get('given_name', ''),
            'last_name': id_token.get('family_name', ''),
            'language': language,
        }
<commit_msg>LILY-3349: Fix deprecation of social OAuth scopes<commit_after>from django.conf import settings

from ..exceptions import InvalidProfileError
from .base import BaseAuthProvider

class GoogleAuthProvider(BaseAuthProvider):
    client_id = settings.SOCIAL_AUTH_GOOGLE_CLIENT_ID
    client_secret = settings.SOCIAL_AUTH_GOOGLE_SECRET
    scope = [
        'openid',
        'email',
        'profile'
    ]
    auth_uri = 'https://accounts.google.com/o/oauth2/v2/auth'
    token_uri = 'https://www.googleapis.com/oauth2/v4/token'
    jwks_uri = 'https://www.googleapis.com/oauth2/v3/certs'

    def parse_profile(self, session, token):
        id_token = token['id_token']

        email = id_token.get('email', '')
        if not email or not id_token.get('email_verified', False):
            raise InvalidProfileError()

        picture = self.get_picture(session=session, url=id_token.get('picture', ''))
        language = self.get_language(id_token.get('locale', ''))

        return {
            'email': email,
            'picture': picture,
            'first_name': id_token.get('given_name', ''),
            'last_name': id_token.get('family_name', ''),
            'language': language,
        }
<|endoftext|>


<commit_before># Creates GUI that allows user to change settings, and runs the main script

from tkinter import *
from tkinter import messagebox, simpledialog
from HourlyNotifications_FileHandling import Directory
from HourlyNotifications_Play import Sound

def main():

    gui = Interface()
    sounds = Directory.get_sounds()
    if not sounds:
        gui.alert_missing()
    try:
        saved_choices, saved_volume = Directory.get_settings(graphics=True)
        gui.set_saved_volume(saved_volume)
    except:
        saved_choices = None
    finally:
        gui.draw_topbar()
        gui.create_selections(sounds, saved_choices)
        gui.run()

class Interface:

    def __init__(self):
        self.root = Tk()
        self.root.title("Hourly Notifications")
        self.selections = []
        self.column_count = 6
        self.row_count = 4
        self.topbar = Menu(self.root)
        self.volume = 20

    def draw_topbar(self):
        """
        Create top menu bar using tkinter methods
        :return: NoneType
        """
        settings = Menu(self.topbar, tearoff=0)
        settings.add_command(label="Set Volume", command=self.ask_new_volume)
        settings.add_command(label="Exit", command=self.root.destroy)
        self.topbar.add_cascade(label="Advanced Settings", menu=settings)
        self.topbar.add_command(label="Save", command=self.save)
        self.root.config(menu=self.topbar)

    def create_selections(self, sounds, saved_choices):
        """
        Increment through rows, columns, and hours to create Selections
        :param sounds: list
        :param saved_choices: dict
        :return: NoneType
        """
        hour = 0
        for c in range(self.column_count):
            for r in range(self.row_count):
                try:
                    box = Selection(self.root, c, r, hour, sounds, saved_choice=saved_choices[hour])
                except:
                    box = Selection(self.root, c, r, hour, sounds)
                hour += 1
                self.selections.append(box)

    def save(self):
        """
        Get user choices, save using Directory, and notify the user save was successful
        :return: NoneType
        """
        selection_values = []
        for selection in self.selections:
            selection_values.append(selection.get_choice())
        default = Selection.get_default_choice()
        Directory.save_settings(selection_values, default, self.volume)
        messagebox.showinfo("Notice", "Settings saved.")

    def alert_missing(self):
        """
        Popup warning for missing audio
        :return: NoneType
        """
        messagebox.showwarning("Error", "Sound files not located. Program will exit.")
        self.root.destroy()

    def run(self):
        """
        Main program loops
        :return: NoneType
        """
        self.root.resizable(width=False, height=False)
        self.root.after(1000, self.run_script)
        self.root.protocol("WM_DELETE_WINDOW", self.root.iconify)
        self.root.mainloop()

    def run_script(self):
        """
        Uses Sound to check if it is time to play notification
        :return:
        """
        Sound.decide_play()
        self.root.after(10000, self.run_script)

    def set_saved_volume(self, volume):
        """
        Allows user to see what the volume is currently set to
        :param volume: int
        :return: NoneType
        """
        self.volume = volume

    def ask_new_volume(self):
        """
        Create popup box that lets user change volume percentage
        :return: NoneType
        """
        new_volume = simpledialog.askinteger("Notification Volume", "Set New Volume (Max. 100%)", parent=self.root,
                                              initialvalue=self.volume, maxvalue=100)
        if new_volume:  # if user didn't cancel
            self.volume = new_volume
            Sound.set_volume(self.volume / 100)
            self.save()

class Selection:

    uni_padding = (5,5)
    label_padding = (5, 0)
    dropdown_padding = (0, 5)
    default_choice = "Choose a sound file"

    @classmethod
    def get_default_choice(cls):
        """
        :return: str
        """
        return cls.default_choice

    def __init__(self, root, c, r, hour, sounds, saved_choice=None):
        """
        :param root: Tk
        :param c: int
        :param r: int
        :param hour: int
        :param sounds: list
        :param saved_choice: str or NoneType
        """
        self.root = root
        self.hour = hour
        self.c = c
        self.r = r
        self.saved_choice = saved_choice

        # initialize tkinter objects
        self.label = Text(root, height=1, width=15)
        self.choice = StringVar(self.root)
        self.dropdown = OptionMenu(root, self.choice, *sounds)

        # draw self
        self.draw_label()
        self.draw_dropdown()

    def draw_label(self):
        """
        Draw text indicating what time's notification can be set in following menu
        :return: NoneType
        """
        self.label.tag_config('center', justify=CENTER)  # creates a tag with name 'center' that can center text
        self.label.insert(END, "Sound for " + str(self.hour) + ":00", 'center')

        # Each row of Selection objects actually has two subrows; Tkinter uses these subrows to draw
        self.label.grid(row=self.r * 2, column=self.c,
                        padx=Selection.uni_padding, pady=Selection.label_padding)

    def draw_dropdown(self):
        """
        Draw menu which lets users choose notification for a given time
        :return: NoneType
        """
        if self.saved_choice:
            self.choice.set(self.saved_choice)
        else:
            self.choice.set(Selection.default_choice)
        self.dropdown.grid(row=(self.r * 2) + 1, column=self.c,
                           padx=Selection.uni_padding, pady=Selection.dropdown_padding)

    def get_choice(self):
        """
        :return: str
        """
        return self.choice.get()

main()
<commit_msg>Fixed volume restriction bug<commit_after># Creates GUI that allows user to change settings, and runs the main script

from tkinter import *
from tkinter import messagebox, simpledialog
from HourlyNotifications_FileHandling import Directory
from HourlyNotifications_Play import Sound

def main():

    gui = Interface()
    sounds = Directory.get_sounds()
    if not sounds:
        gui.alert_missing()
    try:
        saved_choices, saved_volume = Directory.get_settings(graphics=True)
        gui.set_saved_volume(saved_volume)
    except:
        saved_choices = None
    finally:
        gui.draw_topbar()
        gui.create_selections(sounds, saved_choices)
        gui.run()

class Interface:

    def __init__(self):
        self.root = Tk()
        self.root.title("Hourly Notifications")
        self.selections = []
        self.column_count = 6
        self.row_count = 4
        self.topbar = Menu(self.root)
        self.volume = 20

    def draw_topbar(self):
        """
        Create top menu bar using tkinter methods
        :return: NoneType
        """
        settings = Menu(self.topbar, tearoff=0)
        settings.add_command(label="Set Volume", command=self.ask_new_volume)
        settings.add_command(label="Exit", command=self.root.destroy)
        self.topbar.add_cascade(label="Advanced Settings", menu=settings)
        self.topbar.add_command(label="Save", command=self.save)
        self.root.config(menu=self.topbar)

    def create_selections(self, sounds, saved_choices):
        """
        Increment through rows, columns, and hours to create Selections
        :param sounds: list
        :param saved_choices: dict
        :return: NoneType
        """
        hour = 0
        for c in range(self.column_count):
            for r in range(self.row_count):
                try:
                    box = Selection(self.root, c, r, hour, sounds, saved_choice=saved_choices[hour])
                except:
                    box = Selection(self.root, c, r, hour, sounds)
                hour += 1
                self.selections.append(box)

    def save(self):
        """
        Get user choices, save using Directory, and notify the user save was successful
        :return: NoneType
        """
        selection_values = []
        for selection in self.selections:
            selection_values.append(selection.get_choice())
        default = Selection.get_default_choice()
        Directory.save_settings(selection_values, default, self.volume)
        messagebox.showinfo("Notice", "Settings saved.")

    def alert_missing(self):
        """
        Popup warning for missing audio
        :return: NoneType
        """
        messagebox.showwarning("Error", "Sound files not located. Program will exit.")
        self.root.destroy()

    def run(self):
        """
        Main program loops
        :return: NoneType
        """
        self.root.resizable(width=False, height=False)
        self.root.after(1000, self.run_script)
        self.root.protocol("WM_DELETE_WINDOW", self.root.iconify)
        self.root.mainloop()

    def run_script(self):
        """
        Uses Sound to check if it is time to play notification
        :return:
        """
        Sound.decide_play()
        self.root.after(10000, self.run_script)

    def set_saved_volume(self, volume):
        """
        Allows user to see what the volume is currently set to
        :param volume: int
        :return: NoneType
        """
        self.volume = volume

    def ask_new_volume(self):
        """
        Create popup box that lets user change volume percentage
        :return: NoneType
        """
        new_volume = simpledialog.askinteger("Notification Volume", "Set New Volume (1% to 100%)", parent=self.root,
                                              initialvalue=self.volume, minvalue=1, maxvalue=100)
        if new_volume:  # if user didn't cancel
            self.volume = new_volume
            Sound.set_volume(self.volume / 100)
            self.save()

class Selection:

    uni_padding = (5,5)
    label_padding = (5, 0)
    dropdown_padding = (0, 5)
    default_choice = "Choose a sound file"

    @classmethod
    def get_default_choice(cls):
        """
        :return: str
        """
        return cls.default_choice

    def __init__(self, root, c, r, hour, sounds, saved_choice=None):
        """
        :param root: Tk
        :param c: int
        :param r: int
        :param hour: int
        :param sounds: list
        :param saved_choice: str or NoneType
        """
        self.root = root
        self.hour = hour
        self.c = c
        self.r = r
        self.saved_choice = saved_choice

        # initialize tkinter objects
        self.label = Text(root, height=1, width=15)
        self.choice = StringVar(self.root)
        self.dropdown = OptionMenu(root, self.choice, *sounds)

        # draw self
        self.draw_label()
        self.draw_dropdown()

    def draw_label(self):
        """
        Draw text indicating what time's notification can be set in following menu
        :return: NoneType
        """
        self.label.tag_config('center', justify=CENTER)  # creates a tag with name 'center' that can center text
        self.label.insert(END, "Sound for " + str(self.hour) + ":00", 'center')

        # Each row of Selection objects actually has two subrows; Tkinter uses these subrows to draw
        self.label.grid(row=self.r * 2, column=self.c,
                        padx=Selection.uni_padding, pady=Selection.label_padding)

    def draw_dropdown(self):
        """
        Draw menu which lets users choose notification for a given time
        :return: NoneType
        """
        if self.saved_choice:
            self.choice.set(self.saved_choice)
        else:
            self.choice.set(Selection.default_choice)
        self.dropdown.grid(row=(self.r * 2) + 1, column=self.c,
                           padx=Selection.uni_padding, pady=Selection.dropdown_padding)

    def get_choice(self):
        """
        :return: str
        """
        return self.choice.get()

main()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2009 Edgewall Software
# Copyright (C) 2003-2004 Jonas Borgström <jonas@edgewall.com>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Jonas Borgström <jonas@edgewall.com>

import pkg_resources
import re

from genshi.builder import tag

from trac.config import IntOption, ListOption
from trac.core import *
from trac.perm import IPermissionRequestor
from trac.search.api import ISearchSource
from trac.util import as_int
from trac.util.datefmt import format_datetime, user_time
from trac.util.html import find_element
from trac.util.presentation import Paginator
from trac.util.text import quote_query_string
from trac.util.translation import _
from trac.web.api import IRequestHandler
from trac.web.chrome import (INavigationContributor, ITemplateProvider,
                             add_link, add_stylesheet, add_warning,
                             web_context)
from trac.wiki.api import IWikiSyntaxProvider
from trac.wiki.formatter import extract_link

class SearchModule(Component):
    """Controller for the search sub-system"""

    implements(INavigationContributor, IPermissionRequestor, IRequestHandler,
               ITemplateProvider, IWikiSyntaxProvider)

    search_sources = ExtensionPoint(ISearchSource)

    RESULTS_PER_PAGE = 10

    min_query_length = IntOption('search', 'min_query_length', 3,
        """Minimum length of query string allowed when performing a search.""")

    default_disabled_filters = ListOption('search', 'default_disabled_filters',
        doc="""Specifies which search filters should be disabled by
               default on the search page. This will also restrict the
               filters for the quick search function. The filter names
               defined by default components are: `wiki`, `ticket`,
               `milestone` and `changeset`.  For plugins, look for
               their implementation of the ISearchSource interface, in
               the `get_search_filters()` method, the first member of
               returned tuple. Once disabled, search filters can still
               be manually enabled by the user on the search page.
               (since 0.12)""")

    # INavigationContributor methods

    def get_active_navigation_item(self, req):
        return 'search'

    def get_navigation_items(self, req):
        if 'SEARCH_VIEW' in req.perm:
            yield ('mainnav', 'search',
                   tag.a(_('Search'), href=req.href.search(), accesskey=4))

    # IPermissionRequestor methods

    def get_permission_actions(self):
        return ['SEARCH_VIEW']

    # IRequestHandler methods

    def match_request(self, req):
        return re.match(r'/search(?:/opensearch)?$', req.path_info) is not None

    def process_request(self, req):
        req.perm.assert_permission('SEARCH_VIEW')

        if req.path_info == '/search/opensearch':
            return ('opensearch.xml', {},
                    'application/opensearchdescription+xml')

        query = req.args.get('q')
        available_filters = []
        for source in self.search_sources:
            available_filters.extend(source.get_search_filters(req) or [])
        available_filters.sort(key=lambda f: f[1].lower())

        filters = self._get_selected_filters(req, available_filters)
        data = self._prepare_data(req, query, available_filters, filters)
        if query:
            data['quickjump'] = self._check_quickjump(req, query)
            if query.startswith('!'):
                query = query[1:]

            terms = self._parse_query(req, query)
            if terms:
                results = self._do_search(req, terms, filters)
                if results:
                    data.update(self._prepare_results(req, filters, results))

        add_stylesheet(req, 'common/css/search.css')
        return 'search.html', data, None

    # ITemplateProvider methods

    def get_htdocs_dirs(self):
        return []

    def get_templates_dirs(self):
        return [pkg_resources.resource_filename('trac.search', 'templates')]

    # IWikiSyntaxProvider methods

    def get_wiki_syntax(self):
        return []

    def get_link_resolvers(self):
        yield ('search', self._format_link)

    def _format_link(self, formatter, ns, target, label):
        path, query, fragment = formatter.split_link(target)
        if path:
            href = formatter.href.search(q=path)
            if query:
                href += '&' + quote_query_string(query[1:])
        else:
            href = formatter.href.search() + quote_query_string(query)
        href += fragment
        return tag.a(label, class_='search', href=href)

    # IRequestHandler helper methods

    def _get_selected_filters(self, req, available_filters):
        """Return selected filters or the default filters if none was selected.
        """
        filters = [f[0] for f in available_filters if f[0] in req.args]
        if not filters:
            filters = [f[0] for f in available_filters
                       if f[0] not in self.default_disabled_filters and
                       (len(f) < 3 or len(f) > 2 and f[2])]
        return filters

    def _prepare_data(self, req, query, available_filters, filters):
        return {'filters': [{'name': f[0], 'label': f[1],
                             'active': f[0] in filters}
                            for f in available_filters],
                'query': query, 'quickjump': None, 'results': []}

    def _check_quickjump(self, req, kwd):
        """Look for search shortcuts"""
        noquickjump = as_int(req.args.get('noquickjump'), 0)
        # Source quickjump   FIXME: delegate to ISearchSource.search_quickjump
        quickjump_href = None
        if kwd[0] == '/':
            quickjump_href = req.href.browser(kwd)
            name = kwd
            description = _('Browse repository path %(path)s', path=kwd)
        else:
            context = web_context(req, 'search')
            link = find_element(extract_link(self.env, context, kwd), 'href')
            if link is not None:
                quickjump_href = link.attrib.get('href')
                name = link.children
                description = link.attrib.get('title', '')
        if quickjump_href:
            # Only automatically redirect to local quickjump links
            if not quickjump_href.startswith(req.base_path or '/'):
                noquickjump = True
            if noquickjump:
                return {'href': quickjump_href, 'name': tag.em(name),
                        'description': description}
            else:
                req.redirect(quickjump_href)

    def _get_search_terms(self, query):
        """Break apart a search query into its various search terms.

        Terms are grouped implicitly by word boundary, or explicitly by (single
        or double) quotes.
        """
        terms = []
        for term in re.split('(".*?")|(\'.*?\')|(\s+)', query):
            if term is not None and term.strip():
                if term[0] == term[-1] and term[0] in "'\"":
                    term = term[1:-1]
                terms.append(term)
        return terms

    def _parse_query(self, req, query):
        """Parse query and refuse those which would result in a huge result set
        """
        terms = self._get_search_terms(query)
        if terms and (len(terms) > 1 or
                      len(terms[0]) >= self.min_query_length):
            return terms

        add_warning(req, _('Search query too short. '
                           'Query must be at least %(num)s characters long.',
                           num=self.min_query_length))

    def _do_search(self, req, terms, filters):
        results = []
        for source in self.search_sources:
            results.extend(source.get_search_results(req, terms, filters)
                           or [])
        return sorted(results, key=lambda x: x[2], reverse=True)

    def _prepare_results(self, req, filters, results):
        page = req.args.get('page', 1)
        page = as_int(page, default=1, min=1)
        try:
            results = Paginator(results, page - 1, self.RESULTS_PER_PAGE)
        except TracError:
            add_warning(req, _("Page %(page)s is out of range.", page=page))
            page = 1
            results = Paginator(results, page - 1, self.RESULTS_PER_PAGE)

        for idx, result in enumerate(results):
            results[idx] = {'href': result[0], 'title': result[1],
                            'date': user_time(req, format_datetime, result[2]),
                            'author': result[3], 'excerpt': result[4]}

        pagedata = []
        shown_pages = results.get_shown_pages(21)
        for shown_page in shown_pages:
            page_href = req.href.search([(f, 'on') for f in filters],
                                        q=req.args.get('q'),
                                        page=shown_page, noquickjump=1)
            pagedata.append([page_href, None, str(shown_page),
                             _("Page %(num)d", num=shown_page)])

        fields = ['href', 'class', 'string', 'title']
        results.shown_pages = [dict(zip(fields, p)) for p in pagedata]

        results.current_page = {'href': None, 'class': 'current',
                                'string': str(results.page + 1),
                                'title': None}

        if results.has_next_page:
            next_href = req.href.search(zip(filters, ['on'] * len(filters)),
                                        q=req.args.get('q'), page=page + 1,
                                        noquickjump=1)
            add_link(req, 'next', next_href, _('Next Page'))

        if results.has_previous_page:
            prev_href = req.href.search(zip(filters, ['on'] * len(filters)),
                                        q=req.args.get('q'), page=page - 1,
                                        noquickjump=1)
            add_link(req, 'prev', prev_href, _('Previous Page'))

        page_href = req.href.search(
            zip(filters, ['on'] * len(filters)), q=req.args.get('q'),
            noquickjump=1)
        return {'results': results, 'page_href': page_href}
<commit_msg>1.0.14dev: Avoid `TypeError` with repeated `q` argument<commit_after># -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2009 Edgewall Software
# Copyright (C) 2003-2004 Jonas Borgström <jonas@edgewall.com>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Jonas Borgström <jonas@edgewall.com>

import pkg_resources
import re

from genshi.builder import tag

from trac.config import IntOption, ListOption
from trac.core import *
from trac.perm import IPermissionRequestor
from trac.search.api import ISearchSource
from trac.util import as_int
from trac.util.datefmt import format_datetime, user_time
from trac.util.html import find_element
from trac.util.presentation import Paginator
from trac.util.text import quote_query_string
from trac.util.translation import _
from trac.web.api import IRequestHandler
from trac.web.chrome import (INavigationContributor, ITemplateProvider,
                             add_link, add_stylesheet, add_warning,
                             web_context)
from trac.wiki.api import IWikiSyntaxProvider
from trac.wiki.formatter import extract_link

class SearchModule(Component):
    """Controller for the search sub-system"""

    implements(INavigationContributor, IPermissionRequestor, IRequestHandler,
               ITemplateProvider, IWikiSyntaxProvider)

    search_sources = ExtensionPoint(ISearchSource)

    RESULTS_PER_PAGE = 10

    min_query_length = IntOption('search', 'min_query_length', 3,
        """Minimum length of query string allowed when performing a search.""")

    default_disabled_filters = ListOption('search', 'default_disabled_filters',
        doc="""Specifies which search filters should be disabled by
               default on the search page. This will also restrict the
               filters for the quick search function. The filter names
               defined by default components are: `wiki`, `ticket`,
               `milestone` and `changeset`.  For plugins, look for
               their implementation of the ISearchSource interface, in
               the `get_search_filters()` method, the first member of
               returned tuple. Once disabled, search filters can still
               be manually enabled by the user on the search page.
               (since 0.12)""")

    # INavigationContributor methods

    def get_active_navigation_item(self, req):
        return 'search'

    def get_navigation_items(self, req):
        if 'SEARCH_VIEW' in req.perm:
            yield ('mainnav', 'search',
                   tag.a(_('Search'), href=req.href.search(), accesskey=4))

    # IPermissionRequestor methods

    def get_permission_actions(self):
        return ['SEARCH_VIEW']

    # IRequestHandler methods

    def match_request(self, req):
        return re.match(r'/search(?:/opensearch)?$', req.path_info) is not None

    def process_request(self, req):
        req.perm.assert_permission('SEARCH_VIEW')

        if req.path_info == '/search/opensearch':
            return ('opensearch.xml', {},
                    'application/opensearchdescription+xml')

        query = req.args.getfirst('q')
        available_filters = []
        for source in self.search_sources:
            available_filters.extend(source.get_search_filters(req) or [])
        available_filters.sort(key=lambda f: f[1].lower())

        filters = self._get_selected_filters(req, available_filters)
        data = self._prepare_data(req, query, available_filters, filters)
        if query:
            data['quickjump'] = self._check_quickjump(req, query)
            if query.startswith('!'):
                query = query[1:]

            terms = self._parse_query(req, query)
            if terms:
                results = self._do_search(req, terms, filters)
                if results:
                    data.update(self._prepare_results(req, filters, results))

        add_stylesheet(req, 'common/css/search.css')
        return 'search.html', data, None

    # ITemplateProvider methods

    def get_htdocs_dirs(self):
        return []

    def get_templates_dirs(self):
        return [pkg_resources.resource_filename('trac.search', 'templates')]

    # IWikiSyntaxProvider methods

    def get_wiki_syntax(self):
        return []

    def get_link_resolvers(self):
        yield ('search', self._format_link)

    def _format_link(self, formatter, ns, target, label):
        path, query, fragment = formatter.split_link(target)
        if path:
            href = formatter.href.search(q=path)
            if query:
                href += '&' + quote_query_string(query[1:])
        else:
            href = formatter.href.search() + quote_query_string(query)
        href += fragment
        return tag.a(label, class_='search', href=href)

    # IRequestHandler helper methods

    def _get_selected_filters(self, req, available_filters):
        """Return selected filters or the default filters if none was selected.
        """
        filters = [f[0] for f in available_filters if f[0] in req.args]
        if not filters:
            filters = [f[0] for f in available_filters
                       if f[0] not in self.default_disabled_filters and
                       (len(f) < 3 or len(f) > 2 and f[2])]
        return filters

    def _prepare_data(self, req, query, available_filters, filters):
        return {'filters': [{'name': f[0], 'label': f[1],
                             'active': f[0] in filters}
                            for f in available_filters],
                'query': query, 'quickjump': None, 'results': []}

    def _check_quickjump(self, req, kwd):
        """Look for search shortcuts"""
        noquickjump = as_int(req.args.get('noquickjump'), 0)
        # Source quickjump   FIXME: delegate to ISearchSource.search_quickjump
        quickjump_href = None
        if kwd[0] == '/':
            quickjump_href = req.href.browser(kwd)
            name = kwd
            description = _('Browse repository path %(path)s', path=kwd)
        else:
            context = web_context(req, 'search')
            link = find_element(extract_link(self.env, context, kwd), 'href')
            if link is not None:
                quickjump_href = link.attrib.get('href')
                name = link.children
                description = link.attrib.get('title', '')
        if quickjump_href:
            # Only automatically redirect to local quickjump links
            if not quickjump_href.startswith(req.base_path or '/'):
                noquickjump = True
            if noquickjump:
                return {'href': quickjump_href, 'name': tag.em(name),
                        'description': description}
            else:
                req.redirect(quickjump_href)

    def _get_search_terms(self, query):
        """Break apart a search query into its various search terms.

        Terms are grouped implicitly by word boundary, or explicitly by (single
        or double) quotes.
        """
        terms = []
        for term in re.split('(".*?")|(\'.*?\')|(\s+)', query):
            if term is not None and term.strip():
                if term[0] == term[-1] and term[0] in "'\"":
                    term = term[1:-1]
                terms.append(term)
        return terms

    def _parse_query(self, req, query):
        """Parse query and refuse those which would result in a huge result set
        """
        terms = self._get_search_terms(query)
        if terms and (len(terms) > 1 or
                      len(terms[0]) >= self.min_query_length):
            return terms

        add_warning(req, _('Search query too short. '
                           'Query must be at least %(num)s characters long.',
                           num=self.min_query_length))

    def _do_search(self, req, terms, filters):
        results = []
        for source in self.search_sources:
            results.extend(source.get_search_results(req, terms, filters)
                           or [])
        return sorted(results, key=lambda x: x[2], reverse=True)

    def _prepare_results(self, req, filters, results):
        page = req.args.get('page', 1)
        page = as_int(page, default=1, min=1)
        try:
            results = Paginator(results, page - 1, self.RESULTS_PER_PAGE)
        except TracError:
            add_warning(req, _("Page %(page)s is out of range.", page=page))
            page = 1
            results = Paginator(results, page - 1, self.RESULTS_PER_PAGE)

        for idx, result in enumerate(results):
            results[idx] = {'href': result[0], 'title': result[1],
                            'date': user_time(req, format_datetime, result[2]),
                            'author': result[3], 'excerpt': result[4]}

        pagedata = []
        shown_pages = results.get_shown_pages(21)
        for shown_page in shown_pages:
            page_href = req.href.search([(f, 'on') for f in filters],
                                        q=req.args.get('q'),
                                        page=shown_page, noquickjump=1)
            pagedata.append([page_href, None, str(shown_page),
                             _("Page %(num)d", num=shown_page)])

        fields = ['href', 'class', 'string', 'title']
        results.shown_pages = [dict(zip(fields, p)) for p in pagedata]

        results.current_page = {'href': None, 'class': 'current',
                                'string': str(results.page + 1),
                                'title': None}

        if results.has_next_page:
            next_href = req.href.search(zip(filters, ['on'] * len(filters)),
                                        q=req.args.get('q'), page=page + 1,
                                        noquickjump=1)
            add_link(req, 'next', next_href, _('Next Page'))

        if results.has_previous_page:
            prev_href = req.href.search(zip(filters, ['on'] * len(filters)),
                                        q=req.args.get('q'), page=page - 1,
                                        noquickjump=1)
            add_link(req, 'prev', prev_href, _('Previous Page'))

        page_href = req.href.search(
            zip(filters, ['on'] * len(filters)), q=req.args.get('q'),
            noquickjump=1)
        return {'results': results, 'page_href': page_href}
<|endoftext|>


<commit_before>from __future__ import print_function

from util import *
import nbtencoder as nbt

import argparse
import sys, os

cprintconf.name = "Generator"
cprintconf.color = bcolors.PEACH

parser = argparse.ArgumentParser()
parser.add_argument("-m", "--mode", help="Choose activation mode for system", dest="mode", default="", choices=["m", "i"])
parser.add_argument("-f", "--command_file", help="File to load commands from", dest="filepath",
	default=None)
parser.add_argument("-C", "--no-copy", help="Don't copy the output command", dest="nocopy", action="store_true")
parser.add_argument("-q", "--quiet", help="Silence output", dest="quiet", action="store_true")
parser.add_argument("-v", "--verbose", help="Detailed output", dest="loud", action="store_true")
args = parser.parse_args()

if args.quiet:
	def cprint(*args, **kwargs):
		pass

if args.nocopy:
	class pyperclip:
		@staticmethod
		def copy(*args, **kwargs): pass
		@staticmethod
		def paste(*args, **kwargs): pass
else:
	import pyperclip

class Command:
	def __init__(self, cmd, init=False, conditional=False):
		self.cmd = cmd
		self.cond = conditional
		self.init = init
	def __str__(self):
		return self.cmd
	def prettystr(self):
		return format("{cmd}{init}{cond}",
			cmd = self.cmd,
			init = "\n  - Initialization" if self.init else "",
			cond = "\n  - Conditional" if self.cond else "",)

def generate_sand(command_obj, direction, block="chain_command_block", auto=True):
	return {
		"Block": block,
		"Data": direction+8 if command_obj.cond else direction,
		"Time": 1,
		"TileEntityData": {
			"Command": str(command_obj),
			"auto": int(auto),
			"TrackOutput": nbt.int_b(0)
		},
		"id": "FallingSand"
	}

def normal_sand(block, data=0):
	return {
		"Block": block,
		"Data": data,
		"Time": 1,
		"id": "FallingSand"
	}

def ride(entities):
	topmost = None
	absoluteTopmost = None

	for entity in entities:
		if topmost == None:
			absoluteTopmost = entity
		else:
			topmost["Riding"] = entity
		topmost = entity
	return absoluteTopmost

if __name__ == "__main__":
	cprint("""{peach}----------------------------------------{endc}
	  {cyan}TheDestruc7i0n{endc} and {golden}Wire Segal{endc}'s 1.9 One Command Generator
	 {green}Prepend your command with `INIT:` to make it only run when the structure is deployed.{endc}
	 {green}Prepend your command with `COND:` to make it a conditional command.{endc}
	        Please report any bugs at the GitHub repo: {line}{blue}https://github.com/destruc7i0n/OneCommand/issues{endc}
	        {peach}----------------------------------------{endc}""", strip=True)

	# get mode if not specified by argument
	if not args.mode:
		mode = cinput("Manual (m) or Instant (i)? ").strip().rstrip().lower()
		if mode not in ["m", "i"]:
			raise ValueError("Not manual or instant")
	else:
		mode = args.mode

	commands = []
	# get commands if file not specified
	if not args.filepath:
		x = 1
		command = cinput("Command {num}: ", num=x).strip().rstrip()
		while command:
			x += 1
			commands.append(command)
			command = cinput("Command {num}: ", num=x).strip().rstrip()
	# get commands from specified file
	else:
		if os.path.exists(args.filepath):
			commands = open(args.filepath).read().split("\n")
		else:
			raise IOError(format("File {file} not found.", file=args.filepath))

	init_commands = []
	clock_commands = []
	# do all INIT and COND checking
	for command in commands:
		if not command: continue
		command = command.strip().rstrip()
		if command[0] == "#": continue
		init = False
		conditional = False
		while command[:5] in ["INIT:","COND:"]:
			if command[:5] == "COND:": conditional = True
			elif command[:5] == "INIT:": init = True
			command = command[5:]
		command_obj = Command(command, conditional=conditional, init=init)
		if init:
			init_commands.append(command_obj)
		else:
			clock_commands.append(command_obj)

	final_command_obj = None
	if clock_commands or init_commands:
		command_sands = []

		for command in init_commands:
			if args.loud:
				cprint(command.prettystr())
			if command is init_commands[0]:
				command_sands.append(generate_sand(command, 0, "command_block"))
			else:
				command_sands.append(generate_sand(command, 0))

		if mode == 'i' and clock_commands:
			block = "command_block" if not init_commands else "chain_command_block"
			offset = len(clock_commands) + 1
			blockdata = Command(format("blockdata ~ ~-{offset} ~ {auto:1b}", offset = offset), init=True)
			if args.loud:
				cprint(blockdata.prettystr())
			command_sands.append(generate_sand(blockdata, 0, block))

		offset = len(init_commands) + int(bool(mode == 'i' and clock_commands))
		if offset:
			fill = Command(format("fill ~ ~-1 ~ ~ ~{offset} ~ air", offset = offset), init=True)
			if args.loud:
				cprint(fill.prettystr())
			command_sands.append(generate_sand(fill, 0))
			command_sands.append(normal_sand("barrier"))

		for command in clock_commands[::-1]:
			if args.loud:
				cprint(command.prettystr())
			if command is clock_commands[0]:
				command_sands.append(generate_sand(command, 1, "repeating_command_block", False))
			else:
				command_sands.append(generate_sand(command, 1))
		final_command_obj = nbt.cmd("summon FallingSand ~ ~1 ~ ", ride(command_sands))

	final_command = nbt.JSON2Command(final_command_obj)

	if len(final_command) <= 32500 and final_command:
		pyperclip.copy(final_command)
		if args.nocopy:
			cprint("{bold}Final command - {endc}", func=sys.stderr.write)
		else:
			cprint("{bold}Copied to clipboard - {endc}", func=sys.stderr.write)
		sys.stdout.write(final_command + "\n")
	elif not final_command:
		cprint("No command generated.", color=bcolors.RED)
	else:
		cprint("Command too large ({length} > 32500)", length=len(final), color=bcolors.RED)
<commit_msg>auto only on top sand<commit_after>from __future__ import print_function

from util import *
import nbtencoder as nbt

import argparse
import sys, os

cprintconf.name = "Generator"
cprintconf.color = bcolors.PEACH

parser = argparse.ArgumentParser()
parser.add_argument("-m", "--mode", help="Choose activation mode for system", dest="mode", default="", choices=["m", "i"])
parser.add_argument("-f", "--command_file", help="File to load commands from", dest="filepath",
	default=None)
parser.add_argument("-C", "--no-copy", help="Don't copy the output command", dest="nocopy", action="store_true")
parser.add_argument("-q", "--quiet", help="Silence output", dest="quiet", action="store_true")
parser.add_argument("-v", "--verbose", help="Detailed output", dest="loud", action="store_true")
args = parser.parse_args()

if args.quiet:
	def cprint(*args, **kwargs):
		pass

if args.nocopy:
	class pyperclip:
		@staticmethod
		def copy(*args, **kwargs): pass
		@staticmethod
		def paste(*args, **kwargs): pass
else:
	import pyperclip

class Command:
	def __init__(self, cmd, init=False, conditional=False):
		self.cmd = cmd
		self.cond = conditional
		self.init = init
	def __str__(self):
		return self.cmd
	def prettystr(self):
		return format("{cmd}{init}{cond}",
			cmd = self.cmd,
			init = "\n  - Initialization" if self.init else "",
			cond = "\n  - Conditional" if self.cond else "",)

def generate_sand(command_obj, direction, block="chain_command_block"):
	return {
		"Block": block,
		"Data": direction+8 if command_obj.cond else direction,
		"Time": 1,
		"TileEntityData": {
			"Command": str(command_obj),
			"TrackOutput": nbt.int_b(0)
		},
		"id": "FallingSand"
	}

def normal_sand(block, data=0):
	return {
		"Block": block,
		"Data": data,
		"Time": 1,
		"id": "FallingSand"
	}

def ride(entities):
	topmost = None
	absoluteTopmost = None

	for entity in entities:
		if topmost == None:
			absoluteTopmost = entity
		else:
			topmost["Riding"] = entity
		topmost = entity
	return absoluteTopmost

if __name__ == "__main__":
	cprint("""{peach}----------------------------------------{endc}
	  {cyan}TheDestruc7i0n{endc} and {golden}Wire Segal{endc}'s 1.9 One Command Generator
	 {green}Prepend your command with `INIT:` to make it only run when the structure is deployed.{endc}
	 {green}Prepend your command with `COND:` to make it a conditional command.{endc}
	        Please report any bugs at the GitHub repo: {line}{blue}https://github.com/destruc7i0n/OneCommand/issues{endc}
	        {peach}----------------------------------------{endc}""", strip=True)

	# get mode if not specified by argument
	if not args.mode:
		mode = cinput("Manual (m) or Instant (i)? ").strip().rstrip().lower()
		if mode not in ["m", "i"]:
			raise ValueError("Not manual or instant")
	else:
		mode = args.mode

	commands = []
	# get commands if file not specified
	if not args.filepath:
		x = 1
		command = cinput("Command {num}: ", num=x).strip().rstrip()
		while command:
			x += 1
			commands.append(command)
			command = cinput("Command {num}: ", num=x).strip().rstrip()
	# get commands from specified file
	else:
		if os.path.exists(args.filepath):
			commands = open(args.filepath).read().split("\n")
		else:
			raise IOError(format("File {file} not found.", file=args.filepath))

	init_commands = []
	clock_commands = []
	# do all INIT and COND checking
	for command in commands:
		if not command: continue
		command = command.strip().rstrip()
		if command[0] == "#": continue
		init = False
		conditional = False
		while command[:5] in ["INIT:","COND:"]:
			if command[:5] == "COND:": conditional = True
			elif command[:5] == "INIT:": init = True
			command = command[5:]
		command_obj = Command(command, conditional=conditional, init=init)
		if init:
			init_commands.append(command_obj)
		else:
			clock_commands.append(command_obj)

	final_command_obj = None
	if clock_commands or init_commands:
		command_sands = []

		for command in init_commands:
			if args.loud:
				cprint(command.prettystr())
			if command is init_commands[0]:
				topsand = generate_sand(command, 0, "command_block")
				topsand["TileEntityData"]["auto"] = 1
				command_sands.append(topsand)
			else:
				command_sands.append(generate_sand(command, 0))

		if mode == 'i' and clock_commands:
			block = "command_block" if not init_commands else "chain_command_block"
			offset = len(clock_commands) + 1
			blockdata = Command(format("blockdata ~ ~-{offset} ~ {auto:1b}", offset = offset), init=True)
			if args.loud:
				cprint(blockdata.prettystr())
			command_sands.append(generate_sand(blockdata, 0, block))

		offset = len(init_commands) + int(bool(mode == 'i' and clock_commands))
		if offset:
			fill = Command(format("fill ~ ~-1 ~ ~ ~{offset} ~ air", offset = offset), init=True)
			if args.loud:
				cprint(fill.prettystr())
			command_sands.append(generate_sand(fill, 0))
			command_sands.append(normal_sand("barrier"))

		for command in clock_commands[::-1]:
			if args.loud:
				cprint(command.prettystr())
			if command is clock_commands[0]:
				command_sands.append(generate_sand(command, 1, "repeating_command_block"))
			else:
				command_sands.append(generate_sand(command, 1))
		final_command_obj = nbt.cmd("summon FallingSand ~ ~1 ~ ", ride(command_sands))

	final_command = nbt.JSON2Command(final_command_obj)

	if len(final_command) <= 32500 and final_command:
		pyperclip.copy(final_command)
		if args.nocopy:
			cprint("{bold}Final command - {endc}", func=sys.stderr.write)
		else:
			cprint("{bold}Copied to clipboard - {endc}", func=sys.stderr.write)
		sys.stdout.write(final_command + "\n")
	elif not final_command:
		cprint("No command generated.", color=bcolors.RED)
	else:
		cprint("Command too large ({length} > 32500)", length=len(final), color=bcolors.RED)
<|endoftext|>


<commit_before>from __future__ import division

import numpy as np
from fractions import gcd

class TorusKnot(object):
    """Representation of a torus knot.

    A torus knot is one that can be drawn on the surface of a
    torus. It is parameterised by two integers p and q as below; in
    fact this returns a single knot (a single curve) only if p and q
    are coprime, otherwise it describes multiple linked curves.  The
    methods of this class return the full link even if there is only
    one component (i.e. p and q *are* coprime).

    Parameters
    ----------
    p : int
        The number of times the knot winds around the outside of the
        torus. Defaults to 2.
    q : int
        The number of times the knot passes through the hole in the
        centre of the torus. Defaults to 3.
    num_points : int
        The number of points in the returned piecewise linear
        curve. If there are multiple curves (i.e. a torus link), this
        is the number of points in *each* curve.  Defaults to 100.
    major_radius : float
        Distance from the center of the torus tube to the center of the torus.
        Defaults to 10.
    minor_radius : float
        The radius of the torus tube. Defaults to 5.

    """

    def __init__(self, p=3, q=2, num_points=100, major_radius=10.,
                 minor_radius=5.):
        self._p = p
        self._q = q
        self._num_points = num_points
        self._major_radius = major_radius
        self._minor_radius = minor_radius

        self._calculate_vertices()

    def _calculate_vertices(self):
        angles = np.linspace(0, 2*np.pi, self._num_points)

        num_components = self.num_components

        divisions = (np.max([self._q, self._p]) *
                     np.min([self._q, self._p]) / self.num_components)
        starting_angles = np.linspace(
            0, 2*np.pi, divisions + 1)[
            :num_components]
        q = self._q / num_components
        p = self._p / num_components

        components = []
        for starting_angle in starting_angles:
            vertices = np.zeros((self._num_points, 3))
            local_angles = angles + starting_angle
            radii = (self._minor_radius * np.cos(q * angles) +
                     self._major_radius)
            vertices[:, 0] = radii * np.cos(p * local_angles)
            vertices[:, 1] = radii * np.sin(p * local_angles)
            vertices[:, 2] = (self._minor_radius * -1 *
                              np.sin(q * angles))
            components.append(vertices)

        self._components = components

    @property
    def first_component(self):
        '''The vertices of the first component line of the torus knot or link.
        '''
        return self._components[0]

    @property
    def components(self):

        '''A list of the vertices in each line of the torus knot or link.'''
        return self._components

    @property
    def num_components(self):
        '''The number of component lines in the torus link. This is equal
        to the greatest common divisor of p and q.
        '''
        return gcd(self._p, self._q)

    @property
    def q(self):
        '''The q parameter of the torus knot or link.'''
        return self._q

    @q.setter
    def q(self, q):
        self._q = q
        self._calculate_vertices()

    @property
    def p(self):
        '''The p parameter of the torus knot or link.'''
        return self._p

    @p.setter
    def p(self, p):
        self._p = p
        self._calculate_vertices()

    @property
    def minor_radius(self):
        '''The minor radius of the torus.'''
        return self._minor_radius

    @minor_radius.setter
    def minor_radius(self, r):
        self._minor_radius = r
        self._calculate_vertices()

    @property
    def major_radius(self):
        '''The major radius of the torus.'''
        return self._major_radius

    @major_radius.setter
    def major_radius(self, r):
        self._major_radius = r
        self._calculate_vertices()

    @property
    def num_points(self):
        '''The number of points in the vertices returned for each knot/link
        component'''
        return self._num_points

    @num_points.setter
    def num_points(self, r):
        self._num_points = r
        self._calculate_vertices()
<commit_msg>Improved documentation of TorusKnot geometry<commit_after>from __future__ import division

import numpy as np
from fractions import gcd

class TorusKnot(object):
    """Representation of a torus knot or link.

    A torus knot is one that can be drawn on the surface of a
    torus. It is parameterised by two integers p and q as below; in
    fact this returns a single knot (a single curve) only if p and q
    are coprime, otherwise it describes multiple linked curves.

    Parameters
    ----------
    p : int
        The number of times the knot winds around the outside of the
        torus. Defaults to 2.
    q : int
        The number of times the knot passes through the hole in the
        centre of the torus. Defaults to 3.
    num_points : int
        The number of points in the returned piecewise linear
        curve. If there are multiple curves (i.e. a torus link), this
        is the number of points in *each* curve.  Defaults to 100.
    major_radius : float
        Distance from the center of the torus tube to the center of the torus.
        Defaults to 10.
    minor_radius : float
        The radius of the torus tube. Defaults to 5.

    """

    def __init__(self, p=3, q=2, num_points=100, major_radius=10.,
                 minor_radius=5.):
        self._p = p
        self._q = q
        self._num_points = num_points
        self._major_radius = major_radius
        self._minor_radius = minor_radius

        self._calculate_vertices()

    def _calculate_vertices(self):
        angles = np.linspace(0, 2*np.pi, self._num_points)

        num_components = self.num_components

        divisions = (np.max([self._q, self._p]) *
                     np.min([self._q, self._p]) / self.num_components)
        starting_angles = np.linspace(
            0, 2*np.pi, divisions + 1)[
            :num_components]
        q = self._q / num_components
        p = self._p / num_components

        components = []
        for starting_angle in starting_angles:
            vertices = np.zeros((self._num_points, 3))
            local_angles = angles + starting_angle
            radii = (self._minor_radius * np.cos(q * angles) +
                     self._major_radius)
            vertices[:, 0] = radii * np.cos(p * local_angles)
            vertices[:, 1] = radii * np.sin(p * local_angles)
            vertices[:, 2] = (self._minor_radius * -1 *
                              np.sin(q * angles))
            components.append(vertices)

        self._components = components

    @property
    def first_component(self):
        '''The vertices of the first component line of the torus knot or link.
        '''
        return self._components[0]

    @property
    def components(self):
        '''A list of the vertices in each line of the torus knot or link.
        Even if p and q are coprime, this is a list with just one
        entry.
        '''
        return self._components

    @property
    def num_components(self):
        '''The number of component lines in the torus link. This is equal
        to the greatest common divisor of p and q.
        '''
        return gcd(self._p, self._q)

    @property
    def q(self):
        '''The q parameter of the torus knot or link.'''
        return self._q

    @q.setter
    def q(self, q):
        self._q = q
        self._calculate_vertices()

    @property
    def p(self):
        '''The p parameter of the torus knot or link.'''
        return self._p

    @p.setter
    def p(self, p):
        self._p = p
        self._calculate_vertices()

    @property
    def minor_radius(self):
        '''The minor radius of the torus.'''
        return self._minor_radius

    @minor_radius.setter
    def minor_radius(self, r):
        self._minor_radius = r
        self._calculate_vertices()

    @property
    def major_radius(self):
        '''The major radius of the torus.'''
        return self._major_radius

    @major_radius.setter
    def major_radius(self, r):
        self._major_radius = r
        self._calculate_vertices()

    @property
    def num_points(self):
        '''The number of points in the vertices returned for each knot/link
        component'''
        return self._num_points

    @num_points.setter
    def num_points(self, r):
        self._num_points = r
        self._calculate_vertices()
<|endoftext|>


<commit_before>import logging.config
from flask import Flask, Blueprint
from server import settings
from server.api.jenkins.endpoints.sites import ns as jenkins_sites_namespace
from server.api.jenkins.endpoints.jobs import ns as jenkins_jobs_namespace
from server.api.jenkins.endpoints.builds import ns as jenkins_builds_namespace
from server.api.jenkins.endpoints.test_reports import ns as jenkins_test_reports_namespace
from server.api.jenkins.endpoints.stats import ns as jenkins_test_stats_namespace
from server.api.jenkins.endpoints.datas import ns as jenkins_datas_namespace
from server.api.common import api
from server.db import db

app = Flask(__name__)
logging.config.fileConfig('logging.conf')
log = logging.getLogger(__name__)

def configure_app(flask_app):
    flask_app.config['SERVER_NAME'] = settings.FLASK_SERVER_NAME
    flask_app.config['MONGO_DBNAME'] = settings.MONGO_DBNAME
    flask_app.config['SWAGGER_UI_DOC_EXPANSION'] = settings.RESTPLUS_SWAGGER_UI_DOC_EXPANSION
    flask_app.config['RESTPLUS_VALIDATE'] = settings.RESTPLUS_VALIDATE
    flask_app.config['RESTPLUS_MASK_SWAGGER'] = settings.RESTPLUS_MASK_SWAGGER
    flask_app.config['ERROR_404_HELP'] = settings.RESTPLUS_ERROR_404_HELP

def initialize_app(flask_app):
    configure_app(flask_app)

    blueprint = Blueprint('api', __name__, url_prefix='/api')
    api.init_app(blueprint)

    api.add_namespace(jenkins_sites_namespace)
    api.add_namespace(jenkins_jobs_namespace)
    api.add_namespace(jenkins_builds_namespace)
    api.add_namespace(jenkins_test_reports_namespace)
    api.add_namespace(jenkins_test_stats_namespace)
    api.add_namespace(jenkins_datas_namespace)

    flask_app.register_blueprint(blueprint)

    db.init_app(flask_app)

def reset_database(flask_app):
    log.info("Drop database")
    db.cx.drop_database(flask_app.config['MONGO_DBNAME'])

def main():
    initialize_app(app)
    log.info('Starting development server at http://{}/api/'.format(app.config['SERVER_NAME']))

    reset_db = not True
    if reset_db:
        with app.app_context():
            reset_database(app)

    app.run(debug=settings.FLASK_DEBUG)

if __name__ == "__main__":
    main()
<commit_msg>fix logging config path<commit_after>import logging.config
from flask import Flask, Blueprint
from server import settings
from server.api.jenkins.endpoints.sites import ns as jenkins_sites_namespace
from server.api.jenkins.endpoints.jobs import ns as jenkins_jobs_namespace
from server.api.jenkins.endpoints.builds import ns as jenkins_builds_namespace
from server.api.jenkins.endpoints.test_reports import ns as jenkins_test_reports_namespace
from server.api.jenkins.endpoints.stats import ns as jenkins_test_stats_namespace
from server.api.jenkins.endpoints.datas import ns as jenkins_datas_namespace
from server.api.common import api
from server.db import db
import os

app = Flask(__name__)
logging_conf_file = os.path.abspath("server/logging.conf")
print(logging_conf_file)
logging.config.fileConfig(logging_conf_file)
log = logging.getLogger(__name__)

def configure_app(flask_app):
    flask_app.config['SERVER_NAME'] = settings.FLASK_SERVER_NAME
    flask_app.config['MONGO_DBNAME'] = settings.MONGO_DBNAME
    flask_app.config['SWAGGER_UI_DOC_EXPANSION'] = settings.RESTPLUS_SWAGGER_UI_DOC_EXPANSION
    flask_app.config['RESTPLUS_VALIDATE'] = settings.RESTPLUS_VALIDATE
    flask_app.config['RESTPLUS_MASK_SWAGGER'] = settings.RESTPLUS_MASK_SWAGGER
    flask_app.config['ERROR_404_HELP'] = settings.RESTPLUS_ERROR_404_HELP

def initialize_app(flask_app):
    configure_app(flask_app)

    blueprint = Blueprint('api', __name__, url_prefix='/api')
    api.init_app(blueprint)

    api.add_namespace(jenkins_sites_namespace)
    api.add_namespace(jenkins_jobs_namespace)
    api.add_namespace(jenkins_builds_namespace)
    api.add_namespace(jenkins_test_reports_namespace)
    api.add_namespace(jenkins_test_stats_namespace)
    api.add_namespace(jenkins_datas_namespace)

    flask_app.register_blueprint(blueprint)

    db.init_app(flask_app)

def reset_database(flask_app):
    log.info("Drop database")
    db.cx.drop_database(flask_app.config['MONGO_DBNAME'])

def main():
    initialize_app(app)
    log.info('Starting development server at http://{}/api/'.format(app.config['SERVER_NAME']))

    reset_db = not True
    if reset_db:
        with app.app_context():
            reset_database(app)

    app.run(debug=settings.FLASK_DEBUG)

if __name__ == "__main__":
    main()
<|endoftext|>


<commit_before>from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.core import validators
from django.db import backend, connection
from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models
from django.db.models.query import Q
from django.db.models.manager import Manager
from django.db.models.base import Model, AdminOptions
from django.db.models.fields import *
from django.db.models.fields.related import ForeignKey, OneToOneField, ManyToManyField, ManyToOneRel, ManyToManyRel, OneToOneRel, TABULAR, STACKED
from django.db.models.fields.generic import GenericRelation, GenericRel, GenericForeignKey
from django.db.models import signals
from django.utils.functional import curry
from django.utils.text import capfirst

# Admin stages.
ADD, CHANGE, BOTH = 1, 2, 3

class LazyDate(object):
    """
    Use in limit_choices_to to compare the field to dates calculated at run time
    instead of when the model is loaded.  For example::

        ... limit_choices_to = {'date__gt' : models.LazyDate(days=-3)} ...

    which will limit the choices to dates greater than three days ago.
    """
    def __init__(self, **kwargs):
        self.delta = datetime.timedelta(**kwargs)

    def __str__(self):
        return str(self.__get_value__())

    def __repr__(self):
        return "<LazyDate: %s>" % self.delta

    def __get_value__(self):
        return datetime.datetime.now() + self.delta

    def __getattr__(self, attr):
        return getattr(self.__get_value__(), attr)
<commit_msg>Added django.db.models.permalink decorator, which decorates a function that returns a viewname, viewargs and viewkwargs. The decorator returns the result of a reverse URL lookup on those parameters. Documentation is forthcoming.<commit_after>from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.core import validators
from django.db import backend, connection
from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models
from django.db.models.query import Q
from django.db.models.manager import Manager
from django.db.models.base import Model, AdminOptions
from django.db.models.fields import *
from django.db.models.fields.related import ForeignKey, OneToOneField, ManyToManyField, ManyToOneRel, ManyToManyRel, OneToOneRel, TABULAR, STACKED
from django.db.models.fields.generic import GenericRelation, GenericRel, GenericForeignKey
from django.db.models import signals
from django.utils.functional import curry
from django.utils.text import capfirst

# Admin stages.
ADD, CHANGE, BOTH = 1, 2, 3

# Decorator. Takes a function that returns a tuple in this format:
#     (viewname, viewargs, viewkwargs)
# Returns a function that calls urlresolvers.reverse() on that data, to return
# the URL for those parameters.
def permalink(func):
    from django.core.urlresolvers import reverse
    def inner(*args, **kwargs):
        bits = func(*args, **kwargs)
        viewname = bits[0]
        return reverse(bits[0], None, *bits[1:2])
    return inner

class LazyDate(object):
    """
    Use in limit_choices_to to compare the field to dates calculated at run time
    instead of when the model is loaded.  For example::

        ... limit_choices_to = {'date__gt' : models.LazyDate(days=-3)} ...

    which will limit the choices to dates greater than three days ago.
    """
    def __init__(self, **kwargs):
        self.delta = datetime.timedelta(**kwargs)

    def __str__(self):
        return str(self.__get_value__())

    def __repr__(self):
        return "<LazyDate: %s>" % self.delta

    def __get_value__(self):
        return datetime.datetime.now() + self.delta

    def __getattr__(self, attr):
        return getattr(self.__get_value__(), attr)
<|endoftext|>


<commit_before>"""
websocket - WebSocket client library for Python

Copyright (C) 2010 Hiroki Ohtani(liris)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA  02110-1335  USA

"""
import hashlib
import hmac
import os

import six

from ._cookiejar import SimpleCookieJar
from ._exceptions import *
from ._http import *
from ._logging import *
from ._socket import *

if six.PY3:
    from base64 import encodebytes as base64encode
else:
    from base64 import encodestring as base64encode

__all__ = ["handshake_response", "handshake"]

if hasattr(hmac, "compare_digest"):
    compare_digest = hmac.compare_digest
else:
    def compare_digest(s1, s2):
        return s1 == s2

# websocket supported version.
VERSION = 13

CookieJar = SimpleCookieJar()

class handshake_response(object):

    def __init__(self, status, headers, subprotocol):
        self.status = status
        self.headers = headers
        self.subprotocol = subprotocol
        CookieJar.add(headers.get("set-cookie"))

def handshake(sock, hostname, port, resource, **options):
    headers, key = _get_handshake_headers(resource, hostname, port, options)

    header_str = "\r\n".join(headers)
    send(sock, header_str)
    dump("request header", header_str)

    status, resp = _get_resp_headers(sock)
    success, subproto = _validate(resp, key, options.get("subprotocols"))
    if not success:
        raise WebSocketException("Invalid WebSocket Header")

    return handshake_response(status, resp, subproto)

def _get_handshake_headers(resource, host, port, options):
    headers = [
        "GET %s HTTP/1.1" % resource,
        "Upgrade: websocket",
        "Connection: Upgrade"
    ]
    if port == 80 or port == 443:
        hostport = host
    else:
        hostport = "%s:%d" % (host, port)

    if "host" in options and options["host"] is not None:
        headers.append("Host: %s" % options["host"])
    else:
        headers.append("Host: %s" % hostport)

    if "origin" in options and options["origin"] is not None:
        headers.append("Origin: %s" % options["origin"])
    else:
        headers.append("Origin: http://%s" % hostport)

    key = _create_sec_websocket_key()
    headers.append("Sec-WebSocket-Key: %s" % key)
    headers.append("Sec-WebSocket-Version: %s" % VERSION)

    subprotocols = options.get("subprotocols")
    if subprotocols:
        headers.append("Sec-WebSocket-Protocol: %s" % ",".join(subprotocols))

    if "header" in options:
        header = options["header"]
        if isinstance(header, dict):
            header = map(": ".join, header.items())
        headers.extend(header)

    server_cookie = CookieJar.get(host)
    client_cookie = options.get("cookie", None)

    cookie = "; ".join(filter(None, [server_cookie, client_cookie]))

    if cookie:
        headers.append("Cookie: %s" % cookie)

    headers.append("")
    headers.append("")

    return headers, key

def _get_resp_headers(sock, success_status=101):
    status, resp_headers = read_headers(sock)
    if status != success_status:
        raise WebSocketBadStatusException("Handshake status %d", status)
    return status, resp_headers

_HEADERS_TO_CHECK = {
    "upgrade": "websocket",
    "connection": "upgrade",
}

def _validate(headers, key, subprotocols):
    subproto = None
    for k, v in _HEADERS_TO_CHECK.items():
        r = headers.get(k, None)
        if not r:
            return False, None
        r = r.lower()
        if v != r:
            return False, None

    if subprotocols:
        subproto = headers.get("sec-websocket-protocol", None).lower()
        if not subproto or subproto not in [s.lower() for s in subprotocols]:
            error("Invalid subprotocol: " + str(subprotocols))
            return False, None

    result = headers.get("sec-websocket-accept", None)
    if not result:
        return False, None
    result = result.lower()

    if isinstance(result, six.text_type):
        result = result.encode('utf-8')

    value = (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode('utf-8')
    hashed = base64encode(hashlib.sha1(value).digest()).strip().lower()
    success = compare_digest(hashed, result)

    if success:
        return True, subproto
    else:
        return False, None

def _create_sec_websocket_key():
    randomness = os.urandom(16)
    return base64encode(randomness).decode('utf-8').strip()
<commit_msg>refs #357<commit_after>"""
websocket - WebSocket client library for Python

Copyright (C) 2010 Hiroki Ohtani(liris)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA  02110-1335  USA

"""
import hashlib
import hmac
import os

import six

from ._cookiejar import SimpleCookieJar
from ._exceptions import *
from ._http import *
from ._logging import *
from ._socket import *

if six.PY3:
    from base64 import encodebytes as base64encode
else:
    from base64 import encodestring as base64encode

__all__ = ["handshake_response", "handshake"]

if hasattr(hmac, "compare_digest"):
    compare_digest = hmac.compare_digest
else:
    def compare_digest(s1, s2):
        return s1 == s2

# websocket supported version.
VERSION = 13

CookieJar = SimpleCookieJar()

class handshake_response(object):

    def __init__(self, status, headers, subprotocol):
        self.status = status
        self.headers = headers
        self.subprotocol = subprotocol
        CookieJar.add(headers.get("set-cookie"))

def handshake(sock, hostname, port, resource, **options):
    headers, key = _get_handshake_headers(resource, hostname, port, options)

    header_str = "\r\n".join(headers)
    send(sock, header_str)
    dump("request header", header_str)

    status, resp = _get_resp_headers(sock)
    success, subproto = _validate(resp, key, options.get("subprotocols"))
    if not success:
        raise WebSocketException("Invalid WebSocket Header")

    return handshake_response(status, resp, subproto)

def _pack_hostname(hostname):
    # IPv6 address
    if ':' in hostname:
        return '[' + hostname + ']'

    return hostname

def _get_handshake_headers(resource, host, port, options):
    headers = [
        "GET %s HTTP/1.1" % resource,
        "Upgrade: websocket",
        "Connection: Upgrade"
    ]
    if port == 80 or port == 443:
        hostport = _pack_hostname(host)
    else:
        hostport = "%s:%d" % (_pack_hostname(host), port)

    if "host" in options and options["host"] is not None:
        headers.append("Host: %s" % options["host"])
    else:
        headers.append("Host: %s" % hostport)

    if "origin" in options and options["origin"] is not None:
        headers.append("Origin: %s" % options["origin"])
    else:
        headers.append("Origin: http://%s" % hostport)

    key = _create_sec_websocket_key()
    headers.append("Sec-WebSocket-Key: %s" % key)
    headers.append("Sec-WebSocket-Version: %s" % VERSION)

    subprotocols = options.get("subprotocols")
    if subprotocols:
        headers.append("Sec-WebSocket-Protocol: %s" % ",".join(subprotocols))

    if "header" in options:
        header = options["header"]
        if isinstance(header, dict):
            header = map(": ".join, header.items())
        headers.extend(header)

    server_cookie = CookieJar.get(host)
    client_cookie = options.get("cookie", None)

    cookie = "; ".join(filter(None, [server_cookie, client_cookie]))

    if cookie:
        headers.append("Cookie: %s" % cookie)

    headers.append("")
    headers.append("")

    return headers, key

def _get_resp_headers(sock, success_status=101):
    status, resp_headers = read_headers(sock)
    if status != success_status:
        raise WebSocketBadStatusException("Handshake status %d", status)
    return status, resp_headers

_HEADERS_TO_CHECK = {
    "upgrade": "websocket",
    "connection": "upgrade",
}

def _validate(headers, key, subprotocols):
    subproto = None
    for k, v in _HEADERS_TO_CHECK.items():
        r = headers.get(k, None)
        if not r:
            return False, None
        r = r.lower()
        if v != r:
            return False, None

    if subprotocols:
        subproto = headers.get("sec-websocket-protocol", None).lower()
        if not subproto or subproto not in [s.lower() for s in subprotocols]:
            error("Invalid subprotocol: " + str(subprotocols))
            return False, None

    result = headers.get("sec-websocket-accept", None)
    if not result:
        return False, None
    result = result.lower()

    if isinstance(result, six.text_type):
        result = result.encode('utf-8')

    value = (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode('utf-8')
    hashed = base64encode(hashlib.sha1(value).digest()).strip().lower()
    success = compare_digest(hashed, result)

    if success:
        return True, subproto
    else:
        return False, None

def _create_sec_websocket_key():
    randomness = os.urandom(16)
    return base64encode(randomness).decode('utf-8').strip()
<|endoftext|>


<commit_before>"""write meeee"""
import optimus
from optimus.examples.mnist import load_mnist

# 1.1 Create Inputs
input_data = optimus.Input(
    name='image',
    shape=(None, 1, 28, 28))

class_labels = optimus.Input(
    name='label',
    shape=(None,),
    dtype='int32')

decay = optimus.Input(
    name='decay_param',
    shape=None)

sparsity = optimus.Input(
    name='sparsity_param',
    shape=None)

learning_rate = optimus.Input(
    name='learning_rate',
    shape=None)

# 1.2 Create Nodes
conv = optimus.Conv3D(
    name='conv',
    input_shape=input_data.shape,
    weight_shape=(15, 1, 9, 9),
    pool_shape=(2, 2),
    act_type='relu')

affine = optimus.Affine(
    name='affine',
    input_shape=conv.output.shape,
    output_shape=(None, 512,),
    act_type='relu')

classifier = optimus.Softmax(
    name='classifier',
    input_shape=affine.output.shape,
    n_out=10,
    act_type='linear')

# 1.1 Create Losses
nll = optimus.NegativeLogLikelihood(
    name="negloglikelihood")

conv_decay = optimus.L2Magnitude(
    name='weight_decay')

affine_sparsity = optimus.L1Magnitude(
    name="feature_sparsity")

# 2. Define Edges
connect_manager = optimus.ConnectionManager([
    (input_data, conv.input),
    (conv.output, affine.input),
    (affine.output, classifier.input),
    (classifier.output, nll.likelihood),
    (class_labels, nll.target_idx),
    (conv.weights, conv_decay.input),
    (decay, conv_decay.weight),
    (affine.output, affine_sparsity.input),
    (sparsity, affine_sparsity.weight)])

update_manager = optimus.ConnectionManager([
    (learning_rate, conv.weights),
    (learning_rate, conv.bias),
    (learning_rate, affine.weights),
    (learning_rate, affine.bias),
    (learning_rate, classifier.weights),
    (learning_rate, classifier.bias)])

train = optimus.Graph(
    name='mnist_3layer',
    inputs=[input_data, class_labels, decay, sparsity, learning_rate],
    nodes=[conv, affine, classifier],
    connections=connect_manager.connections,
    outputs=[optimus.Graph.TOTAL_LOSS, classifier.output],
    losses=[nll, conv_decay, affine_sparsity],
    updates=update_manager.connections)

optimus.random_init(classifier.weights)

# 3. Create Data
dset = load_mnist("/Users/ejhumphrey/Desktop/mnist.pkl")[0]
source = optimus.Queue(dset, batch_size=50, refresh_prob=0.0, cache_size=5000)

driver = optimus.Driver(graph=train, name='example_classifier')

hyperparams = {
    learning_rate.name: 0.02,
    sparsity.name: 0.001,
    decay.name: 0.1}

driver.fit(source, hyperparams=hyperparams, max_iter=5000, save_freq=25)
<commit_msg>mnist_classifier example in progress, but things aren't learning at the moment...?<commit_after>"""write meeee"""
import optimus
from optimus.examples.mnist import load_mnist

# 1.1 Create Inputs
input_data = optimus.Input(
    name='image',
    shape=(None, 1, 28, 28))

class_labels = optimus.Input(
    name='label',
    shape=(None,),
    dtype='int32')

decay = optimus.Input(
    name='decay_param',
    shape=None)

sparsity = optimus.Input(
    name='sparsity_param',
    shape=None)

learning_rate = optimus.Input(
    name='learning_rate',
    shape=None)

# 1.2 Create Nodes
conv = optimus.Conv3D(
    name='conv',
    input_shape=input_data.shape,
    weight_shape=(15, 1, 9, 9),
    pool_shape=(2, 2),
    act_type='relu')

affine = optimus.Affine(
    name='affine',
    input_shape=conv.output.shape,
    output_shape=(None, 512,),
    act_type='relu')

classifier = optimus.Softmax(
    name='classifier',
    input_shape=affine.output.shape,
    n_out=10,
    act_type='linear')

# 1.1 Create Losses
nll = optimus.NegativeLogLikelihood(
    name="negloglikelihood")

conv_decay = optimus.L2Magnitude(
    name='weight_decay')

affine_sparsity = optimus.L1Magnitude(
    name="feature_sparsity")

# 2. Define Edges
train_edges = optimus.ConnectionManager([
    (input_data, conv.input),
    (conv.output, affine.input),
    (affine.output, classifier.input),
    (classifier.output, nll.likelihood),
    (class_labels, nll.target_idx),
    (conv.weights, conv_decay.input),
    (decay, conv_decay.weight),
    (affine.output, affine_sparsity.input),
    (sparsity, affine_sparsity.weight)])

update_manager = optimus.ConnectionManager([
    (learning_rate, conv.weights),
    (learning_rate, conv.bias),
    (learning_rate, affine.weights),
    (learning_rate, affine.bias),
    (learning_rate, classifier.weights),
    (learning_rate, classifier.bias)])

train = optimus.Graph(
    name='mnist_3layer',
    inputs=[input_data, class_labels, decay, sparsity, learning_rate],
    nodes=[conv, affine, classifier],
    connections=train_edges.connections,
    outputs=[optimus.Graph.TOTAL_LOSS, classifier.output],
    losses=[nll, conv_decay, affine_sparsity],
    updates=update_manager.connections)

optimus.random_init(classifier.weights)

# est_edges = optimus.ConnectionManager([
#     (input_data, conv.input),
#     (conv.output, affine.input),
#     (affine.output, classifier.input)])

# estimate = optimus.Graph(
#     name='mnist_classifier',
#     inputs=[input_data],
#     nodes=[conv, affine, classifier],
#     connections=est_edges.connections,
#     outputs=[classifier.output])

# # 3. Create Data
dset = load_mnist("/Users/ejhumphrey/Desktop/mnist.pkl")[0]
source = optimus.Queue(dset, batch_size=50, refresh_prob=0.0, cache_size=50000)

driver = optimus.Driver(graph=train, name='example_classifier')

hyperparams = {
    learning_rate.name: 0.01,
    sparsity.name: 0.002,
    decay.name: 0.002}

driver.fit(source, hyperparams=hyperparams, max_iter=5000, print_freq=25)
<|endoftext|>