<commit_before>#!/usr/bin/python

import json

import bottle
from bottle_mongo import MongoPlugin

app = bottle.Bottle()
app.config.update({
    'mongodb.uri': 'mongodb://localhost:27017/',
    'mongodb.db': 'kala'
})

app.config.load_config('settings.ini')

app.install(MongoPlugin(
    uri=app.config['mongodb.uri'],
    db=app.config['mongodb.db'],
    json_mongo=True))

def _get_json(name):
    result = bottle.request.query.get(name)
    return json.loads(result) if result else None

@app.route('/<collection>')
def get(mongodb, collection):
    filter_ = _get_json('filter')
    projection = _get_json('projection')
    skip = int(bottle.request.query.get('skip', 0))
    limit = int(bottle.request.query.get('limit', 100))
    sort = _get_json('sort')
    # Turns a JSON array of arrays to a list of tuples.
    sort = [tuple(field) for field in sort] if sort else None

    cursor = mongodb[collection].find(
        filter=filter_, projection=projection, skip=skip, limit=limit,
        sort=sort
    )

    return {'results': [document for document in cursor]}

def main():
    app.run()

if __name__ == '__main__':
    main()
<commit_msg>allow environment variables to be used for config<commit_after>#!/usr/bin/python

import os
import json

import bottle
from bottle_mongo import MongoPlugin

app = bottle.Bottle()
app.config.update({
    'mongodb.uri': 'mongodb://localhost:27017/',
    'mongodb.db': 'kala'
})

app.config.load_config(os.environ.get('KALA_CONFIGFILE', 'settings.ini'))

app.install(MongoPlugin(
    uri=os.environ.get('KALA_MONGODB_URI', app.config['mongodb.uri']),
    db=os.environ.get('KALA_MONGODB_DB', app.config['mongodb.db']),
    json_mongo=True))

def _get_json(name):
    result = bottle.request.query.get(name)
    return json.loads(result) if result else None

@app.route('/<collection>')
def get(mongodb, collection):
    filter_ = _get_json('filter')
    projection = _get_json('projection')
    skip = int(bottle.request.query.get('skip', 0))
    limit = int(bottle.request.query.get('limit', 100))
    sort = _get_json('sort')
    # Turns a JSON array of arrays to a list of tuples.
    sort = [tuple(field) for field in sort] if sort else None

    cursor = mongodb[collection].find(
        filter=filter_, projection=projection, skip=skip, limit=limit,
        sort=sort
    )

    return {'results': [document for document in cursor]}

def main():
    app.run()

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


<commit_before>import sys
import os
import directories
import config
import albow
import mceutils
from pygame import display, event, key, KMOD_ALT, KMOD_CTRL, KMOD_LALT, KMOD_META, KMOD_RALT, KMOD_SHIFT, mouse, \
    MOUSEMOTION
from albow.dialogs import Dialog, QuickDialog, wrapped_label
from albow import alert, ask, AttrRef, Button, Column, get_font, Grid, input_text, IntField, Menu, root, Row, \
    TableColumn, TableView, TextField, TimeField, Widget, CheckBox
from albow.controls import Label, SmallValueDisplay, ValueDisplay
from albow.translate import tr
from glbackground import Panel

ESCAPE = '\033'

def remapMouseButton(button):
    buttons = [0, 1, 3, 2, 4, 5, 6, 7]  # mouse2 is right button, mouse3 is middle
    if button < len(buttons):
        return buttons[button]
    return button

def getKey(evt, i=0):
    keyname = key.name(evt.key)
    if keyname == 'Enter':
            keyname = 'Return'
    if 'left' in keyname and len(keyname) > 5:
        keyname = keyname[5:]
    elif 'right' in keyname and len(keyname) > 6:
        keyname = keyname[6:]
    if keyname == 'Meta':
        keyname = 'Ctrl'
    try:
        keyname = keyname.replace(keyname[0], keyname[0].upper(), 1)
    finally:
        newKeyname = ""
        if evt.shift == True and keyname != "Shift" and i != 1:
            newKeyname += "Shift-"
        if evt.ctrl == True and keyname != "Ctrl" and i != 1:
            newKeyname += "Ctrl-"
        if evt.alt == True and keyname != "Alt" and i != 1:
            newKeyname += "Alt-"

        keyname = newKeyname + keyname
        return keyname

class KeyConfigPanel(Dialog):
    keyConfigKeys = [
        "<Movement Controls>",
        "Forward",
        "Back",
        "Left",
        "Right",
        "Up",
        "Down",
        "Brake",
        "",
        "<Camera Controls>",
        "Pan Up",
        "Pan Down",
        "Pan Left",
        "Pan Right",
        "",
        "<Tool Controls>",
        "Rotate",
        "Roll",
        "Flip",
        "Mirror",
        "Swap",
        "Delete Blocks",
        "Increase Reach",
        "Decrease Reach",
        "Reset Reach",
        "",
        "<Function Controls>",
        "Quit",
        "Swap View",
        "Select All",
        "Deselect",
        "Cut",
        "Copy",
        "Paste",
        "Reload World",
        "Open",
        "Quick Load",
        "Undo",
        "Save",
        "New World",
        "Close World",
        "World Info",
        "Goto Panel",
        "Export Selection"
    ]

    presets = {"WASD": [
        ("Forward", "W"),
        ("Back", "S"),
        ("Left", "A"),
        ("Right", "D"),
        ("Up", "Space"),
        ("Down", "Shift"),
        ("Brake", "C"),

        ("Rotate", "E"),
        ("Roll", "R"),
        ("Flip", "F"),
        ("Mirror", "G"),
        ("Swap", "X"),
        ("Increase Reach", "Scroll Up"),
        ("Decrease Reach", "Scroll Down"),
        ("Reset Reach", "Mouse3"),
        ("Delete Blocks", "Delete"),
    ],
               "Arrows": [
                   ("Forward", "Up"),
                   ("Back", "Down"),
                   ("Left", "Left"),
                   ("Right", "Right"),
                   ("Up", "Page Up"),
                   ("Down", "Page Down"),
                   ("Brake", "Space"),

                   ("Rotate", "Home"),
                   ("Roll", "End"),
                   ("Flip", "Insert"),
                   ("Mirror", "Delete"),
                   ("Swap", "\\"),
                   ("Increase Reach", "Scroll Up"),
                   ("Decrease Reach", "Scroll Down"),
                   ("Reset Reach", "Mouse3"),
                   ("Delete Blocks", "Backspace")
               ],
               "Numpad": [
                   ("Forward", "[8]"),
                   ("Back", "[5]"),
                   ("Left", "[4]"),
                   ("Right", "[6]"),
                   ("Up", "[7]"),
                   ("Down", "[1]"),
                   ("Brake", "[0]"),

                   ("Rotate", "[-]"),
                   ("Roll", "[+]"),
                   ("Flip", "[/]"),
                   ("Mirror", "[*]"),
                   ("Swap", "[.]"),
                   ("Increase Reach", "Scroll Up"),
                   ("Decrease Reach", "Scroll Down"),
                   ("Reset Reach", "Mouse3"),
                   ("Delete Blocks", "Delete")
               ]}

    selectedKeyIndex = 0

    def __init__(self):
        Dialog.__init__(self)
        keyConfigTable = albow.TableView(
            columns=[albow.TableColumn("Command", 200, "l"), albow.TableColumn("Assigned Key", 150, "r")])
        keyConfigTable.num_rows = lambda: len(self.keyConfigKeys)
        keyConfigTable.row_data = self.getRowData
        keyConfigTable.row_is_selected = lambda x: x == self.selectedKeyIndex
        keyConfigTable.click_row = self.selectTableRow
        tableWidget = albow.Widget()
        tableWidget.add(keyConfigTable)
        tableWidget.shrink_wrap()

        self.keyConfigTable = keyConfigTable

        buttonRow = (albow.Button("Assign Key...", action=self.askAssignSelectedKey),
                     albow.Button("Done", action=self.done))

        buttonRow = albow.Row(buttonRow)

        choiceButton = mceutils.ChoiceButton(["WASD", "Arrows", "Numpad"], choose=self.choosePreset)
        if config.config.get("Keys", "Forward") == "Up":
            choiceButton.selectedChoice = "Arrows"
        if config.config.get("Keys", "Forward") == "[8]":
            choiceButton.selectedChoice = "Numpad"

        choiceRow = albow.Row((albow.Label("Presets: "), choiceButton))
        self.choiceButton = choiceButton

        col = albow.Column((tableWidget, choiceRow, buttonRow))
        self.add(col)
        self.shrink_wrap()

    def done(self):
        config.saveConfig()
        self.dismiss()

    def choosePreset(self):
        preset = self.choiceButton.selectedChoice
        keypairs = self.presets[preset]
        for configKey, key in keypairs:
            config.config.set("Keys", configKey, key)

    def getRowData(self, i):
        configKey = self.keyConfigKeys[i]
        if self.isConfigKey(configKey):
            key = config.config.get("Keys", configKey)
            if key == 'mouse4' or key == 'mouse6':
                key = 'Scroll Up'
                config.config.set("Keys", configKey, "Scroll Up")
            if key == 'mouse5' or key == 'mouse7':
                key = 'Scroll Down'
                config.config.set("Keys", configKey, "Scroll Down")
        else:
            key = ""
        return configKey, key

    def isConfigKey(self, configKey):
        return not (len(configKey) == 0 or configKey[0] == "<")

    def selectTableRow(self, i, evt):
        self.selectedKeyIndex = i
        if evt.num_clicks == 2:
            self.askAssignSelectedKey()

    def askAssignSelectedKey(self):
        self.askAssignKey(self.keyConfigKeys[self.selectedKeyIndex])

    def askAssignKey(self, configKey, labelString=None):
        if not self.isConfigKey(configKey):
            return

        panel = Panel()
        panel.bg_color = (0.5, 0.5, 0.6, 1.0)

        if labelString is None:
            labelString = tr("Press a key to assign to the action \"{0}\"\n\nPress ESC to cancel.").format(configKey)
        label = albow.Label(labelString)
        panel.add(label)
        panel.shrink_wrap()

        def panelKeyUp(evt):
            keyname = getKey(evt)
            panel.dismiss(keyname)

        def panelMouseUp(evt):
            button = remapMouseButton(evt.button)
            if button == 3:
                keyname = "Mouse3"
            elif button == 4 or buttom == 6:
                keyname = "Scroll Up"
            elif button == 5 or button == 7:
                keyname = "Scroll Down"
            if button > 2:
                panel.dismiss(keyname)

        panel.key_up = panelKeyUp
        panel.mouse_up = panelMouseUp

        keyname = panel.present()
        if keyname != "Escape":
            occupiedKeys = [(v, k) for (k, v) in config.config.items("Keys") if config.getNewKey(v) == keyname and k != configKey.lower()]
            oldkey = config.config.get("Keys", configKey)
            config.config.set("Keys", configKey, keyname)
            for keyname, setting in occupiedKeys:
                settings = setting.split(' ')
                newSettings = []
                for set in settings:
                    newSettings.append(set[0].upper() + set[1:])
                setting = ' '.join(newSettings)
                if self.askAssignKey(setting,
                                     tr("The key {0} is no longer bound to {1}. "
                                     "Press a new key for the action \"{1}\"\n\n"
                                     "Press ESC to cancel.")
                                     .format(keyname, setting)):
                    config.config.set("Keys", configKey, oldkey)
                    return True
        else:
            return True<commit_msg>Another small fix<commit_after>import sys
