<commit_before>from __future__ import absolute_import
import __init__

import wx, os, platform, types, webbrowser

from gui import configBase
from gui import preview3d
from gui import sliceProgessPanel
from gui import preferencesDialog
from gui import configWizard
from gui import firmwareInstall
from gui import printWindow
from gui import icon
from util import validators
from util import profile
from util import version
from util import sliceRun

class simpleModeWindow(configBase.configWindowBase):
	"Main user interface window for Quickprint mode"
	def __init__(self):
		super(simpleModeWindow, self).__init__(title='Cura - Quickprint - ' + version.getVersion())

		wx.EVT_CLOSE(self, self.OnClose)
		#self.SetIcon(icon.getMainIcon())

		menubar = wx.MenuBar()
		fileMenu = wx.Menu()
		i = fileMenu.Append(-1, 'Load model file...')
		self.Bind(wx.EVT_MENU, self.OnLoadModel, i)
		fileMenu.AppendSeparator()
		i = fileMenu.Append(-1, 'Preferences...')
		self.Bind(wx.EVT_MENU, self.OnPreferences, i)
		fileMenu.AppendSeparator()
		i = fileMenu.Append(wx.ID_EXIT, 'Quit')
		self.Bind(wx.EVT_MENU, self.OnQuit, i)
		menubar.Append(fileMenu, '&File')

		expertMenu = wx.Menu()
		i = expertMenu.Append(-1, 'Switch to Normal mode...')
		self.Bind(wx.EVT_MENU, self.OnNormalSwitch, i)
		expertMenu.AppendSeparator()
		i = expertMenu.Append(-1, 'ReRun first run wizard...')
		self.Bind(wx.EVT_MENU, self.OnFirstRunWizard, i)
		menubar.Append(expertMenu, 'Expert')

		helpMenu = wx.Menu()
		i = helpMenu.Append(-1, 'Online documentation...')
		self.Bind(wx.EVT_MENU, lambda e: webbrowser.open('https://github.com/daid/Cura/wiki'), i)
		i = helpMenu.Append(-1, 'Report a problem...')
		self.Bind(wx.EVT_MENU, lambda e: webbrowser.open('https://github.com/daid/Cura/issues'), i)
		menubar.Append(helpMenu, 'Help')
		self.SetMenuBar(menubar)

		if profile.getPreference('lastFile') != '':
			self.filelist = profile.getPreference('lastFile').split(';')
			self.SetTitle(self.filelist[-1] + ' - Cura - ' + version.getVersion())
		else:
			self.filelist = []
		self.progressPanelList = []

		#Preview window
		self.preview3d = preview3d.previewPanel(self)

		configPanel = wx.Panel(self)
		self.printTypeNormal = wx.RadioButton(configPanel, -1, 'Normal quality print', style=wx.RB_GROUP)
		self.printTypeLow = wx.RadioButton(configPanel, -1, 'Fast low quality print')
		self.printTypeHigh = wx.RadioButton(configPanel, -1, 'High quality print')
		self.printTypeJoris = wx.RadioButton(configPanel, -1, 'Thin walled cup or vase')

		self.printMaterialPLA = wx.RadioButton(configPanel, -1, 'PLA', style=wx.RB_GROUP)
		self.printMaterialABS = wx.RadioButton(configPanel, -1, 'ABS')
		self.printMaterialDiameter = wx.TextCtrl(configPanel, -1, profile.getProfileSetting('filament_diameter'))

		self.printSupport = wx.CheckBox(configPanel, -1, 'Print support structure')

		sizer = wx.GridBagSizer()
		configPanel.SetSizer(sizer)

		sb = wx.StaticBox(configPanel, label="Select a print type:")
		boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)
		boxsizer.Add(self.printTypeNormal)
		boxsizer.Add(self.printTypeLow)
		boxsizer.Add(self.printTypeHigh)
		boxsizer.Add(self.printTypeJoris)
		sizer.Add(boxsizer, (0,0), flag=wx.EXPAND)

		sb = wx.StaticBox(configPanel, label="Material:")
		boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)
		boxsizer.Add(self.printMaterialPLA)
		boxsizer.Add(self.printMaterialABS)
		boxsizer.Add(wx.StaticText(configPanel, -1, 'Diameter:'))
		boxsizer.Add(self.printMaterialDiameter)
		sizer.Add(boxsizer, (1,0), flag=wx.EXPAND)

		sb = wx.StaticBox(configPanel, label="Other:")
		boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)
		boxsizer.Add(self.printSupport)
		sizer.Add(boxsizer, (2,0), flag=wx.EXPAND)

		# load and slice buttons.
		loadButton = wx.Button(self, -1, 'Load Model')
		sliceButton = wx.Button(self, -1, 'Prepare print')
		printButton = wx.Button(self, -1, 'Print')
		self.Bind(wx.EVT_BUTTON, self.OnLoadModel, loadButton)
		self.Bind(wx.EVT_BUTTON, self.OnSlice, sliceButton)
		self.Bind(wx.EVT_BUTTON, self.OnPrint, printButton)
		#Also bind double clicking the 3D preview to load an STL file.
		self.preview3d.glCanvas.Bind(wx.EVT_LEFT_DCLICK, self.OnLoadModel, self.preview3d.glCanvas)

		#Main sizer, to position the preview window, buttons and tab control
		sizer = wx.GridBagSizer()
		self.SetSizer(sizer)
		sizer.Add(configPanel, (0,0), span=(1,1), flag=wx.EXPAND)
		sizer.Add(self.preview3d, (0,1), span=(1,3), flag=wx.EXPAND)
		sizer.AddGrowableCol(2)
		sizer.AddGrowableRow(0)
		sizer.Add(loadButton, (1,1), flag=wx.RIGHT, border=5)
		sizer.Add(sliceButton, (1,2), flag=wx.RIGHT, border=5)
		sizer.Add(printButton, (1,3), flag=wx.RIGHT, border=5)
		self.sizer = sizer

		if len(self.filelist) > 0:
			self.preview3d.loadModelFiles(self.filelist)

		self.updateProfileToControls()

		self.Fit()
		self.SetMinSize(self.GetSize())
		self.Centre()
		self.Show(True)

	def OnPreferences(self, e):
		prefDialog = preferencesDialog.preferencesDialog(self)
		prefDialog.Centre()
		prefDialog.Show(True)

	def OnDefaultMarlinFirmware(self, e):
		firmwareInstall.InstallFirmware()

	def OnCustomFirmware(self, e):
		dlg=wx.FileDialog(self, "Open firmware to upload", os.path.split(profile.getPreference('lastFile'))[0], style=wx.FD_OPEN|wx.FD_FILE_MUST_EXIST)
		dlg.SetWildcard("HEX file (*.hex)|*.hex;*.HEX")
		if dlg.ShowModal() == wx.ID_OK:
			filename = dlg.GetPath()
			if not(os.path.exists(filename)):
				return
			#For some reason my Ubuntu 10.10 crashes here.
			firmwareInstall.InstallFirmware(filename)

	def OnFirstRunWizard(self, e):
		configWizard.configWizard()
		self.updateProfileToControls()

	def OnLoadModel(self, e):
		dlg=wx.FileDialog(self, "Open file to print", os.path.split(profile.getPreference('lastFile'))[0], style=wx.FD_OPEN|wx.FD_FILE_MUST_EXIST)
		dlg.SetWildcard("STL files (*.stl)|*.stl;*.STL")
		if dlg.ShowModal() == wx.ID_OK:
			self.filelist = [dlg.GetPath()]
			profile.putPreference('lastFile', ';'.join(self.filelist))
			self.preview3d.loadModelFiles(self.filelist, True)
			self.preview3d.setViewMode("Normal")
		dlg.Destroy()

	def OnSlice(self, e):
		if len(self.filelist) < 1:
			wx.MessageBox('You need to load a file before you can slice it.', 'Print error', wx.OK | wx.ICON_INFORMATION)
			return
		#save the current profile so we can put it back latter
		oldProfile = profile.getGlobalProfileString()

		put = profile.putProfileSetting
		get = profile.getProfileSetting

		put('layer_height', '0.2')
		put('wall_thickness', '0.8')
		put('solid_layer_thickness', '0.6')
		put('fill_density', '20')
		put('skirt_line_count', '1')
		put('skirt_gap', '6.0')
		put('print_speed', '50')
		put('print_temperature', '0')
		put('support', 'None')
		#put('machine_center_x', '100')
		#put('machine_center_y', '100')
		#put('retraction_min_travel', '5.0')
		#put('retraction_speed', '13.5')
		#put('retraction_amount', '0.0')
		#put('retraction_extra', '0.0')
		put('travel_speed', '150')
		put('max_z_speed', '3.0')
		put('bottom_layer_speed', '25')
		put('cool_min_layer_time', '10')
		put('fan_enabled', 'True')
		put('fan_layer', '1')
		put('fan_speed', '100')
		#put('model_scale', '1.0')
		#put('flip_x', 'False')
		#put('flip_y', 'False')
		#put('flip_z', 'False')
		#put('model_rotate_base', '0')
		#put('model_multiply_x', '1')
		#put('model_multiply_y', '1')
		put('extra_base_wall_thickness', '0.0')
		put('sequence', 'Loops > Perimeter > Infill')
		put('force_first_layer_sequence', 'True')
		put('infill_type', 'Line')
		put('solid_top', 'True')
		put('fill_overlap', '15')
		put('support_rate', '50')
		put('support_distance', '0.5')
		put('joris', 'False')
		put('cool_min_feedrate', '5')
		put('bridge_speed', '100')
		put('raft_margin', '5')
		put('raft_base_material_amount', '100')
		put('raft_interface_material_amount', '100')
		put('bottom_thickness', '0.0')

		if self.printSupport.GetValue():
			put('support', 'Exterior Only')

		nozzle_size = float(get('nozzle_size'))
		if self.printTypeNormal.GetValue():
			put('wall_thickness', nozzle_size * 2.0)
			put('layer_height', '0.2')
			put('fill_density', '20')
		elif self.printTypeLow.GetValue():
			put('wall_thickness', nozzle_size * 1.0)
			put('layer_height', '0.3')
			put('fill_density', '10')
			put('print_speed', '80')
			put('bottom_layer_speed', '40')
		elif self.printTypeHigh.GetValue():
			put('wall_thickness', nozzle_size * 3.0)
			put('layer_height', '0.1')
			put('fill_density', '30')
			put('bottom_layer_speed', '15')
			put('bottom_thickness', '0.2')
		elif self.printTypeJoris.GetValue():
			put('wall_thickness', nozzle_size * 1.5)
			put('layer_height', '0.3')
			put('fill_density', '0')
			put('joris', 'True')
			put('extra_base_wall_thickness', '15.0')
			put('sequence', 'Infill > Loops > Perimeter')
			put('force_first_layer_sequence', 'False')
			put('solid_top', 'False')
			put('support', 'None')
			put('cool_min_layer_time', '3')

		put('filament_diameter', self.printMaterialDiameter.GetValue())
		if self.printMaterialPLA.GetValue():
			put('filament_density', '1.00')
			put('enable_raft', 'False')
			put('skirt_line_count', '1')
		if self.printMaterialABS.GetValue():
			put('filament_density', '0.85')
			put('enable_raft', 'True')
			put('skirt_line_count', '0')
			put('fan_layer', '1')
			put('bottom_thickness', '0.0')

		#Create a progress panel and add it to the window. The progress panel will start the Skein operation.
		spp = sliceProgessPanel.sliceProgessPanel(self, self, self.filelist)
		self.sizer.Add(spp, (len(self.progressPanelList)+2,0), span=(1,4), flag=wx.EXPAND)
		self.sizer.Layout()
		newSize = self.GetSize();
		newSize.IncBy(0, spp.GetSize().GetHeight())
		self.SetSize(newSize)
		self.progressPanelList.append(spp)

		#Restore the old profile.
		profile.loadGlobalProfileFromString(oldProfile)

	def OnPrint(self, e):
		if len(self.filelist) < 1:
			wx.MessageBox('You need to load a file and slice it before you can print it.', 'Print error', wx.OK | wx.ICON_INFORMATION)
			return
		if not os.path.exists(sliceRun.getExportFilename(self.filelist[0])):
			wx.MessageBox('You need to slice the file to GCode before you can print it.', 'Print error', wx.OK | wx.ICON_INFORMATION)
			return
		printWindow.printFile(sliceRun.getExportFilename(self.filelist[0]))

	def OnNormalSwitch(self, e):
		from gui import mainWindow
		profile.putPreference('startMode', 'Normal')
		mainWindow.mainWindow()
		self.Close()

	def removeSliceProgress(self, spp):
		self.progressPanelList.remove(spp)
		newSize = self.GetSize();
		newSize.IncBy(0, -spp.GetSize().GetHeight())
		self.SetSize(newSize)
		self.sizer.Remove(spp)
		spp.Destroy()
		for spp in self.progressPanelList:
			self.sizer.Remove(spp)
		i = 2
		for spp in self.progressPanelList:
			self.sizer.Add(spp, (i,0), span=(1,4), flag=wx.EXPAND)
			i += 1
		self.sizer.Layout()

	def OnQuit(self, e):
		self.Close()

	def OnClose(self, e):
		self.Destroy()

	def updateProfileToControls(self):
		super(simpleModeWindow, self).updateProfileToControls()
		self.preview3d.updateProfileToControls()

