Here are the examples of the csharp api System.IO.StreamReader.ReadLine() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2693 Examples
19
View Source File : XnaToFnaExt.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public static Thread AsyncPipeErr(this Process p, bool nullify = false) {
Thread t = nullify ?
new Thread(() => {
try { StreamReader err = p.StandardError; while (!p.HasExited) err.ReadLine(); } catch { }
}) {
Name = $"STDERR pipe thread for {p.ProcessName}",
IsBackground = true
} :
new Thread(() => {
try { StreamReader err = p.StandardError; while (!p.HasExited) Console.WriteLine(err.ReadLine()); } catch { }
}) {
Name = $"STDERR pipe thread for {p.ProcessName}",
IsBackground = true
};
t.Start();
return t;
}
19
View Source File : XnaToFnaExt.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public static Thread AsyncPipeOut(this Process p, bool nullify = false) {
Thread t = nullify ?
new Thread(() => {
try { StreamReader @out = p.StandardOutput; while (!p.HasExited) @out.ReadLine(); } catch { }
}) {
Name = $"STDOUT pipe thread for {p.ProcessName}",
IsBackground = true
} :
new Thread(() => {
try { StreamReader @out = p.StandardOutput; while (!p.HasExited) Console.WriteLine(@out.ReadLine()); } catch { }
}) {
Name = $"STDOUT pipe thread for {p.ProcessName}",
IsBackground = true
};
t.Start();
return t;
}
19
View Source File : RawFileType.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
private static string GetDCRawOptions()
{
string options = string.Empty;
using (StreamReader reader = new StreamReader(OptionsFilePath, System.Text.Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string trimmed = RemoveCommentsAndWhiteSpace(line);
if (trimmed.Length > 0)
{
options = trimmed;
break;
}
}
}
return options;
}
19
View Source File : VMFAdapter.cs
License : MIT License
Project Creator : 1upD
License : MIT License
Project Creator : 1upD
public NailsMap Import()
{
try {
// Reset adapter VMF
this._vmf = new VMF();
NailsMap map = new NailsMap();
List<string> lines = new List<string>();
using (StreamReader sr = new StreamReader(new FileStream(this._filename, FileMode.OpenOrCreate)))
{
while (!sr.EndOfStream)
{
lines.Add(sr.ReadLine());
}
}
VMF input_vmf = new VMF(lines.ToArray());
for (int blockIndex = 0; blockIndex < input_vmf.Body.Count; blockIndex++)
{
// Should this object be included when the VMF is output?
bool includeThisBlock = true;
// Get the next object from the VMF
var obj = input_vmf.Body[blockIndex];
try
{
// Try to cast to block
VMFParser.VBlock block = (VMFParser.VBlock)obj;
// If this block is an enreplacedy
if (block.Name == "enreplacedy")
{
var body = block.Body;
foreach (var innerObj in body) {
try
{
VMFParser.VProperty prop = (VMFParser.VProperty)innerObj;
// If this block is an instance
if (prop.Name == "clreplacedname" && prop.Value == "func_instance")
{
VProperty fileProperty = (VProperty)body.Where(p => p.Name == "file").ToList()[0];
var filePathParts = fileProperty.Value.Split('/');
// If this is a nails instance
if (filePathParts[0] == "Nails")
{
// Get position
VProperty originProperty = (VProperty)body.Where(p => p.Name == "origin").ToList()[0];
var originParts = originProperty.Value.Split(' ');
int x_pos = int.Parse(originParts[0]) / this._horizontal_scale;
int y_pos = int.Parse(originParts[1]) / this._horizontal_scale;
int z_pos = int.Parse(originParts[2]) / this._vertical_scale;
string style = filePathParts[1];
map.MarkLocation(style, x_pos, y_pos, z_pos);
// Remove this block from the vmf
includeThisBlock = false;
}
break;
}
} catch (InvalidCastException e)
{
log.Error("Invalid cast exception. VMF Object is not a VProperty.", e);
}
}
}
} catch(InvalidCastException e)
{
log.Error("Invalid cast exception. VMF object is not a VBlock.", e);
}
// If this object is not a Nails block, add it to the adapter's VMF to be output later
if (includeThisBlock)
{
this._vmf.Body.Add(obj);
}
}
return map;
} catch (Exception e)
{
log.Error("VMFAdapter.Import(): Caught exception: ", e);
log.Info(string.Format("Failed to read from VMF file: {0}", this._filename));
}
return null;
}
19
View Source File : GrblCodeTranslator.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
private static void LoadBuildCoads(Dictionary<string, string> dict, string path)
{
if (!File.Exists(path))
{
MainWindow.Logger.Warn("Build Code File Missing: {0}", path);
}
try
{
using (var reader = new StreamReader(path))
{
while (!reader.EndOfStream)
{
// Todo Remove Header -> First line
reader.ReadLine(); // Read and Discard Header line
var line = reader.ReadLine().Replace("\"", ""); // Remove " from each line
var values = line.Split(','); // Split into Values - values[0] Code, values[1] Desc, values [2] Enabled/Disabled
dict.Add(values[0], values[1] + " " + values[2]); // Add to BuildCodes Dictionary
}
}
}
catch (Exception ex)
{
MainWindow.Logger.Error(ex.Message);
return;
}
}
19
View Source File : Svc.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
public string ReadLine()
{
lock(sync)
{
++nline;
return stream?.ReadLine();
}
}
19
View Source File : DateAndSizeRollingFileAppenderTests.cs
License : MIT License
Project Creator : Abc-Arbitrage
License : MIT License
Project Creator : Abc-Arbitrage
private string GetLastLine()
{
var reader = new StreamReader(File.Open(_appender.CurrentFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
string written = null;
while (!reader.EndOfStream)
{
written = reader.ReadLine();
}
return written;
}
19
View Source File : PackageManifestUpdater.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
internal static bool IsMSBuildForUnityEnabled()
{
string manifestPath = GetPackageManifestFilePath();
if (string.IsNullOrWhiteSpace(manifestPath))
{
return false;
}
// Load the manifest file.
string manifestFileContents = File.ReadAllText(manifestPath);
if (string.IsNullOrWhiteSpace(manifestFileContents))
{
return false;
}
// Read the package manifest a line at a time.
using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(manifestStream))
{
// Read the manifest file a line at a time.
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (line.Contains(MSBuildPackageName))
{
// Split the line into packageName : packageVersion
string[] lineComponents = line.Split(new char[] { ':' }, 2);
return IsAppropriateMBuildVersion(MSBuildPackageVersion, lineComponents[1]);
}
}
}
}
return false;
}
19
View Source File : PackageManifestUpdater.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
internal static void EnsureMSBuildForUnity()
{
PackageManifest manifest = null;
string manifestPath = GetPackageManifestFilePath();
if (string.IsNullOrWhiteSpace(manifestPath))
{
return;
}
// Read the package manifest into a list of strings (for easy finding of entries)
// and then deserialize.
List<string> manifestFileLines = new List<string>();
using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(manifestStream))
{
// Read the manifest file a line at a time.
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
manifestFileLines.Add(line);
}
// Go back to the start of the file.
manifestStream.Seek(0, 0);
// Deserialize the scoped registries portion of the package manifest.
manifest = JsonUtility.FromJson<PackageManifest>(reader.ReadToEnd());
}
}
if (manifest == null)
{
Debug.LogError($"Failed to read the package manifest file ({manifestPath})");
return;
}
// Ensure that pre-existing scoped registries are retained.
List<ScopedRegistry> scopedRegistries = new List<ScopedRegistry>();
if ((manifest.scopedRegistries != null) && (manifest.scopedRegistries.Length > 0))
{
scopedRegistries.AddRange(manifest.scopedRegistries);
}
// Attempt to find an entry in the scoped registries collection for the MSBuild for Unity URL
bool needToAddRegistry = true;
foreach (ScopedRegistry registry in scopedRegistries)
{
if (registry.url == MSBuildRegistryUrl)
{
needToAddRegistry = false;
}
}
// If no entry was found, add one.
if (needToAddRegistry)
{
ScopedRegistry registry = new ScopedRegistry();
registry.name = MSBuildRegistryName;
registry.url = MSBuildRegistryUrl;
registry.scopes = MSBuildRegistryScopes;
scopedRegistries.Add(registry);
}
// Update the manifest's scoped registries, as the collection may have been modified.
manifest.scopedRegistries = scopedRegistries.ToArray();
int dependenciesStartIndex = -1;
int scopedRegistriesStartIndex = -1;
int scopedRegistriesEndIndex = -1;
int packageLine = -1;
// Presume that we need to add the MSBuild for Unity package. If this value is false,
// we will check to see if the currently configured version meets or exceeds the
// minimum requirements.
bool needToAddPackage = true;
// Attempt to find the MSBuild for Unity package entry in the dependencies collection
// This loop also identifies the dependencies collection line and the start / end of a
// pre-existing scoped registries collections
for (int i = 0; i < manifestFileLines.Count; i++)
{
if (manifestFileLines[i].Contains("\"scopedRegistries\":"))
{
scopedRegistriesStartIndex = i;
}
if (manifestFileLines[i].Contains("],") && (scopedRegistriesStartIndex != -1) && (scopedRegistriesEndIndex == -1))
{
scopedRegistriesEndIndex = i;
}
if (manifestFileLines[i].Contains("\"dependencies\": {"))
{
dependenciesStartIndex = i;
}
if (manifestFileLines[i].Contains(MSBuildPackageName))
{
packageLine = i;
needToAddPackage = false;
}
}
// If no package was found add it to the dependencies collection.
if (needToAddPackage)
{
// Add the package to the collection (pad the entry with four spaces)
manifestFileLines.Insert(dependenciesStartIndex + 1, $" \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",");
}
else
{
// Replace the line that currently exists
manifestFileLines[packageLine] = $" \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",";
}
// Update the manifest file.
// First, serialize the scoped registry collection.
string serializedRegistriesJson = JsonUtility.ToJson(manifest, true);
// Ensure that the file is truncated to ensure it is always valid after writing.
using (FileStream outFile = new FileStream(manifestPath, FileMode.Truncate, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(outFile))
{
bool scopedRegistriesWritten = false;
// Write each line of the manifest back to the file.
for (int i = 0; i < manifestFileLines.Count; i++)
{
if ((i >= scopedRegistriesStartIndex) && (i <= scopedRegistriesEndIndex))
{
// Skip these lines, they will be replaced.
continue;
}
if (!scopedRegistriesWritten && (i > 0))
{
// Trim the leading '{' and '\n' from the serialized scoped registries
serializedRegistriesJson = serializedRegistriesJson.Remove(0, 2);
// Trim, the trailing '\n' and '}'
serializedRegistriesJson = serializedRegistriesJson.Remove(serializedRegistriesJson.Length - 2);
// Append a trailing ',' to close the scopedRegistries node
serializedRegistriesJson = serializedRegistriesJson.Insert(serializedRegistriesJson.Length, ",");
writer.WriteLine(serializedRegistriesJson);
scopedRegistriesWritten = true;
}
writer.WriteLine(manifestFileLines[i]);
}
}
}
}
19
View Source File : LeapMotionConfigurationChecker.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
[MenuItem("Mixed Reality Toolkit/Utilities/Leap Motion/Configure CSC File for Leap Motion")]
static void UpdateCSC()
{
// The csc file will always be in the root of replacedets
string cscFilePath = Path.Combine(Application.dataPath, "csc.rsp");
// Each line of the csc file
List<string> cscFileLines = new List<string>();
// List of the warning numbers after "-nowarn: " in the csc file
List<string> warningNumbers = new List<string>();
// List of new warning numbers to add to the csc file
List<string> warningNumbersToAdd = new List<string>()
{
"618",
"649"
};
using (StreamReader streamReader = new StreamReader(cscFilePath))
{
while (streamReader.Peek() > -1)
{
string cscFileLine = streamReader.ReadLine();
if (cscFileLine.Contains("-nowarn"))
{
string[] currentWarningNumbers = cscFileLine.Split(',', ':');
warningNumbers = currentWarningNumbers.ToList();
// Remove "nowarn" from the warningNumbers list
warningNumbers.Remove("-nowarn");
foreach (string warningNumberToAdd in warningNumbersToAdd)
{
// Add the new warning numbers if they are not already in the file
if (!warningNumbers.Contains(warningNumberToAdd))
{
warningNumbers.Add(warningNumberToAdd);
}
}
cscFileLines.Add(string.Join(",", warningNumbers));
}
else
{
cscFileLines.Add(cscFileLine);
}
}
}
using (StreamWriter streamWriter = new StreamWriter(cscFilePath))
{
foreach (string cscLine in cscFileLines)
{
if (cscLine.StartsWith("1701"))
{
string warningNumbersJoined = string.Join(",", warningNumbers);
streamWriter.WriteLine(string.Concat("-nowarn:", warningNumbersJoined));
}
else
{
streamWriter.WriteLine(cscLine);
}
}
}
Debug.Log($"Saving {cscFilePath}");
}
19
View Source File : LeapMotionConfigurationChecker.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static bool LeapCorereplacedetsVersionSupport()
{
string versionLeapPath = Path.Combine(Application.dataPath, pathDifference, "LeapMotion", "Core", "Version.txt");
using (StreamReader streamReader = new StreamReader(versionLeapPath))
{
while (streamReader.Peek() > -1)
{
string line = streamReader.ReadLine();
foreach (string versionNumberSupported in leapCorereplacedetsVersionsSupported)
{
// If the leap core replacedets version number is supported
if (line.Contains(versionNumberSupported))
{
currentLeapCorereplacedetsVersion = versionNumberSupported;
return true;
}
}
}
return false;
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : abock
License : MIT License
Project Creator : abock
static async IAsyncEnumerable<string> DownloadAsync(
[EnumeratorCancellation]CancellationToken cancellationToken)
{
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(
unicodeEmojiTestsUrl,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken);
response.EnsureSuccessStatusCode();
var encodingName = response
.Content
.Headers
.ContentType
?.CharSet ?? "utf-8";
var encoding = Encoding.GetEncoding(encodingName);
var stream = await response.Content.ReadreplacedtreamAsync();
var reader = new StreamReader(stream, encoding);
while (true)
{
var line = reader.ReadLine();
if (line is null)
break;
yield return line;
}
}
19
View Source File : OVRSceneLoader.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
private SceneInfo GetSceneInfo()
{
SceneInfo sceneInfo = new SceneInfo();
try
{
StreamReader reader = new StreamReader(sceneLoadDataPath);
sceneInfo.version = System.Convert.ToInt64(reader.ReadLine());
List<string> sceneList = new List<string>();
while (!reader.EndOfStream)
{
sceneList.Add(reader.ReadLine());
}
sceneInfo.scenes = sceneList;
}
catch
{
logTextBox.text += "<color=red>Failed to get scene info data.\n</color>";
}
return sceneInfo;
}
19
View Source File : AscReader.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static float[] ReadFloats(StreamReader file, string separator, float noDataValue)
{
string line = file.ReadLine();
float[] values = line.Split(new[] {separator}, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
float rawValue = float.Parse(x, NumberFormatInfo.InvariantInfo);
return rawValue.CompareTo(noDataValue) == 0 ? float.NaN : rawValue;
} ).ToArray();
return values;
}
19
View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public DoubleSeries GetAcousticChannel(int channelNumber)
{
if (channelNumber > 7)
throw new InvalidOperationException("Only channels 0-7 allowed");
if (_acousticPlotData.Count != 0)
{
return _acousticPlotData[channelNumber];
}
// e.g. resource format: SciChart.Examples.ExternalDependencies.Resources.Data.EURUSD_Daily.csv
var csvResource = string.Format("{0}.{1}", ResourceDirectory, "AcousticPlots.csv.gz");
var ch0 = new DoubleSeries(100000);
var ch1 = new DoubleSeries(100000);
var ch2 = new DoubleSeries(100000);
var ch3 = new DoubleSeries(100000);
var ch4 = new DoubleSeries(100000);
var ch5 = new DoubleSeries(100000);
var ch6 = new DoubleSeries(100000);
var ch7 = new DoubleSeries(100000);
var replacedembly = typeof(DataManager).replacedembly;
using (var stream = replacedembly.GetManifestResourceStream(csvResource))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
line = streamReader.ReadLine();
while (line != null)
{
// Line Format:
// Date, Open, High, Low, Close, Volume
// 2007.07.02 03:30, 1.35310, 1.35310, 1.35280, 1.35310, 12
var tokens = line.Split(',');
double x = double.Parse(tokens[0], NumberFormatInfo.InvariantInfo);
double y0 = double.Parse(tokens[1], NumberFormatInfo.InvariantInfo);
double y1 = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo);
double y2 = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo);
double y3 = double.Parse(tokens[4], NumberFormatInfo.InvariantInfo);
double y4 = double.Parse(tokens[5], NumberFormatInfo.InvariantInfo);
double y5 = double.Parse(tokens[6], NumberFormatInfo.InvariantInfo);
double y6 = double.Parse(tokens[7], NumberFormatInfo.InvariantInfo);
double y7 = double.Parse(tokens[8], NumberFormatInfo.InvariantInfo);
ch0.Add(new XYPoint() { X = x, Y = y0 });
ch1.Add(new XYPoint() { X = x, Y = y1 });
ch2.Add(new XYPoint() { X = x, Y = y2 });
ch3.Add(new XYPoint() { X = x, Y = y3 });
ch4.Add(new XYPoint() { X = x, Y = y4 });
ch5.Add(new XYPoint() { X = x, Y = y5 });
ch6.Add(new XYPoint() { X = x, Y = y6 });
ch7.Add(new XYPoint() { X = x, Y = y7 });
line = streamReader.ReadLine();
}
}
_acousticPlotData.AddRange(new[] { ch0, ch1, ch2, ch3, ch4, ch5, ch6, ch7});
return _acousticPlotData[channelNumber];
}
19
View Source File : AscReader.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static int ReadInt(StreamReader file, string prefix)
{
string line = file.ReadLine();
line = line.Replace(prefix, string.Empty).Trim();
return int.Parse(line, NumberFormatInfo.InvariantInfo);
}
19
View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public PriceSeries GetPriceData(string dataset)
{
if (_dataSets.ContainsKey(dataset))
{
return _dataSets[dataset];
}
// e.g. resource format: SciChart.Examples.ExternalDependencies.Resources.Data.EURUSD_Daily.csv
var csvResource = string.Format("{0}.{1}", ResourceDirectory, Path.ChangeExtension(dataset, "csv.gz"));
var priceSeries = new PriceSeries();
priceSeries.Symbol = dataset;
var replacedembly = typeof(DataManager).replacedembly;
// Debug.WriteLine(string.Join(", ", replacedembly.GetManifestResourceNames()));
using (var stream = replacedembly.GetManifestResourceStream(csvResource))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
var priceBar = new PriceBar();
// Line Format:
// Date, Open, High, Low, Close, Volume
// 2007.07.02 03:30, 1.35310, 1.35310, 1.35280, 1.35310, 12
var tokens = line.Split(',');
priceBar.DateTime = DateTime.Parse(tokens[0], DateTimeFormatInfo.InvariantInfo);
priceBar.Open = double.Parse(tokens[1], NumberFormatInfo.InvariantInfo);
priceBar.High = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo);
priceBar.Low = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo);
priceBar.Close = double.Parse(tokens[4], NumberFormatInfo.InvariantInfo);
priceBar.Volume = long.Parse(tokens[5], NumberFormatInfo.InvariantInfo);
priceSeries.Add(priceBar);
line = streamReader.ReadLine();
}
}
_dataSets.Add(dataset, priceSeries);
return priceSeries;
}
19
View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public IEnumerable<Tick> GetTicks()
{
// e.g. resource format: SciChart.Examples.ExternalDependencies.Resources.Data.EURUSD_Daily.csv
var csvResourceZipped = string.Format("{0}.{1}", ResourceDirectory, "TickData.csv.gz");
var ticks = new List<Tick>();
var replacedembly = typeof(DataManager).replacedembly;
// Debug.WriteLine(string.Join(", ", replacedembly.GetManifestResourceNames()));
using (var stream = replacedembly.GetManifestResourceStream(csvResourceZipped))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
var tick = new Tick();
// Line Format:
// Date, Open, High, Low, Close, Volume
// 2007.07.02 03:30, 1.35310, 1.35310, 1.35280, 1.35310, 12
var tokens = line.Split(',');
tick.DateTime = DateTime.Parse(tokens[0], DateTimeFormatInfo.InvariantInfo) +
TimeSpan.Parse(tokens[1], DateTimeFormatInfo.InvariantInfo);
tick.Open = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo);
tick.High = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo);
tick.Low = double.Parse(tokens[4], NumberFormatInfo.InvariantInfo);
tick.Close = double.Parse(tokens[5], NumberFormatInfo.InvariantInfo);
tick.Volume = long.Parse(tokens[7], NumberFormatInfo.InvariantInfo);
ticks.Add(tick);
line = streamReader.ReadLine();
}
}
return ticks;
}
19
View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public IList<VitalSignsData> GetVitalSignsData()
{
var csvResourceZipped = string.Format("{0}.{1}", ResourceDirectory, "VitalSignsTrace.csv.gz");
var vitalSignsData = new List<VitalSignsData>();
var replacedembly = typeof(DataManager).replacedembly;
using (var stream = replacedembly.GetManifestResourceStream(csvResourceZipped))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
// Line Format:
// XValue, HeartRate, BloodPressure, BloodVolume, BloodOxygenation
// 3.12833, 0.873118, 0.625403, 0.209285, 0.100243
var tokens = line.Split(',');
vitalSignsData.Add(new VitalSignsData
{
XValue = double.Parse(tokens[0], NumberFormatInfo.InvariantInfo),
ECGHeartRate = double.Parse(tokens[1], NumberFormatInfo.InvariantInfo),
BloodPressure = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo),
BloodVolume = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo),
BloodOxygenation = double.Parse(tokens[4], NumberFormatInfo.InvariantInfo)
});
line = streamReader.ReadLine();
}
}
return vitalSignsData;
}
19
View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public IEnumerable<TradeData> GetTradeticks()
{
var dataSource = new List<TradeData>();
var asm = replacedembly.GetExecutingreplacedembly();
var csvResource = asm.GetManifestResourceNames().Single(x => x.ToUpper(CultureInfo.InvariantCulture).Contains("TRADETICKS.CSV.GZ"));
using (var stream = asm.GetManifestResourceStream(csvResource))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
var data = new TradeData();
// Line Format:
// Date, Open, High, Low, Close, Volume
// 2007.07.02 03:30, 1.35310, 1.35310, 1.35280, 1.35310, 12
var tokens = line.Split(',');
data.TradeDate = DateTime.Parse(tokens[0], DateTimeFormatInfo.InvariantInfo);
data.TradePrice = double.Parse(tokens[1], NumberFormatInfo.InvariantInfo);
data.TradeSize = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo);
dataSource.Add(data);
line = streamReader.ReadLine();
}
}
return dataSource;
}
19
View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public List<WeatherData> LoadWeatherData()
{
var values = new List<WeatherData>();
var asm = replacedembly.GetExecutingreplacedembly();
var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains("WeatherData.txt.gz"));
using (var stream = asm.GetManifestResourceStream(resourceString))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
var tokens = line.Split(',');
values.Add(new WeatherData
{
// ID, Date, MinTemp, MaxTemp, Rainfall, Sunshine, UVIndex, WindSpd, WindDir, Forecast, LocalStation
ID = int.Parse(tokens[0], NumberFormatInfo.InvariantInfo),
Date = DateTime.Parse(tokens[1], DateTimeFormatInfo.InvariantInfo),
MinTemp = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo),
MaxTemp = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo),
Rainfall = double.Parse(tokens[4], NumberFormatInfo.InvariantInfo),
Sunshine = double.Parse(tokens[5], NumberFormatInfo.InvariantInfo),
UVIndex = int.Parse(tokens[6], NumberFormatInfo.InvariantInfo),
WindSpeed = int.Parse(tokens[7], NumberFormatInfo.InvariantInfo),
WindDirection = (WindDirection) Enum.Parse(typeof(WindDirection), tokens[8]),
Forecast = tokens[9],
LocalStation = bool.Parse(tokens[10])
});
line = streamReader.ReadLine();
}
}
return values;
}
19
View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public double[] LoadWaveformData()
{
var values = new List<double>();
var asm = replacedembly.GetExecutingreplacedembly();
var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains("Waveform.txt.gz"));
using (var stream = asm.GetManifestResourceStream(resourceString))
using (var gz = new GZipStream(stream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(gz))
{
string line = streamReader.ReadLine();
while (line != null)
{
values.Add(double.Parse(line, NumberFormatInfo.InvariantInfo));
line = streamReader.ReadLine();
}
}
return values.ToArray();
}
19
View Source File : AscReader.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static int ReadInt(StreamReader file, string prefix)
{
string line = file.ReadLine();
line = line.Replace(prefix, "").Trim();
return int.Parse(line, CultureInfo.InvariantCulture);
}
19
View Source File : AscReader.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static float[] ReadFloats(StreamReader file, string separator, float noDataValue)
{
string line = file.ReadLine();
float[] values = line.Split(new[] {separator}, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
float rawValue = float.Parse(x, CultureInfo.InvariantCulture);
return rawValue.CompareTo(noDataValue) == 0 ? float.NaN : rawValue;
} ).ToArray();
return values;
}
19
View Source File : SweepingEcg.xaml.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private double[] LoadWaveformData(string filename)
{
var values = new List<double>();
// Load the waveform.csv file for the source data
var asm = typeof (SweepingEcg).replacedembly;
var resourceString = asm.GetManifestResourceNames().Single(x => x.Contains(filename));
using (var stream = asm.GetManifestResourceStream(resourceString))
using (var streamReader = new StreamReader(stream))
{
string line = streamReader.ReadLine();
while (line != null)
{
values.Add(double.Parse(line, NumberFormatInfo.InvariantInfo));
line = streamReader.ReadLine();
}
}
return values.ToArray();
}
19
View Source File : MutationCache.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static List<string> ReadScript(string filename)
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
var resourceName = prefix + filename.Replace('/', '.');
using (var stream = replacedembly.GetManifestResourceStream(resourceName))
{
if (stream == null) return null;
var lines = new List<string>();
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
lines.Add(reader.ReadLine());
}
return lines;
}
}
19
View Source File : Program_DbUpdates.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static void UpdateToLatestWorldDatabase(string dbURL, string dbFileName)
{
Console.WriteLine();
if (IsRunningInContainer)
{
Console.WriteLine(" ");
Console.WriteLine("This process will take a while, depending on many factors, and may look stuck while reading and importing the world database, please be patient! ");
Console.WriteLine(" ");
}
Console.Write($"Downloading {dbFileName} .... ");
using (var client = new WebClient())
{
try
{
client.DownloadFile(dbURL, dbFileName);
}
catch
{
Console.Write($"Download for {dbFileName} failed!");
return;
}
}
Console.WriteLine("download complete!");
Console.Write($"Extracting {dbFileName} .... ");
ZipFile.ExtractToDirectory(dbFileName, ".", true);
Console.WriteLine("extraction complete!");
Console.Write($"Deleting {dbFileName} .... ");
File.Delete(dbFileName);
Console.WriteLine("Deleted!");
var sqlFile = dbFileName.Substring(0, dbFileName.Length - 4);
Console.Write($"Importing {sqlFile} into SQL server at {ConfigManager.Config.MySql.World.Host}:{ConfigManager.Config.MySql.World.Port} (This will take a while, please be patient) .... ");
using (var sr = File.OpenText(sqlFile))
{
var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={ConfigManager.Config.MySql.World.Host};port={ConfigManager.Config.MySql.World.Port};user={ConfigManager.Config.MySql.World.Username};preplacedword={ConfigManager.Config.MySql.World.Preplacedword};DefaultCommandTimeout=120");
var line = string.Empty;
var completeSQLline = string.Empty;
var dbname = ConfigManager.Config.MySql.World.Database;
while ((line = sr.ReadLine()) != null)
{
line = line.Replace("ace_world", dbname);
//do minimal amount of work here
if (line.EndsWith(";"))
{
completeSQLline += line + Environment.NewLine;
var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, completeSQLline);
try
{
script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
var count = script.Execute();
}
catch (MySql.Data.MySqlClient.MySqlException)
{
}
completeSQLline = string.Empty;
}
else
completeSQLline += line + Environment.NewLine;
}
}
Console.WriteLine(" complete!");
Console.Write($"Deleting {sqlFile} .... ");
File.Delete(sqlFile);
Console.WriteLine("Deleted!");
}
19
View Source File : Program_Setup.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
private static void DoOutOfBoxSetup(string configFile)
{
var exeLocation = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location);
var configJsExample = Path.Combine(exeLocation, "Config.js.example");
var exampleFile = new FileInfo(configJsExample);
if (!exampleFile.Exists)
{
log.Error("config.js.example Configuration file is missing. Please copy the file config.js.example to config.js and edit it to match your needs before running ACE.");
throw new Exception("missing config.js configuration file");
}
else
{
if (!IsRunningInContainer)
{
Console.WriteLine("config.js Configuration file is missing, cloning from example file.");
File.Copy(configJsExample, configFile, true);
}
else
{
Console.WriteLine("config.js Configuration file is missing, ACEmulator is running in a container, cloning from docker file.");
var configJsDocker = Path.Combine(exeLocation, "Config.js.docker");
File.Copy(configJsDocker, configFile, true);
}
}
var fileText = File.ReadAllText(configFile);
var config = JsonConvert.DeserializeObject<MasterConfiguration>(new JsMinifier().Minify(fileText));
Console.WriteLine("Performing setup for ACEmulator...");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Welcome to ACEmulator! To configure your world for first use, please follow the instructions below. Press enter at each prompt to accept default values.");
Console.WriteLine();
Console.WriteLine();
Console.Write($"Enter the name for your World (default: \"{config.Server.WorldName}\"): ");
var variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_WORLD_NAME");
if (!string.IsNullOrWhiteSpace(variable))
config.Server.WorldName = variable.Trim();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("The next two entries should use defaults, unless you have specific network environments...");
Console.WriteLine();
Console.WriteLine();
Console.Write($"Enter the Host address for your World (default: \"{config.Server.Network.Host}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.Server.Network.Host = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the Port for your World (default: \"{config.Server.Network.Port}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.Server.Network.Port = Convert.ToUInt32(variable.Trim());
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write($"Enter the directory location for your DAT files (default: \"{config.Server.DatFilesDirectory}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_DAT_FILES_DIRECTORY");
if (!string.IsNullOrWhiteSpace(variable))
{
var path = Path.GetFullPath(variable.Trim());
if (!Path.EndsInDirectorySeparator(path))
path += Path.DirectorySeparatorChar;
//path = path.Replace($"{Path.DirectorySeparatorChar}", $"{Path.DirectorySeparatorChar}{Path.DirectorySeparatorChar}");
config.Server.DatFilesDirectory = path;
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Next we will configure your SQL server connections. You will need to know your database name, username and preplacedword for each.");
Console.WriteLine("Default names for the databases are recommended, and it is also recommended you not use root for login to database. The preplacedword must not be blank.");
Console.WriteLine("It is also recommended the SQL server be hosted on the same machine as this server, so defaults for Host and Port would be ideal as well.");
Console.WriteLine("As before, pressing enter will use default value.");
Console.WriteLine();
Console.WriteLine();
Console.Write($"Enter the database name for your authentication database (default: \"{config.MySql.Authentication.Database}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_NAME");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Database = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the database name for your shard database (default: \"{config.MySql.Shard.Database}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_NAME");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Database = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the database name for your world database (default: \"{config.MySql.World.Database}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_NAME");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Database = variable.Trim();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write("Typically, all three databases will be on the same SQL server, is this how you want to proceed? (Y/n) ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = "n";
if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
{
Console.Write($"Enter the Host address for your SQL server (default: \"{config.MySql.World.Host}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
{
config.MySql.Authentication.Host = variable.Trim();
config.MySql.Shard.Host = variable.Trim();
config.MySql.World.Host = variable.Trim();
}
Console.WriteLine();
Console.Write($"Enter the Port for your SQL server (default: \"{config.MySql.World.Port}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
{
config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
}
Console.WriteLine();
}
else
{
Console.Write($"Enter the Host address for your authentication database (default: \"{config.MySql.Authentication.Host}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_HOST");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Host = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the Port for your authentication database (default: \"{config.MySql.Authentication.Port}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_PORT");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
Console.WriteLine();
Console.Write($"Enter the Host address for your shard database (default: \"{config.MySql.Shard.Host}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_HOST");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Host = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the Port for your shard database (default: \"{config.MySql.Shard.Port}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_PORT");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
Console.WriteLine();
Console.Write($"Enter the Host address for your world database (default: \"{config.MySql.World.Host}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_HOST");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Host = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the Port for your world database (default: \"{config.MySql.World.Port}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_PORT");
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine();
Console.Write("Typically, all three databases will be on the using the same SQL server credentials, is this how you want to proceed? (Y/n) ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = "y";
if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
{
Console.Write($"Enter the username for your SQL server (default: \"{config.MySql.World.Username}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_USER");
if (!string.IsNullOrWhiteSpace(variable))
{
config.MySql.Authentication.Username = variable.Trim();
config.MySql.Shard.Username = variable.Trim();
config.MySql.World.Username = variable.Trim();
}
Console.WriteLine();
Console.Write($"Enter the preplacedword for your SQL server (default: \"{config.MySql.World.Preplacedword}\"): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_PreplacedWORD");
if (!string.IsNullOrWhiteSpace(variable))
{
config.MySql.Authentication.Preplacedword = variable.Trim();
config.MySql.Shard.Preplacedword = variable.Trim();
config.MySql.World.Preplacedword = variable.Trim();
}
}
else
{
Console.Write($"Enter the username for your authentication database (default: \"{config.MySql.Authentication.Username}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Username = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the preplacedword for your authentication database (default: \"{config.MySql.Authentication.Preplacedword}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Authentication.Preplacedword = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the username for your shard database (default: \"{config.MySql.Shard.Username}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Username = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the preplacedword for your shard database (default: \"{config.MySql.Shard.Preplacedword}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.Shard.Preplacedword = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the username for your world database (default: \"{config.MySql.World.Username}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Username = variable.Trim();
Console.WriteLine();
Console.Write($"Enter the preplacedword for your world database (default: \"{config.MySql.World.Preplacedword}\"): ");
variable = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(variable))
config.MySql.World.Preplacedword = variable.Trim();
}
Console.WriteLine("commiting configuration to memory...");
using (StreamWriter file = File.CreateText(configFile))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;
//serializer.NullValueHandling = NullValueHandling.Ignore;
//serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
serializer.Serialize(file, config);
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write("Do you want to ACEmulator to attempt to initilize your SQL databases? This will erase any existing ACEmulator specific databases that may already exist on the server (Y/n): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_INITIALIZE_DATABASES")) ? "y" : "n";
if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine();
Console.Write($"Waiting for connection to SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
for (; ; )
{
try
{
using (var sqlTestConnection = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120"))
{
Console.Write(".");
sqlTestConnection.Open();
}
break;
}
catch (MySql.Data.MySqlClient.MySqlException)
{
Console.Write(".");
Thread.Sleep(5000);
}
}
Console.WriteLine(" connected!");
if (IsRunningInContainer)
{
Console.Write("Clearing out temporary ace% database .... ");
var sqlDBFile = "DROP DATABASE `ace%`;";
var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);
Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
try
{
script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
var count = script.Execute();
}
catch (MySql.Data.MySqlClient.MySqlException)
{
}
Console.WriteLine(" done!");
}
Console.WriteLine("Searching for base SQL scripts .... ");
foreach (var file in new DirectoryInfo($"DatabaseSetupScripts{Path.DirectorySeparatorChar}Base").GetFiles("*.sql").OrderBy(f => f.Name))
{
Console.Write($"Found {file.Name} .... ");
var sqlDBFile = File.ReadAllText(file.FullName);
var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
switch (file.Name)
{
case "AuthenticationBase":
sqlConnectInfo = $"server={config.MySql.Authentication.Host};port={config.MySql.Authentication.Port};user={config.MySql.Authentication.Username};preplacedword={config.MySql.Authentication.Preplacedword};DefaultCommandTimeout=120";
break;
case "ShardBase":
sqlConnectInfo = $"server={config.MySql.Shard.Host};port={config.MySql.Shard.Port};user={config.MySql.Shard.Username};preplacedword={config.MySql.Shard.Preplacedword};DefaultCommandTimeout=120";
break;
}
var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);
Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
try
{
script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
var count = script.Execute();
}
catch (MySql.Data.MySqlClient.MySqlException)
{
}
Console.WriteLine(" complete!");
}
Console.WriteLine("Base SQL scripts import complete!");
Console.WriteLine("Searching for Update SQL scripts .... ");
PatchDatabase("Authentication", config.MySql.Authentication.Host, config.MySql.Authentication.Port, config.MySql.Authentication.Username, config.MySql.Authentication.Preplacedword, config.MySql.Authentication.Database);
PatchDatabase("Shard", config.MySql.Shard.Host, config.MySql.Shard.Port, config.MySql.Shard.Username, config.MySql.Shard.Preplacedword, config.MySql.Shard.Database);
PatchDatabase("World", config.MySql.World.Host, config.MySql.World.Port, config.MySql.World.Username, config.MySql.World.Preplacedword, config.MySql.World.Database);
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write("Do you want to download the latest world database and import it? (Y/n): ");
variable = Console.ReadLine();
if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_DOWNLOAD_LATEST_WORLD_RELEASE")) ? "y" : "n";
if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine();
if (IsRunningInContainer)
{
Console.WriteLine(" ");
Console.WriteLine("This process will take a while, depending on many factors, and may look stuck while reading and importing the world database, please be patient! ");
Console.WriteLine(" ");
}
Console.Write("Looking up latest release from ACEmulator/ACE-World-16PY-Patches .... ");
// webrequest code provided by OptimShi
var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
var request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = "Mozilla//5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko//20100101 Firefox//72.0";
request.UserAgent = "ACE.Server";
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
var html = reader.ReadToEnd();
reader.Close();
response.Close();
dynamic json = JsonConvert.DeserializeObject(html);
string tag = json[0].tag_name;
string dbURL = json[0].replacedets[0].browser_download_url;
string dbFileName = json[0].replacedets[0].name;
// webrequest code provided by OptimShi
Console.WriteLine($"Found {tag} !");
Console.Write($"Downloading {dbFileName} .... ");
using (var client = new WebClient())
{
client.DownloadFile(dbURL, dbFileName);
}
Console.WriteLine("download complete!");
Console.Write($"Extracting {dbFileName} .... ");
ZipFile.ExtractToDirectory(dbFileName, ".", true);
Console.WriteLine("extraction complete!");
Console.Write($"Deleting {dbFileName} .... ");
File.Delete(dbFileName);
Console.WriteLine("Deleted!");
var sqlFile = dbFileName.Substring(0, dbFileName.Length - 4);
Console.Write($"Importing {sqlFile} into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} (This will take a while, please be patient) .... ");
using (var sr = File.OpenText(sqlFile))
{
var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120");
var line = string.Empty;
var completeSQLline = string.Empty;
while ((line = sr.ReadLine()) != null)
{
//do minimal amount of work here
if (line.EndsWith(";"))
{
completeSQLline += line + Environment.NewLine;
var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, completeSQLline);
try
{
script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
var count = script.Execute();
}
catch (MySql.Data.MySqlClient.MySqlException)
{
}
completeSQLline = string.Empty;
}
else
completeSQLline += line + Environment.NewLine;
}
}
Console.WriteLine(" complete!");
Console.Write($"Deleting {sqlFile} .... ");
File.Delete(sqlFile);
Console.WriteLine("Deleted!");
}
Console.WriteLine("exiting setup for ACEmulator.");
}
19
View Source File : ProcessInvoker.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private void StartReadStream(StreamReader reader, ConcurrentQueue<string> dataBuffer)
{
Task.Run(() =>
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (line != null)
{
dataBuffer.Enqueue(line);
_outputProcessEvent.Set();
}
}
Trace.Info("STDOUT/STDERR stream read finished.");
if (Interlocked.Decrement(ref _asyncStreamReaderCount) == 0 && _waitingOnStreams)
{
_processExitedCompletionSource.TrySetResult(true);
_processStandardInWriteCancellationTokenSource.Cancel();
}
});
}
19
View Source File : PagingLoggerL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void WriteAndShipLog()
{
CleanLogFolder();
try
{
//Arrange
using (var hc = new TestHostContext(this))
{
var pagingLogger = new PagingLogger();
hc.SetSingleton<IJobServerQueue>(_jobServerQueue.Object);
pagingLogger.Initialize(hc);
Guid timeLineId = Guid.NewGuid();
Guid timeLineRecordId = Guid.NewGuid();
int totalBytes = PagesToWrite * PagingLogger.PageSize;
int bytesWritten = 0;
int logDataSize = System.Text.Encoding.UTF8.GetByteCount(LogData);
_jobServerQueue.Setup(x => x.QueueFileUpload(timeLineId, timeLineRecordId, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), true))
.Callback((Guid timelineId, Guid timelineRecordId, string type, string name, string path, bool deleteSource) =>
{
bool fileExists = File.Exists(path);
replacedert.True(fileExists);
using (var freader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read), System.Text.Encoding.UTF8))
{
string line;
while ((line = freader.ReadLine()) != null)
{
replacedert.EndsWith(LogData, line);
bytesWritten += logDataSize;
}
}
File.Delete(path);
});
//Act
int bytesSent = 0;
pagingLogger.Setup(timeLineId, timeLineRecordId);
while (bytesSent < totalBytes)
{
pagingLogger.Write(LogData);
bytesSent += logDataSize;
}
pagingLogger.End();
//replacedert
_jobServerQueue.Verify(x => x.QueueFileUpload(timeLineId, timeLineRecordId, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), true), Times.AtLeast(PagesToWrite));
replacedert.Equal(bytesSent, bytesWritten);
}
}
finally
{
//cleanup
CleanLogFolder();
}
}
19
View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 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
View Source File : UpdateManager.cs
License : MIT License
Project Creator : admaiorastudio
License : MIT License
Project Creator : admaiorastudio
private void KillRunningProcesses()
{
if (File.Exists(_processDatFilePath))
{
using (var s = File.OpenText(_processDatFilePath))
{
int processId = 0;
try
{
while(!s.EndOfStream)
{
processId = Int32.Parse(s.ReadLine());
if (processId == 0)
continue;
var process = Process.GetProcessById(processId);
if (process != null && !process.HasExited)
process.Kill();
}
}
catch (Exception ex)
{
if (processId != 0)
System.Diagnostics.Debug.WriteLine($"RealXaml was unable to kill process with id {processId}");
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
}
19
View Source File : RemotePost.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string PostAndGetResponseString(string url, NameValueCollection parameters)
{
if (string.IsNullOrWhiteSpace(url) || (parameters == null || !parameters.HasKeys()))
{
return string.Empty;
}
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
var postString = ConstructStringFromParameters(parameters);
var bytedata = Encoding.UTF8.GetBytes(postString);
httpRequest.ContentLength = bytedata.Length;
var requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
var httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
var responseStream = httpWebResponse.GetResponseStream();
var sb = new StringBuilder();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream, Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
}
}
return sb.ToString();
}
19
View Source File : File.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public virtual string ReadLine()
{
if (!info.Exists)
{
return string.Empty;
}
if (AlwaysOpen)
{
return textReader.ReadLine();
}
using (textReader = info.OpenText())
{
return textReader.ReadLine();
}
}
19
View Source File : UserSettings.cs
License : MIT License
Project Creator : Aeroblast
License : MIT License
Project Creator : Aeroblast
public static void ReadSettings()
{
if (File.Exists(fontSetting))
{
string line;
using (var file = new StreamReader(fontSetting))
while ((line = file.ReadLine()) != null)
{
string[] para = GetPara(line);
if (para.Length == 2 && para[0] == "BookFontSize") { if (!int.TryParse(para[1], out bookFontSize)) bookFontSize = 18; }
if (para.Length >= 3)
{
string code = Util.TrimLanguageCode(para[0]);
if (Util.isLanguageCode(code))
{
if (!fontFamilySettings.ContainsKey(code))
fontFamilySettings.Add(code, para);
}
}
}
}
if (File.Exists(generalSetting))
{
string line;
using (var file = new StreamReader(generalSetting))
while ((line = file.ReadLine()) != null)
{
string[] para = GetPara(line);
if (para.Length == 2)
switch (para[0])
{
case "Theme":
theme = para[1].ToLower();
break;
case "WarmColor":
warmColor = para[1];
ImageHack.SetWarmColor(warmColor);
break;
case "ViewMode":
viewMode = para[1];
break;
}
}
}
if (File.Exists(userBookCss))
{
userBookCssContent = File.ReadAllText(userBookCss);
}
if (File.Exists(userBookCss_ltr))
{
userBookCssContent_ltr = File.ReadAllText(userBookCss_ltr);
}
if (File.Exists(userBookCss_rtl))
{
userBookCssContent_rtl = File.ReadAllText(userBookCss_rtl);
}
HtmlHack.LoadUser();
}
19
View Source File : ObjLoader.cs
License : The Unlicense
Project Creator : aeroson
License : The Unlicense
Project Creator : aeroson
Mesh Parse(Resource resource, GameObject appendToGameObject)
{
using (StreamReader textReader = new StreamReader(resource))
{
int i1, i2, i3, i4;
string line;
while ((line = textReader.ReadLine()) != null)
{
line = line.Trim(trimCharacters);
line = line.Replace(" ", " ");
string[] parameters = line.Split(splitCharacters);
switch (parameters[0])
{
case "p": // Point
break;
case "v": // Vertex
var v = Vector3.Zero;
Parse(ref parameters[1], ref v.X);
Parse(ref parameters[2], ref v.Y);
Parse(ref parameters[3], ref v.Z);
verticesObj.Add(v);
break;
case "vt": // TexCoord
gotUvs = true;
var vt = Vector2.Zero;
Parse(ref parameters[1], ref vt.X);
Parse(ref parameters[2], ref vt.Y);
uvsObj.Add(vt);
break;
case "vn": // Normal
gotNormal = true;
var vn = Vector3.Zero;
Parse(ref parameters[1], ref vn.X);
Parse(ref parameters[2], ref vn.Y);
Parse(ref parameters[3], ref vn.Z);
normalsObj.Add(vn);
break;
case "f":
switch (parameters.Length)
{
case 4:
i1 = ParseFaceParameter(parameters[1]);
i2 = ParseFaceParameter(parameters[2]);
i3 = ParseFaceParameter(parameters[3]);
triangleIndiciesMesh.Add(i1);
triangleIndiciesMesh.Add(i2);
triangleIndiciesMesh.Add(i3);
break;
case 5:
i1 = ParseFaceParameter(parameters[1]);
i2 = ParseFaceParameter(parameters[2]);
i3 = ParseFaceParameter(parameters[3]);
i4 = ParseFaceParameter(parameters[4]);
triangleIndiciesMesh.Add(i1);
triangleIndiciesMesh.Add(i2);
triangleIndiciesMesh.Add(i3);
triangleIndiciesMesh.Add(i1);
triangleIndiciesMesh.Add(i3);
triangleIndiciesMesh.Add(i4);
break;
}
break;
case "mtllib":
if (Resource.ResourceInFolderExists(resource, parameters[1]))
{
materialLibrary = new MaterialLibrary(Resource.GetResourceInFolder(resource, parameters[1]));
}
break;
case "usemtl":
if (materialLibrary!=null) lastMaterial = materialLibrary.GetMat(parameters[1]);
break;
}
}
textReader.Close();
}
if(appendToGameObject!=null) return EndObjPart(appendToGameObject);
Debug.Info("Loaded " + resource.originalPath + " vertices:" + verticesMesh.Count + " faces:" + triangleIndiciesMesh.Count / 3);
return EndMesh();
}
19
View Source File : ExportDialog.cs
License : GNU General Public License v2.0
Project Creator : afrantzis
License : GNU General Public License v2.0
Project Creator : afrantzis
private void LoadFromPatternFile(ListStore ls)
{
StreamReader reader;
try {
FileStream fs = GetPatternFile(FileMode.Open, FileAccess.Read);
reader = new StreamReader(fs);
}
catch (Exception e) {
System.Console.WriteLine(e.Message);
return;
}
string pattern;
while ((pattern = reader.ReadLine()) != null) {
ls.AppendValues(pattern);
}
reader.BaseStream.Close();
}
19
View Source File : ManageClient.cs
License : MIT License
Project Creator : agc93
License : MIT License
Project Creator : agc93
public async Task<bool> CheckValidSession() {
var uri = "/Core/Libs/Common/Widgets/MyModerationHistoryTab";
using (var req = new HttpRequestMessage(HttpMethod.Get, uri))
{
var resp = await _httpClient.SendAsync(req);
if (!resp.IsSuccessStatusCode) {
return false;
}
var str = await resp.Content.ReadreplacedtreamAsync();
var reader = new StreamReader(str);
string line;
int lineOffset = 0;
while ((line = reader.ReadLine()) != null && lineOffset < 10)
{
if (line.Contains("og:") || line.Contains("Error"))
{
return false;
}
lineOffset++;
}
return true;
// return resp.IsSuccessStatusCode && (resp.Content.Headers.ContentLength.HasValue && resp.Content.Headers.ContentLength < 100000) && (resp.Headers.Where(c => c.Key == "Set-Cookie").Count() < 2);
}
}
19
View Source File : GuiderImpl.cs
License : MIT License
Project Creator : agalasso
License : MIT License
Project Creator : agalasso
public string ReadLine()
{
try
{
return sr.ReadLine();
}
catch (Exception)
{
// phd2 disconnected
return null;
}
}
19
View Source File : Platform.Posix.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static string[] EnumerateLibLdConf(string fileName)
{
if (!File.Exists(fileName)) return null;
var libLoadConf = new List<string>();
using (var fileReader = new StreamReader(fileName))
{
while (!fileReader.EndOfStream)
{
string line = fileReader.ReadLine().TrimStart(new char[] { ' ' });
// Comments
if (line.StartsWith("#", StringComparison.OrdinalIgnoreCase)) continue;
int commentI;
if (-1 < (commentI = line.IndexOf("#")))
{
// remove Comments
line = line.Substring(0, commentI);
}
if (string.IsNullOrWhiteSpace(line.Trim())) continue;
// Include /etc/ld.so.conf.d/*.conf, say enumerate files
if (line.StartsWith("include ", StringComparison.OrdinalIgnoreCase))
{
string folder = null;
string filesPattern = line.Substring("include ".Length);
int filesPatternI;
if (-1 == (filesPatternI = filesPattern.IndexOf('*')))
{
filesPatternI = filesPattern.Length;
}
if (-1 < (filesPatternI = filesPattern.LastIndexOf('/', filesPatternI)))
{
folder = filesPattern.Substring(0, filesPatternI + 1);
filesPattern = filesPattern.Substring(filesPatternI + 1);
}
if (folder == null || !Directory.Exists(folder)) continue;
string[] files = Directory.EnumerateFiles(folder, filesPattern, SearchOption.TopDirectoryOnly).ToArray();
foreach (string file in files)
{
string[] _libLoadConf = EnumerateLibLdConf(file);
if (_libLoadConf != null) libLoadConf.AddRange(_libLoadConf);
}
continue;
}
// Folder
string path = EnsureNotEndingSlash(line);
if (path != null && Directory.Exists(path)) libLoadConf.Add(path);
}
}
return libLoadConf.ToArray();
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
void ReadSettings()
{
currentlyReading = true;
StreamReader sr = null;
string checkVer = c_toolVer;
try
{
using (sr = new StreamReader(settingsFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
try
{
int equalsign = line.IndexOf('=');
if (equalsign > 0)
{
string varName = line.Substring(0, equalsign);
string varValue = line.Substring(equalsign + 1);
if (varName == "ToolVersion" || varName == "GameVersion")
{
checkVer = varValue;
}
else if (varName == "GameMode")
{
rbSingleplayer.Checked = (varValue == "sp");
}
else if (varName == "Beep")
{
chkBeep.Checked = bool.Parse(varValue);
}
else if (varName == "FoV")
{
SetFoV(float.Parse(varValue));
}
else if (varName == "FoVOffset" || varName == "RelativeFoVOffset")
{
dword_ptr tmp = dword_ptr.Parse(varValue, NumberStyles.AllowHexSpecifier);
if (tmp > (dword_ptr)gameMode.GetValue("c_baseAddr"))
pFoV = (varName == "RelativeFoVOffset" ? (dword_ptr)gameMode.GetValue("c_baseAddr") : 0) + tmp;
}
else if (varName == "UpdateNotify")
{
chkUpdate.Checked = bool.Parse(varValue);
}
else if (varName == "DisableHotkeys")
{
chkHotkeys.Checked = bool.Parse(varValue);
}
else if (varName == "HotkeyIncrease")
{
catchKeys[0] = (Keys)int.Parse(varValue);
btnKeyZoomOut.Text = VirtualKeyName(catchKeys[0]);
}
else if (varName == "HotkeyDecrease")
{
catchKeys[1] = (Keys)int.Parse(varValue);
btnKeyZoomIn.Text = VirtualKeyName(catchKeys[1]);
}
else if (varName == "HotkeyReset")
{
catchKeys[2] = (Keys)int.Parse(varValue);
btnKeyReset.Text = VirtualKeyName(catchKeys[2]);
}
}
}
catch { }
}
}
}
finally
{
if (sr != null)
sr.Close();
}
if (checkVer != c_toolVer)
pFoV = (dword_ptr)gameMode.GetValue("c_pFoV");
UpdateCheck();
currentlyReading = false;
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
private void ReadData()
{
currentlyReading = true;
StreamReader sr = null;
string checkVer = c_toolVer;
bool[] read = { false, false, false, false, false, false,
false, false, false };
try
{
sr = new StreamReader(settingsFile);
while (sr.Peek() > -1)
{
StringRead(sr.ReadLine(), ref read, ref checkVer);
}
}
catch
{
//if (!read[0]) toolVer = c_toolVer;
/*if (!read[1]) pFoV = c_pFoV;
if (!read[2]) fFoV = c_FoV;
if (!read[3]) doBeep = c_doBeep;
if (!read[4]) updateChk = c_updateChk;
if (!read[5]) hotKeys = c_hotKeys;
if (!read[6]) catchKeys[0] = c_catchKeys[0];
if (!read[7]) catchKeys[1] = c_catchKeys[1];
if (!read[8]) catchKeys[2] = c_catchKeys[2];*/
}
finally
{
if (sr != null) sr.Close();
}
if (checkVer != c_toolVer)
pFoV = c_pFoV;
if (!requestSent)
{
try
{
request = (HttpWebRequest)WebRequest.Create(c_checkURL);
request.BeginGetResponse(new AsyncCallback(UpdateResponse), null);
requestSent = true;
}
catch { }
}
currentlyReading = false;
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev
License : GNU General Public License v3.0
Project Creator : AgentRev
void ReadSettings()
{
currentlyReading = true;
StreamReader sr = null;
string checkVer = c_toolVer;
try
{
using (sr = new StreamReader(settingsFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
try
{
int equalsign = line.IndexOf('=');
if (equalsign > 0)
{
string varName = line.Substring(0, equalsign);
string varValue = line.Substring(equalsign + 1);
if (varName == "ToolVersion" || varName == "GameVersion")
{
checkVer = varValue;
}
else if (varName == "GameMode")
{
rbSingleplayer.Checked = (varValue == "sp");
}
else if (varName == "Beep")
{
chkBeep.Checked = bool.Parse(varValue);
}
else if (varName == "FoV")
{
SetFoV(float.Parse(varValue));
}
else if (varName == "FoVOffset" || varName == "RelativeFoVOffset")
{
int tmp = int.Parse(varValue, NumberStyles.AllowHexSpecifier);
if (tmp > (int)gameMode.GetValue("c_baseAddr") && tmp < 0x40000000)
pFoV = (varName == "RelativeFoVOffset" ? (int)gameMode.GetValue("c_baseAddr") : 0) + tmp;
}
else if (varName == "UpdatePopup" || varName == "UpdateCheck")
{
chkUpdate.Checked = bool.Parse(varValue);
}
else if (varName == "DisableHotkeys")
{
chkHotkeys.Checked = bool.Parse(varValue);
}
else if (varName == "HotkeyIncrease")
{
catchKeys[0] = (Keys)int.Parse(varValue);
btnKeyZoomOut.Text = VirtualKeyName(catchKeys[0]);
}
else if (varName == "HotkeyDecrease")
{
catchKeys[1] = (Keys)int.Parse(varValue);
btnKeyZoomIn.Text = VirtualKeyName(catchKeys[1]);
}
else if (varName == "HotkeyReset")
{
catchKeys[2] = (Keys)int.Parse(varValue);
btnKeyReset.Text = VirtualKeyName(catchKeys[2]);
}
}
}
catch { }
}
}
}
finally
{
if (sr != null)
sr.Close();
}
if (checkVer != c_toolVer)
pFoV = (int)gameMode.GetValue("c_pFoV");
if (!requestSent)
{
try
{
request = (HttpWebRequest)WebRequest.Create(c_checkURL);
request.BeginGetResponse(new AsyncCallback(UpdateResponse), null);
requestSent = true;
}
catch { }
}
currentlyReading = false;
}
19
View Source File : HashResolver.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
private static void LoadFromResource(string filename)
{
using (var s = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(typeof(HashResolver), filename))
{
var sw = new StreamReader(s);
string name;
while ((name = sw.ReadLine()) != null)
{
uint hash = Hasher.Hash(name);
if (!_knownNames.ContainsKey(hash))
{
_knownNames.Add(hash, name);
}
}
}
}
19
View Source File : StreamReader.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public string ReadLine()
{
return M_StreamReader.ReadLine();
}
19
View Source File : Encryption.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private static string Decrypt(string data, Byte[] key, Byte[] iv)
{
Byte[] tmp = Convert.FromBase64String(data);
string result = string.Empty;
System.Security.Cryptography.TripleDES tripleDES = System.Security.Cryptography.TripleDES.Create();
ICryptoTransform decryptor = tripleDES.CreateDecryptor(key, iv);
using (MemoryStream ms = new MemoryStream(tmp))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
StreamReader reader = new StreamReader(cs);
result = reader.ReadLine();
}
}
tripleDES.Clear();
return result;
}
19
View Source File : OpensslEsiaSigner.cs
License : GNU General Public License v3.0
Project Creator : AISGorod
License : GNU General Public License v3.0
Project Creator : 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
View Source File : Wifi.cs
License : MIT License
Project Creator : Akaion
License : MIT License
Project Creator : Akaion
private static IEnumerable<string> GetProfiles()
{
var profileList = new List<string>();
var ready = false;
// Create a process to get the wlan profiles
using (var process = new Process())
{
string output;
// Set the specifications for the process
process.StartInfo.FileName = "netsh";
process.StartInfo.Arguments = "wlan show profiles";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
// Start the process
process.Start();
while ((output = process.StandardOutput.ReadLine()) != null)
{
if (ready)
{
// Remove blank characters from string
var removeSpaces = output.Replace(" ", string.Empty);
// Format the string to get the SSID
var formattedString = removeSpaces.Substring(removeSpaces.IndexOf(":", StringComparison.Ordinal) + 1);
if (formattedString.Length > 3)
{
profileList.Add(formattedString);
}
}
else
{
if (output.StartsWith("User profiles"))
{
ready = true;
// Skip the next line to begin gathering profiles
process.StandardOutput.ReadLine();
}
}
}
}
return profileList;
}
19
View Source File : Wifi.cs
License : MIT License
Project Creator : Akaion
License : MIT License
Project Creator : Akaion
private static string GetPreplacedword(string profile)
{
var preplacedword = "";
using (var process = new Process())
{
string output;
// Set the specifications for the process
process.StartInfo.FileName = "netsh";
process.StartInfo.Arguments = $"wlan show profiles name=\"{profile}\" key=clear";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
// Start the process
process.Start();
while ((output = process.StandardOutput.ReadLine()) != null)
{
if (output.Contains("Key Content"))
{
// Remove blank characters from string
var removeSpaces = output.Replace(" ", string.Empty);
// Format the string to get the preplacedword
var formattedString = removeSpaces.Substring(removeSpaces.IndexOf(":", StringComparison.Ordinal) + 1);
preplacedword = formattedString;
}
}
}
return preplacedword;
}
19
View Source File : CancerspaceInspector.cs
License : GNU General Public License v3.0
Project Creator : AkaiMage
License : GNU General Public License v3.0
Project Creator : AkaiMage
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) {
if (!initialized) {
customRenderQueue = (materialEditor.target as Material).shader.renderQueue;
rng = new System.Random();
initialized = true;
}
cancerfree = (materialEditor.target as Material).shader.name.Contains("Cancerfree");
GUIStyle defaultStyle = new GUIStyle(EditorStyles.foldout);
defaultStyle.fontStyle = FontStyle.Bold;
defaultStyle.onNormal = EditorStyles.boldLabel.onNormal;
defaultStyle.onFocused = EditorStyles.boldLabel.onFocused;
List<CSCategory> categories = new List<CSCategory>();
categories.Add(new CSCategory(Styles.falloffSettingsreplacedle, defaultStyle, me => {
CSProperty falloffCurve = FindProperty("_FalloffCurve", props);
CSProperty falloffDepth = FindProperty("_DepthFalloff", props);
CSProperty falloffColor = FindProperty("_ColorFalloff", props);
DisplayRegularProperty(me, falloffCurve);
if (falloffCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_MinFalloff", props));
DisplayRegularProperty(me, FindProperty("_MaxFalloff", props));
DisplayRegularProperty(me, falloffDepth);
if (falloffDepth.prop.floatValue > .5) {
CSProperty falloffDepthCurve = FindProperty("_DepthFalloffCurve", props);
DisplayRegularProperty(me, falloffDepthCurve);
if (falloffDepthCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_DepthMinFalloff", props));
DisplayRegularProperty(me, FindProperty("_DepthMaxFalloff", props));
}
DisplayRegularProperty(me, falloffColor);
if (falloffColor.prop.floatValue > .5) {
CSProperty falloffColorCurve = FindProperty("_ColorFalloffCurve", props);
DisplayRegularProperty(me, FindProperty("_ColorChannelForFalloff", props));
DisplayRegularProperty(me, falloffColorCurve);
if (falloffColorCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_ColorMinFalloff", props));
DisplayRegularProperty(me, FindProperty("_ColorMaxFalloff", props));
}
}));
categories.Add(new CSCategory(Styles.particleSystemSettingsreplacedle, defaultStyle, me => {
CSProperty falloffCurve = FindProperty("_LifetimeFalloffCurve", props);
CSProperty falloff = FindProperty("_LifetimeFalloff", props);
DisplayRegularProperty(me, FindProperty("_ParticleSystem", props));
DisplayRegularProperty(me, falloff);
if (falloff.prop.floatValue > .5) {
DisplayRegularProperty(me, falloffCurve);
if (falloffCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_LifetimeMinFalloff", props));
DisplayRegularProperty(me, FindProperty("_LifetimeMaxFalloff", props));
}
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.screenShakeSettingsreplacedle, defaultStyle, me => {
DisplayFloatWithSliderMode(me, FindProperty("_XShake", props));
DisplayFloatWithSliderMode(me, FindProperty("_YShake", props));
DisplayFloatWithSliderMode(me, FindProperty("_XShakeSpeed", props));
DisplayFloatWithSliderMode(me, FindProperty("_YShakeSpeed", props));
DisplayFloatWithSliderMode(me, FindProperty("_ShakeAmplitude", props));
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.wobbleSettingsreplacedle, defaultStyle, me => {
DisplayFloatRangeProperty(me, FindProperty("_XWobbleAmount", props));
DisplayFloatRangeProperty(me, FindProperty("_YWobbleAmount", props));
DisplayFloatRangeProperty(me, FindProperty("_XWobbleTiling", props));
DisplayFloatRangeProperty(me, FindProperty("_YWobbleTiling", props));
DisplayFloatWithSliderMode(me, FindProperty("_XWobbleSpeed", props));
DisplayFloatWithSliderMode(me, FindProperty("_YWobbleSpeed", props));
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.blurSettingsreplacedle, defaultStyle, me => {
DisplayFloatWithSliderMode(me, FindProperty("_BlurRadius", props));
DisplayIntSlider(me, FindProperty("_BlurSampling", props), 1, 5);
DisplayRegularProperty(me, FindProperty("_AnimatedSampling", props));
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.distortionMapSettingsreplacedle, defaultStyle, me => {
CSProperty distortionType = FindProperty("_DistortionType", props);
CSProperty distortionMapRotation = FindProperty("_DistortionMapRotation", props);
CSProperty distortionAmplitude = FindProperty("_DistortionAmplitude", props);
CSProperty distortionRotation = FindProperty("_DistortionRotation", props);
CSProperty distortFlipbook = FindProperty("_DistortFlipbook", props);
DisplayRegularProperty(me, distortionType);
DisplayRegularProperty(me, FindProperty("_DistortionTarget", props));
switch ((int) distortionType.prop.floatValue) {
case 0:
DisplayRegularProperty(me, FindProperty("_BumpMap", props));
DisplayFloatWithSliderMode(me, distortionMapRotation);
DisplayFloatWithSliderMode(me, distortionAmplitude);
DisplayFloatWithSliderMode(me, distortionRotation);
DisplayFloatWithSliderMode(me, FindProperty("_BumpMapScrollSpeedX", props));
DisplayFloatWithSliderMode(me, FindProperty("_BumpMapScrollSpeedY", props));
break;
case 1:
DisplayRegularProperty(me, FindProperty("_MeltMap", props));
DisplayFloatWithSliderMode(me, distortionMapRotation);
DisplayFloatWithSliderMode(me, distortionAmplitude);
DisplayFloatWithSliderMode(me, distortionRotation);
DisplayFloatWithSliderMode(me, FindProperty("_MeltController", props));
DisplayFloatWithSliderMode(me, FindProperty("_MeltActivationScale", props));
break;
}
DisplayRegularProperty(me, distortFlipbook);
if (distortFlipbook.prop.floatValue != 0) {
DisplayIntField(me, FindProperty("_DistortFlipbookTotalFrames", props));
DisplayIntField(me, FindProperty("_DistortFlipbookStartFrame", props));
DisplayIntField(me, FindProperty("_DistortFlipbookRows", props));
DisplayIntField(me, FindProperty("_DistortFlipbookColumns", props));
DisplayFloatProperty(me, FindProperty("_DistortFlipbookFPS", props));
}
}));
categories.Add(new CSCategory(Styles.overlaySettingsreplacedle, defaultStyle, me => {
CSProperty overlayImageType = FindProperty("_OverlayImageType", props);
CSProperty overlayImage = FindProperty("_MainTex", props);
CSProperty overlayRotation = FindProperty("_MainTexRotation", props);
CSProperty overlayPixelate = FindProperty("_PixelatedSampling", props);
CSProperty overlayScrollSpeedX = FindProperty("_MainTexScrollSpeedX", props);
CSProperty overlayScrollSpeedY = FindProperty("_MainTexScrollSpeedY", props);
CSProperty overlayBoundary = FindProperty("_OverlayBoundaryHandling", props);
CSProperty overlayColor = FindProperty("_OverlayColor", props);
if (!cancerfree) BlendModePopup(me, FindProperty("_BlendMode", props));
DisplayRegularProperty(me, overlayImageType);
switch ((int) overlayImageType.prop.floatValue) {
// TODO: replace these with proper enums so there's no magic numbers
case 0:
DisplayRegularProperty(me, overlayBoundary);
DisplayRegularProperty(me, overlayPixelate);
me.TexturePropertySingleLine(Styles.overlayImageText, overlayImage.prop, overlayColor.prop);
me.TextureScaleOffsetProperty(overlayImage.prop);
DisplayFloatWithSliderMode(me, overlayRotation);
if (overlayBoundary.prop.floatValue != 0) {
DisplayFloatWithSliderMode(me, overlayScrollSpeedX);
DisplayFloatWithSliderMode(me, overlayScrollSpeedY);
}
break;
case 1:
DisplayRegularProperty(me, overlayBoundary);
DisplayRegularProperty(me, overlayPixelate);
me.TexturePropertySingleLine(Styles.overlayImageText, overlayImage.prop, overlayColor.prop);
me.TextureScaleOffsetProperty(overlayImage.prop);
DisplayFloatWithSliderMode(me, overlayRotation);
if (overlayBoundary.prop.floatValue != 0) {
DisplayFloatWithSliderMode(me, overlayScrollSpeedX);
DisplayFloatWithSliderMode(me, overlayScrollSpeedY);
}
DisplayIntField(me, FindProperty("_FlipbookTotalFrames", props));
DisplayIntField(me, FindProperty("_FlipbookStartFrame", props));
DisplayIntField(me, FindProperty("_FlipbookRows", props));
DisplayIntField(me, FindProperty("_FlipbookColumns", props));
DisplayFloatProperty(me, FindProperty("_FlipbookFPS", props));
break;
case 2:
DisplayRegularProperty(me, FindProperty("_OverlayCubemap", props));
DisplayColorProperty(me, overlayColor);
DisplayVec3WithSliderMode(
me,
"Rotation",
FindProperty("_OverlayCubemapRotationX", props),
FindProperty("_OverlayCubemapRotationY", props),
FindProperty("_OverlayCubemapRotationZ", props)
);
DisplayVec3WithSliderMode(
me,
"Rotation Speed",
FindProperty("_OverlayCubemapSpeedX", props),
FindProperty("_OverlayCubemapSpeedY", props),
FindProperty("_OverlayCubemapSpeedZ", props)
);
break;
}
DisplayFloatRangeProperty(me, FindProperty("_BlendAmount", props));
}));
if (cancerfree) categories.Add(new CSCategory(Styles.blendSettingsreplacedle, defaultStyle, me => {
DisplayRegularProperty(me, FindProperty("_BlendOp", props));
DisplayRegularProperty(me, FindProperty("_BlendSource", props));
DisplayRegularProperty(me, FindProperty("_BlendDestination", props));
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.screenColorAdjustmentsreplacedle, defaultStyle, me => {
CSProperty colorBurningToggle = FindProperty("_Burn", props);
DisplayVec3WithSliderMode(
me,
"HSV Add",
FindProperty("_HueAdd", props),
FindProperty("_SaturationAdd", props),
FindProperty("_ValueAdd", props)
);
DisplayVec3WithSliderMode(
me,
"HSV Multiply",
FindProperty("_HueMultiply", props),
FindProperty("_SaturationMultiply", props),
FindProperty("_ValueMultiply", props)
);
DisplayFloatRangeProperty(me, FindProperty("_InversionAmount", props));
DisplayColorProperty(me, FindProperty("_Color", props));
BlendModePopup(me, FindProperty("_ScreenColorBlendMode", props));
DisplayRegularProperty(me, colorBurningToggle);
if (colorBurningToggle.prop.floatValue == 1) {
DisplayFloatRangeProperty(me, FindProperty("_BurnLow", props));
DisplayFloatRangeProperty(me, FindProperty("_BurnHigh", props));
}
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.screenTransformreplacedle, defaultStyle, me => {
DisplayRegularProperty(me, FindProperty("_ScreenBoundaryHandling", props));
DisplayRegularProperty(me, FindProperty("_ScreenReprojection", props));
DisplayFloatWithSliderMode(me, FindProperty("_Zoom", props));
DisplayRegularProperty(me, FindProperty("_Pixelation", props));
CSProperty screenXOffsetR = FindProperty("_ScreenXOffsetR", props);
CSProperty screenXOffsetG = FindProperty("_ScreenXOffsetG", props);
CSProperty screenXOffsetB = FindProperty("_ScreenXOffsetB", props);
CSProperty screenXOffsetA = FindProperty("_ScreenXOffsetA", props);
CSProperty screenYOffsetR = FindProperty("_ScreenYOffsetR", props);
CSProperty screenYOffsetG = FindProperty("_ScreenYOffsetG", props);
CSProperty screenYOffsetB = FindProperty("_ScreenYOffsetB", props);
CSProperty screenYOffsetA = FindProperty("_ScreenYOffsetA", props);
CSProperty screenXMultiplierR = FindProperty("_ScreenXMultiplierR", props);
CSProperty screenXMultiplierG = FindProperty("_ScreenXMultiplierG", props);
CSProperty screenXMultiplierB = FindProperty("_ScreenXMultiplierB", props);
CSProperty screenXMultiplierA = FindProperty("_ScreenXMultiplierA", props);
CSProperty screenYMultiplierR = FindProperty("_ScreenYMultiplierR", props);
CSProperty screenYMultiplierG = FindProperty("_ScreenYMultiplierG", props);
CSProperty screenYMultiplierB = FindProperty("_ScreenYMultiplierB", props);
CSProperty screenYMultiplierA = FindProperty("_ScreenYMultiplierA", props);
if (sliderMode) {
DisplayFloatRangeProperty(me, screenXOffsetA);
DisplayFloatRangeProperty(me, screenYOffsetA);
DisplayFloatRangeProperty(me, screenXOffsetR);
DisplayFloatRangeProperty(me, screenYOffsetR);
DisplayFloatRangeProperty(me, screenXOffsetG);
DisplayFloatRangeProperty(me, screenYOffsetG);
DisplayFloatRangeProperty(me, screenXOffsetB);
DisplayFloatRangeProperty(me, screenYOffsetB);
DisplayFloatRangeProperty(me, screenXMultiplierA);
DisplayFloatRangeProperty(me, screenYMultiplierA);
DisplayFloatRangeProperty(me, screenXMultiplierR);
DisplayFloatRangeProperty(me, screenYMultiplierR);
DisplayFloatRangeProperty(me, screenXMultiplierG);
DisplayFloatRangeProperty(me, screenYMultiplierG);
DisplayFloatRangeProperty(me, screenXMultiplierB);
DisplayFloatRangeProperty(me, screenYMultiplierB);
} else {
DisplayVec4Field(me, "Screen X Offset (RGB)", screenXOffsetR, screenXOffsetG, screenXOffsetB, screenXOffsetA);
DisplayVec4Field(me, "Screen Y Offset (RGB)", screenYOffsetR, screenYOffsetG, screenYOffsetB, screenYOffsetA);
DisplayVec4Field(me, "Screen X Multiplier (RGB)", screenXMultiplierR, screenXMultiplierG, screenXMultiplierB, screenXMultiplierA);
DisplayVec4Field(me, "Screen Y Multiplier (RGB)", screenYMultiplierR, screenYMultiplierG, screenYMultiplierB, screenYMultiplierA);
}
DisplayFloatRangeProperty(me, FindProperty("_ScreenRotationAngle", props));
}));
categories.Add(new CSCategory(Styles.targetObjectSettingsreplacedle, defaultStyle, me => {
DisplayVec4Field(
me,
"Position",
FindProperty("_ObjectPositionX", props),
FindProperty("_ObjectPositionY", props),
FindProperty("_ObjectPositionZ", props),
FindProperty("_ObjectPositionA", props)
);
DisplayVec3Field(
me,
"Rotation",
FindProperty("_ObjectRotationX", props),
FindProperty("_ObjectRotationY", props),
FindProperty("_ObjectRotationZ", props)
);
DisplayVec4Field(
me,
"Scale",
FindProperty("_ObjectScaleX", props),
FindProperty("_ObjectScaleY", props),
FindProperty("_ObjectScaleZ", props),
FindProperty("_ObjectScaleA", props)
);
DisplayRegularProperty(me, FindProperty("_Puffiness", props));
}));
categories.Add(new CSCategory(Styles.stencilreplacedle, defaultStyle, me => {
DisplayIntSlider(me, FindProperty("_StencilRef", props), 0, 255);
DisplayRegularProperty(me, FindProperty("_StencilComp", props));
DisplayRegularProperty(me, FindProperty("_StencilPreplacedOp", props));
DisplayRegularProperty(me, FindProperty("_StencilFailOp", props));
DisplayRegularProperty(me, FindProperty("_StencilZFailOp", props));
DisplayIntSlider(me, FindProperty("_StencilReadMask", props), 0, 255);
DisplayIntSlider(me, FindProperty("_StencilWriteMask", props), 0, 255);
}));
categories.Add(new CSCategory(Styles.maskingreplacedle, defaultStyle, me => {
if (!cancerfree) {
DisplayRegularProperty(me, FindProperty("_DistortionMask", props));
DisplayFloatRangeProperty(me, FindProperty("_DistortionMaskOpacity", props));
}
DisplayRegularProperty(me, FindProperty("_OverlayMask", props));
DisplayFloatRangeProperty(me, FindProperty("_OverlayMaskOpacity", props));
DisplayRegularProperty(me, FindProperty("_OverallEffectMask", props));
DisplayFloatRangeProperty(me, FindProperty("_OverallEffectMaskOpacity", props));
BlendModePopup(me, FindProperty("_OverallEffectMaskBlendMode", props));
EditorGUILayout.Space();
DisplayRegularProperty(me, FindProperty("_OverallAmplitudeMask", props));
DisplayFloatRangeProperty(me, FindProperty("_OverallAmplitudeMaskOpacity", props));
}));
categories.Add(new CSCategory(Styles.miscSettingsreplacedle, defaultStyle, me => {
DisplayRegularProperty(me, FindProperty("_CullMode", props));
DisplayRegularProperty(me, FindProperty("_ZTest", props));
DisplayRegularProperty(me, FindProperty("_ZWrite", props));
ShowColorMaskFlags(me, FindProperty("_ColorMask", props));
DisplayRegularProperty(me, FindProperty("_MirrorMode", props));
DisplayRegularProperty(me, FindProperty("_EyeSelector", props));
DisplayRegularProperty(me, FindProperty("_PlatformSelector", props));
CSProperty projectionType = FindProperty("_ProjectionType", props);
DisplayRegularProperty(me, projectionType);
if (projectionType.prop.floatValue != 2) {
DisplayVec3WithSliderMode(
me,
Styles.projectionRotationText,
FindProperty("_ProjectionRotX", props),
FindProperty("_ProjectionRotY", props),
FindProperty("_ProjectionRotZ", props)
);
}
}));
if (!cancerfree) categories.Add(new CSCategory(Styles.renderQueueExportreplacedle, defaultStyle, me => {
Material material = me.target as Material;
customRenderQueue = EditorGUILayout.IntSlider(Styles.customRenderQueueSliderText, customRenderQueue, 0, 5000);
if (GUILayout.Button(Styles.exportCustomRenderQueueButtonText)) {
int relativeQueue = customRenderQueue - ((int) UnityEngine.Rendering.RenderQueue.Transparent);
string newQueueString = "Transparent" + (relativeQueue >= 0 ? "+" : "") + relativeQueue;
string shaderName = "RedMage/Cancer" + (cancerfree ? "free" : "space");
string newShaderPath = shaderName + " Queue " + customRenderQueue;
string shaderPath = replacedetDatabase.GetreplacedetPath(material.shader.GetInstanceID());
string outputLocation = shaderPath.Substring(0, shaderPath.Replace("\\", "/").LastIndexOf('/') + 1) + "CancerspaceQueue" + customRenderQueue + ".shader";
try {
using (StreamWriter sw = new StreamWriter(outputLocation)) {
using (StreamReader sr = new StreamReader(shaderPath)) {
string line;
while ((line = sr.ReadLine()) != null) {
if (line.Contains("\"Transparent+")) {
Regex rx = new Regex(@"Transparent[+-]\d+", RegexOptions.Compiled);
MatchCollection matches = rx.Matches(line);
foreach (Match match in matches) {
line = line.Replace(match.Value, newQueueString);
}
} else if (line.Contains(shaderName)) {
Regex rx = new Regex("\"[^\"]+\"", RegexOptions.Compiled);
MatchCollection matches = rx.Matches(line);
foreach (Match match in matches) {
line = line.Replace(match.Value, "\"" + newShaderPath + "\"");
}
}
if (!cancerfree) line = line.Replace("_Garb", "_Garb" + customRenderQueue);
sw.Write(line);
sw.WriteLine();
}
}
}
} catch (Exception e) {
Debug.Log("AAAGAGHH WHAT? HOW? WHY??? WHAT ARE YOU DOING? Shader file could not be read / written.");
Debug.Log(e.Message);
return;
}
replacedetDatabase.Refresh();
material.shader = Shader.Find(newShaderPath);
replacedetDatabase.Savereplacedets();
}
}));
EditorGUIUtility.labelWidth = 0f;
sliderMode = EditorGUILayout.ToggleLeft(Styles.sliderModeCheckboxText, sliderMode);
showRandomizerOptions = EditorGUILayout.ToggleLeft(Styles.randomizerOptionsCheckboxText, showRandomizerOptions);
if (showRandomizerOptions) {
randomizingCurrentPreplaced = GUILayout.Button("Randomize Values");
}
int oldflags = GetExpansionFlags();
int newflags = 0;
for (int i = 0; i < categories.Count; ++i) {
bool expanded = EditorGUILayout.Foldout((oldflags & (1 << i)) != 0, categories[i].name, true, categories[i].style);
newflags |= (expanded ? 1 : 0) << i;
if (expanded) {
EditorGUI.indentLevel++;
categories[i].setupDelegate(materialEditor);
EditorGUI.indentLevel--;
}
}
SetExpansionFlags(newflags);
if (!cancerfree) GUI.enabled = false;
materialEditor.RenderQueueField();
randomizingCurrentPreplaced = false;
}
See More Examples