import os
import directories
import config
import albow
import mceutils
from pygame import display, event, key, KMOD_ALT, KMOD_CTRL, KMOD_LALT, KMOD_META, KMOD_RALT, KMOD_SHIFT, mouse, \
    MOUSEMOTION
from albow.dialogs import Dialog, QuickDialog, wrapped_label
from albow import alert, ask, AttrRef, Button, Column, get_font, Grid, input_text, IntField, Menu, root, Row, \
    TableColumn, TableView, TextField, TimeField, Widget, CheckBox
from albow.controls import Label, SmallValueDisplay, ValueDisplay
from albow.translate import tr
from glbackground import Panel

ESCAPE = '\033'

def remapMouseButton(button):
    buttons = [0, 1, 3, 2, 4, 5, 6, 7]  # mouse2 is right button, mouse3 is middle
    if button < len(buttons):
        return buttons[button]
    return button

def getKey(evt, i=0):
    keyname = key.name(evt.key)
    if keyname == 'Enter':
            keyname = 'Return'
    if 'left' in keyname and len(keyname) > 5:
        keyname = keyname[5:]
    elif 'right' in keyname and len(keyname) > 6:
        keyname = keyname[6:]
    if keyname == 'Meta':
        keyname = 'Ctrl'
    try:
        keyname = keyname.replace(keyname[0], keyname[0].upper(), 1)
    finally:
        newKeyname = ""
        if evt.shift == True and keyname != "Shift" and i != 1:
            newKeyname += "Shift-"
        if evt.ctrl == True and keyname != "Ctrl" and i != 1:
            newKeyname += "Ctrl-"
        if evt.alt == True and keyname != "Alt" and i != 1:
            newKeyname += "Alt-"

        keyname = newKeyname + keyname
        return keyname

class KeyConfigPanel(Dialog):
    keyConfigKeys = [
        "<Movement Controls>",
        "Forward",
        "Back",
        "Left",
        "Right",
        "Up",
        "Down",
        "Brake",
        "",
        "<Camera Controls>",
        "Pan Up",
        "Pan Down",
        "Pan Left",
        "Pan Right",
        "",
        "<Tool Controls>",
        "Rotate",
        "Roll",
        "Flip",
        "Mirror",
        "Swap",
        "Delete Blocks",
        "Increase Reach",
        "Decrease Reach",
        "Reset Reach",
        "",
        "<Function Controls>",
        "Quit",
        "Swap View",
        "Select All",
        "Deselect",
        "Cut",
        "Copy",
        "Paste",
        "Reload World",
        "Open",
        "Quick Load",
        "Undo",
        "Save",
        "New World",
        "Close World",
        "World Info",
        "Goto Panel",
        "Export Selection"
    ]

    presets = {"WASD": [
        ("Forward", "W"),
        ("Back", "S"),
        ("Left", "A"),
        ("Right", "D"),
        ("Up", "Space"),
        ("Down", "Shift"),
        ("Brake", "C"),

        ("Rotate", "E"),
        ("Roll", "R"),
        ("Flip", "F"),
        ("Mirror", "G"),
        ("Swap", "X"),
        ("Increase Reach", "Scroll Up"),
        ("Decrease Reach", "Scroll Down"),
        ("Reset Reach", "Mouse3"),
        ("Delete Blocks", "Delete"),
    ],
               "Arrows": [
                   ("Forward", "Up"),
                   ("Back", "Down"),
                   ("Left", "Left"),
                   ("Right", "Right"),
                   ("Up", "Page Up"),
                   ("Down", "Page Down"),
                   ("Brake", "Space"),

                   ("Rotate", "Home"),
                   ("Roll", "End"),
                   ("Flip", "Insert"),
                   ("Mirror", "Delete"),
                   ("Swap", "\\"),
                   ("Increase Reach", "Scroll Up"),
                   ("Decrease Reach", "Scroll Down"),
                   ("Reset Reach", "Mouse3"),
                   ("Delete Blocks", "Backspace")
               ],
               "Numpad": [
                   ("Forward", "[8]"),
                   ("Back", "[5]"),
                   ("Left", "[4]"),
                   ("Right", "[6]"),
                   ("Up", "[7]"),
                   ("Down", "[1]"),
                   ("Brake", "[0]"),

                   ("Rotate", "[-]"),
                   ("Roll", "[+]"),
                   ("Flip", "[/]"),
                   ("Mirror", "[*]"),
                   ("Swap", "[.]"),
                   ("Increase Reach", "Scroll Up"),
                   ("Decrease Reach", "Scroll Down"),
                   ("Reset Reach", "Mouse3"),
                   ("Delete Blocks", "Delete")
               ]}

    selectedKeyIndex = 0

    def __init__(self):
        Dialog.__init__(self)
        keyConfigTable = albow.TableView(
            columns=[albow.TableColumn("Command", 200, "l"), albow.TableColumn("Assigned Key", 150, "r")])
        keyConfigTable.num_rows = lambda: len(self.keyConfigKeys)
        keyConfigTable.row_data = self.getRowData
        keyConfigTable.row_is_selected = lambda x: x == self.selectedKeyIndex
        keyConfigTable.click_row = self.selectTableRow
        tableWidget = albow.Widget()
        tableWidget.add(keyConfigTable)
        tableWidget.shrink_wrap()

        self.keyConfigTable = keyConfigTable

        buttonRow = (albow.Button("Assign Key...", action=self.askAssignSelectedKey),
                     albow.Button("Done", action=self.done))

        buttonRow = albow.Row(buttonRow)

        choiceButton = mceutils.ChoiceButton(["WASD", "Arrows", "Numpad"], choose=self.choosePreset)
        if config.config.get("Keys", "Forward") == "Up":
            choiceButton.selectedChoice = "Arrows"
        if config.config.get("Keys", "Forward") == "[8]":
            choiceButton.selectedChoice = "Numpad"

        choiceRow = albow.Row((albow.Label("Presets: "), choiceButton))
        self.choiceButton = choiceButton

        col = albow.Column((tableWidget, choiceRow, buttonRow))
        self.add(col)
        self.shrink_wrap()

    def done(self):
        config.saveConfig()
        self.dismiss()

    def choosePreset(self):
        preset = self.choiceButton.selectedChoice
        keypairs = self.presets[preset]
        for configKey, key in keypairs:
            config.config.set("Keys", configKey, key)

    def getRowData(self, i):
        configKey = self.keyConfigKeys[i]
        if self.isConfigKey(configKey):
            key = config.config.get("Keys", configKey)
            if key == 'mouse4' or key == 'mouse6':
                key = 'Scroll Up'
                config.config.set("Keys", configKey, "Scroll Up")
            if key == 'mouse5' or key == 'mouse7':
                key = 'Scroll Down'
                config.config.set("Keys", configKey, "Scroll Down")
        else:
            key = ""
        return configKey, key

    def isConfigKey(self, configKey):
        return not (len(configKey) == 0 or configKey[0] == "<")

    def selectTableRow(self, i, evt):
        self.selectedKeyIndex = i
        if evt.num_clicks == 2:
            self.askAssignSelectedKey()

    def askAssignSelectedKey(self):
        self.askAssignKey(self.keyConfigKeys[self.selectedKeyIndex])

    def askAssignKey(self, configKey, labelString=None):
        if not self.isConfigKey(configKey):
            return

        panel = Panel()
        panel.bg_color = (0.5, 0.5, 0.6, 1.0)

        if labelString is None:
            labelString = tr("Press a key to assign to the action \"{0}\"\n\nPress ESC to cancel.").format(configKey)
        label = albow.Label(labelString)
        panel.add(label)
        panel.shrink_wrap()

        def panelKeyUp(evt):
            keyname = getKey(evt)
            panel.dismiss(keyname)

        def panelMouseUp(evt):
            button = remapMouseButton(evt.button)
            if button == 3:
                keyname = "Mouse3"
            elif button == 4 or button == 6:
                keyname = "Scroll Up"
            elif button == 5 or button == 7:
                keyname = "Scroll Down"
            if button > 2:
                panel.dismiss(keyname)

        panel.key_up = panelKeyUp
        panel.mouse_up = panelMouseUp

        keyname = panel.present()
        if keyname != "Escape":
            occupiedKeys = [(v, k) for (k, v) in config.config.items("Keys") if config.getNewKey(v) == keyname and k != configKey.lower()]
            oldkey = config.config.get("Keys", configKey)
            config.config.set("Keys", configKey, keyname)
            for keyname, setting in occupiedKeys:
                settings = setting.split(' ')
                newSettings = []
                for set in settings:
                    newSettings.append(set[0].upper() + set[1:])
                setting = ' '.join(newSettings)
                if self.askAssignKey(setting,
                                     tr("The key {0} is no longer bound to {1}. "
                                     "Press a new key for the action \"{1}\"\n\n"
                                     "Press ESC to cancel.")
                                     .format(keyname, setting)):
                    config.config.set("Keys", configKey, oldkey)
                    return True
        else:
            return True<|endoftext|>


<commit_before>import socket,time
import binascii

def is_odd(num):
		return num & 0x1
def int_to_bcd(x):
    if x < 0:
        raise ValueError("Cannot be a negative integer")

    bcdstring = ''
    while x > 0:
        nibble = x % 16
        bcdstring = str(nibble) + bcdstring
        x >>= 4
    return int(bcdstring)

