Пример #1
0
 def SaveList(self, exportlist, week, path, price, publisher):
     if path:
         print "Creating file"
         w = StreamWriter(path, False)
         w.WriteLine("Checklist for week of " + week)
         w.WriteLine()
         w.WriteLine()
         for item in exportlist:
             w.Write("[] ")
             if publisher:
                 w.Write(item["Publisher"] + " ")
             w.Write(item["Title"])
             if price:
                 w.Write(" " + item["Price"])
             w.WriteLine()
         w.Close()
         w.Dispose()
Пример #2
0
def SaveFile(filename, data):
    store = IsolatedStorageFile.GetUserStoreForApplication()
    isolatedStream = IsolatedStorageFileStream(filename, FileMode.Create,
                                               store)

    writer = StreamWriter(isolatedStream)
    writer.Write(data)

    writer.Close()
    isolatedStream.Close()
def uploadOneFile(dataTable):
    outputFile = StreamWriter(outputFilePath, "a")
    fileName = dataTable.Name
    outputFile.Write("<p>" + str(datetime.datetime.now()) + " - " + fileName +
                     " - start <br/>\n")

    webRequest = HttpWebRequest.Create(rcqBackendURI + fileName)
    response = webRequest.GetResponse()
    streamReader = StreamReader(response.GetResponseStream())
    jsonData = streamReader.ReadToEnd()
    ps.CurrentProgress.CheckCancel()

    outputFile.Write(
        str(datetime.datetime.now()) + " - " + fileName + " " + str(jsonData) +
        "<br/>\n")

    outputFile.Write(
        str(datetime.datetime.now()) + " - " + fileName +
        " - SDBF file re-generated <br/>\n")
    dataTable.Refresh()
    ps.CurrentProgress.CheckCancel()
    outputFile.Write(
        str(datetime.datetime.now()) + " - " + fileName +
        " - Analysis Refreshed <br/>\n")

    try:
        (found,
         item) = lm.TryGetItem(folder + fileName, LibraryItemType.SbdfDataFile,
                               LibraryItemRetrievalOption.IncludeProperties)
        if found:
            table.ExportDataToLibrary(item, fileName)
            outputFile.Write(
                str(datetime.datetime.now()) + " - " + fileName +
                " - exported (ow) <br/>\n")
        else:
            (found2, item2) = lm.TryGetItem(
                folder, LibraryItemType.Folder,
                LibraryItemRetrievalOption.IncludeProperties)
            if found2:
                table.ExportDataToLibrary(item2, fileName)
                outputFile.Write(
                    str(datetime.datetime.now()) + " - " + fileName +
                    " - exported (1st) <br/>\n")
    except Exception as e:
        outputFile.Write(
            str(datetime.datetime.now()) + " - " + "Exception Occured:" +
            str(e) + " <br/>\n")

    outputFile.Write("</p>\n")
    outputFile.Close()
def execute():
    try:
        table = Document.ActiveDataTableReference

        outputFile = StreamWriter(outputFilePath, "w+")
        outputFile.Write(
            "<html><head><title>Spotfire SDBF Uploader</title></head><body><script>setTimeout(function(){window.location.reload(true);}, 5000);</script><div style='font-size:16px;padding:12px;'>\n"
        )
        outputFile.Write("<p>Export Folder is '" + folder + "'</p>\n")
        outputFile.Close()

        print "start infinite loop"
        while True:
            print "START refreshing all tables"
            for table in Document.Data.Tables:
                print "Processing - " + table.Name + ""
                ps.CurrentProgress.ExecuteSubtask("Processing - " +
                                                  table.Name + "")
                uploadOneFile(table)
                print "Processing - " + table.Name + " - DONE"
                ps.CurrentProgress.CheckCancel()
                print "Processing - " + table.Name + " - DONE CheckCancel"
            print "END refreshing all tables"

            ps.CurrentProgress.CheckCancel()
            print "CheckCancel Done, sleeping 10ms"
            time.sleep(10)
            print "waking up"

    except BaseException as e:  # user canceled
        print "Cancelation, excpetion: " + str(e)
        outputFile = StreamWriter(Document.Properties["outputFilePath"], "a")
        outputFile.Write(str(e) + " - Export Stopped")
        outputFile.Write(str(datetime.datetime.now()) + " - Export Stopped")
        outputFile.Write("</div></body></html>")
        outputFile.Close()
        print "end of exec"
        pass