<commit_msg>Add temperature for simple mode, #192<commit_after>from __future__ import absolute_import
import __init__

import wx, os, platform, types, webbrowser

from gui import configBase
from gui import preview3d
from gui import sliceProgessPanel
from gui import preferencesDialog
from gui import configWizard
from gui import firmwareInstall
from gui import printWindow
from gui import icon
from util import validators
from util import profile
from util import version
from util import sliceRun

class simpleModeWindow(configBase.configWindowBase):
	"Main user interface window for Quickprint mode"
	def __init__(self):
		super(simpleModeWindow, self).__init__(title='Cura - Quickprint - ' + version.getVersion())

		wx.EVT_CLOSE(self, self.OnClose)
		#self.SetIcon(icon.getMainIcon())

		menubar = wx.MenuBar()
		fileMenu = wx.Menu()
		i = fileMenu.Append(-1, 'Load model file...')
		self.Bind(wx.EVT_MENU, self.OnLoadModel, i)
		fileMenu.AppendSeparator()
		i = fileMenu.Append(-1, 'Preferences...')
		self.Bind(wx.EVT_MENU, self.OnPreferences, i)
		fileMenu.AppendSeparator()
		i = fileMenu.Append(wx.ID_EXIT, 'Quit')
		self.Bind(wx.EVT_MENU, self.OnQuit, i)
		menubar.Append(fileMenu, '&File')

		expertMenu = wx.Menu()
		i = expertMenu.Append(-1, 'Switch to Normal mode...')
		self.Bind(wx.EVT_MENU, self.OnNormalSwitch, i)
		expertMenu.AppendSeparator()
		i = expertMenu.Append(-1, 'ReRun first run wizard...')
		self.Bind(wx.EVT_MENU, self.OnFirstRunWizard, i)
		menubar.Append(expertMenu, 'Expert')

		helpMenu = wx.Menu()
		i = helpMenu.Append(-1, 'Online documentation...')
		self.Bind(wx.EVT_MENU, lambda e: webbrowser.open('https://github.com/daid/Cura/wiki'), i)
		i = helpMenu.Append(-1, 'Report a problem...')
		self.Bind(wx.EVT_MENU, lambda e: webbrowser.open('https://github.com/daid/Cura/issues'), i)
		menubar.Append(helpMenu, 'Help')
		self.SetMenuBar(menubar)

		if profile.getPreference('lastFile') != '':
			self.filelist = profile.getPreference('lastFile').split(';')
			self.SetTitle(self.filelist[-1] + ' - Cura - ' + version.getVersion())
		else:
			self.filelist = []
		self.progressPanelList = []

		#Preview window
		self.preview3d = preview3d.previewPanel(self)

		configPanel = wx.Panel(self)
		self.printTypeNormal = wx.RadioButton(configPanel, -1, 'Normal quality print', style=wx.RB_GROUP)
		self.printTypeLow = wx.RadioButton(configPanel, -1, 'Fast low quality print')
		self.printTypeHigh = wx.RadioButton(configPanel, -1, 'High quality print')
		self.printTypeJoris = wx.RadioButton(configPanel, -1, 'Thin walled cup or vase')

		self.printMaterialPLA = wx.RadioButton(configPanel, -1, 'PLA', style=wx.RB_GROUP)
		self.printMaterialABS = wx.RadioButton(configPanel, -1, 'ABS')
		self.printMaterialDiameter = wx.TextCtrl(configPanel, -1, profile.getProfileSetting('filament_diameter'))

		self.printSupport = wx.CheckBox(configPanel, -1, 'Print support structure')

		sizer = wx.GridBagSizer()
		configPanel.SetSizer(sizer)

		sb = wx.StaticBox(configPanel, label="Select a print type:")
		boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)
		boxsizer.Add(self.printTypeNormal)
		boxsizer.Add(self.printTypeLow)
		boxsizer.Add(self.printTypeHigh)
		boxsizer.Add(self.printTypeJoris)
		sizer.Add(boxsizer, (0,0), flag=wx.EXPAND)

		sb = wx.StaticBox(configPanel, label="Material:")
		boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)
		boxsizer.Add(self.printMaterialPLA)
		boxsizer.Add(self.printMaterialABS)
		boxsizer.Add(wx.StaticText(configPanel, -1, 'Diameter:'))
		boxsizer.Add(self.printMaterialDiameter)
		sizer.Add(boxsizer, (1,0), flag=wx.EXPAND)

		sb = wx.StaticBox(configPanel, label="Other:")
		boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)
		boxsizer.Add(self.printSupport)
		sizer.Add(boxsizer, (2,0), flag=wx.EXPAND)

		# load and slice buttons.
		loadButton = wx.Button(self, -1, 'Load Model')
		sliceButton = wx.Button(self, -1, 'Prepare print')
		printButton = wx.Button(self, -1, 'Print')
		self.Bind(wx.EVT_BUTTON, self.OnLoadModel, loadButton)
		self.Bind(wx.EVT_BUTTON, self.OnSlice, sliceButton)
		self.Bind(wx.EVT_BUTTON, self.OnPrint, printButton)
		#Also bind double clicking the 3D preview to load an STL file.
		self.preview3d.glCanvas.Bind(wx.EVT_LEFT_DCLICK, self.OnLoadModel, self.preview3d.glCanvas)

		#Main sizer, to position the preview window, buttons and tab control
		sizer = wx.GridBagSizer()
		self.SetSizer(sizer)
		sizer.Add(configPanel, (0,0), span=(1,1), flag=wx.EXPAND)
		sizer.Add(self.preview3d, (0,1), span=(1,3), flag=wx.EXPAND)
		sizer.AddGrowableCol(2)
		sizer.AddGrowableRow(0)
		sizer.Add(loadButton, (1,1), flag=wx.RIGHT, border=5)
		sizer.Add(sliceButton, (1,2), flag=wx.RIGHT, border=5)
		sizer.Add(printButton, (1,3), flag=wx.RIGHT, border=5)
		self.sizer = sizer

		if len(self.filelist) > 0:
			self.preview3d.loadModelFiles(self.filelist)

		self.updateProfileToControls()

		self.Fit()
		self.SetMinSize(self.GetSize())
		self.Centre()
		self.Show(True)

	def OnPreferences(self, e):
		prefDialog = preferencesDialog.preferencesDialog(self)
		prefDialog.Centre()
		prefDialog.Show(True)

	def OnDefaultMarlinFirmware(self, e):
		firmwareInstall.InstallFirmware()

	def OnCustomFirmware(self, e):
		dlg=wx.FileDialog(self, "Open firmware to upload", os.path.split(profile.getPreference('lastFile'))[0], style=wx.FD_OPEN|wx.FD_FILE_MUST_EXIST)
		dlg.SetWildcard("HEX file (*.hex)|*.hex;*.HEX")
		if dlg.ShowModal() == wx.ID_OK:
			filename = dlg.GetPath()
			if not(os.path.exists(filename)):
				return
			#For some reason my Ubuntu 10.10 crashes here.
			firmwareInstall.InstallFirmware(filename)

	def OnFirstRunWizard(self, e):
		configWizard.configWizard()
		self.updateProfileToControls()

	def OnLoadModel(self, e):
		dlg=wx.FileDialog(self, "Open file to print", os.path.split(profile.getPreference('lastFile'))[0], style=wx.FD_OPEN|wx.FD_FILE_MUST_EXIST)
		dlg.SetWildcard("STL files (*.stl)|*.stl;*.STL")
		if dlg.ShowModal() == wx.ID_OK:
			self.filelist = [dlg.GetPath()]
			profile.putPreference('lastFile', ';'.join(self.filelist))
			self.preview3d.loadModelFiles(self.filelist, True)
			self.preview3d.setViewMode("Normal")
		dlg.Destroy()

	def OnSlice(self, e):
		if len(self.filelist) < 1:
			wx.MessageBox('You need to load a file before you can slice it.', 'Print error', wx.OK | wx.ICON_INFORMATION)
			return
		#save the current profile so we can put it back latter
		oldProfile = profile.getGlobalProfileString()

		put = profile.putProfileSetting
		get = profile.getProfileSetting

		put('layer_height', '0.2')
		put('wall_thickness', '0.8')
		put('solid_layer_thickness', '0.6')
		put('fill_density', '20')
		put('skirt_line_count', '1')
		put('skirt_gap', '6.0')
		put('print_speed', '50')
		put('print_temperature', '230')
		put('support', 'None')
		#put('machine_center_x', '100')
		#put('machine_center_y', '100')
		#put('retraction_min_travel', '5.0')
		#put('retraction_speed', '13.5')
		#put('retraction_amount', '0.0')
		#put('retraction_extra', '0.0')
		put('travel_speed', '150')
		put('max_z_speed', '3.0')
		put('bottom_layer_speed', '25')
		put('cool_min_layer_time', '10')
		put('fan_enabled', 'True')
		put('fan_layer', '1')
		put('fan_speed', '100')
		#put('model_scale', '1.0')
		#put('flip_x', 'False')
		#put('flip_y', 'False')
		#put('flip_z', 'False')
		#put('model_rotate_base', '0')
		#put('model_multiply_x', '1')
		#put('model_multiply_y', '1')
		put('extra_base_wall_thickness', '0.0')
		put('sequence', 'Loops > Perimeter > Infill')
		put('force_first_layer_sequence', 'True')
		put('infill_type', 'Line')
		put('solid_top', 'True')
		put('fill_overlap', '15')
		put('support_rate', '50')
		put('support_distance', '0.5')
		put('joris', 'False')
		put('cool_min_feedrate', '5')
		put('bridge_speed', '100')
		put('raft_margin', '5')
		put('raft_base_material_amount', '100')
		put('raft_interface_material_amount', '100')
		put('bottom_thickness', '0.0')

		if self.printSupport.GetValue():
			put('support', 'Exterior Only')

		nozzle_size = float(get('nozzle_size'))
		if self.printTypeNormal.GetValue():
			put('wall_thickness', nozzle_size * 2.0)
			put('layer_height', '0.2')
			put('fill_density', '20')
		elif self.printTypeLow.GetValue():
			put('wall_thickness', nozzle_size * 1.0)
			put('layer_height', '0.3')
			put('fill_density', '10')
			put('print_speed', '80')
			put('bottom_layer_speed', '40')
		elif self.printTypeHigh.GetValue():
			put('wall_thickness', nozzle_size * 3.0)
			put('layer_height', '0.1')
			put('fill_density', '30')
			put('bottom_layer_speed', '15')
			put('bottom_thickness', '0.2')
		elif self.printTypeJoris.GetValue():
			put('wall_thickness', nozzle_size * 1.5)
			put('layer_height', '0.3')
			put('fill_density', '0')
			put('joris', 'True')
			put('extra_base_wall_thickness', '15.0')
			put('sequence', 'Infill > Loops > Perimeter')
			put('force_first_layer_sequence', 'False')
			put('solid_top', 'False')
			put('support', 'None')
			put('cool_min_layer_time', '3')

		put('filament_diameter', self.printMaterialDiameter.GetValue())
		if self.printMaterialPLA.GetValue():
			put('filament_density', '1.00')
			put('enable_raft', 'False')
			put('skirt_line_count', '1')
		if self.printMaterialABS.GetValue():
			put('filament_density', '0.85')
			put('enable_raft', 'True')
			put('skirt_line_count', '0')
			put('fan_layer', '1')
			put('bottom_thickness', '0.0')
			put('print_temperature', '260')

		#Create a progress panel and add it to the window. The progress panel will start the Skein operation.
		spp = sliceProgessPanel.sliceProgessPanel(self, self, self.filelist)
		self.sizer.Add(spp, (len(self.progressPanelList)+2,0), span=(1,4), flag=wx.EXPAND)
		self.sizer.Layout()
		newSize = self.GetSize();
		newSize.IncBy(0, spp.GetSize().GetHeight())
		self.SetSize(newSize)
		self.progressPanelList.append(spp)

		#Restore the old profile.
		profile.loadGlobalProfileFromString(oldProfile)

	def OnPrint(self, e):
		if len(self.filelist) < 1:
			wx.MessageBox('You need to load a file and slice it before you can print it.', 'Print error', wx.OK | wx.ICON_INFORMATION)
			return
		if not os.path.exists(sliceRun.getExportFilename(self.filelist[0])):
			wx.MessageBox('You need to slice the file to GCode before you can print it.', 'Print error', wx.OK | wx.ICON_INFORMATION)
			return
		printWindow.printFile(sliceRun.getExportFilename(self.filelist[0]))

	def OnNormalSwitch(self, e):
		from gui import mainWindow
		profile.putPreference('startMode', 'Normal')
		mainWindow.mainWindow()
		self.Close()

	def removeSliceProgress(self, spp):
		self.progressPanelList.remove(spp)
		newSize = self.GetSize();
		newSize.IncBy(0, -spp.GetSize().GetHeight())
		self.SetSize(newSize)
		self.sizer.Remove(spp)
		spp.Destroy()
		for spp in self.progressPanelList:
			self.sizer.Remove(spp)
		i = 2
		for spp in self.progressPanelList:
			self.sizer.Add(spp, (i,0), span=(1,4), flag=wx.EXPAND)
			i += 1
		self.sizer.Layout()

	def OnQuit(self, e):
		self.Close()

	def OnClose(self, e):
		self.Destroy()

	def updateProfileToControls(self):
		super(simpleModeWindow, self).updateProfileToControls()
		self.preview3d.updateProfileToControls()