class Koyo():
	def __init__(self,ip,debug=False):
		self.ip = ip
		self.debug=debug
		self.port = 28784
		self.address = (self.ip,self.port)
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
		self.sock.settimeout(3)
		#self.sock.bind((self.ip,28784))
	def WriteC(self,variable,value):
		v=5
		if(value):
			v=4
		msg='484150512adf240b001a000700014'+str(v)+'01f'
		msg+=str(format(variable,'x')).zfill(3)
		if not value:
			value=180+variable
		elif(value and not is_odd(variable)):
			value=180+variable+1
		else:
			value=180+variable-1
		hexvalue=format(value,'x')
		if self.debug:
			print msg+'17'+hexvalue
		try:
			self.sock.sendto(bytearray.fromhex(msg),(self.ip,self.port))
			data0 = self.sock.recvfrom(1024)
			data1 = self.sock.recvfrom(1024)
		except socket.timeout:
			time.sleep(1)
			pass
	def WriteOutput(self,variable,value):
		v=5
		if(value):
			v=4
		msg='484150512adf240b001a000700014'+str(v)+'01e8'
		msg+=str(format(variable,'x')).zfill(2)
		if not value:
			value=172+variable
		elif(value and not is_odd(variable)):
			value=172+variable+1
		else:
			value=172+variable-1
		hexvalue=format(value,'x')
		if self.debug:
			print msg+'17'+hexvalue
		try:
			self.sock.sendto(bytearray.fromhex(msg),(self.ip,self.port))
			data0 = self.sock.recvfrom(1024)
			data1 = self.sock.recvfrom(1024)
		except socket.timeout:
			time.sleep(1)
			pass
	def ReadOutputs(self):
		msg='484150fa03953508001900011e02414131'
		try:
			self.sock.sendto(bytearray.fromhex(msg),(self.ip,self.port))
			reply1 = self.sock.recvfrom(1024)
			data = self.sock.recvfrom(1024)[0]
			value = ('{0:b}'.format(bytearray(data)[13]).zfill(8)[::-1])+\
			('{0:b}'.format(bytearray(data)[14]).zfill(8)[::-1])
		except socket.timeout:
			print 'Socket TimeOut'
			return -1
		if self.debug:
			print bytearray(data)
			print value
		return value
	def ReadOutput(self,variable):
		outputs=self.ReadOutputs()
		return outputs[variable]=='1'
	def ReadC(self,variable):              #484150fd9ffb3408001900011e06814131
		value = self.ReadC_All()
		return value[variable]=='1'
	def ReadC_All(self):
		try:
			self.sock.sendto(bytearray.fromhex('484150fd9ffb3408001900011e06814131'),(self.ip,self.port))
			reply1 = self.sock.recvfrom(1024)
			reply2 = self.sock.recvfrom(1024)
			data = reply2[0]
			value =  ('{0:b}'.format(bytearray(data)[13]).zfill(8)[::-1])+\
			('{0:b}'.format(bytearray(data)[14]).zfill(8)[::-1])+\
			('{0:b}'.format(bytearray(data)[15]).zfill(8)[::-1])+\
			('{0:b}'.format(bytearray(data)[16]).zfill(8)[::-1])
			return value
		except socket.timeout:
			print "socket timeout"
			pass
			return -1
	def ReadInput(self,input):
		msg='4841502900382808001900011e02014131'
		if(input>16):
			msg='4841505e01687108001900011e02024131'
			input=0
		try:
			self.sock.sendto(bytearray.fromhex(msg),(self.ip,self.port))
			reply1 = self.sock.recvfrom(1024)
			data = self.sock.recvfrom(1024)[0]
		except socket.timeout:
			print 'Socket TimeOut'
			return -1
		if self.debug:
			print bytearray(data)
		value =  ('{0:b}'.format(bytearray(data)[13]).zfill(8)[::-1])+\
		('{0:b}'.format(bytearray(data)[14]).zfill(8)[::-1])
		return value[input]=='1'
	def ChangeIP(self,mac,newIP):
		msg='4841506b04fa510f0015'+mac+'0c001000'+\
		'{:02X}{:02X}{:02X}{:02X}'.format(*map(int, newIP.split('.')))
		self.ip=newIP
		#print msg
		self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
		self.sock.sendto(bytearray.fromhex(msg),('<broadcast>',self.port))
		self.sock.recvfrom(1024),self.sock.recvfrom(1024)
	def FindKoyo(self):
		msg='484150f805a550010005'
		self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
		self.sock.settimeout(3)
		self.sock.sendto(bytearray.fromhex(msg),('<broadcast>',self.port))
		recv=''
		while True:
			try:
				newmesg=self.sock.recvfrom(1024)
			except socket.timeout:
				break
			ips=map(ord,str(newmesg[0]))
			ip=str(ips[len(ips)-5])+'.'+str(ips[len(ips)-4])+'.'+str(ips[len(ips)-3])+'.'+str(ips[len(ips)-2])
			mac = str(hex(ips[len(ips)-13])[2:].zfill(2))+\
				str(hex(ips[len(ips)-12])[2:].zfill(2))+\
				str(hex(ips[len(ips)-11])[2:].zfill(2))+\
				str(hex(ips[len(ips)-10])[2:].zfill(2))+\
				str(hex(ips[len(ips)-9])[2:].zfill(2))+\
				str(hex(ips[len(ips)-8])[2:].zfill(2))
			print ip,mac
			newmesg=recv
		print 'done'
	def ReadV(self,v): #read v memory words into an int 0-65535
		v=33620017+int(str(variable),8)
		meh = hex(v).replace('0x','')
		if(len(meh) & 0x1):
			meh=meh.zfill(len(meh)+1)
		msg='484150a80a64bf08001900011e'+meh
		try:
			self.sock.sendto(bytearray.fromhex(msg),(self.ip,self.port))
			self.sock.recvfrom(1024)
			data = self.sock.recvfrom(1024)[0]
			if(self.debug):
				print binascii.hexlify(data)
			value= hex(bytearray(data)[14]).replace('0x','').zfill(2)+hex(bytearray(data)[13]).replace('0x','').zfill(2)
			if(int(value,16)!=0 and self.debug):
				print int(str(variable),8),variable,value,int(value,16)
			return int(value,16)
		except socket.timeout:
			print 'timeout err'
			return -1<commit_msg>Delete koyo.py<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env python3

""" Graded Lab #2 for Inf1340, Fall 2015 """

__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"

"""
Instructions: Add a function to to get input from the user and use that
function in name_that_shape()

The function should prompt the user for input until a legal value is
entered. A legal value is any integer.

"""

def name_that_shape():
    """
    For a given number of sides in a regular polygon, returns the shape name

    Inputs | Expected Outputs
    -------------------------
      < 3  | Error
      3    | triangle
      4    | quadrilateral
      5    | pentagon
      6    | hexagon
      7    | heptagon
      8    | octagon
      9    | nonagon
      10   | decagon
      > 10 | Error

    Errors: ValueError when input is a string or float

    """

    sides = int(raw_input("Number of sides:"))

    if sides == 3:
        print("triangle")
    elif sides == 4:
        print("quadrilateral")
    elif sides == 5:
        print("pentagon")
    elif sides == 6:
        print("hexagon")
    elif sides == 7:
        print("heptagon")
    elif sides == 8:
        print("octagon")
    elif sides == 9:
        print("nonagon")
    elif sides == 10:
        print("decagon")
    else:
        print("Error")

# name_that_shape()
<commit_msg>Code test 1<commit_after>#!/usr/bin/env python3

""" Graded Lab #2 for Inf1340, Fall 2015 """

__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"

"""
Instructions: Add a function to to get input from the user and use that
function in name_that_shape()

The function should prompt the user for input until a legal value is
entered. A legal value is any integer.

"""

def user_input():
    sides = ""

    while True:
        try:
            sides = int(raw_input("How many sides?"))
        except:
            ValueError
            print ("Please provide an integer")
        return int(sides)

def name_that_shape():
    """
    For a given number of sides in a regular polygon, returns the shape name

    Inputs | Expected Outputs
    -------------------------
      < 3  | Error
      3    | triangle
      4    | quadrilateral
      5    | pentagon
      6    | hexagon
      7    | heptagon
      8    | octagon
      9    | nonagon
      10   | decagon
      > 10 | Error

    Errors: ValueError when input is a string or float

    """

    sides = user_input()

    if sides == 3:
        print("triangle")
    elif sides == 4:
        print("quadrilateral")
    elif sides == 5:
        print("pentagon")
    elif sides == 6:
        print("hexagon")
    elif sides == 7:
        print("heptagon")
    elif sides == 8:
        print("octagon")
    elif sides == 9:
        print("nonagon")
    elif sides == 10:
        print("decagon")
    else:
        print("Error")

name_that_shape()
<|endoftext|>


<commit_before>import requests
import time
import os
import json
from database import get_user_id, check_silenced

def post_text(user_text, bot_id):
    print("Posting message")
    time.sleep(1)
    if len(user_text.strip()) == 0:
        raise ValueError("Can't post empty message")
    if(not check_silenced(bot_id)[0]):
        requests.post('https://api.groupme.com/v3/bots/post', params = {'bot_id' : bot_id, 'text' : user_text}).raise_for_status()
    else:
        print("BOT IS SILENCED")

def post_text_mention(user_text, bot_id, mention_ids):
    print("Posting message with mention")
    time.sleep(1)
    if len(user_text.strip()) == 0:
        raise ValueError("Can't post empty message")
    if not isinstance(mention_ids, list):
        mention_ids = [mention_ids]
    print("User id: " + str(mention_ids))
    mentions = json.dumps(mention_ids)
    loci = []
    for x in range(len(mention_ids)):
        loci.append([0,0])
    lociA = json.dumps(loci)
    print(lociA)
    print(mentions)
    payload = {
      'text': user_text,
      'bot_id': bot_id,
      'attachments': [{ 'loci': lociA, 'type': "mentions", 'user_ids': mentions }]
    };

    if(not check_silenced(bot_id)[0]):
        requests.post('https://api.groupme.com/v3/bots/post', json=payload).raise_for_status()
        requests.post('http://requestbin.fullcontact.com/1neu8ut1', json=payload).raise_for_status()
    else:
        print("BOT IS SILENCED")

def get_group_info(group_id):
    access_token = os.environ.get("GROUPME_ACCESS_TOKEN")
    info = requests.get('https://api.groupme.com/v3/groups/' + group_id + '?token=' + access_token).json()
    return info
<commit_msg>Adding to payload after creation<commit_after>import requests
import time
import os
import json
from database import get_user_id, check_silenced

def post_text(user_text, bot_id):
    print("Posting message")
    time.sleep(1)
    if len(user_text.strip()) == 0:
        raise ValueError("Can't post empty message")
    if(not check_silenced(bot_id)[0]):
        requests.post('https://api.groupme.com/v3/bots/post', params = {'bot_id' : bot_id, 'text' : user_text}).raise_for_status()
    else:
        print("BOT IS SILENCED")

def post_text_mention(user_text, bot_id, mention_ids):
    print("Posting message with mention")
    time.sleep(1)
    if len(user_text.strip()) == 0:
        raise ValueError("Can't post empty message")
    if not isinstance(mention_ids, list):
        mention_ids = [mention_ids]
    print("User id: " + str(mention_ids))
    mentions = json.dumps(mention_ids)
    payload = {
      'text': user_text,
      'bot_id': bot_id,
      'attachments': [{ 'loci': [], 'type': "mentions", 'user_ids': [] }]
    };
    lociA = []
    for x in range(len(mention_ids)):
        payload.attachments[0]['loci'].append([0,0])

    payload.attachments[0]['loci'].append(mention_ids)

    if(not check_silenced(bot_id)[0]):
        requests.post('https://api.groupme.com/v3/bots/post', json=payload).raise_for_status()
        requests.post('http://requestbin.fullcontact.com/1neu8ut1', json=payload).raise_for_status()
    else:
        print("BOT IS SILENCED")

