rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
self.filepath = filepath | if sys.platform == 'win32': self.filepath = filepath.encode(utils.get_system_encode()) else: self.filepath = filepath | def __init__(self, grouper, filepath): #threading.Thread.__init__(self) self.grouper = grouper self.filepath = filepath self.run() |
self.file = str(parser.filename) | self.file = parser.filename.encode('utf-8') | def SetParser(self, parser): self.level = parser.GetImageWindowLevel() self.window = parser.GetImageWindowWidth() |
gauss.SetInput(imagedata) | gauss.SetInput(clip.GetOutput()) | def BuildEditedImage(imagedata, points): """ Editing the original image in accordance with the edit points in the editor, it is necessary to generate the vtkPolyData via vtkContourFilter """ for point in points: x, y, z = point colour = points[point] imagedata.SetScalarComponentFromDouble(x, y, z, 0, colour) imagedata.... |
return gauss.GetOutput() | app = vtk.vtkImageAppend() app.PreserveExtentsOn() app.SetAppendAxis(2) app.SetInput(0, imagedata) app.SetInput(1, gauss.GetOutput()) app.Update() return app.GetOutput() | def BuildEditedImage(imagedata, points): """ Editing the original image in accordance with the edit points in the editor, it is necessary to generate the vtkPolyData via vtkContourFilter """ for point in points: x, y, z = point colour = points[point] imagedata.SetScalarComponentFromDouble(x, y, z, 0, colour) imagedata.... |
self.SpinMin.SetValue(self.SliderData.minRange) | self.SpinMin.SetValue(self.SliderData.minValue) | def DrawControls(self): """self.SpinMin = wx.SpinCtrl(parent=self, id=-1, initial=self.SliderData.minValue, min=self.SliderData.minRange, max=self.SliderData.maxRange, size=wx.Size(55,15)) self.SpinMin.SetValue(self.SliderData.minValue) # needed in MacOS 10.5.5 |
self.SpinMax.SetValue(self.SliderData.maxRange) | self.SpinMax.SetValue(self.SliderData.maxValue) | def DrawControls(self): """self.SpinMin = wx.SpinCtrl(parent=self, id=-1, initial=self.SliderData.minValue, min=self.SliderData.minRange, max=self.SliderData.maxRange, size=wx.Size(55,15)) self.SpinMin.SetValue(self.SliderData.minValue) # needed in MacOS 10.5.5 |
print "Setting max range ", value | def SetMaxRange(self, value): print "Setting max range ", value self.SliderData.SetMaxRange(value) self.SpinMin.SetMax(value) self.SpinMax.SetMax(value) self.GradientPanel.Refresh() | |
milliseconds=1, id=-1, parent=None) | milliseconds=1500, id=-1, parent=None) | def __init__(self): bmp = wx.Image("../icons/splash_en.png").ConvertToBitmap() wx.SplashScreen.__init__(self, bitmap=bmp, splashStyle=wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, milliseconds=1, id=-1, parent=None) self.Bind(wx.EVT_CLOSE, self.OnClose) |
self.image_viewer = wx.StaticBitmap(self, -1) | self.image_viewer = DicomPaintPanel(self) | def _init_ui(self): self.SetBackgroundColour(PREVIEW_BACKGROUND) |
self.image_viewer.SetBitmap(image) | self.image_viewer.SetImage(image) | def SetDicomToPreview(self, dicom_info): """ Set a dicom to preview. """ self.dicom_info = dicom_info self.SetTitle(dicom_info.title) self.SetSubtitle(dicom_info.subtitle) self.ID = dicom_info.id dicom_info.size = self.image_viewer.GetSize() image = dicom_info.preview self.image_viewer.SetBitmap(image) self.data = dico... |
c = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT) | c = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNFACE) print c | def OnEnter(self, evt): if not self.select_on: #c = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DHILIGHT) c = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT) self.SetBackgroundColour(c) |
session.CreateItens() | save_session = True | def __init__(self): |
if (save_session): session.CreateItens() session.SetLanguage(lang) session.CreateSessionFile() | def __init__(self): | |
session = Session() | def OnClose(self, evt): # Make sure the default handler runs too so this window gets # destroyed evt.Skip() self.Hide() # if the timer is still running then go ahead and show the # main frame now if self.fc.IsRunning(): self.fc.Stop() session = Session() #if not (session.ReadSession()): # session.CreateItens() la... | |
lang = session.GetLanguage() print lang i18n.InstallLanguage(lang) | def OnClose(self, evt): # Make sure the default handler runs too so this window gets # destroyed evt.Skip() self.Hide() # if the timer is still running then go ahead and show the # main frame now if self.fc.IsRunning(): self.fc.Stop() session = Session() #if not (session.ReadSession()): # session.CreateItens() la... | |
return "" | return "300" | def GetImageWindowLevel(self, preset=WL_PRESET, multiple=WL_MULT): """ Return image window center / level (related to brightness). This is an integer or a floating point. If the value can't be read, return "". |
return "" | return "2000" | def GetImageWindowWidth(self, preset=WL_PRESET, multiple=WL_MULT): """ Return image window width (related to contrast). This is an integer or a floating point. If the value can't be read, return "". |
return locale.getdefaultlocale()[0] | lc = locale.getdefaultlocale()[0] if lc: return lc return 'en' | def GetLocaleOS(): """Return language of the operating system.""" if sys.platform == 'darwin': locale.setlocale(locale.LC_ALL, "") return locale.getlocale()[0] return locale.getdefaultlocale()[0] |
filelist = Extract(filename, tempfile.gettempdir()) | filelist = Extract(filename, tempfile.mkdtemp()) | def OpenPlistProject(self, filename): import data.measures as ms |
self.Disable() | self.slice_plane.Disable() | def OnCloseProject(self, pubsub_evt): if self.raycasting_volume: self.raycasting_volume = False if self.slice_plane: self.Disable() #slice_plane_...SetInteractor(self.interactor._Iren) self.mouse_pressed = 0 self.on_wl = False |
self.AddPointReference(self.picker.GetPickPosition(), 5) | def OnInsertSeed(self, obj, evt): x,y = self.interactor.GetEventPosition() #x,y = obj.GetLastEventPosition() self.picker.Pick(x, y, 0, self.ren) point_id = self.picker.GetPointId() self.seed_points.append(point_id) self.AddPointReference(self.picker.GetPickPosition(), 5) self.interactor.Render() | |
if (prj.Project().original_orientation == const.AXIAL): | if (prj.Project().original_orientation == const.CORONAL): flip_image = False else: | def AddNewActor(self, pubsub_evt): """ Create surface actor, save into project and send it to viewer. """ surface_data = pubsub_evt.data |
else: flip_image = False | def AddNewActor(self, pubsub_evt): """ Create surface actor, save into project and send it to viewer. """ surface_data = pubsub_evt.data | |
return locale.getlocale()[0] lc = locale.getdefaultlocale()[0] if lc: return lc return 'en' | os_locale = locale.getlocale()[0] else: os_locale = locale.getdefaultlocale()[0] if os_locale: if os_locale in locales_dict.keys(): default_locale = os_locale else: for l in locales_dict: if l.startswith(os_locale): default_locale = l return default_locale | def GetLocaleOS(): """Return language of the operating system.""" if sys.platform == 'darwin': locale.setlocale(locale.LC_ALL, "") return locale.getlocale()[0] lc = locale.getdefaultlocale()[0] if lc: return lc return 'en' |
return data | encoding = self.GetEncoding() return data.decode(encoding) | def GetStudyDescription(self): """ Return study description (string). Return "" if not defined. |
if dlg.ShowModal() == wx.ID_OK: | try: if dlg.ShowModal() == wx.ID_OK: filepath = dlg.GetPath() except(wx._core.PyAssertionError): | def ShowOpenProjectDialog(): # Default system path current_dir = os.path.abspath(".") dlg = wx.FileDialog(None, message=_("Open InVesalius 3 project..."), defaultDir="", defaultFile="", wildcard=WILDCARD_OPEN, style=wx.OPEN|wx.CHANGE_DIR) # inv3 filter is default dlg.SetFilterIndex(0) # Show the dialog and retrieve t... |
wx.SplashScreen.__init__(self, bmp, wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, 1500, None, -1) | wx.SplashScreen.__init__(self, bitmap=bmp, splashStyle=wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, milliseconds=1, id=-1, parent=None) | def __init__(self): bmp = wx.Image("../icons/splash_en.png").ConvertToBitmap() wx.SplashScreen.__init__(self, bmp, wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, 1500, None, -1) self.Bind(wx.EVT_CLOSE, self.OnClose) |
from session import Session | def __init__(self): bmp = wx.Image("../icons/splash_en.png").ConvertToBitmap() wx.SplashScreen.__init__(self, bmp, wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, 1500, None, -1) self.Bind(wx.EVT_CLOSE, self.OnClose) | |
self.fc = wx.FutureCall(1000, self.ShowMain) | self.fc = wx.FutureCall(1, self.ShowMain) | def __init__(self): bmp = wx.Image("../icons/splash_en.png").ConvertToBitmap() wx.SplashScreen.__init__(self, bmp, wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, 1500, None, -1) self.Bind(wx.EVT_CLOSE, self.OnClose) |
method.EXT_argnames = inspect.getargspec( method ).args[1:] | method.EXT_argnames = inspect.getargspec( method )[0][1:] | def _register_method( self, cls_or_name, method, flags=None ): """ Actually registers the given function as a method of cls_or_name. """ clsname = getname(cls_or_name) if clsname not in self.classes: self.classes[clsname] = {} if flags is None: flags = {} self.classes[ clsname ][ method.__name__ ] = method method.EXT_a... |
QMessageBox.information(self, self.tr("Conversion Completed!!!"), self.tr("Finish. All files were converted!"), QMessageBox.Ok ) | QMessageBox.information(self, self.tr("¡¡¡Conversion Completed!!!"), self.tr("Finish. All files were converted!"), QMessageBox.Ok ) | def completed(self): global nomore #print "finished" if not nomore: #print "another file" self.actual=self.actual+1 #print self.actual #print self.total if self.actual<self.total: #print "process another" self.processStepbyStep() else: print "it's the end of the list as we know it ^_^" self.ui.b_back_2.setVisible(1) se... |
qtTranslator = QTranslator() qtTranslator.load("qt_"+locale, "/usr/share/qt4/translations") app.installTranslator(qtTranslator) | qtTranslatorQT = QTranslator() qtTranslatorQT.load("qt_"+locale, "/usr/share/qt4/translations") app.installTranslator(qtTranslatorQT) | def stop(self): global nomore nomore=True self.engega.kill() #print "terminated" self.terminate() |
results = self.query(event_id=event_id) | results = self.query(event_id=id) | def get(self, id): """Return a setlist with the given ``id``. |
def __init__(self, inputDoc): from pyPdf import PdfFileWriter, PdfFileReader | Algorithm described at: http://blogs.gnome.org/cneumair/2007/03/15/printing-instruction-manuals-how-to-reorder-postscript-files/ """ import sys from pyPdf import PdfFileWriter, PdfFileReader def main(): if len(sys.argv) < 2: print "Usage: bookfold.py input.pdf" sys.exit(1) else: print sys.argv[1] inputDoc = sys.argv[... | def __init__(self, inputDoc): from pyPdf import PdfFileWriter, PdfFileReader |
input2 = PdfFileReader(file("temp.pdf", "rb")) output = PdfFileWriter() totalPages = input2.getNumPages() | input2 = PdfFileReader(file("temp.pdf", "rb")) output = PdfFileWriter() totalPages = input2.getNumPages() for i in range(1, totalPages/2+1): if i % 2: output.addPage(input2.getPage(totalPages-i)) output.addPage(input2.getPage(i-1)) print totalPages+1-i,",",i,",", else: output.addPage(input2.getPage(i-1)) output.addPa... | def __init__(self, inputDoc): from pyPdf import PdfFileWriter, PdfFileReader |
for i in range(1, totalPages/2+1): if i % 2: output.addPage(input2.getPage(totalPages-i)) output.addPage(input2.getPage(i-1)) print totalPages+1-i,",",i,",", else: output.addPage(input2.getPage(i-1)) output.addPage(input2.getPage(totalPages-i)) print i,",",totalPages+1-i,",", | outputStream = file("output.pdf", "wb") output.write(outputStream) outputStream.close() | def __init__(self, inputDoc): from pyPdf import PdfFileWriter, PdfFileReader |
outputStream = file("output.pdf", "wb") output.write(outputStream) outputStream.close() | import os os.remove("temp.pdf") | def __init__(self, inputDoc): from pyPdf import PdfFileWriter, PdfFileReader |
import os os.remove("temp.pdf") import sys bookfold = bookfold(sys.argv[1]) | if __name__ == "__main__": main() | def __init__(self, inputDoc): from pyPdf import PdfFileWriter, PdfFileReader |
BLANK_FILE_NAME = dirname(abspath(__file__)) + "/blank.pdf" | BLANK_FILE_NAME = dirname(realpath(__file__)) + "/blank.pdf" | def main(): # Handle Arguments BLANK_FILE_NAME = dirname(abspath(__file__)) + "/blank.pdf" if len(sys.argv) < 2: print "Usage: ./bookfold.py input.pdf" sys.exit(1) else: print sys.argv[1] input_doc = sys.argv[1] blank = PdfFileReader(file(BLANK_FILE_NAME, "rb")) input1 = PdfFileReader(file(input_doc, "rb")) # Copy ... |
departure_cols = departure_row.findAll('td', recursive=False) arrival_cols = arrival_row.findAll('td', recursive=False) | def get_col1(row, s): return row.find('td', attrs = {'class' : re.compile(s)}).string.strip() def get_col2(row, s): return row.find('td', attrs = {'class' : re.compile(s)}).div.string.strip() | def parse_connection(self, departure_row, arrival_row): departure_cols = departure_row.findAll('td', recursive=False) arrival_cols = arrival_row.findAll('td', recursive=False) |
departure_cols[0].contents[3].contents[0], | get_col2(departure_row, 'station'), | def parse_connection(self, departure_row, arrival_row): departure_cols = departure_row.findAll('td', recursive=False) arrival_cols = arrival_row.findAll('td', recursive=False) |
arrival_cols[0].contents[0], | get_col1(arrival_row, 'station'), | def parse_connection(self, departure_row, arrival_row): departure_cols = departure_row.findAll('td', recursive=False) arrival_cols = arrival_row.findAll('td', recursive=False) |
departure_cols[1].contents[0].split()[1], | get_col1(departure_row, 'date$').split()[1], | def parse_connection(self, departure_row, arrival_row): departure_cols = departure_row.findAll('td', recursive=False) arrival_cols = arrival_row.findAll('td', recursive=False) |
departure_cols[3].contents[0], | get_col1(departure_row, 'time$'), | def parse_connection(self, departure_row, arrival_row): departure_cols = departure_row.findAll('td', recursive=False) arrival_cols = arrival_row.findAll('td', recursive=False) |
arrival_cols[1].contents[0].split()[1], | get_col1(arrival_row, 'date$').split()[1], | def parse_connection(self, departure_row, arrival_row): departure_cols = departure_row.findAll('td', recursive=False) arrival_cols = arrival_row.findAll('td', recursive=False) |
arrival_cols[3].contents[0], | get_col1(arrival_row, 'time$'), | def parse_connection(self, departure_row, arrival_row): departure_cols = departure_row.findAll('td', recursive=False) arrival_cols = arrival_row.findAll('td', recursive=False) |
departure_cols[4].string, | get_col1(departure_row, 'duration'), | def parse_connection(self, departure_row, arrival_row): departure_cols = departure_row.findAll('td', recursive=False) arrival_cols = arrival_row.findAll('td', recursive=False) |
departure_cols[5].string, | get_col1(departure_row, 'changes'), | def parse_connection(self, departure_row, arrival_row): departure_cols = departure_row.findAll('td', recursive=False) arrival_cols = arrival_row.findAll('td', recursive=False) |
departure_cols[6].a.contents[-1], | get_col1(departure_row, 'products'), | def parse_connection(self, departure_row, arrival_row): departure_cols = departure_row.findAll('td', recursive=False) arrival_cols = arrival_row.findAll('td', recursive=False) |
print '\n'.join(s) | print >> sys.stderr, '\n'.join(s) | def dump(self): if self.options_fr0m: logging.error('Unknown or ambiguous departure station:') s = [' %-6s %s' % (k, enc_html2utf8(s)) for s, k in self.options_fr0m] print '\n'.join(s) if self.options_to: logging.error('Unknown or ambiguous destination station:') s = [' %-6s %s' % (k, enc_html2utf8(s)) for s, k in se... |
print c.to_csv() | sys.stdout.write(c.to_csv().encode('utf-8') + '\n') | def _add_connection(c): print c.to_csv() |
print self.form['REQ0Tariff_TravellerReductionClass.1'] | def fill_form(self, travelData): logging.info('fill form "%s"...' % self.form.name) self.form['REQ0JourneyStopsS0G'] = convert_encoding(travelData.fr0m) self.form['REQ0JourneyStopsZ0G'] = convert_encoding(travelData.to) self.form['REQ0JourneyDate'] = travelData.get_departure_date() self.form['REQ0JourneyTime'] = travel... | |
pf = image.GetPixelFormat().GetScalarType() assert pf in get_gdcm_to_numpy_typemap().keys(), \ | pf = image.GetPixelFormat() assert pf.GetScalarType() in get_gdcm_to_numpy_typemap().keys(), \ | def gdcm_to_numpy(image): """Converts a GDCM image to a numpy array. """ pf = image.GetPixelFormat().GetScalarType() assert pf in get_gdcm_to_numpy_typemap().keys(), \ "Unsupported array type %s"%pf shape = image.GetDimension(0) * image.GetDimension(1), pf.GetSamplesPerPixel() if image.GetNumberOfDimensions() == 3: sh... |
dtype = get_numpy_array_type(pf) | dtype = get_numpy_array_type(pf.GetScalarType()) | def gdcm_to_numpy(image): """Converts a GDCM image to a numpy array. """ pf = image.GetPixelFormat().GetScalarType() assert pf in get_gdcm_to_numpy_typemap().keys(), \ "Unsupported array type %s"%pf shape = image.GetDimension(0) * image.GetDimension(1), pf.GetSamplesPerPixel() if image.GetNumberOfDimensions() == 3: sh... |
self.assertRaises(Exception, test_view('stock_product_location')) | test_view('stock_product_location') | def test0005views(self): ''' Test views. ''' self.assertRaises(Exception, test_view('stock_product_location')) |
num = self.params.get('num', self.default_demos) | num = int(self.params.get('num', self.default_demos)) | def gethighscores(self): scores = self.get_scores() num = self.params.get('num', self.default_demos) scores_list = scores.keys() scores_list.sort(None, None, True) |
return firstpart.split('_')[3] | try: return firstpart.split('_')[3] except: print path | def getCCDColourFromMosPath(path): basename = os.path.basename(path) firstpart = basename.partition('.')[0] return firstpart.split('_')[3] |
data = f.ReadAsArray(x+250,y-50,400,300) | data = f.ReadAsArray(x+250,y-50,dx,dy) | def get_ctx_fname(obsid): """create full path for ctx file from obsid and ccd. ccd in this case is the mode of ctx operation. i call it ccd here because it is at the same place in the file name """ if obsid.startswith('P'): phase = 'PSP' else: phase = 'ESP' ccd = mydict[obsid]['CCDColour'] dname = ht.DEST_BASE + phase... |
data = f.ReadAsArray(x+190,y,400,300) | data = f.ReadAsArray(x+215,y,dx,dy) | def get_ctx_fname(obsid): """create full path for ctx file from obsid and ccd. ccd in this case is the mode of ctx operation. i call it ccd here because it is at the same place in the file name """ if obsid.startswith('P'): phase = 'PSP' else: phase = 'ESP' ccd = mydict[obsid]['CCDColour'] dname = ht.DEST_BASE + phase... |
data = f.ReadAsArray(x+240,y,400,300) | data = f.ReadAsArray(x+240,y,dx,dy) | def get_ctx_fname(obsid): """create full path for ctx file from obsid and ccd. ccd in this case is the mode of ctx operation. i call it ccd here because it is at the same place in the file name """ if obsid.startswith('P'): phase = 'PSP' else: phase = 'ESP' ccd = mydict[obsid]['CCDColour'] dname = ht.DEST_BASE + phase... |
'inca_ctx_psp_' + obsid) | 'inca_ctx_' + obsid) | def get_ctx_fname(obsid): """create full path for ctx file from obsid and ccd. ccd in this case is the mode of ctx operation. i call it ccd here because it is at the same place in the file name """ if obsid.startswith('P'): phase = 'PSP' else: phase = 'ESP' ccd = mydict[obsid]['CCDColour'] dname = ht.DEST_BASE + phase... |
self.data = {} | self.data = [] | def __init__(self): self.data = {} self.roiName = '' self.obsID = '' self.ccdColour = '' self.inputSample = '' self.inputLine = '' self.extraTargetCode = '' self.outputFileName = '' self.mapSampleOffset = '' self.mapLineOffset = '' self.coregSampleOffset = '' self.coregLineOffset = '' self.nsamples = '' self.nlines = '... |
outputFileName = "_".join([self.roi_name, self.CCDColour]) | outputFileName = "_".join([self.roiName, self.ccdColour]) | def write_out(self): outputFileName = "_".join([self.roi_name, self.CCDColour]) outFile = open(outputFileName, 'wb') csvWriter = csv.writer(outFile) csvWriter.writerow(self.keys) csvWriter.writerows(self.data) outFile.close() |
elif not (obsID.startswith('PSP') or obsID.startswith('ESP'): | elif not (obsID.startswith('PSP') or obsID.startswith('ESP')): | def parse_excel_and_hirsync(dataType, excelFile, do=False): import xlrd import HiRsync book = xlrd.open_workbook(excelFile) sh = book.sheet_by_index(0) print str(sh.nrows) + " lines" # loop over rows in excel sheet for r in range(sh.nrows): obsID = sh.row_values(r)[0] if obsID == "": print "Line " + str(r) + " empty" c... |
if myCoords.pixelValue == "Null": | if myCoords.pixelValue == "NULL": | def find_coords(params): if params.extraTargetCode == '': print """found no extra target code, will only search for target code of obsID \n""" params.extraTargetCode = 'ouk;ohuoenuiuc' #dummy extra target code print "searching..." # get subData in obsID in case i need it later params.sciencePhase, params.orbit, params... |
if not myCoords.pixelValue == "Null" : | if not myCoords.pixelValue == "NULL" : | def find_coords(params): if params.extraTargetCode == '': print """found no extra target code, will only search for target code of obsID \n""" params.extraTargetCode = 'ouk;ohuoenuiuc' #dummy extra target code print "searching..." # get subData in obsID in case i need it later params.sciencePhase, params.orbit, params... |
params.inputLine = sys.argv[1:] | params.inputLine = args | def find_coords(params): if params.extraTargetCode == '': print """found no extra target code, will only search for target code of obsID \n""" params.extraTargetCode = 'ouk;ohuoenuiuc' #dummy extra target code print "searching..." # get subData in obsID in case i need it later params.sciencePhase, params.orbit, params... |
fixed = args[2] tobeShifted = args[3] samples = int(args[4]) lines = int(args[5]) | def prev(self, event): self.xOff2 += 1 * self.multiplier self.im2.set_data(self.read_data()) self.ax.set_title('{2}, deltaX: {0}, deltaY: {1}'.\ format(self.xOff2 - self.xOff2Old, self.yOff2 - self.yOff2Old, self.sub2.obsID)) self.fig.canvas.draw() | |
print "Usage: {0} finder_output_file fixed tobeShifted samples "\ "lines".format(args[0]) print """\nfixed and tobeShifted should be given as the line numbers of the images you want to co-register as seen in the output file from the coordinate finder (counted human-way from 1), so for example '5 2', if you want the del... | print "Usage: {0} finder_output_file".format(args[0]) | def prev(self, event): self.xOff2 += 1 * self.multiplier self.im2.set_data(self.read_data()) self.ax.set_title('{2}, deltaX: {0}, deltaY: {1}'.\ format(self.xOff2 - self.xOff2Old, self.yOff2 - self.yOff2Old, self.sub2.obsID)) self.fig.canvas.draw() |
with open(finder_output_file, 'r') as f: infile = f.readlines() | roidata.read_in(finder_output_file) for i, obsID in enumerate(sorted(roidata.dict.keys())): print i + 1, obsID fixed = raw_input('Number of obsID for reference: ') tobeShifted = raw_input('Number of obsID to be shifted (=co-registered): ') | def prev(self, event): self.xOff2 += 1 * self.multiplier self.im2.set_data(self.read_data()) self.ax.set_title('{2}, deltaX: {0}, deltaY: {1}'.\ format(self.xOff2 - self.xOff2Old, self.yOff2 - self.yOff2Old, self.sub2.obsID)) self.fig.canvas.draw() |
ctx = Context("SSH_MAT_" + target + username, { "expire": 30, "alert_on_expire": self.alert }, update = True, idmef=idmef) ctx.addAlertReference(idmef) | ctx = Context("SSH_MAT_" + target + username, { "expire": 30, "alert_on_expire": self.alert }, update=True) if ctx.getUpdateCount() == 0: ctx.authtype = { data: True } ctx.addAlertReference(idmef) | def run(self, idmef): if idmef.Get("alert.analyzer(-1).manufacturer") != "OpenSSH": return |
if not hasattr(ctx, "authtype"): ctx.authtype = { data: True } else: | elif not ctx.authtype.has_key(data): | def run(self, idmef): if idmef.Get("alert.analyzer(-1).manufacturer") != "OpenSSH": return |
ctx.Set("alert.assessment.impact.description", source + " has repeated actions taken against it recently at least 5 times. It may have been infected with a worm.") | ctx.Set("alert.assessment.impact.description", source + " has repeated actions taken against it recently at least %d times. It may have been infected with a worm." % (self.__repeat_target)) | def run(self, idmef): ctxt = idmef.Get("alert.classification.text") if not ctxt: return |
egg = download_setuptools(version, download_base, to_dir, download_delay) | egg = download_setuptools(DOWNLOAD_VERSION, download_base, to_dir, download_delay) | def do_download(): egg = download_setuptools(version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg |
def alert(self, ctx): if len(ctx.authtype) > 1: ctx.Set("alert.classification.text", "Multiple authentication methods") ctx.Set("alert.correlation_alert.name", "Multiple authentication methods") ctx.Set("alert.assessment.impact.severity", "medium") ctx.Set("alert.assessment.impact.description", "Multiple ways of authen... | def alert(self, ctx): if len(ctx.authtype) > 1: ctx.Set("alert.classification.text", "Multiple authentication methods") ctx.Set("alert.correlation_alert.name", "Multiple authentication methods") ctx.Set("alert.assessment.impact.severity", "medium") ctx.Set("alert.assessment.impact.description", "Multiple ways of authen... | |
ctx = Context("SSH_MAT_" + target + username, { "expire": 30, "alert_on_expire": self.alert }, update=True) | ctx = Context("SSH_MAT_" + target + username, { "expire": 30, "alert_on_expire": alert }, update=True) | def run(self, idmef): if idmef.Get("alert.analyzer(-1).manufacturer") != "OpenSSH": return |
docs_plugin_support = ["docs/sample-plugin/setup.py"] docs_plugin_files = ["docs/sample-plugin/myplugin/__init__.py", "docs/sample-plugin/myplugin/main.py"] | def init_siteconfig(self, prefix): config = open("PreludeCorrelator/siteconfig.py", "w") print >> config, "conf_dir = '%s'" % os.path.abspath(prefix + "/etc/prelude-correlator") print >> config, "lib_dir = '%s'" % os.path.abspath(prefix + "/var/lib/prelude-correlator") config.close() | |
data_files = [ ("", ["prelude-correlator.conf"]), ("docs/sample-plugin", docs_plugin_support), ("docs/sample-plugin/myplugin", docs_plugin_files) ] | data_files = [ ("", ["prelude-correlator.conf"]) ] | def init_siteconfig(self, prefix): config = open("PreludeCorrelator/siteconfig.py", "w") print >> config, "conf_dir = '%s'" % os.path.abspath(prefix + "/etc/prelude-correlator") print >> config, "lib_dir = '%s'" % os.path.abspath(prefix + "/var/lib/prelude-correlator") config.close() |
("share/doc/prelude-correlator/sample-plugin", docs_plugin_support), ("share/doc/prelude-correlator/sample-plugin/myplugin", docs_plugin_files), | def init_siteconfig(self, prefix): config = open("PreludeCorrelator/siteconfig.py", "w") print >> config, "conf_dir = '%s'" % os.path.abspath(prefix + "/etc/prelude-correlator") print >> config, "lib_dir = '%s'" % os.path.abspath(prefix + "/var/lib/prelude-correlator") config.close() | |
elif type(value) is tuple or type(value) is list: if not value: value = None | def Set(self, path, value): if type(value) == PreludeEasy.IDMEFValue: cur = self.Get(path) if cur and value.Match(cur, PreludeEasy.IDMEFCriterion.OPERATOR_EQUAL) > 0: return | |
self.warnings(("[unknown:%d] " % level) + log) | self.warning(("[unknown:%d] " % level) + log) | def __log_callback(self, level, log): log = log.rstrip('\n') |
if value: raise Exception, "Invalid input value" value = None | if not value: value = None | def Set(self, path, value): if type(value) == PreludeEasy.IDMEFValue: cur = self.Get(path) if cur and value.Match(cur, PreludeEasy.IDMEFCriterion.OPERATOR_EQUAL) > 0: return |
for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" | DB_PATH = settings.DB_DIR + "%s.sqlite" | def retweet(initial_status_id=None): for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" connection = sqlite3.connect(DB_PATH % USER) cursor = connection.cursor() # Create the table that will hold the tweets we've retweeted. cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY ... |
cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY KEY, timestamp VARCHAR(255))""") connection.commit() | def retweet(initial_status_id=None): for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" connection = sqlite3.connect(DB_PATH % USER) cursor = connection.cursor() # Create the table that will hold the tweets we've retweeted. cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY ... | |
cursor.execute("""INSERT INTO retweets (status_id, timestamp) VALUES ('%s', '%s')""" % (initial_status_id, datetime.datetime.now())) | cursor.execute("""INSERT INTO retweets_2 (status_id, timestamp) VALUES ('%s', '%s')""" % (initial_status_id, datetime.datetime.now())) | def retweet(initial_status_id=None): for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" connection = sqlite3.connect(DB_PATH % USER) cursor = connection.cursor() # Create the table that will hold the tweets we've retweeted. cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY ... |
except Exception, e: | except sqlite3.IntegrityError: | def retweet(initial_status_id=None): for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" connection = sqlite3.connect(DB_PATH % USER) cursor = connection.cursor() # Create the table that will hold the tweets we've retweeted. cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY ... |
cursor.execute("""SELECT MAX(status_id) FROM retweets""") | cursor.execute("""SELECT MAX(status_id) FROM retweets_2""") | def retweet(initial_status_id=None): for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" connection = sqlite3.connect(DB_PATH % USER) cursor = connection.cursor() # Create the table that will hold the tweets we've retweeted. cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY ... |
reply_text = clean_reply.sub("@", reply.text) | is_banned = False | def retweet(initial_status_id=None): for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" connection = sqlite3.connect(DB_PATH % USER) cursor = connection.cursor() # Create the table that will hold the tweets we've retweeted. cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY ... |
if not reply_text.lower().startswith("@%s" % USER.lower()): continue | retweeting_from = reply.user.screen_name.lower() | def retweet(initial_status_id=None): for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" connection = sqlite3.connect(DB_PATH % USER) cursor = connection.cursor() # Create the table that will hold the tweets we've retweeted. cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY ... |
clean_tweet = cut_reply.sub("", reply_text).strip() | cursor.execute("""SELECT username FROM bans WHERE username='%s'""" % retweeting_from) rows = cursor for row in rows: is_banned = True break if not is_banned: reply_text = clean_reply.sub("@", reply.text) if not reply_text.lower().startswith("@%s" % USER.lower()): continue clean_tweet = cut_reply.sub("", reply_text)... | def retweet(initial_status_id=None): for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" connection = sqlite3.connect(DB_PATH % USER) cursor = connection.cursor() # Create the table that will hold the tweets we've retweeted. cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY ... |
new_tweet = "RT @%s %s" % (reply.user.GetScreenName(), clean_tweet) if len(new_tweet) > 140: new_tweet = new_tweet[:140] i = 137 while i > 0: if new_tweet[i] == " ": new_tweet = "%s..." % new_tweet[:i] break else: new_tweet = new_tweet[:i] i -= 1 | try: api.PostUpdate(new_tweet) cursor.execute("""INSERT INTO retweets_2 (status_id, timestamp) VALUES ('%s', '%s')""" % (reply.id, datetime.datetime.now())) connection.commit() except Exception, e: print e cursor.close() connection.close() def ban(username, account): DB_PATH = settings.DB_DIR + "%s.sqlite" connect... | def retweet(initial_status_id=None): for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" connection = sqlite3.connect(DB_PATH % USER) cursor = connection.cursor() # Create the table that will hold the tweets we've retweeted. cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY ... |
try: api.PostUpdate(new_tweet) | if "retweets" in tables: cursor.execute("""INSERT INTO retweets_2 SELECT CAST(status_id AS INTEGER), timestamp FROM retweets""") connection.commit() if "retweets" in tables: cursor.execute("""DROP TABLE retweets""") connection.commit() cursor.close() connection.close() | def retweet(initial_status_id=None): for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" connection = sqlite3.connect(DB_PATH % USER) cursor = connection.cursor() # Create the table that will hold the tweets we've retweeted. cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY ... |
cursor.execute("""INSERT INTO retweets (status_id, timestamp) VALUES ('%s', '%s')""" % (reply.id, datetime.datetime.now())) connection.commit() except Exception, e: print e | def retweet(initial_status_id=None): for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" connection = sqlite3.connect(DB_PATH % USER) cursor = connection.cursor() # Create the table that will hold the tweets we've retweeted. cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY ... | |
retweet(sys.argv[1]) | to_ban = None ban_account = None for arg in sys.argv: if arg.startswith("--ban="): to_ban = arg.split("=")[1] elif arg.startswith("--account="): ban_account = arg.split("=")[1] if to_ban and ban_account: ban(username=to_ban, account=ban_account) else: retweet(initial_status_id=sys.argv[1]) | def retweet(initial_status_id=None): for USER, PASS in ACCOUNTS: DB_PATH = DB_DIR + "%s.sqlite" connection = sqlite3.connect(DB_PATH % USER) cursor = connection.cursor() # Create the table that will hold the tweets we've retweeted. cursor.execute("""CREATE TABLE IF NOT EXISTS retweets (status_id VARCHAR(100) PRIMARY ... |
self.assertRegexp('seen any', 'test has joined') | self.assertRegexp('seen any', 'test <test!user@host.domain.tld> has joined') | def testAny(self): self.assertRegexp('seen any', 'test has joined') self.irc.feedMsg(ircmsgs.mode(self.channel, args=('+o', self.nick), prefix=self.prefix)) self.assertRegexp('seen any %s' % self.nick, '^%s was last seen' % self.nick) |
return ' '.join(s.split()) | beginning = s.startswith(' ') ending = s.endswith(' ') s = ' '.join(s.split()) if beginning: s = ' ' + s if ending: s = s + ' ' return s | def normalizeWhitespace(s): """Normalizes the whitespace in a string; \s+ becomes one space.""" return ' '.join(s.split()) |
self.whatis(irc, msg, [results[0][0]]) | self.whatis(irc, msg, [channel, results[0][0]]) | def p(s, r=arg): return int(bool(r.search(s))) |
@internationalizeDocstring | def remove(self, irc, msg, args, name): """<name> | |
self.assertNotError('ping') | self.assertNotError('unix ping localhost') self.assertError('unix ping') | def testPing(self): self.assertNotError('ping') |
p=lambda i: i>0, type=_('positive integer') *L) | p=lambda i: i>0, type=_('positive integer'), *L) | def getPositiveInt(irc, msg, args, state, *L): getInt(irc, msg, args, state, p=lambda i: i>0, type=_('positive integer') *L) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.