<|endoftext|>


<commit_before>import vim
from os import path
from urllib.parse import urlencode, quote_plus
from urllib.request import urlopen
from urllib.request import Request
from urllib.request import URLError
import json
import subprocess
import time
import re

server_addr = vim.eval('g:padawan#server_addr')
server_command = vim.eval('g:padawan#server_command')
cli = vim.eval('g:padawan#cli')
composer = vim.eval('g:padawan#composer_command')
timeout = float(vim.eval('g:padawan#timeout'))
padawanPath = path.join(path.dirname(__file__), '..')

class Server:
    def start(self):
        command = '{0} > {1}/logs/server.log'.format(
            server_command,
            padawanPath
        )
        subprocess.Popen(
            command,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT
        )
    def stop(self):
        try:
            self.sendRequest('kill', {})
            return True
        except Exception:
            return False
    def restart(self):
        if self.stop():
            self.start()
    def sendRequest(self, command, params, data=''):
        addr = server_addr + "/"+command+"?" + urlencode(params)
        request = Request(addr, headers={
            "Content-Type": "plain/text"
        }, data = quote_plus(data).encode("utf-8"))
        response = urlopen(
            request,
            timeout=timeout
        )
        data = json.load(response)
        if "error" in data:
            raise ValueError(data["error"])
        return data