def get_group_info(group_id):
    access_token = os.environ.get("GROUPME_ACCESS_TOKEN")
    info = requests.get('https://api.groupme.com/v3/groups/' + group_id + '?token=' + access_token).json()
    return info
<|endoftext|>


<commit_before>import os
import json
import hashlib
import hmac

from flask import Flask, request, url_for
from flask_redis import FlaskRedis
import requests

app = Flask(__name__)
app.config['GITHUB_WEBHOOK_SECRET'] = os.environ.get('GITHUB_WEBHOOK_SECRET')
app.config['GITHUB_ACCESS_TOKEN'] = os.environ.get('GITHUB_ACCESS_TOKEN')
app.config['REDIS_URL'] = os.environ.get('REDIS_URL')

redis_store = FlaskRedis(app)

github = requests.Session()
github.headers.update({
    'Content-Type': 'application/json',
    'Authorization': 'token {}'.format(app.config['GITHUB_ACCESS_TOKEN'])
})

class Report(object):
    def __init__(self, text):
        self.raw = text

    def save(self, user, repo, sha):
        redis_store.set(self._redis_key(user, repo, sha), self.raw)

    @staticmethod
    def _redis_key(user, repo, sha):
        return '{}-{}-{}'.format(user, repo, sha)

    @classmethod
    def get(cls, user, repo, sha):
        return cls(redis_store.get(cls._redis_key(user, repo, sha)))

    @property
    def status(self):
        if not self.raw:
            return 'success'
        else:
            return 'failure'

    @property
    def summary(self):
        if not self.raw:
            return 'No issues found'
        else:
            return 'Found {} styling issues'.format(
                len(self.raw.split("\n"))
            )

@app.route('/webhook/', methods=['GET', 'POST'])
def webhook():
    if request.method == 'POST':
        event = request.headers['X-GitHub-Event']
        signature = request.headers['X-Hub-Signature']

        mac = hmac.new(
            app.config['GITHUB_WEBHOOK_SECRET'],
            msg=request.data,
            digestmod=hashlib.sha1
        )
        if not 'sha1={}'.format(mac.hexdigest()) == signature:
            return 'Invalid signature', 403

        if event == 'ping':
            return json.dumps({'msg': 'hi'})
        if event == 'push':
            pending()

        return '', 201

@app.route('/repos/<user>/<repo>/statuses/<sha>', methods=['POST'])
def status(user, repo, sha):
    report = Report(request.get_data().strip())

    report.save(user, repo, sha)

    status = {
        'state': report.status,
        'description': report.summary,
        'context': 'linting',
        'target_url': url_for('report', user=user, repo=repo, sha=sha, _external=True)
    }

    response = github.post(
        'https://api.github.com/repos/{user}/{repo}/statuses/{sha}'.format(
            user=user, repo=repo, sha=sha
        ),
        json.dumps(status)
    )

    response.raise_for_status()
    print status

    return json.dumps(status), 200

@app.route('/reports/<user>/<repo>/statuses/<sha>')
def report(user, repo, sha):
    report = Report.get(user, repo, sha)
    return report.raw, 200

def pending():
    payload = request.json
    ref = payload['head_commit']['id']

    status = {
        'state': 'pending',
        'description': 'Waiting for linting result',
        'context': 'linting'
    }
    response = github.post(
        payload['repository']['statuses_url'].format(sha=ref),
        json.dumps(status)
    )

    response.raise_for_status()

if __name__ == "__main__":
        app.run()
<commit_msg>Fix styling<commit_after>import os
import json
import hashlib
import hmac

from flask import Flask, request, url_for
from flask_redis import FlaskRedis
import requests

app = Flask(__name__)
app.config['GITHUB_WEBHOOK_SECRET'] = os.environ.get('GITHUB_WEBHOOK_SECRET')
app.config['GITHUB_ACCESS_TOKEN'] = os.environ.get('GITHUB_ACCESS_TOKEN')
app.config['REDIS_URL'] = os.environ.get('REDIS_URL')

redis_store = FlaskRedis(app)

github = requests.Session()
github.headers.update({
    'Content-Type': 'application/json',
    'Authorization': 'token {}'.format(app.config['GITHUB_ACCESS_TOKEN'])
})

class Report(object):
    def __init__(self, text):
        self.raw = text

    def save(self, user, repo, sha):
        redis_store.set(self._redis_key(user, repo, sha), self.raw)

    @staticmethod
    def _redis_key(user, repo, sha):
        return '{}-{}-{}'.format(user, repo, sha)

    @classmethod
    def get(cls, user, repo, sha):
        return cls(redis_store.get(cls._redis_key(user, repo, sha)))

    @property
    def status(self):
        if not self.raw:
            return 'success'
        else:
            return 'failure'

    @property
    def summary(self):
        if not self.raw:
            return 'No issues found'
        else:
            return 'Found {} styling issues'.format(
                len(self.raw.split("\n"))
            )

@app.route('/webhook/', methods=['GET', 'POST'])
def webhook():
    if request.method == 'POST':
        event = request.headers['X-GitHub-Event']
        signature = request.headers['X-Hub-Signature']

        mac = hmac.new(
            app.config['GITHUB_WEBHOOK_SECRET'],
            msg=request.data,
            digestmod=hashlib.sha1
        )
        if not 'sha1={}'.format(mac.hexdigest()) == signature:
            return 'Invalid signature', 403

        if event == 'ping':
            return json.dumps({'msg': 'hi'})
        if event == 'push':
            pending()

        return '', 201

@app.route('/repos/<user>/<repo>/statuses/<sha>', methods=['POST'])
def status(user, repo, sha):
    report = Report(request.get_data().strip())

    report.save(user, repo, sha)

    status = {
        'state': report.status,
        'description': report.summary,
        'context': 'linting',
        'target_url': url_for(
            'report', user=user, repo=repo, sha=sha, _external=True
        )
    }

    response = github.post(
        'https://api.github.com/repos/{user}/{repo}/statuses/{sha}'.format(
            user=user, repo=repo, sha=sha
        ),
        json.dumps(status)
    )

    response.raise_for_status()
    print status

    return json.dumps(status), 200

@app.route('/reports/<user>/<repo>/statuses/<sha>')
def report(user, repo, sha):
    report = Report.get(user, repo, sha)
    return report.raw, 200

def pending():
    payload = request.json
    ref = payload['head_commit']['id']

    status = {
        'state': 'pending',
        'description': 'Waiting for linting result',
        'context': 'linting'
    }
    response = github.post(
        payload['repository']['statuses_url'].format(sha=ref),
        json.dumps(status)
    )

    response.raise_for_status()

if __name__ == "__main__":
        app.run()
<|endoftext|>


<commit_before>import gzip
import numpy as np
import os

datasets_dir = 'media/datasets/'

def one_hot(x, n):
    if type(x) == list:
        x = np.array(x)
    x = x.flatten()
    o_h = np.zeros((len(x), n))
    o_h[np.arange(len(x)), x] = 1
    return o_h

def get_labels(filename):
    l = []
    n_l = []
    i = 0
    with gzip.open(filename, 'rb') as f:
        for line in f:
            if line not in l:
                l.append(line)
                i += 1
            n_l.append(i)
    return n_l

def get_data(filename):
    temp = []
    with gzip.open(filename, 'rb') as f:
        for line in f:
            try:
                temp.append(np.array(map(float, str.split(line, '\t'))))
            except Exception as e:
                c = str.split(str(e), ": ")[-1]
                temp.append(np.array(map(float, str.split(line.replace(c, "-1.0"), '\t'))))
    return np.array(temp)

def seq_load(ntrain=50000, ntest=10000):
    data = np.load('media/data1-100.npy')
    labels = np.load('media/labels1-100.npy')
    number_of_classes = 104

    tr_idx = []
    te_idx = []
    train_examples_per_class = ntrain / number_of_classes
    test_examples_per_class = ntest / number_of_classes
    examples_per_class = train_examples_per_class + test_examples_per_class

    labels_list = np.ndarray.tolist(labels)
    for label in set(labels):
        if labels_list.count(label) < examples_per_class:
            print "skipping label #%d, size:%d" % (label, labels_list.count(label))
            continue

        first = labels_list.index(label)
        last = len(labels_list) - labels_list[::-1].index(label)

        tr_idx += np.random.choice(range(first, last), train_examples_per_class, replace=False).tolist()
        te_idx += np.random.choice(range(first, last), test_examples_per_class, replace=False).tolist()

    trX = data[tr_idx].astype(float)
    trY = labels[tr_idx]
    teX = data[te_idx].astype(float)
    teY = data[te_idx]

    return trX, teX, trY, teY

def mnist(ntrain=60000, ntest=10000, onehot=True):
    data_dir = os.path.join(datasets_dir, 'mnist/')
    fd = open(os.path.join(data_dir, 'train-images-idx3-ubyte'))
    loaded = np.fromfile(file=fd, dtype=np.uint8)
    trX = loaded[16:].reshape((60000, 28 * 28)).astype(float)

    fd = open(os.path.join(data_dir, 'train-labels-idx1-ubyte'))
    loaded = np.fromfile(file=fd, dtype=np.uint8)
    trY = loaded[8:].reshape((60000))

    fd = open(os.path.join(data_dir, 't10k-images-idx3-ubyte'))
    loaded = np.fromfile(file=fd, dtype=np.uint8)
    teX = loaded[16:].reshape((10000, 28 * 28)).astype(float)

    fd = open(os.path.join(data_dir, 't10k-labels-idx1-ubyte'))
    loaded = np.fromfile(file=fd, dtype=np.uint8)
    teY = loaded[8:].reshape((10000))

    trX = trX / 255.
    teX = teX / 255.

    trX = trX[:ntrain]
    trY = trY[:ntrain]

    teX = teX[:ntest]
    teY = teY[:ntest]

    if onehot:
        trY = one_hot(trY, 10)
        teY = one_hot(teY, 10)
    else:
        trY = np.asarray(trY)
        teY = np.asarray(teY)

    return trX, teX, trY, teY<commit_msg>popravljen load<commit_after>import gzip
import numpy as np
import os

datasets_dir = 'media/datasets/'

def one_hot(x, n):
    if type(x) == list:
        x = np.array(x)
    x = x.flatten()
    o_h = np.zeros((len(x), n))
    o_h[np.arange(len(x)), x] = 1
    return o_h

def get_labels(filename):
    l = []
    n_l = []
    i = 0
    with gzip.open(filename, 'rb') as f:
        for line in f:
            if line not in l:
                l.append(line)
                i += 1
            n_l.append(i)
    return n_l

def get_data(filename):
    temp = []
    with gzip.open(filename, 'rb') as f:
        for line in f:
            try:
                temp.append(np.array(map(float, str.split(line, '\t'))))
            except Exception as e:
                c = str.split(str(e), ": ")[-1]
                temp.append(np.array(map(float, str.split(line.replace(c, "-1.0"), '\t'))))
    return np.array(temp)