Пример #5
0
def table_text_writer(list_input):

    """Writes table input

    args:

    list_input (list of lists): input to be written

    returns: stream
    """
    from System.IO import  StreamWriter, MemoryStream, SeekOrigin


    list_input = controlled_list(list_input)
    LOGGER.debug(list_input)
    LOGGER.debug('--------')
    header = controlled_list(list_input.pop(0))
    length_of_header = len(header)
    head_line = create_line(header)

    # if only a header line
    if not list_input:
        text = ' ' * (length_of_header)

    else:
        text =''

        LOGGER.debug('Loop')
        for i, text_list in enumerate(list_input):

            text_list = controlled_list(text_list)
            LOGGER.debug(text_list)
            if len(text_list) != length_of_header:

                message = ('Line {} in text: [{}] does not have ' +
                           ' same length as header [{}], will be ' +
                           'skipped').format(i, join_list(text_list),
                                             join_list(header))
                ok_message(message)
            else:

                text += create_line(text_list)

    text = head_line + text
    stream = MemoryStream()
    writer = StreamWriter(stream)
    writer.Write(text)
    writer.Flush()
    stream.Seek(0, SeekOrigin.Begin)
    return stream
Пример #6
0
 def save(self, filename):
    """ Implements the module-level save() method by writing the 
        debug log information to the given file. """
    
    # protect access to the logLines with a mutex (for multiple threads)
    self._mutex.WaitOne(-1)
    try:
       if self._loglines == None:
          raise Exception("you must install the __Logger before using it")
       loglines_copy = list(self._loglines)
    finally:
       self._mutex.ReleaseMutex()
       
    try:
       writer = StreamWriter(filename, False, UTF8Encoding())
       for line in loglines_copy:
          writer.Write(line)
    finally:
       if writer: writer.Dispose()
Пример #7
0
def csvToDataSource(csv, columnDataTypes):
    # Create memorystream to read from
    stream = MemoryStream()
    writer = StreamWriter(stream)
    writer.Write(csv)
    writer.Flush()
    stream.Seek(0, SeekOrigin.Begin)

    # Create text file data source
    readerSettings = TextDataReaderSettings()
    readerSettings.Separator = ','
    readerSettings.AddColumnNameRow(0)
    print 'columnDataTypes ', columnDataTypes
    for i, columnDataType in enumerate(columnDataTypes):
        readerSettings.SetDataType(i, columnDataType)

    dataSource = TextFileDataSource(stream, readerSettings)
    dataSource.ReuseSettingsWithoutPrompting = True
    dataSource.IsPromptingAllowed = False
    return dataSource
Пример #8
0
    def save_file_dialog(self, sender, event):
        """open a savefiledialog dialog"""

        self.save_file_dialog = SaveFileDialog()
        self.save_file_dialog.InitialDirectory = "%s/winforms" % uiaqa_path
        self.save_file_dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
        self.save_file_dialog.FilterIndex = 2
        self.save_file_dialog.RestoreDirectory = True
        
        # save the label content to a file.
        try:
            if self.save_file_dialog.ShowDialog() == DialogResult.OK:
                filepath = self.save_file_dialog.FileName
                s_buf = StreamWriter(filepath)
                s_buf.Write(self.label.Text)
                s_buf.Flush()
                s_buf.Close()
                self.label.Text = "The path you selected is: " + filepath + '\n'
        except IOError, event:
            print 'An error occurred:', event