class Editor:
    def prepare(self, message):
        return message.replace("'", "''")
    def log(self, message):
        vim.command("echo '%s'" % self.prepare(message))
    def notify(self, message):
        vim.command("echom '%s'" % self.prepare(message))
    def progress(self, progress):
        bars = int(progress / 5)
        barsStr = ''
        for i in range(20):
            if i < bars:
                barsStr += '='
            else:
                barsStr += ' '
        barsStr = '[' + barsStr + ']'

        vim.command(
            "redraw | echo 'Progress "+barsStr+' '+str(progress)+"%'"
        )
        return
    def error(self, error):
        self.notify(error)
    def callAfter(self, timeout, callback):
        time.sleep(timeout)
        while callback():
            time.sleep(timeout)

server = Server()
editor = Editor()
pathError = '''padawan command is not found in your $PATH. Please\
make sure you installed padawan.php package and\
configured your $PATH'''

class PadawanClient:
    def GetCompletion(self, filepath, line_num, column_num, contents):
        curPath = self.GetProjectRoot(filepath)

        params = {
                'filepath': filepath.replace(curPath, ""),
                'line': line_num,
                'column': column_num,
                'path': curPath
                }
        result = self.DoRequest('complete', params, contents)

        if not result:
            return {"completion": []}

        return result

    def SaveIndex(self, filepath):
        return self.DoRequest('save', {'filepath': filepath})

    def DoRequest(self, command, params, data=''):
        try:
            return server.sendRequest(command, params, data)
        except URLError:
            editor.error("Padawan.php is not running")
        except Exception as e:
            editor.error("Error occured {0}".format(e.errno, e.strerror))

        return False

    def AddPlugin(self, plugin):
        composerCommand = composer + ' global require '

        command = '{0} {2} && {1} plugin add {2}'.format(
                composerCommand,
                cli,
                plugin
                )

        stream = subprocess.Popen(
                command,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT
                )

        def OnAdd(retcode):
            if not retcode:
                server.restart()
                editor.notify("Plugin installed")
            else:
                if retcode == 127:
                    editor.error(pathError)
                editor.error("Plugin installation failed")

        def LogAdding():
            retcode = stream.poll()
            if retcode is not None:
                return OnAdd(retcode)

            line = str(stream.stdout.readline())
            editor.log(line)
            return True

        editor.callAfter(1e-4, LogAdding)

    def RemovePlugin(self, plugin):
        composerCommand = composer + ' global remove'

        command = '{0} {1}'.format(
                composerCommand,
                plugin
                )

        stream = subprocess.Popen(
                command,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT
                )

        def onRemoved():
            subprocess.Popen(
                    '{0}'.format(
                        cli + ' plugin remove ' + plugin
                        ),
                    shell=True,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT
                    ).wait()
            self.RestartServer()
            return editor.notify("Plugin removed")

        def LogRemoving():
            retcode = stream.poll()
            if retcode is not None:
                return onRemoved()

            line = str(stream.stdout.readline())
            editor.log(line)
            return True

        editor.callAfter(1e-4, LogRemoving)

    def UpdateIndex(self, filepath):
        projectRoot = self.GetProjectRoot(filepath)
        params = {
            'path': projectRoot
            }
        self.DoRequest('update', params)

    def GetClassesList(self, cwd):
        params = {
            'path': cwd
            }
        return self.DoRequest("list", params)

    def Generate(self, filepath):
        curPath = self.GetProjectRoot(filepath)
        stream = subprocess.Popen(
                'cd ' + curPath + ' && ' + cli + ' generate',
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT
                )

        def onGenerationEnd(retcode):
            if retcode > 0:
                if retcode == 127:
                    editor.error(pathError)
                else:
                    editor.error("Error occured, code: {0}".format(str(retcode)))
                return
            server.restart()
            editor.progress(100)
            editor.notify("Index generated")

        def ProcessGenerationPoll():
            retcode = stream.poll()
            if retcode is not None:
                onGenerationEnd(retcode)
                return
            line = str(stream.stdout.readline())
            errorMatch = re.search('Error: (.*)', line)
            if errorMatch is not None:
                retcode = 1
                editor.error("{0}".format(
                    errorMatch.group(1).replace("'", "''")
                    ))
                return
            match = re.search('Progress: ([0-9]+)', line)
            if match is None:
                return True
            progress = int(match.group(1))
            editor.progress(progress)
            return True

        editor.callAfter(1e-4, ProcessGenerationPoll)

    def StartServer(self):
        server.start()

    def StopServer(self):
        server.stop()

    def RestartServer(self):
        server.restart()

    def GetProjectRoot(self, filepath):
        curPath = path.dirname(filepath)
        while curPath != '/' and not path.exists(
                path.join(curPath, 'composer.json')
                ):
            curPath = path.dirname(curPath)

        if curPath == '/':
            curPath = path.dirname(filepath)

        return curPath

client = PadawanClient()
<commit_msg>another fix<commit_after>import vim
from os import path
from urllib.parse import urlencode, quote_plus
from urllib.request import urlopen
from urllib.request import Request
from urllib.request import URLError
import json
import subprocess
import time
import re

server_addr = vim.eval('g:padawan#server_addr')
server_command = vim.eval('g:padawan#server_command')
cli = vim.eval('g:padawan#cli')
composer = vim.eval('g:padawan#composer_command')
timeout = float(vim.eval('g:padawan#timeout'))
padawanPath = path.join(path.dirname(__file__), '..')

class Server:
    def start(self):
        command = '{0} > {1}/logs/server.log'.format(
            server_command,
            padawanPath
        )
        subprocess.Popen(
            command,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT
        )
    def stop(self):
        try:
            self.sendRequest('kill', {})
            return True
        except Exception:
            return False
    def restart(self):
        if self.stop():
            self.start()
    def sendRequest(self, command, params, data=''):
        addr = str(server_addr) + "/"+str(command)+"?" + urlencode(params)
        request = Request(addr, headers={
            "Content-Type": "plain/text"
        }, data = quote_plus(data).encode("utf-8"))
        response = urlopen(
            request,
            timeout=timeout
        )
        data = json.load(response)
        if "error" in data:
            raise ValueError(data["error"])
        return data

class Editor:
    def prepare(self, message):
        return message.replace("'", "''")
    def log(self, message):
        vim.command("echo '%s'" % self.prepare(message))
    def notify(self, message):
        vim.command("echom '%s'" % self.prepare(message))
    def progress(self, progress):
        bars = int(progress / 5)
        barsStr = ''
        for i in range(20):
            if i < bars:
                barsStr += '='
            else:
                barsStr += ' '
        barsStr = '[' + barsStr + ']'

        vim.command(
            "redraw | echo 'Progress "+barsStr+' '+str(progress)+"%'"
        )
        return
    def error(self, error):
        self.notify(error)
    def callAfter(self, timeout, callback):
        time.sleep(timeout)
        while callback():
            time.sleep(timeout)

server = Server()
editor = Editor()
pathError = '''padawan command is not found in your $PATH. Please\
make sure you installed padawan.php package and\
configured your $PATH'''