def seq_load(ntrain=50000, ntest=10000):
    data = np.load('media/data1-100.npy')
    labels = np.load('media/labels1-100.npy')
    number_of_classes = 104

    tr_idx = []
    te_idx = []
    train_examples_per_class = ntrain / number_of_classes
    test_examples_per_class = ntest / number_of_classes
    examples_per_class = train_examples_per_class + test_examples_per_class

    labels_list = np.ndarray.tolist(labels)
    for label in set(labels):
        if labels_list.count(label) < examples_per_class:
            print "skipping label #%d, size:%d" % (label, labels_list.count(label))
            continue

        first = labels_list.index(label)
        last = len(labels_list) - labels_list[::-1].index(label)

        if last - first != labels_list.count(label):
            print "something went wrong..."
            return -1

        temp_tr = np.random.choice(range(first, last), train_examples_per_class, replace=False).tolist()
        tr_idx += temp_tr

        test_set = list(set(range(first, last)) - set(temp_tr))
        te_idx += np.random.choice(test_set, test_examples_per_class, replace=False).tolist()

    trX = data[tr_idx].astype(float)
    trY = labels[tr_idx]
    teX = data[te_idx].astype(float)
    teY = data[te_idx]

    return trX, teX, trY, teY

def mnist(ntrain=60000, ntest=10000, onehot=True):
    data_dir = os.path.join(datasets_dir, 'mnist/')
    fd = open(os.path.join(data_dir, 'train-images-idx3-ubyte'))
    loaded = np.fromfile(file=fd, dtype=np.uint8)
    trX = loaded[16:].reshape((60000, 28 * 28)).astype(float)

    fd = open(os.path.join(data_dir, 'train-labels-idx1-ubyte'))
    loaded = np.fromfile(file=fd, dtype=np.uint8)
    trY = loaded[8:].reshape((60000))

    fd = open(os.path.join(data_dir, 't10k-images-idx3-ubyte'))
    loaded = np.fromfile(file=fd, dtype=np.uint8)
    teX = loaded[16:].reshape((10000, 28 * 28)).astype(float)

    fd = open(os.path.join(data_dir, 't10k-labels-idx1-ubyte'))
    loaded = np.fromfile(file=fd, dtype=np.uint8)
    teY = loaded[8:].reshape((10000))

    trX = trX / 255.
    teX = teX / 255.

    trX = trX[:ntrain]
    trY = trY[:ntrain]

    teX = teX[:ntest]
    teY = teY[:ntest]

    if onehot:
        trY = one_hot(trY, 10)
        teY = one_hot(teY, 10)
    else:
        trY = np.asarray(trY)
        teY = np.asarray(teY)

    return trX, teX, trY, teY<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2013, Mayo Clinic
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
#     Redistributions of source code must retain the above copyright notice, this
#     list of conditions and the following disclaimer.
#
#     Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions and the following disclaimer in the documentation
#     and/or other materials provided with the distribution.
#
#     Neither the name of the <ORGANIZATION> nor the names of its contributors
#     may be used to endorse or promote products derived from this software
#     without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.

from rf2db.db.RF2FileCommon import RF2FileWrapper
from rf2db.db.RF2DBConnection import RF2DBConnection

class RF2RefsetWrapper(RF2FileWrapper):

    def __init__(self, *args, **kwargs):
        RF2FileWrapper.__init__(self, *args, **kwargs)
        self._known_refsets = None
        self._refset_names = None

    def known_refsets(self, ss=True, refresh=False):
        if not self._known_refsets or refresh:
            self._build_knowns(language, ss)
        return self._known_refsets

    def refset_names(self, language='en', ss=True, refresh=False):
        if not self._refset_names or refresh:
            self._build_knowns(language, ss)
        return self._refset_names

    def _build_knowns(self, language, ss):
        # Note: LanguageDB must be local, as it inherits from this class
        self._known_refsets = self.valid_refsets(self._tname(ss))
        from rf2db.db.RF2LanguageFile import LanguageDB
        self._refset_names = {k:v[0] for k,v in LanguageDB().preferred_term_for_concepts(self._known_refsets,
                                                                                language=language).items()}

    """ Return the list of refset identifiers in the supplied refset file
    @param filename: refset file to query
    @param active: True means active only, false means all
    @param moduleids: list of module id's.  If empty or None, return all
    @return: set of refset identifiers
    """
    def valid_refsets(self, ss=True, active=True, moduleids=None):
        stmt = "SELECT DISTINCT refsetId FROM %s WHERE " % self._tname(ss)
        stmt += 'active=1 ' if active else 'True '
        if moduleids:
            stmt += "AND moduleId in (" + ', '.join(str(m) for m in moduleids)
        db = RF2DBConnection()
        db.execute(stmt)
        return list(db.ResultsGenerator(db))

<commit_msg>Error and misplaced documentation<commit_after># -*- coding: utf-8 -*-
# Copyright (c) 2013, Mayo Clinic
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
#     Redistributions of source code must retain the above copyright notice, this
#     list of conditions and the following disclaimer.
#
#     Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions and the following disclaimer in the documentation
#     and/or other materials provided with the distribution.
#
#     Neither the name of the <ORGANIZATION> nor the names of its contributors
#     may be used to endorse or promote products derived from this software
#     without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.

from rf2db.db.RF2FileCommon import RF2FileWrapper
from rf2db.db.RF2DBConnection import RF2DBConnection

class RF2RefsetWrapper(RF2FileWrapper):

    def __init__(self, *args, **kwargs):
        RF2FileWrapper.__init__(self, *args, **kwargs)
        self._known_refsets = None
        self._refset_names = None

    def known_refsets(self, language='en', ss=True, refresh=False):
        if not self._known_refsets or refresh:
            self._build_knowns(language, ss)
        return self._known_refsets

    def refset_names(self, language='en', ss=True, refresh=False):
        if not self._refset_names or refresh:
            self._build_knowns(language, ss)
        return self._refset_names

    def _build_knowns(self, language, ss):
        # Note: LanguageDB must be local, as it inherits from this class
        self._known_refsets = self.valid_refsets(self._tname(ss))
        from rf2db.db.RF2LanguageFile import LanguageDB
        self._refset_names = {k:v[0] for k,v in LanguageDB().preferred_term_for_concepts(self._known_refsets,
                                                                                language=language).items()}

    def valid_refsets(self, ss=True, active=True, moduleids=None):
        stmt = "SELECT DISTINCT refsetId FROM %s WHERE " % self._tname(ss)
        stmt += 'active=1 ' if active else 'True '
        if moduleids:
            stmt += "AND moduleId in (" + ', '.join(str(m) for m in moduleids)
        db = RF2DBConnection()
        db.execute(stmt)
        return list(db.ResultsGenerator(db))

<|endoftext|>


<commit_before>from .prefs_utils import get_pref
from ..rfb_logger import rfb_log
from .. import rfb_logger
from .. import rman_constants
from ..rman_constants import RFB_ADDON_PATH
import os
import bpy
import json
import xml.etree.ElementTree as ET
import subprocess
import platform
import sys

__RMAN_ENV_CONFIG__ = None

class RmanEnvConfig(object):

    def __init__(self):
        self.rmantree = ''
        self.rmantree_from_json = False
        self.rman_version = ''
        self.rman_version_major = 0
        self.rman_version_minor = 0
        self.rman_version_modifier = ''
        self.rman_it_path = ''
        self.rman_lq_path = ''
        self.rman_tractor_path = ''
        self.is_ncr_license = False

    def config_environment(self):

        self.setenv('RMANTREE', self.rmantree)
        self._append_to_path(os.path.join(self.rmantree, 'bin'))
        self._set_it_path()
        self._set_localqueue_path()
        self._config_pythonpath()
        self._set_ocio()
        self._parse_license()

    def getenv(self, k, default=None):
        return os.environ.get(k, default)

    def setenv(self, k, val):
        os.environ[k] = val

    def copyenv(self):
        return os.environ.copy()

    def read_envvars_file(self):
        bl_config_path = bpy.utils.user_resource('CONFIG')
        jsonfile = ''
        for f in os.listdir(bl_config_path):
            if not f.endswith('.json'):
                continue
            if f == 'rfb_envvars.json':
                jsonfile = os.path.join(bl_config_path, f)
                break
        if jsonfile == '':
            return

        rfb_log().warning("Reading rfb_envvars.json")
        jdata = json.load(open(jsonfile))
        environment = jdata.get('environment', list())

        for var, val in environment.items():
            rfb_log().warning("Setting envvar %s to: %s" % (var, val['value']))
            self.setenv(var, val['value'])
            if var == 'RMANTREE':
                self.rmantree_from_json = True

        # Re-init the log level in case RFB_LOG_LEVEL was set
        rfb_logger.init_log_level()

        # Also, set logger file, if any
        rfb_log_file = self.getenv('RFB_LOG_FILE')
        if rfb_log_file:
            rfb_logger.set_file_logger(rfb_log_file)

    def get_shader_registration_paths(self):
        paths = []
        rmantree = self.rmantree
        paths.append(os.path.join(rmantree, 'lib', 'shaders'))
        paths.append(os.path.join(rmantree, 'lib', 'plugins', 'Args'))
        paths.append(os.path.join(RFB_ADDON_PATH, 'Args'))

        RMAN_SHADERPATH = self.getenv('RMAN_SHADERPATH', '')
        for p in RMAN_SHADERPATH.split(os.path.pathsep):
            paths.append(p)

        RMAN_RIXPLUGINPATH = self.getenv('RMAN_RIXPLUGINPATH', '')
        for p in RMAN_RIXPLUGINPATH.split(os.path.pathsep):
            paths.append(os.path.join(p, 'Args'))

        return paths

    def _config_pythonpath(self):

        if platform.system() == 'Windows':
            rman_packages = os.path.join(self.rmantree, 'lib', 'python3.7', 'Lib', 'site-packages')
        else:
            rman_packages = os.path.join(self.rmantree, 'lib', 'python3.7', 'site-packages')
        sys.path.append(rman_packages)
        sys.path.append(os.path.join(self.rmantree, 'bin'))
        pythonbindings = os.path.join(self.rmantree, 'bin', 'pythonbindings')
        sys.path.append(pythonbindings)

    def _append_to_path(self, path):
        if path is not None:
            self.setenv('PATH', path + os.pathsep + self.getenv('PATH'))

    def _set_it_path(self):

        if platform.system() == 'Windows':
            self.rman_it_path = os.path.join(self.rmantree, 'bin', 'it.exe')
        elif platform.system() == 'Darwin':
            self.rman_it_path = os.path.join(
                self.rmantree, 'bin', 'it.app', 'Contents', 'MacOS', 'it')
        else:
            self.rman_it_path = os.path.join(self.rmantree, 'bin', 'it')

    def _set_localqueue_path(self):
        if platform.system() == 'Windows':
            self.rman_lq_path = os.path.join(self.rmantree, 'bin', 'LocalQueue.exe')
        elif platform.system() == 'Darwin':
            self.rman_lq_path = os.path.join(
                self.rmantree, 'bin', 'LocalQueue.app', 'Contents', 'MacOS', 'LocalQueue')
        else:
            self.rman_lq_path= os.path.join(self.rmantree, 'bin', 'LocalQueue')

    def _set_tractor_path(self):
        base = ""
        if platform.system() == 'Windows':
            # default installation path
            base = r'C:\Program Files\Pixar'

        elif platform.system() == 'Darwin':
            base = '/Applications/Pixar'

        elif platform.system() == 'Linux':
            base = '/opt/pixar'

        latestver = 0.0
        guess = ''
        for d in os.listdir(base):
            if "Tractor" in d:
                vstr = d.split('-')[1]
                vf = float(vstr)
                if vf >= latestver:
                    latestver = vf
                    guess = os.path.join(base, d)
        tractor_dir = guess

        if tractor_dir:
            self.rman_tractor_path = os.path.join(tractor_dir, 'bin', 'tractor-spool')

    def get_blender_ocio_config(self):
        # return rman's version filmic-blender OCIO config
        ocioconfig = os.path.join(self.rmantree, 'lib', 'ocio', 'filmic-blender', 'config.ocio')

        return ocioconfig

    def _set_ocio(self):
        # make sure we set OCIO env var
        # so that "it" will also get the correct configuration
        path = self.getenv('OCIO', '')
        if path == '':
            self.setenv('OCIO', self.get_blender_ocio_config())

    def _parse_license(self):
        pixar_license = os.path.join(self.rmantree, '..', 'pixar.license')
        pixar_license = os.environ.get('PIXAR_LICENSE_FILE', pixar_license)

        if not os.path.isfile(pixar_license):
            self.is_ncr_license = False
            return

        tree = ET.parse(pixar_license)
        root = tree.getroot()
        license_info = None
        for child in root:
            if child.tag == 'LicenseInfo':
                license_info = child
                break
        if not license_info:
            self.is_ncr_license = False
            return

        serial_num = None
        for child in license_info:
            if child.tag == 'SerialNumber':
                serial_num = child
                break

        self.is_ncr_license = (serial_num.text == 'Non-commercial')

