Here are the examples of the csharp api System.IO.StreamWriter.Close() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1827 Examples
19
Source : NailsConfig.cs
with MIT License
from 1upD
with MIT License
from 1upD
public static void WriteConfiguration(string filepath, NailsConfig config)
{
try
{
log.Info(string.Format("Writing Nails configuration to file: {0}", filepath));
XmlSerializer serializer = new XmlSerializer(typeof(NailsConfig));
StreamWriter writer = new StreamWriter(filepath);
serializer.Serialize(writer, config);
writer.Close();
}
catch (Exception e)
{
log.Error(string.Format("Error writing Nails configuration to file: {0}", filepath), e);
}
}
19
Source : AlifeConfigurator.cs
with MIT License
from 1upD
with MIT License
from 1upD
public static void WriteConfiguration(string filepath, List<BaseAgent> agents)
{
try
{
log.Info(string.Format("Writing artificial life configuration from file: {0}", filepath));
XmlSerializer serializer = new XmlSerializer(typeof(List<BaseAgent>));
StreamWriter writer = new StreamWriter(filepath);
serializer.Serialize(writer, agents);
writer.Close();
}
catch (Exception e)
{
log.Error(string.Format("Error writing artificial life configuration to file: {0}", filepath), e);
}
}
19
Source : V2rayHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
private int V2rayStartNew(string configStr)
{
ShowMsg(false, string.Format(UIRes.I18N("StartService"), DateTime.Now.ToString()));
try
{
string fileName = V2rayFindexe();
if (fileName == "") return -1;
Process p = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = fileName,
Arguments = "-config stdin:",
WorkingDirectory = Utils.StartupPath(),
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
StandardOutputEncoding = Encoding.UTF8
}
};
p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
string msg = e.Data + Environment.NewLine;
ShowMsg(false, msg);
}
});
p.Start();
p.BeginOutputReadLine();
p.StandardInput.Write(configStr);
p.StandardInput.Close();
if (p.WaitForExit(1000))
{
throw new Exception(p.StandardError.ReadToEnd());
}
Global.processJob.AddProcess(p.Handle);
return p.Id;
}
catch (Exception ex)
{
Utils.SaveLog(ex.Message, ex);
string msg = ex.Message;
ShowMsg(false, msg);
return -1;
}
}
19
Source : Utils.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public static void SaveLog(string strreplacedle, Exception ex)
{
try
{
string path = Path.Combine(StartupPath(), "guiLogs");
string FilePath = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd") + ".txt");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!File.Exists(FilePath))
{
FileStream FsCreate = new FileStream(FilePath, FileMode.Create);
FsCreate.Close();
FsCreate.Dispose();
}
FileStream FsWrite = new FileStream(FilePath, FileMode.Append, FileAccess.Write);
StreamWriter SwWrite = new StreamWriter(FsWrite);
string strContent = ex.ToString();
SwWrite.WriteLine(string.Format("{0}{1}[{2}]{3}", "--------------------------------", strreplacedle, DateTime.Now.ToString("HH:mm:ss"), "--------------------------------"));
SwWrite.Write(strContent);
SwWrite.WriteLine(Environment.NewLine);
SwWrite.WriteLine(" ");
SwWrite.Flush();
SwWrite.Close();
}
catch { }
}
19
Source : Machine.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
public void Disconnect()
{
if (Log != null)
Log.Close();
Log = null;
Connected = false;
WorkerThread.Join();
try
{
Connection.Close();
}
catch { }
Connection.Dispose();
Connection = null;
Mode = OperatingMode.Disconnected;
MachinePosition = new Vector3();
WorkOffset = new Vector3();
FeedRateRealtime = 0;
CurrentTLO = 0;
if (PositionUpdateReceived != null)
PositionUpdateReceived.Invoke();
Status = "Disconnected";
DistanceMode = ParseDistanceMode.Absolute;
Unit = ParseUnit.Metric;
Plane = ArcPlane.XY;
BufferState = 0;
FeedOverride = 100;
RapidOverride = 100;
SpindleOverride = 100;
if (OverrideChanged != null)
OverrideChanged.Invoke();
PinStateLimitX = false;
PinStateLimitY = false;
PinStateLimitZ = false;
PinStateProbe = false;
if (PinStateChanged != null)
PinStateChanged.Invoke();
ToSend.Clear();
ToSendPriority.Clear();
Sent.Clear();
ToSendMacro.Clear();
}
19
Source : Utility.Http.cs
with MIT License
from 7Bytes-Studio
with MIT License
from 7Bytes-Studio
public static string Post(string Url, string postDataStr, CookieContainer cookieContainer = null)
{
cookieContainer = cookieContainer ?? new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
request.CookieContainer = cookieContainer;
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
19
Source : FrmMain.cs
with MIT License
from A-Tabeshfard
with MIT License
from A-Tabeshfard
private void MnuFileSave_Click(object sender, EventArgs e)
{
try
{
if (!((FrmContent)ActiveMdiChild).NameCondition)
MnuFileSaveAs_Click(sender, e);
else
{
_streamWriter = new StreamWriter(ActiveMdiChild.Text);
_streamWriter.Write(((FrmContent)ActiveMdiChild).textBox.Text);
((FrmContent)ActiveMdiChild).SaveCondition = false;
ActiveMdiChild.Text = _saveFileDialog.FileName;
((FrmContent)ActiveMdiChild).NameCondition = true;
((FrmContent)ActiveMdiChild).SaveCondition = false;
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "Note Pad", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (_streamWriter != null)
_streamWriter.Close();
}
}
19
Source : FrmMain.cs
with MIT License
from A-Tabeshfard
with MIT License
from A-Tabeshfard
internal void MnuFileSaveAs_Click(object sender, EventArgs e)
{
try
{
_saveFileDialog.FileName = ActiveMdiChild.Text;
if (_saveFileDialog.ShowDialog() == DialogResult.OK)
{
_streamWriter = new StreamWriter(_saveFileDialog.OpenFile());
_streamWriter.Write(((FrmContent)ActiveMdiChild).textBox.Text);
ActiveMdiChild.Text = _saveFileDialog.FileName;
((FrmContent)ActiveMdiChild).NameCondition = true;
((FrmContent)ActiveMdiChild).SaveCondition = false;
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "Note Pad", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (_streamWriter != null)
_streamWriter.Close();
}
}
19
Source : ZUART.cs
with MIT License
from a2633063
with MIT License
from a2633063
private void lkbSaveRev_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
//if (txtShowData.Text.Length < 1)
//{
// MessageBox("");
// return;
//}
StreamWriter myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "文本文档(*.txt)|*.txt|所有文件(*.*)|*.*";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.replacedle = "保存接受区数据";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
myStream = new StreamWriter(saveFileDialog1.FileName);
myStream.Write(txtShowData.Text); //写入
myStream.Close();//关闭流
}
}
19
Source : ExternalCommunicator.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public void InitializeCommunicator()
{
Application.logMessageReceived += HandleLog;
logPath = Path.GetFullPath(".") + "/unity-environment.log";
logWriter = new StreamWriter(logPath, false);
logWriter.WriteLine(System.DateTime.Now.ToString());
logWriter.WriteLine(" ");
logWriter.Close();
messageHolder = new byte[messageLength];
// Create a TCP/IP socket.
sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect("localhost", comPort);
AcademyParameters accParamerters = new AcademyParameters();
accParamerters.brainParameters = new List<BrainParameters>();
accParamerters.brainNames = new List<string>();
accParamerters.externalBrainNames = new List<string>();
accParamerters.apiNumber = api;
accParamerters.logPath = logPath;
foreach (Brain b in brains)
{
accParamerters.brainParameters.Add(b.brainParameters);
accParamerters.brainNames.Add(b.gameObject.name);
if (b.brainType == BrainType.External)
{
accParamerters.externalBrainNames.Add(b.gameObject.name);
}
}
accParamerters.AcademyName = academy.gameObject.name;
accParamerters.resetParameters = academy.resetParameters;
SendParameters(accParamerters);
}
19
Source : ExternalCommunicator.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
void HandleLog(string logString, string stackTrace, LogType type)
{
logWriter = new StreamWriter(logPath, true);
logWriter.WriteLine(type.ToString());
logWriter.WriteLine(logString);
logWriter.WriteLine(stackTrace);
logWriter.Close();
}
19
Source : Test.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public IEnumerator Dump(string sceneName = null)
{
List<string> scenes = new List<string>();
for (int j = 0; j < USceneManager.sceneCountInBuildSettings; j++)
{
string scenePath = SceneUtility.GetScenePathByBuildIndex(j);
string name = Path.GetFileNameWithoutExtension(scenePath);
scenes.Add(name);
var load = USceneManager.LoadSceneAsync(j, LoadSceneMode.Single);
while (!load.isDone)
{
yield return new WaitForEndOfFrame();
}
yield return new WaitForSeconds(0.2f);
Scene s = USceneManager.GetActiveScene();
StringBuilder sb = new StringBuilder();
foreach (var g in s.GetRootGameObjects())
{
Visit(g.transform, 0, null,sb);
}
try
{
var fs = File.Create($"Z:\\1\\{s.name}.txt");
StreamWriter sw = new StreamWriter(fs);
sw.Write(sb.ToString());
sw.Close();
fs.Close();
}
catch { }
//
}
var load_ = USceneManager.LoadSceneAsync(2, LoadSceneMode.Single);
while (!load_.isDone)
{
yield return new WaitForEndOfFrame();
}
yield return USceneManager.LoadSceneAsync("Quit_To_Menu");
while (USceneManager.GetActiveScene().name != Constants.MENU_SCENE)
{
yield return new WaitForEndOfFrame();
}
}
19
Source : SoapSearch.cs
with MIT License
from ABN-SFLookupTechnicalSupport
with MIT License
from ABN-SFLookupTechnicalSupport
private static void Send(HttpWebRequest webRequest, string soapMessage) {
StreamWriter StreamWriter;
StreamWriter = new StreamWriter(webRequest.GetRequestStream());
StreamWriter.Write(soapMessage);
StreamWriter.Flush();
StreamWriter.Close();
}
19
Source : ExportExampleHelper.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static void ExportExampleToSolution(ref string lastGroup, Example current)
{
string projectName = ProjectWriter.WriteProject(
current, ExportPath + @"\", TryAutomaticallyFindreplacedemblies(), false);
if (!File.Exists(ScriptPath))
{
using (var fs = File.CreateText(ScriptPath))
{
// Write the header
fs.WriteLine("REM Compile and run all exported SciChart examples for testing");
fs.WriteLine("@echo OFF");
fs.WriteLine("");
fs.Close();
}
}
if (lastGroup != null && current.Group != lastGroup)
{
using (var fs = File.AppendText(ScriptPath))
{
fs.WriteLine("@echo Finished Example Group " + lastGroup + ". Press any key to continue...");
fs.WriteLine("pause(0)");
fs.WriteLine("");
}
}
lastGroup = current.Group;
using (var fs = File.AppendText(ScriptPath))
{
fs.WriteLine("@echo Building " + projectName);
fs.WriteLine(@"IF NOT EXIST ""C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin"" @echo VisualStudio folder not exists with the following path: ""C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin"" ");
fs.WriteLine(@"call ""C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\MSBuild.exe"" /p:Configuration=""Debug"" ""{0}/{0}.csproj"" /p:WarningLevel=0", projectName);
fs.WriteLine("if ERRORLEVEL 1 (");
fs.WriteLine(" @echo - Example {0} Failed to compile >> errorlog.txt", projectName);
fs.WriteLine(") else (");
fs.WriteLine(@" start """" ""{0}/bin/Debug/{0}.exe""", projectName);
fs.WriteLine(")");
fs.WriteLine("");
}
}
19
Source : MainViewModel.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static void WriteLog(string entry, string fileName)
{
string strPath = fileName;
System.IO.StreamWriter sw;
if (System.IO.File.Exists(strPath))
sw = System.IO.File.AppendText(strPath);
else
sw = System.IO.File.CreateText(strPath);
if (sw != null)
{
sw.WriteLine(entry + "[" + DateTime.Now.ToLongTimeString() + "]");
sw.Close();
}
}
19
Source : ProcessInvoker.cs
with MIT License
from actions
with MIT License
from actions
public async Task<int> ExecuteAsync(
string workingDirectory,
string fileName,
string arguments,
IDictionary<string, string> environment,
bool requireExitCodeZero,
Encoding outputEncoding,
bool killProcessOnCancel,
Channel<string> redirectStandardIn,
bool inheritConsoleHandler,
bool keepStandardInOpen,
bool highPriorityProcess,
CancellationToken cancellationToken)
{
ArgUtil.Null(_proc, nameof(_proc));
ArgUtil.NotNullOrEmpty(fileName, nameof(fileName));
Trace.Info("Starting process:");
Trace.Info($" File name: '{fileName}'");
Trace.Info($" Arguments: '{arguments}'");
Trace.Info($" Working directory: '{workingDirectory}'");
Trace.Info($" Require exit code zero: '{requireExitCodeZero}'");
Trace.Info($" Encoding web name: {outputEncoding?.WebName} ; code page: '{outputEncoding?.CodePage}'");
Trace.Info($" Force kill process on cancellation: '{killProcessOnCancel}'");
Trace.Info($" Redirected STDIN: '{redirectStandardIn != null}'");
Trace.Info($" Persist current code page: '{inheritConsoleHandler}'");
Trace.Info($" Keep redirected STDIN open: '{keepStandardInOpen}'");
Trace.Info($" High priority process: '{highPriorityProcess}'");
_proc = new Process();
_proc.StartInfo.FileName = fileName;
_proc.StartInfo.Arguments = arguments;
_proc.StartInfo.WorkingDirectory = workingDirectory;
_proc.StartInfo.UseShellExecute = false;
_proc.StartInfo.CreateNoWindow = !inheritConsoleHandler;
_proc.StartInfo.RedirectStandardInput = true;
_proc.StartInfo.RedirectStandardError = true;
_proc.StartInfo.RedirectStandardOutput = true;
// Ensure we process STDERR even the process exit event happen before we start read STDERR stream.
if (_proc.StartInfo.RedirectStandardError)
{
Interlocked.Increment(ref _asyncStreamReaderCount);
}
// Ensure we process STDOUT even the process exit event happen before we start read STDOUT stream.
if (_proc.StartInfo.RedirectStandardOutput)
{
Interlocked.Increment(ref _asyncStreamReaderCount);
}
#if OS_WINDOWS
// If StandardErrorEncoding or StandardOutputEncoding is not specified the on the
// ProcessStartInfo object, then .NET PInvokes to resolve the default console output
// code page:
// [DllImport("api-ms-win-core-console-l1-1-0.dll", SetLastError = true)]
// public extern static uint GetConsoleOutputCP();
StringUtil.EnsureRegisterEncodings();
#endif
if (outputEncoding != null)
{
_proc.StartInfo.StandardErrorEncoding = outputEncoding;
_proc.StartInfo.StandardOutputEncoding = outputEncoding;
}
// Copy the environment variables.
if (environment != null && environment.Count > 0)
{
foreach (KeyValuePair<string, string> kvp in environment)
{
_proc.StartInfo.Environment[kvp.Key] = kvp.Value;
}
}
// Indicate GitHub Actions process.
_proc.StartInfo.Environment["GITHUB_ACTIONS"] = "true";
// Set CI=true when no one else already set it.
// CI=true is common set in most CI provider in GitHub
if (!_proc.StartInfo.Environment.ContainsKey("CI") &&
Environment.GetEnvironmentVariable("CI") == null)
{
_proc.StartInfo.Environment["CI"] = "true";
}
// Hook up the events.
_proc.EnableRaisingEvents = true;
_proc.Exited += ProcessExitedHandler;
// Start the process.
_stopWatch = Stopwatch.StartNew();
_proc.Start();
// Decrease invoked process priority, in platform specifc way, relative to parent
if (!highPriorityProcess)
{
DecreaseProcessPriority(_proc);
}
// Start the standard error notifications, if appropriate.
if (_proc.StartInfo.RedirectStandardError)
{
StartReadStream(_proc.StandardError, _errorData);
}
// Start the standard output notifications, if appropriate.
if (_proc.StartInfo.RedirectStandardOutput)
{
StartReadStream(_proc.StandardOutput, _outputData);
}
if (_proc.StartInfo.RedirectStandardInput)
{
if (redirectStandardIn != null)
{
StartWriteStream(redirectStandardIn, _proc.StandardInput, keepStandardInOpen);
}
else
{
// Close the input stream. This is done to prevent commands from blocking the build waiting for input from the user.
_proc.StandardInput.Close();
}
}
var cancellationFinished = new TaskCompletionSource<bool>();
using (var registration = cancellationToken.Register(async () =>
{
await CancelAndKillProcessTree(killProcessOnCancel);
cancellationFinished.TrySetResult(true);
}))
{
Trace.Info($"Process started with process id {_proc.Id}, waiting for process exit.");
while (true)
{
Task outputSignal = _outputProcessEvent.WaitAsync();
var signaled = await Task.WhenAny(outputSignal, _processExitedCompletionSource.Task);
if (signaled == outputSignal)
{
ProcessOutput();
}
else
{
_stopWatch.Stop();
break;
}
}
// Just in case there was some pending output when the process shut down go ahead and check the
// data buffers one last time before returning
ProcessOutput();
if (cancellationToken.IsCancellationRequested)
{
// Ensure cancellation also finish on the cancellationToken.Register thread.
await cancellationFinished.Task;
Trace.Info($"Process Cancellation finished.");
}
Trace.Info($"Finished process {_proc.Id} with exit code {_proc.ExitCode}, and elapsed time {_stopWatch.Elapsed}.");
}
cancellationToken.ThrowIfCancellationRequested();
// Wait for process to finish.
if (_proc.ExitCode != 0 && requireExitCodeZero)
{
throw new ProcessExitCodeException(exitCode: _proc.ExitCode, fileName: fileName, arguments: arguments);
}
return _proc.ExitCode;
}
19
Source : ProcessInvoker.cs
with MIT License
from actions
with MIT License
from actions
private void StartWriteStream(Channel<string> redirectStandardIn, StreamWriter standardIn, bool keepStandardInOpen)
{
Task.Run(async () =>
{
// Write the contents as UTF8 to handle all characters.
var utf8Writer = new StreamWriter(standardIn.BaseStream, new UTF8Encoding(false));
while (!_processExitedCompletionSource.Task.IsCompleted)
{
ValueTask<string> dequeueTask = redirectStandardIn.Reader.ReadAsync(_processStandardInWriteCancellationTokenSource.Token);
string input = await dequeueTask;
if (input != null)
{
utf8Writer.WriteLine(input);
utf8Writer.Flush();
if (!keepStandardInOpen)
{
Trace.Info("Close STDIN after the first redirect finished.");
standardIn.Close();
break;
}
}
}
Trace.Info("STDIN stream write finished.");
});
}
19
Source : ConnectedInstruction_BACKUP_44876.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
public static void WritetoCsvu(IList<IList<double>> gridValues, string path)
{
Console.WriteLine("Write Begin " + DateTime.Now.ToString());
var sw = new StreamWriter(path);
var cnt = 0;
foreach (var row in gridValues)
{
sw.WriteLine(row[0] + "," + row[1] + "," + row[2] + "," + row[3] + "," + row[4] + "," + row[5] + "," + row[6]);
cnt++;
}
sw.Close();
Console.WriteLine("Write Complete " + DateTime.Now.ToString());
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
static void Main(string[] args)
{
bool DonotLoadGrid = true;
var grid = new List<IList<double>>();
if (!DonotLoadGrid)
{
Console.WriteLine("Loading Stream: " + DateTime.Now.ToString());
var sr = new StreamReader(@"C:\data\table.csv");
while (!sr.EndOfStream)
{
var line = sr.ReadLine();
var fieldValues = line.Split(',');
var fields = new List<double>();
var rdm = new Random(100000);
foreach (var field in fieldValues)
{
var res = 0d;
var add = double.TryParse(field, out res) == true ? res : rdm.NextDouble();
fields.Add(add);
}
grid.Add(fields);
}
Console.WriteLine("Grid loaded successfully!! " + DateTime.Now.ToString());
}
var keepProcessing = true;
while (keepProcessing)
{
Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine("Enter Expression:");
var expression = Console.ReadLine();
if (expression.ToLower() == "exit")
{
keepProcessing = false;
}
else
{
try
{
if(expression.Equals("zspread"))
{
var result = ConnectedInstruction.GetZSpread(grid,3,503);
}
if (expression.Substring(0, 19).ToLower().Equals("logisticregression "))
{
keepProcessing = true;
var paths = expression.Split(' ');
#region Python
var script =@"
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
creditData = pd.read_csv("+paths[1]+@")
print(creditData.head())
print(creditData.describe())
print(creditData.corr())
features = creditData[['income', 'age', 'loan']]
target = creditData.default
feature_train, feature_test, target_train, target_test = train_test_split(features, target, test_size = 0.3)
model = LogisticRegression()
model.fit = model.fit(feature_train, target_train)
predictions = model.fit.predict(feature_test)
print(confusion_matrix(target_test, predictions))
print(accuracy_score(target_test, predictions))
";
var sw = new StreamWriter(@"c:\data\logistic.py");
sw.Write(script);
sw.Close();
#endregion
ProcessStartInfo start = new ProcessStartInfo();
Console.WriteLine("Starting Python Engine...");
start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
start.Arguments = string.Format("{0} {1}", @"c:\data\logistic.py", args);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
Console.WriteLine("Starting Process..."+ DateTime.Now.ToString());
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
}
if(expression.Substring(0,12) == "videoreplacedyse")
{
#region python
var python = @"
from keras.preprocessing.image import img_to_array
import imutils
import cv2
from keras.models import load_model
import numpy as np
import geocoder
#import mysql.connector as con
#mydb = con.connect(
# host=""localhost"",
# user=""yourusername"",
# preplacedwd=""yourpreplacedword"",
# database=""mydatabase""
#)
#mycursor = mydb.cursor()
g = geocoder.ip('me')
# parameters for loading data and images
detection_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\haarcascade_files\\haarcascade_frontalface_default.xml'
emotion_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\models\\_mini_XCEPTION.102-0.66.hdf5'
# hyper-parameters for bounding boxes shape
# loading models
face_detection = cv2.CascadeClreplacedifier(detection_model_path)
emotion_clreplacedifier = load_model(emotion_model_path, compile = False)
EMOTIONS = [""angry"", ""disgust"", ""scared"", ""happy"", ""sad"", ""surprised"",
""neutral""]
# feelings_faces = []
# for index, emotion in enumerate(EMOTIONS):
# feelings_faces.append(cv2.imread('emojis/' + emotion + '.png', -1))
# starting video streaming
cv2.namedWindow('your_face')
camera = cv2.VideoCapture(0)
f = open(""C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Probability.txt"", ""a+"")
while True:
frame = camera.read()[1]
#reading the frame
frame = imutils.resize(frame, width = 300)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detection.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (30, 30), flags = cv2.CASCADE_SCALE_IMAGE)
canvas = np.zeros((250, 300, 3), dtype = ""uint8"")
frameClone = frame.copy()
if len(faces) > 0:
faces = sorted(faces, reverse = True,
key = lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
(fX, fY, fW, fH) = faces
# Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare
# the ROI for clreplacedification via the CNN
roi = gray[fY: fY + fH, fX: fX + fW]
roi = cv2.resize(roi, (64, 64))
roi = roi.astype(""float"") / 255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi, axis = 0)
preds = emotion_clreplacedifier.predict(roi)[0]
emotion_probability = np.max(preds)
label = EMOTIONS[preds.argmax()]
else: continue
for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)):
# construct the label text
text = ""{}: {:.2f}%"".format(emotion, prob * 100)
#sql = ""INSERT INTO predData (Metadata, Probability) VALUES (%s, %s)""
#val = (""Meta"", prob * 100)
f.write(text)
#str1 = ''.join(str(e) for e in g.latlng)
#f.write(str1)
#mycursor.execute(sql, val)
#mydb.commit()
# draw the label + probability bar on the canvas
# emoji_face = feelings_faces[np.argmax(preds)]
w = int(prob * 300)
cv2.rectangle(canvas, (7, (i * 35) + 5),
(w, (i * 35) + 35), (0, 0, 255), -1)
cv2.putText(canvas, text, (10, (i * 35) + 23),
cv2.FONT_HERSHEY_SIMPLEX, 0.45,
(255, 255, 255), 2)
cv2.putText(frameClone, label, (fX, fY - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH),
(0, 0, 255), 2)
# for c in range(0, 3):
# frame[200:320, 10:130, c] = emoji_face[:, :, c] * \
# (emoji_face[:, :, 3] / 255.0) + frame[200:320,
# 10:130, c] * (1.0 - emoji_face[:, :, 3] / 255.0)
cv2.imshow('your_face', frameClone)
cv2.imshow(""Probabilities"", canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
camera.release()
cv2.destroyAllWindows()
";
var sw = new StreamWriter(@"c:\data\face.py");
sw.Write(python);
sw.Close();
#endregion
ProcessStartInfo start = new ProcessStartInfo();
Console.WriteLine("Starting Python Engine...");
start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
start.Arguments = string.Format("{0} {1}", @"c:\data\face.py", args);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
Console.WriteLine("Starting Process..." + DateTime.Now.ToString());
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
}
if (expression.Substring(0,12).ToLower().Equals("kaplanmeier "))
{
keepProcessing = true;
var columnsOfconcern = expression.Split(' ');
Console.WriteLine("Preparing...");
var observations = new List<PairedObservation>();
var ca = GetColumn(grid,int.Parse(columnsOfconcern[1]));
var cb = GetColumn(grid, int.Parse(columnsOfconcern[2]));
var cc = GetColumn(grid, int.Parse(columnsOfconcern[3]));
for(int i=0;i<ca.Count;i++)
{
observations.Add(new PairedObservation((decimal)ca[i], (decimal)cb[i], (decimal)cc[i]));
}
var kp = new KaplanMeier(observations);
}
if (expression.Equals("write"))
{
keepProcessing = true;
ConnectedInstruction.WritetoCsvu(grid, @"c:\data\temp.csv");
}
if (expression.Substring(0, 9) == "getvalue(")
{
keepProcessing = true;
Regex r = new Regex(@"\(([^()]+)\)*");
var res = r.Match(expression);
var val = res.Value.Split(',');
try
{
var gridVal = grid[int.Parse(val[0].Replace("(", "").Replace(")", ""))]
[int.Parse(val[1].Replace("(", "").Replace(")", ""))];
Console.WriteLine(gridVal.ToString() + "\n");
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Hmmm,... apologies, can't seem to find that within range...");
}
}
else
{
keepProcessing = true;
Console.WriteLine("Process Begin:" + DateTime.Now.ToString());
var result = ConnectedInstruction.ParseExpressionAndRunAgainstInMemmoryModel(grid, expression);
Console.WriteLine("Process Ended:" + DateTime.Now.ToString());
}
}
catch (ArgumentOutOfRangeException)
{
}
}
}
}
19
Source : Requestor.cs
with MIT License
from adoprog
with MIT License
from adoprog
public void PostRequest(string url, string json)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{
Log.Error("PostToFlow: Action failed to execute", ex);
}
}
19
Source : SendToFlow.cs
with MIT License
from adoprog
with MIT License
from adoprog
public void PostRequest(string url, string json)
{
try
{
var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch
{
// TODO: Use MA logging API to log error
}
}
19
Source : PaypalHelper.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public WebResponse GetPaymentWebResponse(string incomingReqStr)
{
var newReq = (HttpWebRequest)WebRequest.Create(PayPalBaseUrl);
//Set values for the request back
newReq.Method = "POST";
newReq.ContentType = "application/x-www-form-urlencoded";
var newRequestStr = incomingReqStr + "&cmd=_notify-validate";
newReq.ContentLength = newRequestStr.Length;
//write out the full parameters into the request
var streamOut = new StreamWriter(newReq.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(newRequestStr);
streamOut.Close();
//Send request back to Paypal and receive response
var response = newReq.GetResponse();
return response;
}
19
Source : PaypalHelper.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public IPayPalPaymentDataTransferResponse GetPaymentDataTransferResponse(string idenreplacedyToken, string transactionId)
{
var query = string.Format("cmd=_notify-synch&tx={0}&at={1}", transactionId, idenreplacedyToken);
var request = (HttpWebRequest)WebRequest.Create(PayPalBaseUrl);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = query.Length;
var streamOut = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
streamOut.Write(query);
streamOut.Close();
var streamIn = new StreamReader(request.GetResponse().GetResponseStream());
var response = streamIn.ReadToEnd();
streamIn.Close();
return new PayPalPaymentDataTransferResponse(response);
}
19
Source : HttpURLConnectionClient.cs
with MIT License
from Adyen
with MIT License
from Adyen
public string Request(string endpoint, string json, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null )
{
string responseText = null;
_environment = config.Environment;
var httpWebRequest = GetHttpWebRequest(endpoint, config, isApiKeyRequired, requestOptions );
if (config.HttpRequestTimeout > 0)
{
httpWebRequest.Timeout = config.HttpRequestTimeout;
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
using (var response = (HttpWebResponse) httpWebRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), _encoding))
{
responseText = reader.ReadToEnd();
}
}
}
catch (WebException e)
{
HandleWebException(e);
}
return responseText;
}
19
Source : HttpURLConnectionClient.cs
with MIT License
from Adyen
with MIT License
from Adyen
public async Task<string> RequestAsync(string endpoint, string json, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null)
{
string responseText = null;
//Set security protocol. Only TLS1.2
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = GetHttpWebRequest(endpoint, config, isApiKeyRequired, requestOptions);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
using (var response = (HttpWebResponse)await httpWebRequest.GetResponseAsync())
{
using (var reader = new StreamReader(response.GetResponseStream(), _encoding))
{
responseText = await reader.ReadToEndAsync();
}
}
}
catch (WebException e)
{
HandleWebException(e);
}
return responseText;
}
19
Source : RedBlackTree.cs
with GNU General Public License v2.0
from afrantzis
with GNU General Public License v2.0
from afrantzis
public void DumpToDot(string filename, string replacedle)
{
lock(lockObj) {
StringBuilder sb = new StringBuilder("digraph {\nlabel=\""+replacedle+"\"\n");
DumpToDotInternal(root, sb);
sb.Append("}\n");
StreamWriter sw = new StreamWriter(filename);
sw.Write(sb.ToString());
sw.Close();
}
}
19
Source : GuiderImpl.cs
with MIT License
from agalasso
with MIT License
from agalasso
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (sw != null)
{
sw.Close();
sw.Dispose();
sw = null;
}
if (sr != null)
{
sr.Close();
sr.Dispose();
sr = null;
}
if (tcpCli != null)
{
Debug.WriteLine("Disconnect from phd2");
tcpCli.Close();
tcpCli = null;
}
}
}
19
Source : TxtRecorder.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
private void WriteFile(string log, string type)
{
var writer = GetWriter(type);
if (writer == null)
return;
try
{
writer.Size += log.Length;
writer.Stream.WriteLine(log);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString(), $"TextRecorder.WriteFile->{type}");
writer.Stream.Dispose();
writer.Stream.Close();
ResetFile(type, writer);
}
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev
with GNU General Public License v3.0
from AgentRev
void SaveSettings()
{
if (saveSettings && !currentlyReading)
{
try
{
StreamWriter sw = null;
try
{
if (!Directory.Exists(settingsPath))
Directory.CreateDirectory(settingsPath);
using (sw = new StreamWriter(settingsFile))
{
sw.WriteLine("ToolVersion=" + c_toolVer);
sw.WriteLine("Beep=" + chkBeep.Checked);
sw.WriteLine("FoV=" + fFoV);
sw.WriteLine("FoVOffset=" + pFoV.ToString("x"));
sw.WriteLine("UpdateNotify=" + chkUpdate.Checked);
sw.WriteLine("DisableHotkeys=" + chkHotkeys.Checked);
sw.WriteLine("HotkeyIncrease=" + (int)catchKeys[0]);
sw.WriteLine("HotkeyDecrease=" + (int)catchKeys[1]);
sw.WriteLine("HotkeyReset=" + (int)catchKeys[2]);
}
}
catch
{
if (sw != null)
sw.Close();
File.Delete(settingsFile);
throw;
}
SaveGameMode();
}
catch
{
saveSettings = false;
}
}
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev
with GNU General Public License v3.0
from AgentRev
private void SaveData()
{
if (saveSettings && !currentlyReading)
{
try
{
StreamWriter sw = null;
try
{
if (!Directory.Exists(settingsPath)) Directory.CreateDirectory(settingsPath);
sw = new StreamWriter(Path.Combine(settingsPath, settingsFile));
sw.WriteLine("ToolVersion=" + c_toolVer);
sw.WriteLine("Beep=" + chkBeep.Checked.ToString().ToLower());
sw.WriteLine("FoV=" + ((int)fFoV).ToString());
sw.WriteLine("FoVOffset=" + pFoV.ToString("x"));
sw.WriteLine("UpdatePopup=" + chkUpdate.Checked.ToString().ToLower());
sw.WriteLine("DisableHotkeys=" + chkHotkeys.Checked.ToString().ToLower());
sw.WriteLine("HotkeyIncrease=" + (int)catchKeys[0]);
sw.WriteLine("HotkeyDecrease=" + (int)catchKeys[1]);
sw.WriteLine("HotkeyReset=" + (int)catchKeys[2]);
}
catch
{
//MessageBox.Show("catch");
if (sw != null) sw.Close();
File.Delete(settingsFile);
saveSettings = false;
}
finally
{
if (sw != null) sw.Close();
}
}
catch
{
saveSettings = false;
}
}
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev
with GNU General Public License v3.0
from AgentRev
void SaveSettings()
{
if (saveSettings && !currentlyReading)
{
try
{
StreamWriter sw = null;
try
{
if (!Directory.Exists(settingsPath))
Directory.CreateDirectory(settingsPath);
using (sw = new StreamWriter(settingsFile))
{
sw.WriteLine("ToolVersion=" + c_toolVer);
sw.WriteLine("Beep=" + chkBeep.Checked);
sw.WriteLine("FoV=" + fFoV);
sw.WriteLine("FoVOffset=" + pFoV.ToString("x"));
sw.WriteLine("UpdatePopup=" + chkUpdate.Checked);
sw.WriteLine("DisableHotkeys=" + chkHotkeys.Checked);
sw.WriteLine("HotkeyIncrease=" + (int)catchKeys[0]);
sw.WriteLine("HotkeyDecrease=" + (int)catchKeys[1]);
sw.WriteLine("HotkeyReset=" + (int)catchKeys[2]);
}
}
catch
{
if (sw != null)
sw.Close();
File.Delete(settingsFile);
throw;
}
}
catch
{
saveSettings = false;
}
}
}
19
Source : IdentityBuilderExtensions.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static IOptions<OAuthServiceAccountKey> StoreAuthFile(IServiceProvider provider, string authFilePath)
{
var authOptions = provider.GetRequiredService<IOptions<OAuthServiceAccountKey>>();
var json = JsonConvert.SerializeObject(authOptions.Value);
using (var writer = File.CreateText(authFilePath))
{
writer.Write(json);
writer.Flush();
writer.Close();
}
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", authFilePath);
return authOptions;
}
19
Source : Program.cs
with GNU Affero General Public License v3.0
from aianlinb
with GNU Affero General Public License v3.0
from aianlinb
static void Main(string[] args)
{
string path = args.Length > 0 && Path.GetFileName(args[0]) == "_.index.bin" ? args[0] : "_.index.bin";
if (!File.Exists(path))
{
Console.WriteLine("File not found: " + path);
Console.WriteLine("Click enter to exit . . .");
Console.ReadLine();
return;
}
Console.WriteLine("Loading . . .");
var ic = new IndexContainer(path);
Console.WriteLine("Found:");
Console.WriteLine(ic.Bundles.Length.ToString() + " BundleRecords");
Console.WriteLine(ic.Files.Length.ToString() + " FileRecords");
Console.WriteLine(ic.Directorys.Length.ToString() + " DirectoryRecords");
Console.WriteLine(Environment.NewLine + "Generating FileList . . .");
var sw = File.CreateText("FileList.yml");
foreach (var b in ic.Bundles)
{
sw.WriteLine(b.Name + ":");
foreach (var f in b.Files)
sw.WriteLine("- " + f.path);
}
sw.Flush();
sw.Close();
Console.WriteLine("Done!");
Console.WriteLine(Environment.NewLine + "Click enter to exit . . .");
Console.ReadLine();
}
19
Source : OpensslEsiaSigner.cs
with GNU General Public License v3.0
from AISGorod
with GNU General Public License v3.0
from AISGorod
public string Sign(byte[] data)
{
Process a = new Process();
a.StartInfo.FileName = "openssl";
a.StartInfo.Arguments = $"cms -sign -binary -stream -engine gost -inkey {KEY_FILE} -signer {CRT_FILE} -nodetach -outform pem";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
a.StartInfo.FileName = "wsl";
a.StartInfo.Arguments = "openssl " + a.StartInfo.Arguments;
}
a.StartInfo.RedirectStandardInput = true;
a.StartInfo.RedirectStandardOutput = true;
a.StartInfo.UseShellExecute = false;
a.Start();
a.StandardInput.Write(Encoding.UTF8.GetString(data)); // просто передавать массив байтов не получается - ломает подпись
a.StandardInput.Close();
StringBuilder resultData = new StringBuilder();
bool isKeyProcessing = false;
while (!a.StandardOutput.EndOfStream)
{
string line = a.StandardOutput.ReadLine();
if (line == "-----BEGIN CMS-----")
{
isKeyProcessing = true;
}
else if (line == "-----END CMS-----")
{
isKeyProcessing = false;
}
else if (isKeyProcessing)
{
resultData.Append(line);
}
}
return resultData.ToString();
}
19
Source : NodeEditorUtilities.cs
with MIT License
from aksyr
with MIT License
from aksyr
internal static UnityEngine.Object CreateScript(string pathName, string templatePath) {
string clreplacedName = Path.GetFileNameWithoutExtension(pathName).Replace(" ", string.Empty);
string templateText = string.Empty;
UTF8Encoding encoding = new UTF8Encoding(true, false);
if (File.Exists(templatePath)) {
/// Read procedures.
StreamReader reader = new StreamReader(templatePath);
templateText = reader.ReadToEnd();
reader.Close();
templateText = templateText.Replace("#SCRIPTNAME#", clreplacedName);
templateText = templateText.Replace("#NOTRIM#", string.Empty);
/// You can replace as many tags you make on your templates, just repeat Replace function
/// e.g.:
/// templateText = templateText.Replace("#NEWTAG#", "MyText");
/// Write procedures.
StreamWriter writer = new StreamWriter(Path.GetFullPath(pathName), false, encoding);
writer.Write(templateText);
writer.Close();
replacedetDatabase.Importreplacedet(pathName);
return replacedetDatabase.LoadreplacedetAtPath(pathName, typeof(Object));
} else {
Debug.LogError(string.Format("The template file was not found: {0}", templatePath));
return null;
}
}
19
Source : MainProgram.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args) {
Exception e = (Exception)args.ExceptionObject;
string errorLogLoc = Path.Combine(dataFolderLocation, "error_log.txt");
string subKey = @"SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion";
RegistryKey thekey = Registry.LocalMachine;
RegistryKey skey = thekey.OpenSubKey(subKey);
string windowsVersionName = skey.GetValue("ProductName").ToString();
string rawWindowsVersion = Environment.OSVersion.ToString();
int totalExecutions = 0;
foreach (int action in Properties.Settings.Default.TotalActionsExecuted) {
totalExecutions += action;
}
if (File.Exists(errorLogLoc))
try {
File.Delete(errorLogLoc);
} catch {
DoDebug("Failed to delete error log");
}
if (!File.Exists(errorLogLoc)) {
try {
using (var tw = new StreamWriter(errorLogLoc, true)) {
tw.WriteLine("OS;");
tw.WriteLine("- " + windowsVersionName);
tw.WriteLine("- " + rawWindowsVersion);
tw.WriteLine();
tw.WriteLine("ACC info;");
tw.WriteLine("- Version; " + softwareVersion + ", " + releaseDate);
tw.WriteLine("- UID; " + Properties.Settings.Default.UID);
tw.WriteLine("- Running from; " + currentLocationFull);
tw.WriteLine("- Start with Windows; " + (ACCStartsWithWindows() ? "[Yes]" : "[No]"));
tw.WriteLine("- Check for updates; " + (Properties.Settings.Default.CheckForUpdates ? "[Yes]" : "[No]"));
tw.WriteLine("- In beta program; " + (Properties.Settings.Default.BetaProgram ? "[Yes]" : "[No]"));
tw.WriteLine("- Has completed setup guide; " + (Properties.Settings.Default.HasCompletedTutorial ? "[Yes]" : "[No]"));
tw.WriteLine("- Check path; " + CheckPath());
tw.WriteLine("- Check extension; " + Properties.Settings.Default.ActionFileExtension);
tw.WriteLine("- Actions executed; " + totalExecutions);
tw.WriteLine("- replacedistant type; " + "[Google replacedistant: " + Properties.Settings.Default.replacedistantType[0] + "] [Alexa: " + Properties.Settings.Default.replacedistantType[1] + "] [Unknown: " + Properties.Settings.Default.replacedistantType[1] + "]");
tw.WriteLine();
tw.WriteLine(e);
tw.Close();
}
} catch {
//Caught exception when trying to log exception... *sigh*
}
}
File.AppendAllText(errorLogLoc, DateTime.Now.ToString() + ": " + e + Environment.NewLine);
if (debug) {
Console.WriteLine(e);
}
MessageBox.Show("A critical error occurred. The developer has been notified and will resolve this issue ASAP! Try and start ACC again, and avoid whatever just made it crash (for now) :)", "ACC | Error");
}
19
Source : MainProgram.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
private static bool CreateLogFile() {
try {
using (var tw = new StreamWriter(logFilePath, true)) {
tw.WriteLine(string.Empty);
tw.Close();
}
} catch (Exception e) {
Console.WriteLine("Could not create/clear log file; " + e.Message);
return false;
}
return true;
}
19
Source : ExperimentDataExportController.cs
with MIT License
from AlexanderFroemmgen
with MIT License
from AlexanderFroemmgen
private void GetResultDataCSVExport(int id, string path)
{
/*
* Performance notes:
*
* This lazy style is much faster than loading all data at once.
*
*/
var data =
_context.Experiments
.Include(s => s.Parameters).ThenInclude(p => p.Values)
.Include(s => s.ExperimentInstances)
.Single(s => s.Id == id);
var outputFileStream = new StreamWriter(new FileStream(path, FileMode.Create));
var result = new StringBuilder("simInstanceId;");
foreach (var parameter in data.Parameters.OrderBy(p => p.Name))
{
result.Append(parameter.Name);
result.Append(";");
}
result.Append("value;offset;key;key2;key3;\n");
outputFileStream.Write(result);
result.Clear();
int counter = -1;
int total = data.ExperimentInstances.Count();
var sb = new StringBuilder();
foreach (var simInstanceBlank in data.ExperimentInstances)
{
var simInstance = _context.ExperimentInstances
.Include(i => i.ParameterValues)
.Include(i => i.Records)
// .Include(i => i.LogMessages) Denny
.Single(i => i.Id == simInstanceBlank.Id);
/*
* Design desicion:
*
* All records are in a own row and share the same parameters.
*
*/
var parameterStringBuilder = new StringBuilder(simInstance.Id + ";");
foreach (var paramInstance in simInstance.ParameterValues
.OrderBy(pv => pv.ParameterValue.Parameter.Name)
.Select(a => a.ParameterValue))
{
parameterStringBuilder.Append(paramInstance.Value);
parameterStringBuilder.Append(";");
}
var parameterString = parameterStringBuilder.ToString();
foreach (var record in simInstance.Records)
{
sb.Append(parameterString);
sb.Append(record.Value);
sb.Append(";");
sb.Append(record.Offset);
sb.Append(";");
sb.Append(record.Key);
sb.Append(";");
sb.Append(record.Key2);
sb.Append(";");
sb.Append(record.Key3);
sb.Append(";\n");
}
/* add failed statistics */
sb.Append(parameterString);
sb.Append(simInstance.Status == Data.Persistence.Model.ExperimentStatus.Finished ? 1 : 0);
sb.Append(";0;Finished;\n");
sb.Append(parameterString);
sb.Append((simInstance.Status == Data.Persistence.Model.ExperimentStatus.Error ||
simInstance.Status == Data.Persistence.Model.ExperimentStatus.Aborted) ? 1 : 0);
sb.Append(";0;Error;\n");
/* denny string */
/* var log = simInstance.LogMessages.Where(lm => lm.Key == "Measurement result").SingleOrDefault();
if(log != null) {
var logStr = log.Message.Replace(";", "|");
sb.Append(parameterString);
sb.Append("DennyAdaptationLog");
sb.Append(";");
sb.Append(0);
sb.Append(";");
sb.Append(logStr);
sb.Append(";\n");
} else {
Console.WriteLine("No log message for " + simInstance.Id.ToString());
}*/
/* end denny */
counter++;
if (counter % 50 == 0)
{
Console.WriteLine("Exported " + counter.ToString() + " of " + total.ToString());
outputFileStream.Write(sb);
sb.Clear();
}
}
/* write remaining stuff */
outputFileStream.Write(sb);
outputFileStream.Close();
Console.WriteLine("Finished Export");
}
19
Source : MKMInteract.cs
with GNU Affero General Public License v3.0
from alexander-pick
with GNU Affero General Public License v3.0
from alexander-pick
public static XmlDoreplacedent MakeRequest(string url, string method, string body = null)
{
// throw the exception ourselves to prevent sending requests to MKM that would end with this error
// because MKM tends to revoke the user's app token if it gets too many requests above the limit
// the 429 code is the same MKM uses for this error
if (denyAdditionalRequests)
{
// MKM resets the counter at 0:00 CET. CET is two hours ahead of UCT, so if it is after 22:00 of the same day
// the denial was triggered, that means the 0:00 CET has preplaceded and we can reset the deny
if (DateTime.UtcNow.Date == denyTime.Date && DateTime.UtcNow.Hour < 22)
throw new HttpListenerException(429, "Too many requests. Wait for 0:00 CET for request counter to reset.");
else
denyAdditionalRequests = false;
}
// enforce the maxRequestsPerMinute limit - technically it's just an approximation as the requests
// can arrive to MKM with some delay, but it should be close enough
var now = DateTime.Now;
while (requestTimes.Count > 0 && (now - requestTimes.Peek()).TotalSeconds > 60)
{
requestTimes.Dequeue();// keep only times of requests in the past 60 seconds
}
if (requestTimes.Count >= maxRequestsPerMinute)
{
// wait until 60.01 seconds preplaceded since the oldest request
// we know (now - peek) is <= 60, otherwise it would get dequeued above,
// so we are preplaceding a positive number to sleep
System.Threading.Thread.Sleep(
60010 - (int)(now - requestTimes.Peek()).TotalMilliseconds);
requestTimes.Dequeue();
}
requestTimes.Enqueue(DateTime.Now);
XmlDoreplacedent doc = new XmlDoreplacedent();
for (int numAttempts = 0; numAttempts < MainView.Instance.Config.MaxTimeoutRepeat; numAttempts++)
{
try
{
var request = WebRequest.CreateHttp(url);
request.Method = method;
request.Headers.Add(HttpRequestHeader.Authorization, header.GetAuthorizationHeader(method, url));
request.Method = method;
if (body != null)
{
request.ServicePoint.Expect100Continue = false;
request.ContentLength = System.Text.Encoding.UTF8.GetByteCount(body);
request.ContentType = "text/xml";
var writer = new StreamWriter(request.GetRequestStream());
writer.Write(body);
writer.Close();
}
var response = request.GetResponse() as HttpWebResponse;
// just for checking EoF, it is not accessible directly from the Stream object
// Empty streams can be returned for example for article fetches that result in 0 matches (happens regularly when e.g. seeking nonfoils in foil-only promo sets).
// Preplaceding empty stream to doc.Load causes exception and also sometimes seems to screw up the XML parser
// even when the exception is handled and it then causes problems for subsequent calls => first check if the stream is empty
StreamReader s = new StreamReader(response.GetResponseStream());
if (!s.EndOfStream)
doc.Load(s);
s.Close();
int requestCount = int.Parse(response.Headers.Get("X-Request-Limit-Count"));
int requestLimit = int.Parse(response.Headers.Get("X-Request-Limit-Max"));
if (requestCount >= requestLimit)
{
denyAdditionalRequests = true;
denyTime = DateTime.UtcNow;
}
MainView.Instance.Invoke(new MainView.UpdateRequestCountCallback(MainView.Instance.UpdateRequestCount), requestCount, requestLimit);
break;
}
catch (WebException webEx)
{
// timeout can be either on our side (Timeout) or on server
bool isTimeout = webEx.Status == WebExceptionStatus.Timeout;
if (webEx.Status == WebExceptionStatus.ProtocolError)
{
if (webEx.Response is HttpWebResponse response)
{
isTimeout = response.StatusCode == HttpStatusCode.GatewayTimeout
|| response.StatusCode == HttpStatusCode.ServiceUnavailable;
}
}
// handle only timeouts, client handles other exceptions
if (isTimeout && numAttempts + 1 < MainView.Instance.Config.MaxTimeoutRepeat)
System.Threading.Thread.Sleep(1500); // wait and try again
else
throw webEx;
}
}
return doc;
}
19
Source : BlockMining.cs
with MIT License
from alexanderdna
with MIT License
from alexanderdna
public void Dispose()
{
if (_headerStreamWriter != null)
{
_headerStreamWriter.Close();
_headerStreamWriter.Dispose();
_headerStreamWriter = null;
_headerStream = null;
}
}
19
Source : ConnectCamera.xaml.cs
with MIT License
from AlexBrochu
with MIT License
from AlexBrochu
private void OnSave(object sender, RoutedEventArgs e)
{
if (camera_name.Text == "")
{
camera_name.Background = new SolidColorBrush(Colors.Red);
}
else if(address.Text == "")
{
address.Background = new SolidColorBrush(Colors.Red);
}
else if (user.Text == "")
{
user.Background = new SolidColorBrush(Colors.Red);
}
else if (preplacedword.Preplacedword == "")
{
preplacedword.Background = new SolidColorBrush(Colors.Red);
}
else
{
CameraConnexion cc = new CameraConnexion();
cc.Address = address.Text;
cc.CameraName = camera_name.Text;
cc.Preplacedword = preplacedword.Preplacedword;
cc.User = user.Text;
// write login info in json file
if (cameras == null)
{
cameras = new List<CameraConnexion>();
}
// override camera if is already saved with same name
int index = cameras.FindIndex(element => element.CameraName.Equals(cc.CameraName));
if (index == -1)
{
cameras.Add(cc);
}
else
{
cameras[index] = cc;
}
string json = JsonConvert.SerializeObject(cameras);
if (!File.Exists(path_to_connexion_file))
{
File.CreateText(path_to_connexion_file).Close();
}
using (StreamWriter file = new StreamWriter(path_to_connexion_file, false))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, cameras);
}
LoadConnexion();
}
}
19
Source : ConnectCamera.xaml.cs
with MIT License
from AlexBrochu
with MIT License
from AlexBrochu
private void LoadConnexion()
{
listBox_saved.Items.Clear();
if (!File.Exists(path_to_connexion_file))
{
File.CreateText(path_to_connexion_file).Close();
}
using (StreamReader file = File.OpenText(path_to_connexion_file))
{
JsonSerializer serializer = new JsonSerializer();
cameras = (List<CameraConnexion>)serializer.Deserialize(file, typeof(List<CameraConnexion>));
if (cameras != null)
{
foreach (CameraConnexion cam in cameras)
{
listBox_saved.Items.Add(cam.CameraName);
}
}
}
}
19
Source : ConnectCamera.xaml.cs
with MIT License
from AlexBrochu
with MIT License
from AlexBrochu
private void delete_cam_btn_Click(object sender, RoutedEventArgs e)
{
if (selectedCam == null || cameras == null)
{
delete_cam_btn.IsEnabled = false;
return;
}
// Remove Camera login info
int index = cameras.FindIndex(element => element.CameraName.Equals(selectedCam.CameraName));
if (index >= 0)
{
cameras.RemoveAt(index);
}
string json = JsonConvert.SerializeObject(cameras);
if (!File.Exists(path_to_connexion_file))
{
File.CreateText(path_to_connexion_file).Close();
}
using (StreamWriter file = new StreamWriter(path_to_connexion_file, false))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, cameras);
}
LoadConnexion();
delete_cam_btn.IsEnabled = false;
}
19
Source : CrashHandler.cs
with GNU General Public License v3.0
from alexgracianoarj
with GNU General Public License v3.0
from alexgracianoarj
private static void CreateCrashLog(string directory, Exception exception)
{
StreamWriter writer = null;
try
{
string filePath = Path.Combine(directory, "crash.log");
writer = new StreamWriter(filePath);
writer.WriteLine(string.Format(
Strings.SendLogFile, Properties.Resources.MailAddress));
writer.WriteLine();
writer.WriteLine("Version: {0}", Program.GetVersionString());
writer.WriteLine("Mono: {0}", MonoHelper.IsRunningOnMono ? "yes" : "no");
if (MonoHelper.IsRunningOnMono)
writer.WriteLine("Mono version: {0}", MonoHelper.Version);
writer.WriteLine("OS: {0}", Environment.OSVersion.VersionString);
writer.WriteLine();
writer.WriteLine(exception.Message);
Exception innerException = exception.InnerException;
while (innerException != null)
{
writer.WriteLine(innerException.Message);
innerException = innerException.InnerException;
}
writer.WriteLine();
writer.WriteLine(exception.StackTrace);
}
catch
{
// Do nothing
}
finally
{
if (writer != null)
writer.Close();
}
}
19
Source : IOUtils.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
public void DoWork()
{
while ( IOUtils.ActiveThread )
{
if ( IOUtils.SaveInThreadFlag )
{
IOUtils.SaveInThreadFlag = false;
lock ( locker )
{
IOUtils.SaveInThreadShaderBody = IOUtils.ShaderCopywriteMessage + IOUtils.SaveInThreadShaderBody;
// Add checksum
string checksum = IOUtils.CreateChecksum( IOUtils.SaveInThreadShaderBody );
IOUtils.SaveInThreadShaderBody += IOUtils.CHECKSUM + IOUtils.VALUE_SEPARATOR + checksum;
// Write to disk
StreamWriter fileWriter = new StreamWriter( IOUtils.SaveInThreadPathName );
try
{
fileWriter.Write( IOUtils.SaveInThreadShaderBody );
Debug.Log( "Saving complete" );
}
catch ( Exception e )
{
Debug.LogException( e );
}
finally
{
fileWriter.Close();
}
}
}
}
Debug.Log( "Thread closed" );
}
19
Source : IOUtils.cs
with MIT License
from alexismorin
with MIT License
from alexismorin
public static void SaveTextfileToDisk( string shaderBody, string pathName, bool addAdditionalInfo = true )
{
if ( addAdditionalInfo )
{
shaderBody = ShaderCopywriteMessage + shaderBody;
// Add checksum
string checksum = CreateChecksum( shaderBody );
shaderBody += CHECKSUM + VALUE_SEPARATOR + checksum;
}
// Write to disk
StreamWriter fileWriter = new StreamWriter( pathName );
try
{
fileWriter.Write( shaderBody );
}
catch ( Exception e )
{
Debug.LogException( e );
}
finally
{
fileWriter.Close();
}
}
19
Source : PythonScriptCreator.cs
with MIT License
from AlexLemminG
with MIT License
from AlexLemminG
internal static UnityEngine.Object CreateScriptreplacedetFromTemplate(string pathName, string resourceFile)
{
string fullPath = Path.GetFullPath(pathName);
string text = TemplateText;
// string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName);
// text = Regex.Replace(text, "#NAME#", fileNameWithoutExtension);
bool encoderShouldEmitUTF8Identifier = true;
bool throwOnInvalidBytes = false;
UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier, throwOnInvalidBytes);
bool append = false;
StreamWriter streamWriter = new StreamWriter(fullPath, append, encoding);
streamWriter.Write(text);
streamWriter.Close();
replacedetDatabase.Importreplacedet(pathName);
return replacedetDatabase.LoadreplacedetAtPath(pathName, typeof(UnityEngine.Object));
}
19
Source : AlertToPrice.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void Save()
{
try
{
using (StreamWriter writer = new StreamWriter(@"Engine\" + Name + @"Alert.txt", false))
{
writer.WriteLine(Message);
writer.WriteLine(IsOn);
writer.WriteLine(MessageIsOn);
writer.WriteLine(MusicType);
writer.WriteLine(SignalType);
writer.WriteLine(VolumeReaction);
writer.WriteLine(Slippage);
writer.WriteLine(NumberClosePosition);
writer.WriteLine(OrderPriceType);
writer.WriteLine(TypeActivation);
writer.WriteLine(PriceActivation);
writer.Close();
}
}
catch (Exception)
{
// ignore
}
}
19
Source : Aindicator.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void SaveParametrs()
{
if (Name == "")
{
return;
}
if (_parameters == null ||
_parameters.Count == 0)
{
return;
}
try
{
using (StreamWriter writer = new StreamWriter(@"Engine\" + Name + @"Parametrs.txt", false)
)
{
for (int i = 0; i < _parameters.Count; i++)
{
writer.WriteLine(_parameters[i].GetStringToSave());
}
writer.Close();
}
}
catch (Exception)
{
// ignore
}
}
19
Source : Aindicator.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
public void SaveSeries()
{
if (Name == "")
{
return;
}
if (DataSeries == null ||
DataSeries.Count == 0)
{
return;
}
try
{
using (StreamWriter writer = new StreamWriter(@"Engine\" + Name + @"Values.txt", false)
)
{
for (int i = 0; i < DataSeries.Count; i++)
{
writer.WriteLine(DataSeries[i].GetSaveStr());
}
writer.Close();
}
}
catch (Exception)
{
// ignore
}
}
See More Examples