class PadawanClient:
    def GetCompletion(self, filepath, line_num, column_num, contents):
        curPath = self.GetProjectRoot(filepath)

        params = {
                'filepath': filepath.replace(curPath, ""),
                'line': line_num,
                'column': column_num,
                'path': curPath
                }
        result = self.DoRequest('complete', params, contents)

        if not result:
            return {"completion": []}

        return result

    def SaveIndex(self, filepath):
        return self.DoRequest('save', {'filepath': filepath})

    def DoRequest(self, command, params, data=''):
        try:
            return server.sendRequest(command, params, data)
        except URLError:
            editor.error("Padawan.php is not running")
        except Exception as e:
            editor.error("Error occured {0}".format(e.errno, e.strerror))

        return False

    def AddPlugin(self, plugin):
        composerCommand = composer + ' global require '

        command = '{0} {2} && {1} plugin add {2}'.format(
                composerCommand,
                cli,
                plugin
                )

        stream = subprocess.Popen(
                command,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT
                )

        def OnAdd(retcode):
            if not retcode:
                server.restart()
                editor.notify("Plugin installed")
            else:
                if retcode == 127:
                    editor.error(pathError)
                editor.error("Plugin installation failed")

        def LogAdding():
            retcode = stream.poll()
            if retcode is not None:
                return OnAdd(retcode)

            line = str(stream.stdout.readline())
            editor.log(line)
            return True

        editor.callAfter(1e-4, LogAdding)

    def RemovePlugin(self, plugin):
        composerCommand = composer + ' global remove'

        command = '{0} {1}'.format(
                composerCommand,
                plugin
                )

        stream = subprocess.Popen(
                command,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT
                )

        def onRemoved():
            subprocess.Popen(
                    '{0}'.format(
                        cli + ' plugin remove ' + plugin
                        ),
                    shell=True,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT
                    ).wait()
            self.RestartServer()
            return editor.notify("Plugin removed")

        def LogRemoving():
            retcode = stream.poll()
            if retcode is not None:
                return onRemoved()

            line = str(stream.stdout.readline())
            editor.log(line)
            return True

        editor.callAfter(1e-4, LogRemoving)

    def UpdateIndex(self, filepath):
        projectRoot = self.GetProjectRoot(filepath)
        params = {
            'path': projectRoot
            }
        self.DoRequest('update', params)

    def GetClassesList(self, cwd):
        params = {
            'path': cwd
            }
        return self.DoRequest("list", params)

    def Generate(self, filepath):
        curPath = self.GetProjectRoot(filepath)
        stream = subprocess.Popen(
                'cd ' + curPath + ' && ' + cli + ' generate',
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT
                )

        def onGenerationEnd(retcode):
            if retcode > 0:
                if retcode == 127:
                    editor.error(pathError)
                else:
                    editor.error("Error occured, code: {0}".format(str(retcode)))
                return
            server.restart()
            editor.progress(100)
            editor.notify("Index generated")

        def ProcessGenerationPoll():
            retcode = stream.poll()
            if retcode is not None:
                onGenerationEnd(retcode)
                return
            line = str(stream.stdout.readline())
            errorMatch = re.search('Error: (.*)', line)
            if errorMatch is not None:
                retcode = 1
                editor.error("{0}".format(
                    errorMatch.group(1).replace("'", "''")
                    ))
                return
            match = re.search('Progress: ([0-9]+)', line)
            if match is None:
                return True
            progress = int(match.group(1))
            editor.progress(progress)
            return True

        editor.callAfter(1e-4, ProcessGenerationPoll)

    def StartServer(self):
        server.start()

    def StopServer(self):
        server.stop()

    def RestartServer(self):
        server.restart()

    def GetProjectRoot(self, filepath):
        curPath = path.dirname(filepath)
        while curPath != '/' and not path.exists(
                path.join(curPath, 'composer.json')
                ):
            curPath = path.dirname(curPath)

        if curPath == '/':
            curPath = path.dirname(filepath)

        return curPath

client = PadawanClient()
<|endoftext|>


<commit_before># regress <master> <inputFile_Y> <inputFile_X> <outputFile> <analMode> <outputMode>
#
# time series regression on a data matrix
# each row is (x,y,z,timeseries)
# inputs are signals to regress against
# can process results either by doing dimensionality reduction
# or by fitting a parametric model
#

import sys
import os
from numpy import *
from scipy.linalg import *
from scipy.io import *
from scipy.stats import vonmises
from pyspark import SparkContext
import logging

argsIn = sys.argv[1:]

if len(argsIn) < 6:
  print >> sys.stderr, \
  "(regress) usage: regress <master> <inputFile_Y> <inputFile_X> <outputFile> <regressMode> <outputMode> <opts>"
  exit(-1)

def parseVector(line,mode="raw",xyz=0,inds=None):
	vec = [float(x) for x in line.split(' ')]
	ts = array(vec[3:]) # get tseries
	if inds is not None :
		ts = ts[inds[0]:inds[1]]
	if mode == "dff" :
		meanVal = mean(ts)
		ts = (ts - meanVal) / (meanVal + 0.1)
	if xyz == 1 :
		return ((int(vec[0]),int(vec[1]),int(vec[2])),ts)
	else :
		return ts

def getRegression(y,model) :

	if model.regressMode == 'mean' :
		b = dot(model.X,y)
		return b

	if model.regressMode == 'linear' :
		b = dot(model.Xhat,y)[1:]
		# subtract mean separately for each group of regressors
		for ig in range(0,model.nG) :
			ginds = model.g==ig
			b[ginds] = b[ginds] - mean(b[ginds])
		return b

	if model.regressMode == 'bilinear' :
		b1 = dot(model.X1hat,y)
		b1 = b1 - min(b1)
		b1hat = dot(transpose(model.X1),b1)
		X3 = X2 * b1hat
		X3 = concatenate((ones((1,shape(X3)[1])),X3))
		X3hat = dot(inv(dot(X3,transpose(X3))),X3)
		b2 = dot(X3hat,y)
		b = b2[1:]
		if model.outputMode == 'tuning' :
			return b
		if model.outputMode == 'pca' :
			return (b1 - mean(b1))

def getTuning(y,model) :
	if model.tuningMode == 'circular' :
		y = y - min(y)
		y = y/sum(y)
		r = inner(y,exp(1j*model.s))
		mu = angle(r)
		v = absolute(r)/sum(y)
		if v < 0.53 :
			k = 2*v + (v**3) + 5*(v**5)/6
		elif (v>=0.53) & (v<0.85) :
			k = -.4 + 1.39*v + 0.43/(1-v)
		else :
			k = 1/(v**3 - 4*(v**2) + 3*v)
		return (mu,k)

def getNorms(y,model) :
	b = getRegression(y,model)
	n = zeros((model.nG,))
	for ig in range(0,model.nG) :
		n[ig] = norm(b[model.g==ig])
	return n

# parse inputs
sc = SparkContext(argsIn[0], "regress")
inputFile_Y = str(argsIn[1])
inputFile_X = str(argsIn[2])
outputFile = str(argsIn[3]) + "-regress"
regressMode = str(argsIn[4])
outputMode = str(argsIn[5])
opts = str(argsIn[6])

if not os.path.exists(outputFile) :
	os.makedirs(outputFile)
logging.basicConfig(filename=outputFile+'/'+'stdout.log',level=logging.INFO,format='%(asctime)s %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')

# parse data
logging.info("(regress) loading data")
lines_Y = sc.textFile(inputFile_Y)
Y = lines_Y.map(lambda y : parseVector(y,"dff")).cache()

# parse model
class model : pass
model.regressMode = regressMode
model.outputMode = outputMode
if regressMode == 'mean' :
	X = loadmat(inputFile_X + "_X.mat")['X']
	X = X.astype(float)
	model.X = X
if regressMode == 'linear' :
	X = loadmat(inputFile_X + "_X.mat")['X']
	X = X.astype(float)
	g = loadmat(inputFile_X + "_g.mat")['g']
	g = g.astype(float)[0]
	Xhat = dot(inv(dot(X,transpose(X))),X)
	model.X = X
	model.Xhat = Xhat
	model.g = g
	model.nG = length(unique(model.g))
if regressMode == 'bilinear' :
	X1 = loadmat(inputFile_X + "_X1.mat")['X1']
	X2 = loadmat(inputFile_X + "_X2.mat")['X2']
	X1hat = dot(inv(dot(X1,transpose(X1))),X1)
	model.X1 = X1
	model.X2 = X2
	model.X1hat = X1hat
if outputMode == 'tuning' :
	s = loadmat(inputFile_X + "_s.mat")['s']
	model.s = s
	model.tuningMode = opts
if outputMode == 'pca' :
	model.k = int(opts)

# get simple measure of response strength
r = Y.map(lambda y : float16(norm(y-mean(y)))).collect()
savemat(outputFile+"/"+"r.mat",mdict={'r':r},oned_as='column',do_compression='true')

# reduce dimensionality of regression coefficients using pca
if outputMode == 'pca' :
	B = Y.map(lambda y : getRegression(y,model))
	k = model.k
	n = B.count()
	cov = B.map(lambda b : outer(b,b)).reduce(lambda x,y : (x + y)) / n
	w, v = eig(cov)
	w = real(w)
	v = real(v)
	inds = argsort(w)[::-1]
	comps = transpose(v[:,inds[0:k]])
	savemat(outputFile+"/"+"comps.mat",mdict={'comps':comps},oned_as='column',do_compression='true')
	latent = w[inds[0:k]]
	scores = Y.map(lambda y : float16(inner(getRegression(y,model),comps))).collect()
	savemat(outputFile+"/"+"scores.mat",mdict={'scores':scores},oned_as='column',do_compression='true')
	traj = Y.map(lambda y : outer(y,inner(getRegression(y,model),comps))).reduce(lambda x,y : x + y) / n
	savemat(outputFile+"/"+"traj.mat",mdict={'traj':traj},oned_as='column',do_compression='true')

# process output with a parametric tuning curve
if outputMode == 'tuning' :
	B = Y.map(lambda y : getRegression(y,model))
	if model.tuningMode == 'circular' :
		p = B.map(lambda b : float16(getTuning(b,model))).collect()
		savemat(outputFile+"/"+"p.mat",mdict={'p':p},oned_as='column',do_compression='true')

# get norms of coefficients to make a contrast map
if outputMode == 'norms'
	B = Y.map(lambda y : (y,getNorms(y,model)))
	for ic in range(0,2)
		traj[ic,:] = B.filter(lambda (y,b) : b[ic] > b[1-ic]).map(lambda (y,b) : y * b[ic]).reduce(lambda x,y : x + y) / n
	norms = B.map(lambda (y,b) : float16(b)).collect()
	savemat(outputFile+"/"+"traj.mat",mdict={'traj':traj},oned_as='column',do_compression='true')
	savemat(outputFile+"/"+"norms.mat",mdict={'norms':norms},oned_as='column',do_compression='true')