def _parse_version(s):
    major_vers, minor_vers = s.split('.')
    vers_modifier = ''
    for v in ['b', 'rc']:
        if v in minor_vers:
            i = minor_vers.find(v)
            vers_modifier = minor_vers[i:]
            minor_vers = minor_vers[:i]
            break
    return int(major_vers), int(minor_vers), vers_modifier

# return the major, minor rman version
def _get_rman_version(rmantree):

    try:
        prman = 'prman.exe' if platform.system() == 'Windows' else 'prman'
        exe = os.path.join(rmantree, 'bin', prman)
        desc = subprocess.check_output(
            [exe, "-version"], stderr=subprocess.STDOUT)
        vstr = str(desc, 'ascii').split('\n')[0].split()[-1]
        major_vers, minor_vers, vers_modifier = _parse_version(vstr)
        return major_vers, minor_vers, vers_modifier
    except:
        return 0, 0, ''

def _guess_rmantree():
    '''
    Try to figure out what RMANTREE should be set.

    First, we consult the rfb_envvars.json file to see if it's been set there. If not, we look at the
    rmantree_method preference. The preference can be set to either:

    ENV = Get From RMANTREE Environment Variable
    DETECT = Choose a version based on what's installed on the local machine (looks in the default install path)
    MANUAL =  Use the path that is manually set in the preferences.

    '''

    global __RMAN_ENV_CONFIG__

    rmantree_method = get_pref('rmantree_method', 'ENV')
    choice = get_pref('rmantree_choice')

    rmantree = ''
    version = (0, 0, '')

    __RMAN_ENV_CONFIG__ = RmanEnvConfig()

    if not __RMAN_ENV_CONFIG__.getenv('RFB_IGNORE_ENVVARS_JSON'):
        __RMAN_ENV_CONFIG__.read_envvars_file()

    if __RMAN_ENV_CONFIG__.rmantree_from_json:
        rmantree = __RMAN_ENV_CONFIG__.getenv('RMANTREE', '')

    if rmantree != '':
        version = _get_rman_version(rmantree)
        if version[0] == 0:
            rfb_log().error('RMANTREE from rfb_envvars.json is not valid. Fallback to preferences setting.')
            rmantree = ''
        else:
            rfb_log().warning("Using RMANTREE from rfb_envvars.json")

    # Try and set RMANTREE depending on preferences
    if rmantree == '':

        if rmantree_method == 'MANUAL':
            rmantree = get_pref('path_rmantree')

        if rmantree_method == 'DETECT' and choice != 'NEWEST':
            rmantree = choice

        if rmantree == '' or rmantree_method == 'ENV':
            # Fallback to RMANTREE env var
            if rmantree == '':
                rfb_log().info('Fallback to using RMANTREE.')
            rmantree = os.environ.get('RMANTREE', '')

        if rmantree == '':
            if rmantree_method == 'ENV':
                rfb_log().info('Fallback to autodetecting newest.')

            if choice == 'NEWEST':
                # get from detected installs (at default installation path)
                for vstr, d_rmantree in get_installed_rendermans():
                    d_version = _parse_version(vstr)
                    if d_version > latest:
                        rmantree = d_rmantree
                        version = d_version

        if version[0] == 0:
            version = _get_rman_version(rmantree)

        # check rmantree valid
        if version[0] == 0:
            rfb_log().error(
                "Error loading addon.  RMANTREE %s is not valid.  Correct RMANTREE setting in addon preferences." % rmantree)
            __RMAN_ENV_CONFIG__ = None
            return None

        # check if this version of RenderMan is supported
        if version[0] < rman_constants.RMAN_SUPPORTED_VERSION_MAJOR:
            rfb_log().error("Error loading addon using RMANTREE=%s.  RMANTREE must be version %s or greater.  Correct RMANTREE setting in addon preferences." % (rmantree, rman_constants.RMAN_SUPPORTED_VERSION_STRING))
            __RMAN_ENV_CONFIG__ = None
            return None

        rfb_log().debug("Guessed RMANTREE: %s" % rmantree)

    # Create an RmanEnvConfig object
    __RMAN_ENV_CONFIG__.rmantree = rmantree
    __RMAN_ENV_CONFIG__.rman_version = '%d.%d%s' % (version[0], version[1], version[2])
    __RMAN_ENV_CONFIG__.rman_version_major = version[0]
    __RMAN_ENV_CONFIG__.rman_version_minor = version[1]
    __RMAN_ENV_CONFIG__.rman_version_modifier = version[2]
    __RMAN_ENV_CONFIG__.config_environment()

    return __RMAN_ENV_CONFIG__

def get_installed_rendermans():
    base = {'Windows': r'C:\Program Files\Pixar',
            'Darwin': '/Applications/Pixar',
            'Linux': '/opt/pixar'}[platform.system()]
    rendermans = []

    try:
        for d in os.listdir(base):
            if "RenderManProServer" in d:
                try:
                    vstr = d.split('-')[1]
                    rendermans.append((vstr, os.path.join(base, d)))
                except:
                    pass
    except:
        pass

    return rendermans

def reload_envconfig():
    global __RMAN_ENV_CONFIG__
    if not _guess_rmantree():
        return None
    return __RMAN_ENV_CONFIG__

def envconfig():

    global __RMAN_ENV_CONFIG__
    if not __RMAN_ENV_CONFIG__:
        if not _guess_rmantree():
            return None
    return __RMAN_ENV_CONFIG__

<commit_msg>Switch to using the new rman_utils.license module. For now, we're just using it to determine if we have an NCR license, but we should expand the usage to include querying whether or not a render license is available before we go to render.<commit_after>from .prefs_utils import get_pref
from ..rfb_logger import rfb_log
from .. import rfb_logger
from .. import rman_constants
from ..rman_constants import RFB_ADDON_PATH
import os
import bpy
import json
import subprocess
import platform
import sys

__RMAN_ENV_CONFIG__ = None

class RmanEnvConfig(object):

    def __init__(self):
        self.rmantree = ''
        self.rmantree_from_json = False
        self.rman_version = ''
        self.rman_version_major = 0
        self.rman_version_minor = 0
        self.rman_version_modifier = ''
        self.rman_it_path = ''
        self.rman_lq_path = ''
        self.rman_tractor_path = ''
        self.is_ncr_license = False
        self.license_info = None

    def config_environment(self):

        self.setenv('RMANTREE', self.rmantree)
        self._append_to_path(os.path.join(self.rmantree, 'bin'))
        self._set_it_path()
        self._set_localqueue_path()
        self._config_pythonpath()
        self._set_ocio()
        self._get_license_info()

    def getenv(self, k, default=None):
        return os.environ.get(k, default)

    def setenv(self, k, val):
        os.environ[k] = val

    def copyenv(self):
        return os.environ.copy()

    def read_envvars_file(self):
        bl_config_path = bpy.utils.user_resource('CONFIG')
        jsonfile = ''
        for f in os.listdir(bl_config_path):
            if not f.endswith('.json'):
                continue
            if f == 'rfb_envvars.json':
                jsonfile = os.path.join(bl_config_path, f)
                break
        if jsonfile == '':
            return

        rfb_log().warning("Reading rfb_envvars.json")
        jdata = json.load(open(jsonfile))
        environment = jdata.get('environment', list())

        for var, val in environment.items():
            rfb_log().warning("Setting envvar %s to: %s" % (var, val['value']))
            self.setenv(var, val['value'])
            if var == 'RMANTREE':
                self.rmantree_from_json = True

        # Re-init the log level in case RFB_LOG_LEVEL was set
        rfb_logger.init_log_level()

        # Also, set logger file, if any
        rfb_log_file = self.getenv('RFB_LOG_FILE')
        if rfb_log_file:
            rfb_logger.set_file_logger(rfb_log_file)

    def get_shader_registration_paths(self):
        paths = []
        rmantree = self.rmantree
        paths.append(os.path.join(rmantree, 'lib', 'shaders'))
        paths.append(os.path.join(rmantree, 'lib', 'plugins', 'Args'))
        paths.append(os.path.join(RFB_ADDON_PATH, 'Args'))

        RMAN_SHADERPATH = self.getenv('RMAN_SHADERPATH', '')
        for p in RMAN_SHADERPATH.split(os.path.pathsep):
            paths.append(p)

        RMAN_RIXPLUGINPATH = self.getenv('RMAN_RIXPLUGINPATH', '')
        for p in RMAN_RIXPLUGINPATH.split(os.path.pathsep):
            paths.append(os.path.join(p, 'Args'))

        return paths

    def _config_pythonpath(self):

        if platform.system() == 'Windows':
            rman_packages = os.path.join(self.rmantree, 'lib', 'python3.7', 'Lib', 'site-packages')
        else:
            rman_packages = os.path.join(self.rmantree, 'lib', 'python3.7', 'site-packages')
        sys.path.append(rman_packages)
        sys.path.append(os.path.join(self.rmantree, 'bin'))
        pythonbindings = os.path.join(self.rmantree, 'bin', 'pythonbindings')
        sys.path.append(pythonbindings)

    def _append_to_path(self, path):
        if path is not None:
            self.setenv('PATH', path + os.pathsep + self.getenv('PATH'))

    def _set_it_path(self):

        if platform.system() == 'Windows':
            self.rman_it_path = os.path.join(self.rmantree, 'bin', 'it.exe')
        elif platform.system() == 'Darwin':
            self.rman_it_path = os.path.join(
                self.rmantree, 'bin', 'it.app', 'Contents', 'MacOS', 'it')
        else:
            self.rman_it_path = os.path.join(self.rmantree, 'bin', 'it')

    def _set_localqueue_path(self):
        if platform.system() == 'Windows':
            self.rman_lq_path = os.path.join(self.rmantree, 'bin', 'LocalQueue.exe')
        elif platform.system() == 'Darwin':
            self.rman_lq_path = os.path.join(
                self.rmantree, 'bin', 'LocalQueue.app', 'Contents', 'MacOS', 'LocalQueue')
        else:
            self.rman_lq_path= os.path.join(self.rmantree, 'bin', 'LocalQueue')

    def _set_tractor_path(self):
        base = ""
        if platform.system() == 'Windows':
            # default installation path
            base = r'C:\Program Files\Pixar'

        elif platform.system() == 'Darwin':
            base = '/Applications/Pixar'

        elif platform.system() == 'Linux':
            base = '/opt/pixar'

        latestver = 0.0
        guess = ''
        for d in os.listdir(base):
            if "Tractor" in d:
                vstr = d.split('-')[1]
                vf = float(vstr)
                if vf >= latestver:
                    latestver = vf
                    guess = os.path.join(base, d)
        tractor_dir = guess

        if tractor_dir:
            self.rman_tractor_path = os.path.join(tractor_dir, 'bin', 'tractor-spool')

    def get_blender_ocio_config(self):
        # return rman's version filmic-blender OCIO config
        ocioconfig = os.path.join(self.rmantree, 'lib', 'ocio', 'filmic-blender', 'config.ocio')

        return ocioconfig

    def _set_ocio(self):
        # make sure we set OCIO env var
        # so that "it" will also get the correct configuration
        path = self.getenv('OCIO', '')
        if path == '':
            self.setenv('OCIO', self.get_blender_ocio_config())

    def _get_license_info(self):
        from rman_utils import license as rman_license_info

        self.license_info = rman_license_info.get_license_info(self.rmantree)
        self.is_ncr_license = self.license_info.is_ncr_license