Пример #9
0
                def onSave():
                    try:
                        fs = None
                        sr = None
                        sw = None

                        try:
                            fs = FileStream(__file__, FileMode.Open,
                                            FileAccess.ReadWrite,
                                            FileShare.Read)
                            encoding = UTF8Encoding(False)
                            sr = StreamReader(fs, encoding, True)
                            lines = Regex.Replace(
                                Regex.Replace(
                                    sr.ReadToEnd(), "username\\s*=\\s*\"\"",
                                    String.Format("username = \"{0}\"",
                                                  username),
                                    RegexOptions.CultureInvariant),
                                "password\\s*=\\s*\"\"",
                                String.Format("password = \"{0}\"", password),
                                RegexOptions.CultureInvariant)
                            fs.SetLength(0)
                            sw = StreamWriter(fs, encoding)
                            sw.Write(lines)

                        finally:
                            if sw is not None:
                                sw.Close()

                            if sr is not None:
                                sr.Close()

                            if fs is not None:
                                fs.Close()

                    except Exception, e:
                        Trace.WriteLine(e.clsException.Message)
                        Trace.WriteLine(e.clsException.StackTrace)
Пример #10
0
from System.Net import WebClient

# Create a web client
client = WebClient()


# Download the results of that URL
results = client.DownloadString("http://localhost:8888/spotfireFramework/assetMarketPlace/customLibs/visTimeline/dxp/eventsGroup.csv")

# print these results
print results


stream = MemoryStream()
writer = StreamWriter(stream)
writer.Write(results)
writer.Flush()
stream.Seek(0, SeekOrigin.Begin)

readerSettings = TextDataReaderSettings()
readerSettings.Separator = ","
readerSettings.AddColumnNameRow(0)
readerSettings.SetDataType(0, DataType.String)
readerSettings.SetDataType(1, DataType.String)
readerSettings.SetDataType(2, DataType.DateTime)
readerSettings.SetDataType(3, DataType.DateTime)
readerSettings.SetDataType(4, DataType.String)
readerSettings.SetDataType(5, DataType.String)
readerSettings.SetDataType(6, DataType.String)

dSource = TextFileDataSource(stream, readerSettings)
path = r"lib/EnyimMemcached/build/CommonProperties.targets"

sr = StreamReader(path)
sb = StringBuilder()

line = sr.ReadLine()
while not line is None:
    
    #I'm sure this could all be done in a couple of lines with a nice multi-line Regex
    #All this does is comment out property groups that attempt to set signing 
    if line.Trim().StartsWith("<PropertyGroup") and line.Contains("PrivateKey"):
        
        sb.AppendFormat("<!--{0}\r\n", line)                 
        while line is not None and line.Trim() != "</PropertyGroup>":
            sb.AppendLine(line)
            line = sr.ReadLine()
        else:
            sb.AppendFormat("{0}-->\r\n", line)            
    else:
        sb.AppendLine(line)
    
    line = sr.ReadLine()
        
content = sb.ToString()
content = content.Replace("<DelaySign>true</DelaySign>", "<DelaySign>false</DelaySign>")
content = content.Replace("<SignAssembly>true</SignAssembly>", "<SignAssembly>false</SignAssembly>")
sr.Dispose()

sw = StreamWriter(path, False)
sw.Write(sb.ToString())
sw.Dispose()
Пример #12
0
dt["desc"] = "Enter Customer Onboarding Data"
dt["singleEvent"] = "TRUE"
dataTable.Rows.Add(dt)

textData = "parentType\tparentId\tstart\tend\teventType\tdesc\tsingleEvent\r\n"
for row in dataTable.Rows:
    textData += row["parentType"] + "\t" + str(row["parentId"]) + "\t" + str(
        row["start"]) + "\t" + str(row["end"]) + "\t" + str(
            row["eventType"]) + "\t" + str(
                row["desc"]) + "\t" + row["singleEvent"] + "\r\n"

print textData

stream = MemoryStream()
writer = StreamWriter(stream)
writer.Write(textData)
writer.Flush()
stream.Seek(0, SeekOrigin.Begin)

readerSettings = TextDataReaderSettings()
readerSettings.Separator = "\t"
readerSettings.AddColumnNameRow(0)
readerSettings.SetDataType(0, DataType.String)
readerSettings.SetDataType(1, DataType.String)
readerSettings.SetDataType(2, DataType.Date)
readerSettings.SetDataType(3, DataType.Date)
readerSettings.SetDataType(4, DataType.String)
readerSettings.SetDataType(5, DataType.String)
readerSettings.SetDataType(6, DataType.String)

dSource = TextFileDataSource(stream, readerSettings)