<commit_msg>Rename mode to norm<commit_after># regress <master> <inputFile_Y> <inputFile_X> <outputFile> <analMode> <outputMode>
#
# time series regression on a data matrix
# each row is (x,y,z,timeseries)
# inputs are signals to regress against
# can process results either by doing dimensionality reduction
# or by fitting a parametric model
#

import sys
import os
from numpy import *
from scipy.linalg import *
from scipy.io import *
from scipy.stats import vonmises
from pyspark import SparkContext
import logging

argsIn = sys.argv[1:]

if len(argsIn) < 6:
  print >> sys.stderr, \
  "(regress) usage: regress <master> <inputFile_Y> <inputFile_X> <outputFile> <regressMode> <outputMode> <opts>"
  exit(-1)

def parseVector(line,mode="raw",xyz=0,inds=None):
	vec = [float(x) for x in line.split(' ')]
	ts = array(vec[3:]) # get tseries
	if inds is not None :
		ts = ts[inds[0]:inds[1]]
	if mode == "dff" :
		meanVal = mean(ts)
		ts = (ts - meanVal) / (meanVal + 0.1)
	if xyz == 1 :
		return ((int(vec[0]),int(vec[1]),int(vec[2])),ts)
	else :
		return ts

def getRegression(y,model) :

	if model.regressMode == 'mean' :
		b = dot(model.X,y)
		return b

	if model.regressMode == 'linear' :
		b = dot(model.Xhat,y)[1:]
		# subtract mean separately for each group of regressors
		for ig in range(0,model.nG) :
			ginds = model.g==ig
			b[ginds] = b[ginds] - mean(b[ginds])
		return b

	if model.regressMode == 'bilinear' :
		b1 = dot(model.X1hat,y)
		b1 = b1 - min(b1)
		b1hat = dot(transpose(model.X1),b1)
		X3 = X2 * b1hat
		X3 = concatenate((ones((1,shape(X3)[1])),X3))
		X3hat = dot(inv(dot(X3,transpose(X3))),X3)
		b2 = dot(X3hat,y)
		b = b2[1:]
		if model.outputMode == 'tuning' :
			return b
		if model.outputMode == 'pca' :
			return (b1 - mean(b1))

def getTuning(y,model) :
	if model.tuningMode == 'circular' :
		y = y - min(y)
		y = y/sum(y)
		r = inner(y,exp(1j*model.s))
		mu = angle(r)
		v = absolute(r)/sum(y)
		if v < 0.53 :
			k = 2*v + (v**3) + 5*(v**5)/6
		elif (v>=0.53) & (v<0.85) :
			k = -.4 + 1.39*v + 0.43/(1-v)
		else :
			k = 1/(v**3 - 4*(v**2) + 3*v)
		return (mu,k)

def getNorm(y,model) :
	b = getRegression(y,model)
	n = zeros((model.nG,))
	for ig in range(0,model.nG) :
		n[ig] = norm(b[model.g==ig])
	return n

# parse inputs
sc = SparkContext(argsIn[0], "regress")
inputFile_Y = str(argsIn[1])
inputFile_X = str(argsIn[2])
outputFile = str(argsIn[3]) + "-regress"
regressMode = str(argsIn[4])
outputMode = str(argsIn[5])
opts = str(argsIn[6])

if not os.path.exists(outputFile) :
	os.makedirs(outputFile)
logging.basicConfig(filename=outputFile+'/'+'stdout.log',level=logging.INFO,format='%(asctime)s %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')

# parse data
logging.info("(regress) loading data")
lines_Y = sc.textFile(inputFile_Y)
Y = lines_Y.map(lambda y : parseVector(y,"dff")).cache()

# parse model
class model : pass
model.regressMode = regressMode
model.outputMode = outputMode
if regressMode == 'mean' :
	X = loadmat(inputFile_X + "_X.mat")['X']
	X = X.astype(float)
	model.X = X
if regressMode == 'linear' :
	X = loadmat(inputFile_X + "_X.mat")['X']
	X = X.astype(float)
	g = loadmat(inputFile_X + "_g.mat")['g']
	g = g.astype(float)[0]
	Xhat = dot(inv(dot(X,transpose(X))),X)
	model.X = X
	model.Xhat = Xhat
	model.g = g
	model.nG = length(unique(model.g))
if regressMode == 'bilinear' :
	X1 = loadmat(inputFile_X + "_X1.mat")['X1']
	X2 = loadmat(inputFile_X + "_X2.mat")['X2']
	X1hat = dot(inv(dot(X1,transpose(X1))),X1)
	model.X1 = X1
	model.X2 = X2
	model.X1hat = X1hat
if outputMode == 'tuning' :
	s = loadmat(inputFile_X + "_s.mat")['s']
	model.s = s
	model.tuningMode = opts
if outputMode == 'pca' :
	model.k = int(opts)

# get simple measure of response strength
r = Y.map(lambda y : float16(norm(y-mean(y)))).collect()
savemat(outputFile+"/"+"r.mat",mdict={'r':r},oned_as='column',do_compression='true')

# reduce dimensionality of regression coefficients using pca
if outputMode == 'pca' :
	B = Y.map(lambda y : getRegression(y,model))
	k = model.k
	n = B.count()
	cov = B.map(lambda b : outer(b,b)).reduce(lambda x,y : (x + y)) / n
	w, v = eig(cov)
	w = real(w)
	v = real(v)
	inds = argsort(w)[::-1]
	comps = transpose(v[:,inds[0:k]])
	savemat(outputFile+"/"+"comps.mat",mdict={'comps':comps},oned_as='column',do_compression='true')
	latent = w[inds[0:k]]
	scores = Y.map(lambda y : float16(inner(getRegression(y,model),comps))).collect()
	savemat(outputFile+"/"+"scores.mat",mdict={'scores':scores},oned_as='column',do_compression='true')
	traj = Y.map(lambda y : outer(y,inner(getRegression(y,model),comps))).reduce(lambda x,y : x + y) / n
	savemat(outputFile+"/"+"traj.mat",mdict={'traj':traj},oned_as='column',do_compression='true')

# process output with a parametric tuning curve
if outputMode == 'tuning' :
	B = Y.map(lambda y : getRegression(y,model))
	if model.tuningMode == 'circular' :
		p = B.map(lambda b : float16(getTuning(b,model))).collect()
		savemat(outputFile+"/"+"p.mat",mdict={'p':p},oned_as='column',do_compression='true')

# get norms of coefficients to make a contrast map
if outputMode == 'norm' :
	B = Y.map(lambda y : (y,getNorm(y,model)))
	for ic in range(0,2)
		traj[ic,:] = B.filter(lambda (y,b) : b[ic] > b[1-ic]).map(lambda (y,b) : y * b[ic]).reduce(lambda x,y : x + y) / n
	norms = B.map(lambda (y,b) : float16(b)).collect()
	savemat(outputFile+"/"+"traj.mat",mdict={'traj':traj},oned_as='column',do_compression='true')
	savemat(outputFile+"/"+"norms.mat",mdict={'norms':norms},oned_as='column',do_compression='true')

<|endoftext|>


<commit_before># Copyright (c) Olivier Hervieu <olivier.hervieu@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

__version_info__ = (0, 1, "alpha")
__version__ = '.'.join(str(v) for v in __version_info__)
__url__ = 'http://github.com/ohe/python-applescript/'
__dl_url__ = 'http://github.com/downloads/ohe/python-applescript'
__author__ = 'Olivier Hervieu'
__authoremail__ = 'olivier.hervieu@gmail.com'
<commit_msg>Modify Version<commit_after># Copyright (c) Olivier Hervieu <olivier.hervieu@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

__version_info__ = (0, 1)
__version__ = '.'.join(str(v) for v in __version_info__)
__url__ = 'http://github.com/ohe/python-applescript/'
__dl_url__ = 'http://github.com/downloads/ohe/python-applescript'
__author__ = 'Olivier Hervieu'
__authoremail__ = 'olivier.hervieu@gmail.com'
<|endoftext|>


<commit_before>#! /usr/bin/env python
#
# Open file in Visual Studio
# Source: https://stackoverflow.com/a/33244420/79125
#
# Requires pywin32:
# python -m pip install pypiwin32

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os

import pywintypes
import win32com.client

def open_in_visualstudio(filename, line, column):
    dte = None
    try:
        dte = win32com.client.GetActiveObject("VisualStudio.DTE")

    except pywintypes.com_error as err:
        print("Failed to get handle to Visual Studio:")
        print(err)

    if dte:
        try:
            dte.ItemOperations.OpenFile(filename)
            dte.ActiveDocument.Selection.MoveToLineAndOffset(line, column+1)
            dte.MainWindow.Activate

        except pywintypes.com_error as err:
            print("Failed to open file: "+ filename)
            print(err)