def _parse_version(s):
    major_vers, minor_vers = s.split('.')
    vers_modifier = ''
    for v in ['b', 'rc']:
        if v in minor_vers:
            i = minor_vers.find(v)
            vers_modifier = minor_vers[i:]
            minor_vers = minor_vers[:i]
            break
    return int(major_vers), int(minor_vers), vers_modifier

# return the major, minor rman version
def _get_rman_version(rmantree):

    try:
        prman = 'prman.exe' if platform.system() == 'Windows' else 'prman'
        exe = os.path.join(rmantree, 'bin', prman)
        desc = subprocess.check_output(
            [exe, "-version"], stderr=subprocess.STDOUT)
        vstr = str(desc, 'ascii').split('\n')[0].split()[-1]
        major_vers, minor_vers, vers_modifier = _parse_version(vstr)
        return major_vers, minor_vers, vers_modifier
    except:
        return 0, 0, ''

def _guess_rmantree():
    '''
    Try to figure out what RMANTREE should be set.

    First, we consult the rfb_envvars.json file to see if it's been set there. If not, we look at the
    rmantree_method preference. The preference can be set to either:

    ENV = Get From RMANTREE Environment Variable
    DETECT = Choose a version based on what's installed on the local machine (looks in the default install path)
    MANUAL =  Use the path that is manually set in the preferences.

    '''

    global __RMAN_ENV_CONFIG__

    rmantree_method = get_pref('rmantree_method', 'ENV')
    choice = get_pref('rmantree_choice')

    rmantree = ''
    version = (0, 0, '')

    __RMAN_ENV_CONFIG__ = RmanEnvConfig()

    if not __RMAN_ENV_CONFIG__.getenv('RFB_IGNORE_ENVVARS_JSON'):
        __RMAN_ENV_CONFIG__.read_envvars_file()

    if __RMAN_ENV_CONFIG__.rmantree_from_json:
        rmantree = __RMAN_ENV_CONFIG__.getenv('RMANTREE', '')

    if rmantree != '':
        version = _get_rman_version(rmantree)
        if version[0] == 0:
            rfb_log().error('RMANTREE from rfb_envvars.json is not valid. Fallback to preferences setting.')
            rmantree = ''
        else:
            rfb_log().warning("Using RMANTREE from rfb_envvars.json")

    # Try and set RMANTREE depending on preferences
    if rmantree == '':

        if rmantree_method == 'MANUAL':
            rmantree = get_pref('path_rmantree')

        if rmantree_method == 'DETECT' and choice != 'NEWEST':
            rmantree = choice

        if rmantree == '' or rmantree_method == 'ENV':
            # Fallback to RMANTREE env var
            if rmantree == '':
                rfb_log().info('Fallback to using RMANTREE.')
            rmantree = os.environ.get('RMANTREE', '')

        if rmantree == '':
            if rmantree_method == 'ENV':
                rfb_log().info('Fallback to autodetecting newest.')

            if choice == 'NEWEST':
                # get from detected installs (at default installation path)
                for vstr, d_rmantree in get_installed_rendermans():
                    d_version = _parse_version(vstr)
                    if d_version > latest:
                        rmantree = d_rmantree
                        version = d_version

        if version[0] == 0:
            version = _get_rman_version(rmantree)

        # check rmantree valid
        if version[0] == 0:
            rfb_log().error(
                "Error loading addon.  RMANTREE %s is not valid.  Correct RMANTREE setting in addon preferences." % rmantree)
            __RMAN_ENV_CONFIG__ = None
            return None

        # check if this version of RenderMan is supported
        if version[0] < rman_constants.RMAN_SUPPORTED_VERSION_MAJOR:
            rfb_log().error("Error loading addon using RMANTREE=%s.  RMANTREE must be version %s or greater.  Correct RMANTREE setting in addon preferences." % (rmantree, rman_constants.RMAN_SUPPORTED_VERSION_STRING))
            __RMAN_ENV_CONFIG__ = None
            return None

        rfb_log().debug("Guessed RMANTREE: %s" % rmantree)

    # Create an RmanEnvConfig object
    __RMAN_ENV_CONFIG__.rmantree = rmantree
    __RMAN_ENV_CONFIG__.rman_version = '%d.%d%s' % (version[0], version[1], version[2])
    __RMAN_ENV_CONFIG__.rman_version_major = version[0]
    __RMAN_ENV_CONFIG__.rman_version_minor = version[1]
    __RMAN_ENV_CONFIG__.rman_version_modifier = version[2]
    __RMAN_ENV_CONFIG__.config_environment()

    return __RMAN_ENV_CONFIG__

def get_installed_rendermans():
    base = {'Windows': r'C:\Program Files\Pixar',
            'Darwin': '/Applications/Pixar',
            'Linux': '/opt/pixar'}[platform.system()]
    rendermans = []

    try:
        for d in os.listdir(base):
            if "RenderManProServer" in d:
                try:
                    vstr = d.split('-')[1]
                    rendermans.append((vstr, os.path.join(base, d)))
                except:
                    pass
    except:
        pass

    return rendermans

def reload_envconfig():
    global __RMAN_ENV_CONFIG__
    if not _guess_rmantree():
        return None
    return __RMAN_ENV_CONFIG__

def envconfig():

    global __RMAN_ENV_CONFIG__
    if not __RMAN_ENV_CONFIG__:
        if not _guess_rmantree():
            return None
    return __RMAN_ENV_CONFIG__

<|endoftext|>


<commit_before>"""Scheduler for running via docker."""
import time

import docker
try:
    from pprintpp import pprint
except ImportError:
    from pprint import pprint

from rickshaw.scheduler import Scheduler

class DockerScheduler(Scheduler):
    """A base docker scheduler"""

    def __init__(self, debug=False, **kwargs):
        self.client = docker.from_env()
        try:
            try_test = self.client.nodes.list()
        except:
            print('Remember to give this container/service access to the \
                   docker socket on the host machine with the following command \
                   -v /var/run/docker.sock:/var/run/docker.sock')
        self.cyclus_container = None
        self.server_tag = "ergs/cyclus-server-dev"
        if debug:
            self.server_cmd = "--debug"
        else:
            self.server_cmd = ""
        self.cyclus_server_name = "rickshaw_metadata_server"
        self.cyclus_server_host = None
        self.cyclus_server_ready = False
        self.gathered_annotations = False
        self._have_swarm = False
        self._find_ncpu()

    def _find_ncpu(self):
        try:
            # get NCPUs for swarm
            ncpu = 0.0
            for node in self.client.nodes.list():
                ncpu += node.attrs['Description']['Resources']['NanoCPUs'] * 1e-9
            self._have_swarm = True
        except docker.errors.APIError:
            print('except')
            # get NCPUs for local host
            ncpu = self.client.info()['NCPU']
            self._have_swarm = False
        self.ncpu = int(ncpu)

    def __del__(self):
        self.stop_cyclus_server()

    def start_cyclus_server(self):
        """Starts up a cyclus server at a remote location."""
        print("starting cyclus server")
        cc = self.cyclus_container = self.client.containers.run(self.server_tag,
                                                                self.server_cmd,
                                        ports={'4242/tcp': ('127.0.0.1', 4242)},
                                                   name=self.cyclus_server_name,
                                                         publish_all_ports=True,
                                                                    detach=True)
        host = self.client.networks.get('bridge').attrs['Containers'][cc.id]['IPv4Address']
        if '/' in host:
            self.cyclus_server_host, _, _ = host.rpartition('/')
        else:
            self.cyclus_server_host = host
        print("cyclus server started at host " + host)
        time.sleep(3)
        self.cyclus_server_ready = True
        for line in cc.logs(stream=True):
            print('[cyclus] ' + line.decode(), end='')

    def stop_cyclus_server(self):
        """Stops the cyclus server running in a remote location"""
        if self.cyclus_container is not None:
            self.cyclus_container.stop()
            self.cyclus_container = None
        self.cyclus_server_ready = False

    def queue(self):
        """Obtains the current queue status and retuns the jobs that are scheduled
        and status of each job.
        """
        return [(c.id, c.status) for c in self.client.containers.list()]

    def schedule(self, sim):
        """Schedules a simulation to be executed."""
        #print("would have scheduled sim: ", repr(sim))

    def want_n_more_jobs(self):
        """Determine how many more new jobs to schedule."""
        n = self.ncpu*2 - len(self.queue())
        print("will want, " + str(n))
        pprint(self.client.swarm.attrs)
        return n