# Expects three local variables:
# "filename", "line", "column"
def vim_open_in_visualstudio():
    import vim

    args = {}
    for a in ["filename", "line", "column"]:
        args[a] = vim.eval("l:"+ a)

    for a in ["line", "column"]:
        args[a] = int(args[a])

    filename, line, column = args['filename'], args['line'], args['column']
    # Let python deal with escaping.
    filename = filename.replace('\\', '')
    filename = os.path.abspath(filename)

    # print(filename, line, column)
    return open_in_visualstudio(filename, line, column)

if __name__ == '__main__':
    import sys
    filename = sys.argv[1]
    line = int(sys.argv[2])
    column = int(sys.argv[3])
    open_in_visualstudio(filename, line, column)

<commit_msg>If DTE fails, fallback to old batch method<commit_after>#! /usr/bin/env python
#
# Open file in Visual Studio
# Source: https://stackoverflow.com/a/33244420/79125
#
# Requires pywin32:
# python -m pip install pypiwin32

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
import subprocess

import pywintypes
import win32com.client

def _find_latest_devenv():
    cmd = "C:/Program Files (x86)/Microsoft Visual Studio/2017/Professional/Common7/ide/"
    if os.path.exists(cmd):
        return cmd

    versions = (9, 11, 12, 14)
    for v in versions:
        cmd = "c:/Program Files (x86)/Microsoft Visual Studio {version}.0/Common7/ide/".format(version=v)
        if os.path.exists(cmd):
            return cmd

    return ""

def _open_with_batch(filename, line):
    cmd = _find_latest_devenv() +"/devenv"
    args = ('/Edit "{filename}"'.format(filename=filename),
            '/Command "Edit.GoTo {line}"'.format(line=line))
    ret = subprocess.call([cmd, args])
    if ret != 0:
        print("devenv.exe invocation failed: {code}".format(code=ret))

def open_in_visualstudio(filename, line, column):
    dte = None
    try:
        dte = win32com.client.GetActiveObject("VisualStudio.DTE")

    except pywintypes.com_error as err:
        print("Failed to get handle to Visual Studio (falling back to cmdline):")
        print(err)
        _open_with_batch(filename, line)

    if dte:
        try:
            dte.ItemOperations.OpenFile(filename)
            dte.ActiveDocument.Selection.MoveToLineAndOffset(line, column+1)
            dte.MainWindow.Activate

        except pywintypes.com_error as err:
            print("Failed to open file: "+ filename)
            print(err)

# Expects three local variables:
# "filename", "line", "column"
def vim_open_in_visualstudio():
    import vim

    args = {}
    for a in ["filename", "line", "column"]:
        args[a] = vim.eval("l:"+ a)

    for a in ["line", "column"]:
        args[a] = int(args[a])

    filename, line, column = args['filename'], args['line'], args['column']
    # Let python deal with escaping.
    filename = filename.replace('\\', '')
    filename = os.path.abspath(filename)

    # print(filename, line, column)
    return open_in_visualstudio(filename, line, column)

if __name__ == '__main__':
    import sys
    filename = sys.argv[1]
    line = int(sys.argv[2])
    column = int(sys.argv[3])
    open_in_visualstudio(filename, line, column)

<|endoftext|>


<commit_before># VMware vCloud Python SDK
# Copyright (c) 2014 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import requests
import json
import os
import tempfile
import shutil
import tarfile
import urllib

from os.path import expanduser
from pyvcloud import exceptions
from pyvcloud import _get_logger, Http, Log

from dsl_parser import parser
from dsl_parser.exceptions import *

class Score(object):

    def __init__(self, url, org_url=None, token=None, version='5.7',
                 verify=True, log=False):
        self.url = url
        self.org_url = org_url
        self.token = token
        self.version = version
        self.verify = verify
        self.response = None
        self.blueprints = BlueprintsClient(self, log)
        self.deployments = DeploymentsClient(self, log)
        self.executions = ExecutionsClient(self, log)
        self.events = EventsClient(self, log)
        self.logger = _get_logger() if log else None

    def get_headers(self):
        headers = {}
        headers["x-vcloud-authorization"] = self.token
        headers["x-vcloud-org-url"] = self.org_url
        headers["x-vcloud-version"] = self.version
        return headers

    def get_status(self):
        self.response = Http.get(self.url + '/status',
                                 headers=self.get_headers(),
                                 verify=self.verify, logger=self.logger)
        Log.debug(self.logger, self.response.status_code)
        Log.debug(self.logger, self.response.content)
        return self.response.content

class BlueprintsClient(object):

    def __init__(self, score, log=False):
        self.score = score
        self.logger = _get_logger() if log else None

    def validate(self, blueprint_path):
        return parser.parse_from_path(blueprint_path)

    def list(self):
        self.score.response = Http.get(self.score.url + '/blueprints',
                                       headers=self.score.get_headers(),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def get(self, blueprint_id):
        self.score.response = Http.get(self.score.url +
                                       '/blueprints/%s' % blueprint_id,
                                       headers=self.score.get_headers(),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def delete(self, blueprint_id):
        self.score.response = Http.delete(self.score.url +
                                          '/blueprints/%s' % blueprint_id,
                                          headers=self.score.get_headers(),
                                          verify=self.score.verify,
                                          logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def upload(self, blueprint_path, blueprint_id):
        tempdir = tempfile.mkdtemp()
        try:
            tar_path = self._tar_blueprint(blueprint_path, tempdir)
            application_file = os.path.basename(blueprint_path)
            blueprint = self._upload(
                tar_path,
                blueprint_id=blueprint_id,
                application_file_name=application_file)
            return blueprint
        finally:
            shutil.rmtree(tempdir)

    @staticmethod
    def _tar_blueprint(blueprint_path, tempdir):
        blueprint_path = expanduser(blueprint_path)
        blueprint_name = os.path.basename(os.path.splitext(blueprint_path)[0])
        blueprint_directory = os.path.dirname(blueprint_path)
        if not blueprint_directory:
            # blueprint path only contains a file name from the local directory
            blueprint_directory = os.getcwd()
        tar_path = os.path.join(tempdir, '{0}.tar.gz'.format(blueprint_name))
        with tarfile.open(tar_path, "w:gz") as tar:
            tar.add(blueprint_directory,
                    arcname=os.path.basename(blueprint_directory))
        return tar_path

    def _upload(self, tar_file,
                blueprint_id,
                application_file_name=None):
        query_params = {}
        if application_file_name is not None:
            query_params['application_file_name'] = \
                urllib.quote(application_file_name)

        uri = '/blueprints/{0}'.format(blueprint_id)
        url = '{0}{1}'.format(self.score.url, uri)
        headers = self.score.get_headers()
        with open(tar_file, 'rb') as f:
            self.score.response = Http.put(url, headers=headers,
                                           params=query_params,
                                           data=f, verify=self.score.verify,
                                           logger=self.logger)

        if self.score.response.status_code not in range(200, 210):
            raise exceptions.from_response(self.score.response)
        return self.score.response.json()

class DeploymentsClient(object):

    def __init__(self, score, log=False):
        self.score = score
        self.logger = _get_logger() if log else None

    def list(self):
        self.score.response = Http.get(self.score.url + '/deployments',
                                       headers=self.score.get_headers(),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def get(self, deployment_id):
        self.score.response = Http.get(self.score.url +
                                       '/deployments/%s' % deployment_id,
                                       headers=self.score.get_headers(),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def delete(self, deployment_id):
        self.score.response = Http.delete(self.score.url +
                                          '/deployments/%s' % deployment_id,
                                          headers=self.score.get_headers(),
                                          verify=self.score.verify,
                                          logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def create(self, blueprint_id, deployment_id, inputs=None):
        data = {
            'blueprint_id': blueprint_id
        }
        if inputs:
            data['inputs'] = inputs
        headers = self.score.get_headers()
        headers['Content-type'] = 'application/json'
        self.score.response = Http.put(self.score.url +
                                       '/deployments/%s' % deployment_id,
                                       data=json.dumps(data),
                                       headers=headers,
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

class ExecutionsClient(object):

    def __init__(self, score, log=False):
        self.score = score
        self.logger = _get_logger() if log else None

    def list(self, deployment_id):
        params = {'deployment_id': deployment_id}
        self.score.response = Http.get(self.score.url + '/executions',
                                       headers=self.score.get_headers(),
                                       params=params, verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            Log.error(self.logger, 'list executions returned %s' %
                      self.score.response.status_code)
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def start(self, deployment_id, workflow_id, parameters=None,
              allow_custom_parameters=False, force=False):
        data = {
            'deployment_id': deployment_id,
            'workflow_id': workflow_id,
            'parameters': parameters,
            'allow_custom_parameters': str(allow_custom_parameters).lower(),
            'force': str(force).lower()
        }
        headers = self.score.get_headers()
        headers['Content-type'] = 'application/json'
        self.score.response = Http.post(self.score.url + '/executions',
                                        headers=headers,
                                        data=json.dumps(data),
                                        verify=self.score.verify,
                                        logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def cancel(self, execution_id, force=False):
        data = {
            'execution_id': execution_id,
            'force': str(force).lower()}
        headers = self.score.get_headers()
        headers['Content-type'] = 'application/json'
        self.score.response = Http.put(self.score.url + '/executions',
                                       headers=headers, data=json.dumps(data),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

class EventsClient(object):

    def __init__(self, score, log=False):
        self.score = score
        self.logger = _get_logger() if log else None

    def get(self, execution_id, from_event=0, batch_size=100,
            include_logs=False):
        data = {
            "execution_id": execution_id,
            "from": from_event,
            "size": batch_size,
            "include_logs": include_logs
        }
        headers = self.score.get_headers()
        headers['Content-type'] = 'application/json'
        self.score.response = Http.get(self.score.url + '/events',
                                       headers=headers, data=json.dumps(data),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)
<commit_msg>Revert casting from boolean to strings<commit_after># VMware vCloud Python SDK
# Copyright (c) 2014 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import requests
import json
import os
import tempfile
import shutil
import tarfile
import urllib

from os.path import expanduser
from pyvcloud import exceptions
from pyvcloud import _get_logger, Http, Log

from dsl_parser import parser
from dsl_parser.exceptions import *

class Score(object):

    def __init__(self, url, org_url=None, token=None, version='5.7',
                 verify=True, log=False):
        self.url = url
        self.org_url = org_url
        self.token = token
        self.version = version
        self.verify = verify
        self.response = None
        self.blueprints = BlueprintsClient(self, log)
        self.deployments = DeploymentsClient(self, log)
        self.executions = ExecutionsClient(self, log)
        self.events = EventsClient(self, log)
        self.logger = _get_logger() if log else None

    def get_headers(self):
        headers = {}
        headers["x-vcloud-authorization"] = self.token
        headers["x-vcloud-org-url"] = self.org_url
        headers["x-vcloud-version"] = self.version
        return headers

    def get_status(self):
        self.response = Http.get(self.url + '/status',
                                 headers=self.get_headers(),
                                 verify=self.verify, logger=self.logger)
        Log.debug(self.logger, self.response.status_code)
        Log.debug(self.logger, self.response.content)
        return self.response.content

class BlueprintsClient(object):

    def __init__(self, score, log=False):
        self.score = score
        self.logger = _get_logger() if log else None

    def validate(self, blueprint_path):
        return parser.parse_from_path(blueprint_path)

    def list(self):
        self.score.response = Http.get(self.score.url + '/blueprints',
                                       headers=self.score.get_headers(),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def get(self, blueprint_id):
        self.score.response = Http.get(self.score.url +
                                       '/blueprints/%s' % blueprint_id,
                                       headers=self.score.get_headers(),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def delete(self, blueprint_id):
        self.score.response = Http.delete(self.score.url +
                                          '/blueprints/%s' % blueprint_id,
                                          headers=self.score.get_headers(),
                                          verify=self.score.verify,
                                          logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def upload(self, blueprint_path, blueprint_id):
        tempdir = tempfile.mkdtemp()
        try:
            tar_path = self._tar_blueprint(blueprint_path, tempdir)
            application_file = os.path.basename(blueprint_path)
            blueprint = self._upload(
                tar_path,
                blueprint_id=blueprint_id,
                application_file_name=application_file)
            return blueprint
        finally:
            shutil.rmtree(tempdir)

    @staticmethod
    def _tar_blueprint(blueprint_path, tempdir):
        blueprint_path = expanduser(blueprint_path)
        blueprint_name = os.path.basename(os.path.splitext(blueprint_path)[0])
        blueprint_directory = os.path.dirname(blueprint_path)
        if not blueprint_directory:
            # blueprint path only contains a file name from the local directory
            blueprint_directory = os.getcwd()
        tar_path = os.path.join(tempdir, '{0}.tar.gz'.format(blueprint_name))
        with tarfile.open(tar_path, "w:gz") as tar:
            tar.add(blueprint_directory,
                    arcname=os.path.basename(blueprint_directory))
        return tar_path

    def _upload(self, tar_file,
                blueprint_id,
                application_file_name=None):
        query_params = {}
        if application_file_name is not None:
            query_params['application_file_name'] = \
                urllib.quote(application_file_name)

        uri = '/blueprints/{0}'.format(blueprint_id)
        url = '{0}{1}'.format(self.score.url, uri)
        headers = self.score.get_headers()
        with open(tar_file, 'rb') as f:
            self.score.response = Http.put(url, headers=headers,
                                           params=query_params,
                                           data=f, verify=self.score.verify,
                                           logger=self.logger)

        if self.score.response.status_code not in range(200, 210):
            raise exceptions.from_response(self.score.response)
        return self.score.response.json()

class DeploymentsClient(object):

    def __init__(self, score, log=False):
        self.score = score
        self.logger = _get_logger() if log else None

    def list(self):
        self.score.response = Http.get(self.score.url + '/deployments',
                                       headers=self.score.get_headers(),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def get(self, deployment_id):
        self.score.response = Http.get(self.score.url +
                                       '/deployments/%s' % deployment_id,
                                       headers=self.score.get_headers(),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def delete(self, deployment_id):
        self.score.response = Http.delete(self.score.url +
                                          '/deployments/%s' % deployment_id,
                                          headers=self.score.get_headers(),
                                          verify=self.score.verify,
                                          logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def create(self, blueprint_id, deployment_id, inputs=None):
        data = {
            'blueprint_id': blueprint_id
        }
        if inputs:
            data['inputs'] = inputs
        headers = self.score.get_headers()
        headers['Content-type'] = 'application/json'
        self.score.response = Http.put(self.score.url +
                                       '/deployments/%s' % deployment_id,
                                       data=json.dumps(data),
                                       headers=headers,
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

class ExecutionsClient(object):

    def __init__(self, score, log=False):
        self.score = score
        self.logger = _get_logger() if log else None

    def list(self, deployment_id):
        params = {'deployment_id': deployment_id}
        self.score.response = Http.get(self.score.url + '/executions',
                                       headers=self.score.get_headers(),
                                       params=params, verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            Log.error(self.logger, 'list executions returned %s' %
                      self.score.response.status_code)
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def start(self, deployment_id, workflow_id, parameters=None,
              allow_custom_parameters=False, force=False):
        data = {
            'deployment_id': deployment_id,
            'workflow_id': workflow_id,
            'parameters': parameters,
            'allow_custom_parameters': allow_custom_parameters,
            'force': force,
        }
        headers = self.score.get_headers()
        headers['Content-type'] = 'application/json'
        self.score.response = Http.post(self.score.url + '/executions',
                                        headers=headers,
                                        data=json.dumps(data),
                                        verify=self.score.verify,
                                        logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

    def cancel(self, execution_id, force=False):
        data = {
            'execution_id': execution_id,
            'force': str(force).lower()}
        headers = self.score.get_headers()
        headers['Content-type'] = 'application/json'
        self.score.response = Http.put(self.score.url + '/executions',
                                       headers=headers, data=json.dumps(data),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

class EventsClient(object):

    def __init__(self, score, log=False):
        self.score = score
        self.logger = _get_logger() if log else None

    def get(self, execution_id, from_event=0, batch_size=100,
            include_logs=False):
        data = {
            "execution_id": execution_id,
            "from": from_event,
            "size": batch_size,
            "include_logs": include_logs
        }
        headers = self.score.get_headers()
        headers['Content-type'] = 'application/json'
        self.score.response = Http.get(self.score.url + '/events',
                                       headers=headers, data=json.dumps(data),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)
<|endoftext|>


<commit_before>"""
                                      '||
... ...  .... ... ... ... ...  ....    ||
 ||'  ||  '|.  |   ||  ||  |  '' .||   ||
 ||    |   '|.|     ||| |||   .|' ||   ||
 ||...'     '|       |   |    '|..'|' .||.
 ||      .. |
''''      ''
Created by Dylan Araps.
"""

import os
import platform

__version__ = "2.0.1"
__cache_version__ = "1.1.0"

HOME = os.getenv("HOME", os.getenv("USERPROFILE"))
CACHE_DIR = os.path.join(HOME, ".cache", "wal")
MODULE_DIR = os.path.dirname(__file__)
CONF_DIR = os.path.join(HOME, ".config", "wal")
OS = platform.uname()[0]
<commit_msg>version: bump<commit_after>"""
                                      '||
... ...  .... ... ... ... ...  ....    ||
 ||'  ||  '|.  |   ||  ||  |  '' .||   ||
 ||    |   '|.|     ||| |||   .|' ||   ||
 ||...'     '|       |   |    '|..'|' .||.
 ||      .. |
''''      ''
Created by Dylan Araps.
"""

import os
import platform

__version__ = "2.0.2"
__cache_version__ = "1.1.0"

HOME = os.getenv("HOME", os.getenv("USERPROFILE"))
CACHE_DIR = os.path.join(HOME, ".cache", "wal")
MODULE_DIR = os.path.dirname(__file__)
CONF_DIR = os.path.join(HOME, ".config", "wal")
OS = platform.uname()[0]
<|endoftext|>


<commit_before>"""
Global Constants.
"""
import pathlib

__version__ = "0.3.5"

# Internal variables.
COLOR_COUNT = 16
CACHE_DIR = pathlib.Path.home() / ".cache/wal/"
<commit_msg>version: bump<commit_after>"""
Global Constants.
"""
import pathlib

__version__ = "0.3.6"

# Internal variables.
COLOR_COUNT = 16
CACHE_DIR = pathlib.Path.home() / ".cache/wal/"
<|endoftext|>