<commit_msg>update<commit_after>"""Scheduler for running via docker."""
import time

import docker
try:
    from pprintpp import pprint
except ImportError:
    from pprint import pprint

from rickshaw.scheduler import Scheduler

class DockerScheduler(Scheduler):
    """A base docker scheduler"""

    def __init__(self, debug=False, **kwargs):
        self.client = docker.from_env()
        try:
            try_test = self.client.nodes.list()
        except:
            print('Remember to give this container/service access to the '+
                   'docker socket on the host machine with the following command: '+
                   '-v /var/run/docker.sock:/var/run/docker.sock')
        self.cyclus_container = None
        self.server_tag = "ergs/cyclus-server-dev"
        if debug:
            self.server_cmd = "--debug"
        else:
            self.server_cmd = ""
        self.cyclus_server_name = "rickshaw_metadata_server"
        self.cyclus_server_host = None
        self.cyclus_server_ready = False
        self.gathered_annotations = False
        self._have_swarm = False
        self._find_ncpu()

    def _find_ncpu(self):
        try:
            # get NCPUs for swarm
            ncpu = 0.0
            for node in self.client.nodes.list():
                ncpu += node.attrs['Description']['Resources']['NanoCPUs'] * 1e-9
            self._have_swarm = True
        except docker.errors.APIError:
            print('except')
            # get NCPUs for local host
            ncpu = self.client.info()['NCPU']
            self._have_swarm = False
        self.ncpu = int(ncpu)

    def __del__(self):
        self.stop_cyclus_server()

    def start_cyclus_server(self):
        """Starts up a cyclus server at a remote location."""
        print("starting cyclus server")
        cc = self.cyclus_container = self.client.containers.run(self.server_tag,
                                                                self.server_cmd,
                                        ports={'4242/tcp': ('127.0.0.1', 4242)},
                                                   name=self.cyclus_server_name,
                                                         publish_all_ports=True,
                                                                    detach=True)
        host = self.client.networks.get('bridge').attrs['Containers'][cc.id]['IPv4Address']
        if '/' in host:
            self.cyclus_server_host, _, _ = host.rpartition('/')
        else:
            self.cyclus_server_host = host
        print("cyclus server started at host " + host)
        time.sleep(3)
        self.cyclus_server_ready = True
        for line in cc.logs(stream=True):
            print('[cyclus] ' + line.decode(), end='')

    def stop_cyclus_server(self):
        """Stops the cyclus server running in a remote location"""
        if self.cyclus_container is not None:
            self.cyclus_container.stop()
            self.cyclus_container = None
        self.cyclus_server_ready = False

    def queue(self):
        """Obtains the current queue status and retuns the jobs that are scheduled
        and status of each job.
        """
        return [(c.id, c.status) for c in self.client.containers.list()]

    def schedule(self, sim):
        """Schedules a simulation to be executed."""
        #print("would have scheduled sim: ", repr(sim))

    def want_n_more_jobs(self):
        """Determine how many more new jobs to schedule."""
        n = self.ncpu*2 - len(self.queue())
        print("will want, " + str(n))
        pprint(self.client.swarm.attrs)
        return n
<|endoftext|>


<commit_before>from __future__ import print_function, division
from RPi import GPIO
import sqlite3 as sqlite
from greenhouse_database import GreenhouseDatabase
from datetime import datetime
from time import sleep, time
import math
from sys import exit

try:
    import Adafruit_DHT
except ImportError:
    print("Adafruit DHT library missing.")
    exit(0)

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

db = GreenhouseDatabase()

class Greenhouse(object):
    DHT_SENSOR = Adafruit_DHT.DHT22
    DHT = 19
    SOIL = 26
    LIGHT = 18

    def __init__(self):
        self.darkness_level = 0.01

    @property
    def temperature(self):
        humidity, temperature = self._get_humidity_and_temperature()
        return temperature

    @property
    def humidity(self):
        humidity, temperature = self._get_humidity_and_temperature()
        return humidity

    @property
    def soil(self):
        return self._get_average_soil_moisture(5)

    @property
    def light(self):
        return self._get_average_light_level(5)

    def _get_humidity_and_temperature(self):
        humidity, temperature = Adafruit_DHT.read_retry(
            sensor=self.DHT_SENSOR,
            pin=self.DHT,
            retries=5
        )
        return (humidity, temperature)

    def _get_soil_moisture(self):
        time_taken = self._time_charging_soil_capacitor()
        totally_wet_time = 8E-6
        totally_dry_time = 0.01
        moisture = (
            math.log(time_taken / totally_dry_time) /
            math.log(totally_wet_time / totally_dry_time)
        )
        return max(0, min(1, moisture)) * 100

    def _time_charging_soil_capacitor(self):
        pin = self.SOIL
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, GPIO.LOW)
        sleep(0.1)
        GPIO.setup(pin, GPIO.IN)
        start_time = time()
        end_time = time()
        max_time = 1
        while GPIO.input(pin) == GPIO.LOW and time() - start_time < max_time:
            end_time = time()
        time_taken = end_time - start_time
        return time_taken

    def _get_light_level(self):
        time_taken = self._time_charging_light_capacitor()
        value = 100 * time_taken / self.darkness_level
        return 100 - value

    def _time_charging_light_capacitor(self):
        pin = self.LIGHT
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, GPIO.LOW)
        sleep(0.1)
        GPIO.setup(pin, GPIO.IN)
        start_time = time()
        end_time = time()
        while (
                GPIO.input(pin) == GPIO.LOW and
                time() - start_time < self.darkness_level
            ):
            end_time = time()
        time_taken = end_time - start_time
        return min(time_taken, self.darkness_level)

    def _get_average_soil_moisture(self, num):
        values = [self._get_soil_moisture() for n in range(num)]
        average_value = sum(values) / len(values)
        return average_value

    def _get_average_light_level(self, num):
        values = [self._get_light_level() for n in range(num)]
        average_value = sum(values) / len(values)
        return average_value

    def _get_timestamp(self):
        dt = datetime.now()
        dt_date = str(dt.date())
        dt_time = str(dt.time())
        timestamp = "%s %s" % (dt_date, dt_time[:8])
        return timestamp

    def record_sensor_values(self):
        """
        Save sensor readings to database
        """
        timestamp = self._get_timestamp()
        temperature = self.temperature
        humidity = self.humidity
        soil = self.soil
        light = self.light

        values = (timestamp, temperature, humidity, soil, light)

        db.record_sensor_values(values)

    def export_to_csv(self, file_path=None):
        """
        Export sensor data from database and save as CSV file in file_path
        Defaults to /home/pi/greenhouse.csv
        """
        db.export_to_csv(file_path)

def main():
    greenhouse = Greenhouse()
    greenhouse.record_sensor_values()
    greenhouse.export_to_csv()
    print("Temperature:")
    print(greenhouse.temperature)
    print("Humidity:")
    print(greenhouse.humidity)
    print("Soil:")
    print(greenhouse.soil)
    print("Light:")
    print(greenhouse.light)

if __name__ == '__main__':
    main()
<commit_msg>Explicitly set default CSV path argument<commit_after>from __future__ import print_function, division
from RPi import GPIO
import sqlite3 as sqlite
from greenhouse_database import GreenhouseDatabase
from datetime import datetime
from time import sleep, time
import math
from sys import exit

try:
    import Adafruit_DHT
except ImportError:
    print("Adafruit DHT library missing.")
    exit(0)

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

db = GreenhouseDatabase()

class Greenhouse(object):
    DHT_SENSOR = Adafruit_DHT.DHT22
    DHT = 19
    SOIL = 26
    LIGHT = 18

    def __init__(self):
        self.darkness_level = 0.01

    @property
    def temperature(self):
        humidity, temperature = self._get_humidity_and_temperature()
        return temperature

    @property
    def humidity(self):
        humidity, temperature = self._get_humidity_and_temperature()
        return humidity

    @property
    def soil(self):
        return self._get_average_soil_moisture(5)

    @property
    def light(self):
        return self._get_average_light_level(5)

    def _get_humidity_and_temperature(self):
        humidity, temperature = Adafruit_DHT.read_retry(
            sensor=self.DHT_SENSOR,
            pin=self.DHT,
            retries=5
        )
        return (humidity, temperature)

    def _get_soil_moisture(self):
        time_taken = self._time_charging_soil_capacitor()
        totally_wet_time = 8E-6
        totally_dry_time = 0.01
        moisture = (
            math.log(time_taken / totally_dry_time) /
            math.log(totally_wet_time / totally_dry_time)
        )
        return max(0, min(1, moisture)) * 100

    def _time_charging_soil_capacitor(self):
        pin = self.SOIL
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, GPIO.LOW)
        sleep(0.1)
        GPIO.setup(pin, GPIO.IN)
        start_time = time()
        end_time = time()
        max_time = 1
        while GPIO.input(pin) == GPIO.LOW and time() - start_time < max_time:
            end_time = time()
        time_taken = end_time - start_time
        return time_taken

    def _get_light_level(self):
        time_taken = self._time_charging_light_capacitor()
        value = 100 * time_taken / self.darkness_level
        return 100 - value

    def _time_charging_light_capacitor(self):
        pin = self.LIGHT
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, GPIO.LOW)
        sleep(0.1)
        GPIO.setup(pin, GPIO.IN)
        start_time = time()
        end_time = time()
        while (
                GPIO.input(pin) == GPIO.LOW and
                time() - start_time < self.darkness_level
            ):
            end_time = time()
        time_taken = end_time - start_time
        return min(time_taken, self.darkness_level)

    def _get_average_soil_moisture(self, num):
        values = [self._get_soil_moisture() for n in range(num)]
        average_value = sum(values) / len(values)
        return average_value

    def _get_average_light_level(self, num):
        values = [self._get_light_level() for n in range(num)]
        average_value = sum(values) / len(values)
        return average_value

    def _get_timestamp(self):
        dt = datetime.now()
        dt_date = str(dt.date())
        dt_time = str(dt.time())
        timestamp = "%s %s" % (dt_date, dt_time[:8])
        return timestamp

    def record_sensor_values(self):
        """
        Save sensor readings to database
        """
        timestamp = self._get_timestamp()
        temperature = self.temperature
        humidity = self.humidity
        soil = self.soil
        light = self.light

        values = (timestamp, temperature, humidity, soil, light)

        db.record_sensor_values(values)

    def export_to_csv(self, file_path='/home/pi/greenhouse.csv'):
        """
        Export sensor data from database and save as CSV file in file_path
        Defaults to /home/pi/greenhouse.csv
        """
        db.export_to_csv(file_path)

def main():
    greenhouse = Greenhouse()
    greenhouse.record_sensor_values()
    greenhouse.export_to_csv()
    print("Temperature:")
    print(greenhouse.temperature)
    print("Humidity:")
    print(greenhouse.humidity)
    print("Soil:")
    print(greenhouse.soil)
    print("Light:")
    print(greenhouse.light)

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