Here are the examples of the csharp api System.Collections.Generic.Dictionary.Add(string, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1090 Examples
19
View Source File : MapCodeGenResolverTest.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
[Fact]
public void Map1Deserialize_AtSameLayer_IfNotEqualThenSKip()
{
Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("A1", 1);
dic.Add("A2", 2);
var buf = BssomSerializer.Serialize(dic);
var c1 = BssomSerializer.Deserialize<_Map1_1>(buf);
c1.A1.Is(1);
c1.A3.Is(0);
}
19
View Source File : MapCodeGenResolverTest.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
[Fact]
public void Map1Deserialize_MultiAtSameLayer_IfNotEqualThenSKip()
{
Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("A1", 1);
dic.Add("A2", 2);
dic.Add("B12345678", 3);
dic.Add("C12345678", 4);
var buf = BssomSerializer.Serialize(dic);
var c1 = BssomSerializer.Deserialize<_Map1_1>(buf);
c1.A1.Is(1);
c1.A3.Is(0);
}
19
View Source File : BssomSchemaTest.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
private Dictionary<string, int> GenerateDict(params string[] keys)
{
Dictionary<string, int> dict = new Dictionary<string, int>();
foreach (var item in keys)
{
dict.Add(item, 1);
}
return dict;
}
19
View Source File : MapCodeGenResolverTest.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
[Fact]
public void Map1Deserialize_OneZeroAndOneNotZero()
{
Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("A", 1);
dic.Add("B12345678", 2);
var buf = BssomSerializer.Serialize(dic);
var c1 = BssomSerializer.Deserialize<_Map1_6>(buf);
c1.A.Is(1);
c1.B12345678.Is(2);
}
19
View Source File : MapCodeGenResolverTest.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
[Fact]
public void Map1Deserialize_NotSameLayer_IfNotEqualThenSKip()
{
Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("A1234567", 1);
dic.Add("A12345678", 2);
var buf = BssomSerializer.Serialize(dic);
var c1 = BssomSerializer.Deserialize<_Map1_2>(buf);
c1.A1234567.Is(1);
c1.A12345679.Is(0);
}
19
View Source File : MapCodeGenResolverTest.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
[Fact]
public void Map1Deserialize_MultiNotSameLayer_IfNotEqualThenSKip()
{
Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("A1234567", 1);
dic.Add("A12345678", 2);
dic.Add("B1234567", 3);
dic.Add("B12345678", 4);
var buf = BssomSerializer.Serialize(dic);
var c1 = BssomSerializer.Deserialize<_Map1_3>(buf);
c1.A1234567.Is(1);
c1.A12345679.Is(0);
c1.B1234567.Is(3);
c1.B12345679.Is(0);
}
19
View Source File : MapCodeGenResolverTest.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
[Fact]
public void Map1Deserialize_KeyIsNotNextLayer()
{
Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("A123", 1);
dic.Add("B123", 2);
dic.Add("C123", 3);
dic.Add("D123", 4);
var buf = BssomSerializer.Serialize(dic);
var c1 = BssomSerializer.Deserialize<_Map1_4>(buf);
c1.A123.Is(1);
c1.B123.Is(2);
c1.C123.Is(3);
c1.D123.Is(4);
}
19
View Source File : MapCodeGenResolverTest.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
[Fact]
public void Map1Deserialize_NonField_FormatterIsCorrectly()
{
Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("A12345678", 1);
dic.Add("B12345678", 2);
dic.Add("C12345678", 3);
var buf = BssomSerializer.Serialize(dic);
var c1 = BssomSerializer.Deserialize<_Map1_4_1>(buf);
}
19
View Source File : MapCodeGenResolverTest.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
[Fact]
public void Map1Deserialize_KeyIsNotFirstLayer()
{
Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("A12345678", 1);
dic.Add("B12345678", 2);
dic.Add("C12345678", 3);
var buf = BssomSerializer.Serialize(dic);
var c1 = BssomSerializer.Deserialize<_Map1_5>(buf);
c1.A12345678.Is(1);
c1.B12345678.Is(2);
c1.C12345678.Is(3);
}
19
View Source File : SftpForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void TransfersFileProgress(string id, long precent, long c, long max, int elapsed)
{
try
{
int start = 0, end = Convert.ToInt32(DateTime.Now.ToString("ffff"));
if(TIMEDIC.ContainsKey(id)){
start = TIMEDIC[id];
TIMEDIC[id] = end;
} else {
TIMEDIC.Add(id, end);
}
long startByte = 0, endByte = c;
if (BYTEDIC.ContainsKey(id))
{
startByte = BYTEDIC[id];
BYTEDIC[id] = endByte;
} else {
BYTEDIC.Add(id, endByte);
}
this.BeginInvoke((MethodInvoker)delegate()
{
TransferItem obj = null;
foreach (ListViewItem item in listView3.Items)
{
if (item.Name == id)
{
obj = (TransferItem)item.Tag;
obj.Progress = precent;
item.SubItems[1].Text = TransferStatus.Transfers.ToString();
item.SubItems[2].Text = precent + "%";
item.SubItems[6].Text = Utils.CalculaSpeed(startByte, endByte, max, start, end);
item.SubItems[7].Text = Utils.CalculaTimeLeft(startByte, endByte, max, start, end);
break;
}
}
});
}
catch(Exception ex) {
logger.Error("传输文件的到服务器时异常:" + ex.Message, ex);
ChangeTransferItemStatus("R2L", id, TransferStatus.Failed);
}
}
19
View Source File : NetObjectCache.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
internal int AddObjectKey(object value, out bool existing)
{
if (value == null) throw new ArgumentNullException("value");
if ((object)value == (object)rootObject) // (object) here is no-op, but should be
{ // preserved even if this was typed - needs ref-check
existing = true;
return Root;
}
string s = value as string;
BasicList list = List;
int index;
#if NO_GENERICS
if(s == null)
{
if (objectKeys == null)
{
objectKeys = new ReferenceHashtable();
index = -1;
}
else
{
object tmp = objectKeys[value];
index = tmp == null ? -1 : (int) tmp;
}
}
else
{
if (stringKeys == null)
{
stringKeys = new Hashtable();
index = -1;
}
else
{
object tmp = stringKeys[s];
index = tmp == null ? -1 : (int) tmp;
}
}
#else
if(s == null)
{
#if CF || PORTABLE // CF has very limited proper object ref-tracking; so instead, we'll search it the hard way
index = list.IndexOfReference(value);
#else
if (objectKeys == null)
{
objectKeys = new System.Collections.Generic.Dictionary<object, int>(ReferenceComparer.Default);
index = -1;
}
else
{
if (!objectKeys.TryGetValue(value, out index)) index = -1;
}
#endif
}
else
{
if (stringKeys == null)
{
stringKeys = new System.Collections.Generic.Dictionary<string, int>();
index = -1;
}
else
{
if (!stringKeys.TryGetValue(s, out index)) index = -1;
}
}
#endif
if (!(existing = index >= 0))
{
index = list.Add(value);
if (s == null)
{
#if !CF && !PORTABLE // CF can't handle the object keys very well
objectKeys.Add(value, index);
#endif
}
else
{
stringKeys.Add(s, index);
}
}
return index + 1;
}
19
View Source File : Utility.Unique.cs
License : MIT License
Project Creator : 7Bytes-Studio
License : MIT License
Project Creator : 7Bytes-Studio
public static int GetId(string text)
{
if (!s_IdDic.ContainsKey(text))
{
lock (s_Lock)
{
s_IdDic.Add(text, s_CurrentId++);
}
}
return s_IdDic[text];
}
19
View Source File : RiskFunct.cs
License : GNU General Public License v3.0
Project Creator : 9E4ECDDE
License : GNU General Public License v3.0
Project Creator : 9E4ECDDE
internal static System.Collections.IEnumerator CheckWorld()
{
if (alreadyCheckingWorld)
{
MelonLogger.Error("Attempted to check for world multiple times");
yield break;
}
// Wait for RoomManager to exist before continuing.
ApiWorld currentWorld = null;
while (currentWorld == null)
{
currentWorld = RoomManager.field_Internal_Static_ApiWorld_0;
yield return new WaitForSecondsRealtime(1);
}
var worldId = currentWorld.id;
//MelonLogger.Msg($"Checking World with Id {worldId}");
// Check cache for world, so we keep the number of API calls lower.
//if (checkedWorlds.ContainsKey(worldId))
if (checkedWorlds.TryGetValue(worldId, out int outres))
{
//checkedWorlds.TryGetValue(worldId, out int outres);
NDB.WorldType = outres;
//checkedWorlds[worldId];
//MelonLogger.Msg($"Using cached check {Main.WorldType} for world '{worldId}'");
yield break;
}
// Check for Game Objects first, as it's the lowest cost check.
if (GameObject.Find("eVRCRiskFuncEnable") != null || GameObject.Find("UniversalRiskyFuncEnable") != null || GameObject.Find("ModCompatRiskyFuncEnable ") != null)
{
NDB.WorldType = 0;
checkedWorlds.Add(worldId, 0);
yield break;
}
else if (GameObject.Find("eVRCRiskFuncDisable") != null || GameObject.Find("UniversalRiskyFuncDisable") != null || GameObject.Find("ModCompatRiskyFuncDisable ") != null)
{
NDB.WorldType = 4;
checkedWorlds.Add(worldId, 4);
yield break;
}
alreadyCheckingWorld = true;
// Check if black/whitelisted from EmmVRC - thanks Emilia and the rest of EmmVRC Staff
var uwr = UnityWebRequest.Get($"https://dl.emmvrc.com/riskyfuncs.php?worldid={worldId}");
uwr.SendWebRequest();
while (!uwr.isDone)
yield return new WaitForEndOfFrame();
var result = uwr.downloadHandler.text?.Trim().ToLower();
uwr.Dispose();
if (!string.IsNullOrWhiteSpace(result))
{
switch (result)
{
case "allowed":
NDB.WorldType = 0;
checkedWorlds.Add(worldId, 0);
alreadyCheckingWorld = false;
//MelonLogger.Msg($"EmmVRC allows world '{worldId}'");
yield break;
case "denied":
NDB.WorldType = 3;
checkedWorlds.Add(worldId, 3);
alreadyCheckingWorld = false;
//MelonLogger.Msg($"EmmVRC denies world '{worldId}'");
yield break;
}
}
// No result from server or they're currently down
// Check tags then. should also be in cache as it just got downloaded
API.Fetch<ApiWorld>(
worldId,
new Action<ApiContainer>(
container =>
{
ApiWorld apiWorld;
if ((apiWorld = container.Model.TryCast<ApiWorld>()) != null)
{
short tagResult = 0;
foreach (var worldTag in apiWorld.tags)
{
if (worldTag.IndexOf("game", StringComparison.OrdinalIgnoreCase) != -1 && worldTag.IndexOf("games", StringComparison.OrdinalIgnoreCase) == -1)
{
tagResult = 2;
//MelonLogger.Msg($"Found game tag in world world '{worldId}'");
break;
}
else if (worldTag.IndexOf("club", StringComparison.OrdinalIgnoreCase) != -1)
tagResult = 1;
}
NDB.WorldType = tagResult;
checkedWorlds.Add(worldId, tagResult);
alreadyCheckingWorld = false;
//MelonLogger.Msg($"Tag search result: '{tagResult}' for '{worldId}'");
}
else
{
MelonLogger.Error("Failed to cast ApiModel to ApiWorld");
}
}),
disableCache: false);
}
19
View Source File : UMAData.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public void Merge(UMARecipe recipe, bool dontSerialize)
{
if (recipe == null)
return;
if ((recipe.raceData != null) && (recipe.raceData != raceData))
{
Debug.LogWarning("Merging recipe with conflicting race data: " + recipe.raceData.name);
}
foreach (var dnaEntry in recipe.umaDna)
{
var destDNA = GetOrCreateDna(dnaEntry.Value.GetType(), dnaEntry.Key);
destDNA.Values = dnaEntry.Value.Values;
}
mergedSharedColors.Clear();
if (sharedColors == null)
sharedColors = new OverlayColorData[0];
if (recipe.sharedColors != null)
{
for (int i = 0; i < sharedColors.Length; i++)
{
if (sharedColors[i] != null && sharedColors[i].HasName())
{
while (mergedSharedColors.ContainsKey(sharedColors[i].name))
{
sharedColors[i].name = sharedColors[i].name + ".";
}
mergedSharedColors.Add(sharedColors[i].name, i);
}
}
for (int i = 0; i < recipe.sharedColors.Length; i++)
{
OverlayColorData sharedColor = recipe.sharedColors[i];
if (sharedColor != null && sharedColor.HasName())
{
int sharedIndex;
if (!mergedSharedColors.TryGetValue(sharedColor.name, out sharedIndex))
{
int index = sharedColors.Length;
mergedSharedColors.Add(sharedColor.name, index);
Array.Resize<OverlayColorData>(ref sharedColors, index + 1);
sharedColors[index] = sharedColor.Duplicate();
}
}
}
}
if (slotDataList == null)
slotDataList = new SlotData[0];
if (recipe.slotDataList != null)
{
for (int i = 0; i < recipe.slotDataList.Length; i++)
{
MergeSlot(recipe.slotDataList[i], dontSerialize);
}
}
}
19
View Source File : NvidiaGpuTemperatureReader.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
public override IReadOnlyDictionary<string, int> ReadTemperatures()
{
Dictionary<string, int> temperatures = new();
foreach (PhysicalGPU gpu in PhysicalGPU.GetPhysicalGPUs())
{
string name = gpu.FullName.Replace(" Laptop GPU", string.Empty);
try
{
foreach (GPUThermalSensor sensor in gpu.ThermalInformation.ThermalSensors)
{
temperatures.Add(name, sensor.CurrentTemperature);
}
}
catch (NVIDIAApiException exception)
{
if (exception.Message == "NVAPI_GPU_NOT_POWERED")
{
// GPU is currently powered off.
temperatures.Add(name, 0);
}
else if (exception.Message == "NVAPI_NVIDIA_DEVICE_NOT_FOUND")
{
// NVIDIA device was present previously, but it disappeared? (Driver update in progress?)
// Silently ignore.
}
else
{
throw;
}
}
}
return temperatures;
}
19
View Source File : NvidiaGpuTemperatureReader.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
public override IReadOnlyDictionary<string, int> ReadTemperatures()
{
Dictionary<string, int> temperatures = new();
foreach (PhysicalGPU gpu in PhysicalGPU.GetPhysicalGPUs())
{
string name = gpu.FullName.Replace(" Laptop GPU", string.Empty);
try
{
foreach (GPUThermalSensor sensor in gpu.ThermalInformation.ThermalSensors)
{
temperatures.Add(name, sensor.CurrentTemperature);
}
}
catch (NVIDIAApiException exception)
{
if (exception.Message == "NVAPI_GPU_NOT_POWERED")
{
// GPU is currently powered off.
temperatures.Add(name, 0);
}
else if (exception.Message == "NVAPI_NVIDIA_DEVICE_NOT_FOUND")
{
// NVIDIA device was present previously, but it disappeared? (Driver update in progress?)
// Silently ignore.
}
else
{
throw;
}
}
}
return temperatures;
}
19
View Source File : LibreHardwareMonitorTemperatureReader.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
public override IReadOnlyDictionary<string, int> ReadTemperatures()
{
Dictionary<string, int> temperatures = new();
// OpenHardwareMonitor values
foreach (IHardware hardware in _computer.Hardware)
{
hardware.Update();
foreach (ISensor sensor in hardware.Sensors)
{
if (sensor.SensorType == SensorType.Temperature && sensor.Value.HasValue)
{
if (!sensor.Name.Contains("Average") && !sensor.Name.Contains("Max"))
{
int temperature = sensor.Value != null ? (int)Math.Round(sensor.Value.Value) : 0;
temperatures.Add(sensor.Name, temperature);
}
}
}
}
return temperatures;
}
19
View Source File : GltfUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static Dictionary<string, int> StringIntDictionaryFromJson(string json)
{
string reformatted = JsonDictionaryToArray(json);
StringIntKeyValueArray loadedData = JsonUtility.FromJson<StringIntKeyValueArray>(reformatted);
Dictionary<string, int> dictionary = new Dictionary<string, int>();
for (int i = 0; i < loadedData.items.Length; i++)
{
dictionary.Add(loadedData.items[i].key, loadedData.items[i].value);
}
return dictionary;
}
19
View Source File : DataEntry.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
void requestReportResults()
{
switch (currentState)
{
case states.NOT_INIT:
printOutputLine("The app has not initialized properly and we don't know your userID.");
break;
case states.IDLE:
case states.REQUEST_FIND:
case states.FINDING_ROOM:
case states.REQUEST_JOIN:
case states.REQUEST_CREATE:
case states.REQUEST_LEAVE:
printOutputLine("You need to be in a room with another player to report results on a rated match.");
break;
case states.IN_EMPTY_ROOM:
case states.IN_FULL_ROOM:
if (ratedMatchStarted)
{
printOutputLine("Submitting rated match results.");
Dictionary <string, int> results = new Dictionary<string, int>();
results.Add(localUser.ID.ToString(), 1);
results.Add(remoteUser.ID.ToString(), 2);
Matchmaking.ReportResultsInsecure(currentRoom.ID, results).OnComplete(reportResultsResponse);
}
else
{
printOutputLine("You can't report results unless you've already started a rated match");
}
break;
default:
printOutputLine("You have hit an unknown state.");
break;
}
}
19
View Source File : CaseSensitiveDictionaryContextData.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void Add(
String key,
PipelineContextData value)
{
IndexLookup.Add(key, m_list?.Count ?? 0);
List.Add(new DictionaryContextDataPair(key, value));
}
19
View Source File : TemplateEvaluator.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private void HandleMappingWithWellKnownProperties(
DefinitionInfo definition,
List<MappingDefinition> mappingDefinitions,
MappingToken mapping)
{
// Check if loose properties are allowed
String looseKeyType = null;
String looseValueType = null;
DefinitionInfo? looseKeyDefinition = null;
DefinitionInfo? looseValueDefinition = null;
if (!String.IsNullOrEmpty(mappingDefinitions[0].LooseKeyType))
{
looseKeyType = mappingDefinitions[0].LooseKeyType;
looseValueType = mappingDefinitions[0].LooseValueType;
}
var keys = new HashSet<String>(StringComparer.OrdinalIgnoreCase);
var hasExpressionKey = false;
while (m_unraveler.AllowScalar(definition.Expand, out ScalarToken nextKeyScalar))
{
// Expression
if (nextKeyScalar is ExpressionToken)
{
hasExpressionKey = true;
var anyDefinition = new DefinitionInfo(definition, TemplateConstants.Any);
mapping.Add(nextKeyScalar, Evaluate(anyDefinition));
continue;
}
// Not a string, convert
if (!(nextKeyScalar is StringToken nextKey))
{
nextKey = new StringToken(nextKeyScalar.FileId, nextKeyScalar.Line, nextKeyScalar.Column, nextKeyScalar.ToString());
}
// Duplicate
if (!keys.Add(nextKey.Value))
{
m_context.Error(nextKey, TemplateStrings.ValueAlreadyDefined(nextKey.Value));
m_unraveler.SkipMappingValue();
continue;
}
// Well known
if (m_schema.TryMatchKey(mappingDefinitions, nextKey.Value, out String nextValueType))
{
var nextValueDefinition = new DefinitionInfo(definition, nextValueType);
var nextValue = Evaluate(nextValueDefinition);
mapping.Add(nextKey, nextValue);
continue;
}
// Loose
if (looseKeyType != null)
{
if (looseKeyDefinition == null)
{
looseKeyDefinition = new DefinitionInfo(definition, looseKeyType);
looseValueDefinition = new DefinitionInfo(definition, looseValueType);
}
Validate(nextKey, looseKeyDefinition.Value);
var nextValue = Evaluate(looseValueDefinition.Value);
mapping.Add(nextKey, nextValue);
continue;
}
// Error
m_context.Error(nextKey, TemplateStrings.UnexpectedValue(nextKey.Value));
m_unraveler.SkipMappingValue();
}
// Only one
if (mappingDefinitions.Count > 1)
{
var hitCount = new Dictionary<String, Int32>();
foreach (MappingDefinition mapdef in mappingDefinitions)
{
foreach (String key in mapdef.Properties.Keys)
{
if (!hitCount.TryGetValue(key, out Int32 value))
{
hitCount.Add(key, 1);
}
else
{
hitCount[key] = value + 1;
}
}
}
List<String> nonDuplicates = new List<String>();
foreach (String key in hitCount.Keys)
{
if (hitCount[key] == 1)
{
nonDuplicates.Add(key);
}
}
nonDuplicates.Sort();
String listToDeDuplicate = String.Join(", ", nonDuplicates);
m_context.Error(mapping, TemplateStrings.UnableToDetermineOneOf(listToDeDuplicate));
}
else if (mappingDefinitions.Count == 1 && !hasExpressionKey)
{
foreach (var property in mappingDefinitions[0].Properties)
{
if (property.Value.Required)
{
if (!keys.Contains(property.Key))
{
m_context.Error(mapping, $"Required property is missing: {property.Key}");
}
}
}
}
m_unraveler.ReadMappingEnd();
}
19
View Source File : TemplateReader.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private void HandleMappingWithWellKnownProperties(
DefinitionInfo definition,
List<MappingDefinition> mappingDefinitions,
MappingToken mapping)
{
// Check if loose properties are allowed
String looseKeyType = null;
String looseValueType = null;
DefinitionInfo? looseKeyDefinition = null;
DefinitionInfo? looseValueDefinition = null;
if (!String.IsNullOrEmpty(mappingDefinitions[0].LooseKeyType))
{
looseKeyType = mappingDefinitions[0].LooseKeyType;
looseValueType = mappingDefinitions[0].LooseValueType;
}
var keys = new HashSet<String>(StringComparer.OrdinalIgnoreCase);
var hasExpressionKey = false;
while (m_objectReader.AllowLiteral(out LiteralToken rawLiteral))
{
var nextKeyScalar = ParseScalar(rawLiteral, definition.AllowedContext);
// Expression
if (nextKeyScalar is ExpressionToken)
{
hasExpressionKey = true;
// Legal
if (definition.AllowedContext.Length > 0)
{
m_memory.AddBytes(nextKeyScalar);
var anyDefinition = new DefinitionInfo(definition, TemplateConstants.Any);
mapping.Add(nextKeyScalar, ReadValue(anyDefinition));
}
// Illegal
else
{
m_context.Error(nextKeyScalar, TemplateStrings.ExpressionNotAllowed());
SkipValue();
}
continue;
}
// Not a string, convert
if (!(nextKeyScalar is StringToken nextKey))
{
nextKey = new StringToken(nextKeyScalar.FileId, nextKeyScalar.Line, nextKeyScalar.Column, nextKeyScalar.ToString());
}
// Duplicate
if (!keys.Add(nextKey.Value))
{
m_context.Error(nextKey, TemplateStrings.ValueAlreadyDefined(nextKey.Value));
SkipValue();
continue;
}
// Well known
if (m_schema.TryMatchKey(mappingDefinitions, nextKey.Value, out String nextValueType))
{
m_memory.AddBytes(nextKey);
var nextValueDefinition = new DefinitionInfo(definition, nextValueType);
var nextValue = ReadValue(nextValueDefinition);
mapping.Add(nextKey, nextValue);
continue;
}
// Loose
if (looseKeyType != null)
{
if (looseKeyDefinition == null)
{
looseKeyDefinition = new DefinitionInfo(definition, looseKeyType);
looseValueDefinition = new DefinitionInfo(definition, looseValueType);
}
Validate(nextKey, looseKeyDefinition.Value);
m_memory.AddBytes(nextKey);
var nextValue = ReadValue(looseValueDefinition.Value);
mapping.Add(nextKey, nextValue);
continue;
}
// Error
m_context.Error(nextKey, TemplateStrings.UnexpectedValue(nextKey.Value));
SkipValue();
}
// Only one
if (mappingDefinitions.Count > 1)
{
var hitCount = new Dictionary<String, Int32>();
foreach (MappingDefinition mapdef in mappingDefinitions)
{
foreach (String key in mapdef.Properties.Keys)
{
if (!hitCount.TryGetValue(key, out Int32 value))
{
hitCount.Add(key, 1);
}
else
{
hitCount[key] = value + 1;
}
}
}
List<String> nonDuplicates = new List<String>();
foreach (String key in hitCount.Keys)
{
if(hitCount[key] == 1)
{
nonDuplicates.Add(key);
}
}
nonDuplicates.Sort();
String listToDeDuplicate = String.Join(", ", nonDuplicates);
m_context.Error(mapping, TemplateStrings.UnableToDetermineOneOf(listToDeDuplicate));
}
else if (mappingDefinitions.Count == 1 && !hasExpressionKey)
{
foreach (var property in mappingDefinitions[0].Properties)
{
if (property.Value.Required)
{
if (!keys.Contains(property.Key))
{
m_context.Error(mapping, $"Required property is missing: {property.Key}");
}
}
}
}
ExpectMappingEnd();
}
19
View Source File : ObjectShredder.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public DataTable ExtendTable(DataTable table, Type type)
{
// Extend the table schema if the input table was null or if the value
// in the sequence is derived from type T.
foreach (FieldInfo f in type.GetFields())
{
if (!_ordinalMap.ContainsKey(f.Name))
{
var ft = f.FieldType;
if (ft.IsGenericType && ft.GetGenericTypeDefinition() == typeof(Nullable<>))
{
ft = Nullable.GetUnderlyingType(ft);
}
// Add the field as a column in the table if it doesn't exist
// already.
DataColumn dc = table.Columns.Contains(f.Name)
? table.Columns[f.Name]
: table.Columns.Add(f.Name, ft);
// Add the field to the ordinal map.
_ordinalMap.Add(f.Name, dc.Ordinal);
}
}
foreach (PropertyInfo p in type.GetProperties())
{
if (!_ordinalMap.ContainsKey(p.Name))
{
var pt = p.PropertyType;
if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
{
pt = Nullable.GetUnderlyingType(pt);
}
// Add the property as a column in the table if it doesn't exist
// already.
DataColumn dc = table.Columns.Contains(p.Name)
? table.Columns[p.Name]
: table.Columns.Add(p.Name, pt);
// Add the property to the ordinal map.
_ordinalMap.Add(p.Name, dc.Ordinal);
}
}
// Return the table.
return table;
}
19
View Source File : PortalFacetedIndexSearcher.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private IEnumerable<ConstraintHit> GroupRecordTypeFacet(KeyValuePair<string, IFacetAccessible> currentFacet, IEnumerable<FacetConstraints> clientFacetConstraints)
{
var enreplacedyToRecordMap = new Dictionary<string, string>();
var groupedFacets = new Dictionary<string, int>();
var settingsString = this.RecordTypeFacetsEnreplacedies;
var result = new List<ConstraintHit>();
settingsString = this.RemoveDuplicates(settingsString);
if (string.IsNullOrEmpty(settingsString))
{
return this.BrowseFacetsToConstraintHits(currentFacet, clientFacetConstraints);
}
foreach (var groupName in Web.Mvc.Html.SettingExtensions.SplitSearchFilterOptions(settingsString))
{
var trimmedGroupName = groupName.Value.Trim();
if (string.IsNullOrEmpty(trimmedGroupName))
{
continue;
}
foreach (var logicalName in trimmedGroupName.Split(','))
{
var trimmedLogicalName = logicalName.Trim();
if (string.IsNullOrEmpty(trimmedLogicalName))
{
continue;
}
enreplacedyToRecordMap.Add(trimmedLogicalName, trimmedGroupName);
}
groupedFacets.Add(trimmedGroupName, 0);
}
var browseFacets = currentFacet.Value.GetFacets();
foreach (var facet in browseFacets)
{
var logicalName = facet.Value;
// adds browseFacet if it's not present in site setting grouping
if (!enreplacedyToRecordMap.ContainsKey(logicalName))
{
groupedFacets.Add(logicalName, facet.FacetValueHitCount);
continue;
}
groupedFacets[enreplacedyToRecordMap[logicalName]] += facet.FacetValueHitCount;
}
foreach (var facet in groupedFacets)
{
if (facet.Value > 0 || clientFacetConstraints.Where(constraints => constraints.FacetName == currentFacet.Key).SelectMany(constraints => constraints.Constraints).Any(constraintName => facet.Key.Contains(constraintName)))
{
result.Add(new ConstraintHit(facet.Key, facet.Value, Web.Extensions.LocalizeRecordTypeName(facet.Key.Split(',')[0])));
}
}
return result.OrderByDescending(x => x.HitCount);
}
19
View Source File : LinkEntityAliasGenerator.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void IncrementIndex(string aliasPrefix)
{
if (!this.mapping.ContainsKey(aliasPrefix))
{
this.mapping.Add(aliasPrefix, 0);
}
this.mapping[aliasPrefix]++;
}
19
View Source File : LinkEntityAliasGenerator.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private int GetIndex(string aliasPrefix)
{
if (!this.mapping.ContainsKey(aliasPrefix))
{
this.mapping.Add(aliasPrefix, 0);
}
return this.mapping[aliasPrefix];
}
19
View Source File : Misc.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public static int GetTopOfHeadSleepOffset(string name)
{
if (topOfHeadOffsets.ContainsKey(name))
{
return topOfHeadOffsets[name];
}
//Monitor.Log($"dont yet have offset for {name}");
int top = 0;
if (name == "Krobus")
return 8;
Texture2D tex = Helper.Content.Load<Texture2D>($"Characters/{name}", ContentSource.GameContent);
int sleepidx;
string sleepAnim = SleepAnimation(name);
if (sleepAnim == null || !int.TryParse(sleepAnim.Split('/')[0], out sleepidx))
sleepidx = 8;
if ((sleepidx * 16) / 64 * 32 >= tex.Height)
{
sleepidx = 8;
}
Color[] colors = new Color[tex.Width * tex.Height];
tex.GetData(colors);
//Monitor.Log($"sleep index for {name} {sleepidx}");
int startx = (sleepidx * 16) % 64;
int starty = (sleepidx * 16) / 64 * 32;
//Monitor.Log($"start {startx},{starty}");
for (int i = 0; i < 16 * 32; i++)
{
int idx = startx + (i % 16) + (starty + i / 16) * 64;
if (idx >= colors.Length)
{
Monitor.Log($"Sleep pos couldn't get pixel at {startx + i % 16},{starty + i / 16} ");
break;
}
Color c = colors[idx];
if(c != Color.Transparent)
{
top = i / 16;
break;
}
}
topOfHeadOffsets.Add(name, top);
return top;
}
19
View Source File : Misc.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public static int GetTopOfHeadSleepOffset(string name)
{
if (topOfHeadOffsets.ContainsKey(name))
{
return topOfHeadOffsets[name];
}
//Monitor.Log($"dont yet have offset for {name}");
int top = 0;
if (name == "Krobus")
return 8;
Texture2D tex = Helper.Content.Load<Texture2D>($"Characters/{name}", ContentSource.GameContent);
int sleepidx;
string sleepAnim = SleepAnimation(name);
if (sleepAnim == null || !int.TryParse(sleepAnim.Split('/')[0], out sleepidx))
sleepidx = 8;
if ((sleepidx * 16) / 64 * 32 >= tex.Height)
{
sleepidx = 8;
}
Color[] colors = new Color[tex.Width * tex.Height];
tex.GetData(colors);
//Monitor.Log($"sleep index for {name} {sleepidx}");
int startx = (sleepidx * 16) % 64;
int starty = (sleepidx * 16) / 64 * 32;
//Monitor.Log($"start {startx},{starty}");
for (int i = 0; i < 16 * 32; i++)
{
int idx = startx + (i % 16) + (starty + i / 16) * 64;
if (idx >= colors.Length)
{
Monitor.Log($"Sleep pos couldn't get pixel at {startx + i % 16},{starty + i / 16} ");
break;
}
Color c = colors[idx];
if (c != Color.Transparent)
{
top = i / 16;
break;
}
}
topOfHeadOffsets.Add(name, top);
return top;
}
19
View Source File : ConfigFile.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public int GetInt(string key)
{
int result;
if (integers.TryGetValue(key, out result))
{
return result;
}
string val;
if (allValues.TryGetValue(key, out val))
{
if (int.TryParse(val, out result))
{
integers.Add(key, result);
}
}
return result;
}
19
View Source File : ReplayAnimationRecorder.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public void RecordAnimationCall(ReplayGameObject go, AnimationType type, string animation, float time = 0f)
{
int animationId;
if(!animationsDictionary.TryGetValue(animation, out animationId))
{
animationId = nextAnimId;
animationsDictionary.Add(animation, nextAnimId++);
}
playedAnimations.Add(new AnimationPlayInformation(
animationId,
type,
go.Id,
FengGameManagerMKII.FGM.logic.RoundTime,
time));
}
19
View Source File : ConfigFile.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public void SetInt(string key, int val)
{
if (integers.ContainsKey(key))
{
integers[key] = val;
return;
}
integers.Add(key, val);
}
19
View Source File : ExcelImporter.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public bool Prepare(ISheet sheet)
{
Sheet = sheet;
if (!Initiate() || !CheckFieldMaps()) return false;
ColumnFields2 = new Dictionary<string, int>();
foreach (var mf in ColumnFields) ColumnFields2.Add(mf.Value, mf.Key);
return true;
}
19
View Source File : CSRedisClientAsync.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
async public Task<T[]> CacheShellAsync<T>(string key, string[] fields, int timeoutSeconds, Func<string[], Task<(string, T)[]>> getDataAsync, Func<(T, long), string> serialize, Func<string, (T, long)> deserialize) {
fields = fields?.Distinct().ToArray();
if (fields == null || fields.Length == 0) return new T[0];
if (timeoutSeconds <= 0) return (await getDataAsync(fields)).Select(a => a.Item2).ToArray();
var ret = new T[fields.Length];
var cacheValue = await HashMGetAsync(key, fields);
var fieldsMGet = new Dictionary<string, int>();
for (var a = 0; a < cacheValue.Length; a++) {
if (cacheValue[a] != null) {
try {
var value = deserialize(cacheValue[a]);
if (DateTime.Now.Subtract(dt1970.AddSeconds(value.Item2)).TotalSeconds <= timeoutSeconds) {
ret[a] = value.Item1;
continue;
}
} catch {
await HashDeleteAsync(key, fields[a]);
throw;
}
}
fieldsMGet.Add(fields[a], a);
}
if (fieldsMGet.Any()) {
var getDataIntput = fieldsMGet.Keys.ToArray();
var data = await getDataAsync(getDataIntput);
var mset = new object[fieldsMGet.Count * 2];
var msetIndex = 0;
foreach (var d in data) {
if (fieldsMGet.ContainsKey(d.Item1) == false) throw new Exception($"使用 CacheShell 请确认 getData 返回值 (string, T)[] 中的 Item1 值: {d.Item1} 存在于 输入参数: {string.Join(",", getDataIntput)}");
ret[fieldsMGet[d.Item1]] = d.Item2;
mset[msetIndex++] = d.Item1;
mset[msetIndex++] = serialize((d.Item2, (long)DateTime.Now.Subtract(dt1970).TotalSeconds));
fieldsMGet.Remove(d.Item1);
}
foreach (var fieldNull in fieldsMGet.Keys) {
ret[fieldsMGet[fieldNull]] = default(T);
mset[msetIndex++] = fieldNull;
mset[msetIndex++] = serialize((default(T), (long)DateTime.Now.Subtract(dt1970).TotalSeconds));
}
if (mset.Any()) await HashSetAsync(key, mset);
}
return ret.ToArray();
}
19
View Source File : ExcelImporter.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public bool Prepare(ISheet sheet)
{
Sheet = sheet;
if (!Initiate() || !CheckFieldMaps())
{
return false;
}
ColumnFields2 = new Dictionary<string, int>();
foreach (var mf in ColumnFields)
{
ColumnFields2.Add(mf.Value, mf.Key);
}
return true;
}
19
View Source File : ExcelImporter.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public bool Prepare(ISheet sheet, Dictionary<string, string> map)
{
FieldMap = map;
Sheet = sheet;
Sheet = sheet;
if (!Initiate() || !CheckFieldMaps())
{
return false;
}
ColumnFields2 = new Dictionary<string, int>();
foreach (var mf in ColumnFields)
{
ColumnFields2.Add(mf.Value, mf.Key);
}
return true;
}
19
View Source File : CollectionInitializerSamples.cs
License : The Unlicense
Project Creator : ahotko
License : The Unlicense
Project Creator : ahotko
private void Dictionaries()
{
var dictionary = new Dictionary<string, int>()
{
["one"] = 1,
["two"] = 2,
["three"] = 3
};
Console.WriteLine($"Collection Contents: {string.Join(", ", dictionary.Select(kv => kv.Key + "=" + kv.Value).ToArray())}");
dictionary.Add("zero", 0);
Console.WriteLine($"Collection Contents After Addition: {string.Join(", ", dictionary.Select(kv => kv.Key + "=" + kv.Value).ToArray())}");
}
19
View Source File : NodeParamSet.cs
License : MIT License
Project Creator : aillieo
License : MIT License
Project Creator : aillieo
protected int AddDefaultValue(string key, params object[] args)
{
int len = nodeParams.Length;
Array.Resize(ref nodeParams, len + 1);
R nodeParam = new R();
nodeParam.key = key;
nodeParam.value = default;
for(int i = 0, argCount = args.Length; i< argCount; i+=2)
{
string fieldName = args[i] as string;
if (fieldName != null)
{
FieldInfo fi = typeof(R).GetField(fieldName, BindingFlags.Instance | BindingFlags.Public);
if(fi != null)
{
fi.SetValue(nodeParam, args[i + 1]);
}
}
}
nodeParams[len] = nodeParam;
dict.Add(key, len);
return 0;
}
19
View Source File : NpoiHelper.cs
License : MIT License
Project Creator : aishang2015
License : MIT License
Project Creator : aishang2015
public MemoryStream ExportExcel<T>(
List<T> dataList,
Dictionary<string, string> dic,
string sheetName = "")
{
var workbook = new HSSFWorkbook();
var sheet = workbook.CreateSheet(sheetName);
// 行下标
var rowNum = 1;
var replacedleRow = sheet.CreateRow(rowNum);
// 列下标
var colNum = 0;
// 获取属性
var positionDic = new Dictionary<string, int>();
// 设置标题
foreach (var item in dic)
{
replacedleRow.CreateCell(colNum).SetCellValue(item.Value);
positionDic.Add(item.Value, colNum);
colNum++;
}
// 设置内容
rowNum++;
var properties = typeof(T).GetProperties();
foreach (var item in dataList)
{
var row = sheet.CreateRow(rowNum);
for (int i = 0; i < properties.Length; i++)
{
// 属性字典中没有该属性运行下一个属性
if (!dic.ContainsKey(properties[i].Name))
{
continue;
}
// 获取属性值
var value = properties[i].GetValue(item)?.ToString();
//获取对应列下标,并设定值
var colIndex = positionDic[dic[properties[i].Name]];
row.CreateCell(colIndex).SetCellValue(value);
}
}
var ms = new MemoryStream();
workbook.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
//return File(ms, "application/vns.ms-excel", $"{filename}"); ;
return ms;
}
19
View Source File : TraverserAnimationController.cs
License : MIT License
Project Creator : AitorSimona
License : MIT License
Project Creator : AitorSimona
private void Start()
{
controller = GetComponent<TraverserCharacterController>();
animator = GetComponent<Animator>();
transition = new TraverserTransition(this, ref controller);
animatorParameters = new Dictionary<string, int>();
hipsEffectorOriginalTransform = TraverserTransform.Get(hipsRigEffector.transform.localPosition, hipsRigEffector.transform.localRotation);
spineEffectorOriginalTransform = TraverserTransform.Get(spineRigEffector.transform.localPosition, spineRigEffector.transform.localRotation);
leftLegEffectorOriginalTransform = TraverserTransform.Get(leftLegRigEffector.transform.localPosition, leftLegRigEffector.transform.localRotation);
rightLegEffectorOriginalTransform = TraverserTransform.Get(rightLegRigEffector.transform.localPosition, rightLegRigEffector.transform.localRotation);
aimEffectorOriginalTransform = TraverserTransform.Get(aimRigEffector.transform.localPosition, aimRigEffector.transform.localRotation);
// --- Save all animator parameter hashes for future reference ---
foreach (AnimatorControllerParameter param in animator.parameters)
{
animatorParameters.Add(param.name, param.nameHash);
}
}
19
View Source File : Prefetch.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public static Prefetch Load(Patch patch = null)
{
var prefetch = new Prefetch();
prefetch.Core = patch?.AddFile(IoC.Config.PrefetchFile) ?? IoC.Archiver.LoadGameFile(IoC.Config.PrefetchFile);
prefetch.Data = prefetch.Core.GetType<PrefetchList>();
prefetch.Files = new Dictionary<string, int>();
for (int i = 0; i < prefetch.Data.Files.Count; i++)
prefetch.Files.Add(prefetch.Data.Files[i].Path.Value, i);
return prefetch;
}
19
View Source File : JSONTransformComponent.cs
License : GNU General Public License v2.0
Project Creator : albertogeniola
License : GNU General Public License v2.0
Project Creator : albertogeniola
public override void PreExecute()
{
bool debugging = false;
IDTSVariables100 vars = null;
try
{
VariableDispenser.LockOneForRead(JSON_SOURCE_DEBUG_VAR, ref vars);
object o = vars[JSON_SOURCE_DEBUG_VAR].Value;
if (o != null)
if ((bool)o)
debugging = true;
}
catch(Exception e){
//Do nothing
bool fireAgain = false;
ComponentMetaData.FireInformation(0, ComponentMetaData.Name, "wk_debug variable cannot be found. I won't stop to let debug attachment.", null,0,ref fireAgain);
}
finally
{
if (vars != null)
vars.Unlock();
}
if (debugging)
MessageBox.Show("Start Debugger");
TransformationModel m = GetModel();
_opt = new ParallelOptions();
_opt.MaxDegreeOfParallelism = 4;
bool cancel = false;
// Carico i dettagli dal model
try{
m = GetModel();
}catch(ModelNotFoundException ex) {
ComponentMetaData.FireError(RUNTIME_ERROR_MODEL_INVALID, ComponentMetaData.Name, "Invalid Metadata for this component.", null, 0, out cancel);
return;
}
// Salva il mapping in un array locale
_iomap = m.IoMap.ToArray<IOMapEntry>();
// Salva una copia locale del percorso cui attingere l'array
_pathToArray = m.JsonObjectRelativePath;
// Genera un dizionario ad accesso veloce per il nome della colonna per i dati json: mappo nome colonna - Indice della colonna nella riga.
// Questo dizionario è usato solo per il JSON, mentre per gli input standard non facciamo il lookup, ma usiamo l'indice del buffer.
_startOfJsonColIndex = ComponentMetaData.InputCollection[0].InputColumnCollection.Count;
_outColsMaps = new Dictionary<string, int>();
foreach (IOMapEntry e in _iomap)
{
bool found = false;
for (var i = 0; i<_iomap.Count(); i++)
{
var col = ComponentMetaData.OutputCollection[0].OutputColumnCollection[_startOfJsonColIndex + i];
if (col.Name == e.OutputColName)
{
found = true;
int colIndex = BufferManager.FindColumnByLineageID(ComponentMetaData.OutputCollection[0].Buffer, col.LineageID);
_outColsMaps.Add(e.OutputColName, colIndex);
break;
}
}
if (!found)
{
// Una colonna del model non ha trovato il corrispettivo nel componente attuale
ComponentMetaData.FireError(RUNTIME_ERROR_MODEL_INVALID, ComponentMetaData.Name, "The component is unable to locate the column named " + e.OutputColName + " inside the component metadata. Please review the component.", null, 0, out cancel);
return;
}
}
_inputColIndex = BufferManager.FindColumnByLineageID(ComponentMetaData.InputCollection[0].Buffer, ComponentMetaData.InputCollection[0].InputColumnCollection[GetModel().InputColumnName].LineageID);
// Check if ww should take care of date parsing
if (!m.ParseDates) {
_dateParsePolicy = DateParseHandling.None;
}
}
19
View Source File : JsonSerializer.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
private void WriteObject(object obj)
{
int i = 0;
if (_cirobj.TryGetValue(obj, out i) == false)
_cirobj.Add(obj, _cirobj.Count + 1);
else
{
if (_current_depth > 0 && _params.InlineCircularReferences == false)
{
//_circular = true;
_output.Append("{\"$i\":");
_output.Append(i.ToString());
_output.Append("}");
return;
}
}
if (_params.UsingGlobalTypes == false)
_output.Append('{');
else
{
if (_TypesWritten == false)
{
_output.Append('{');
_before = _output.Length;
//_output = new StringBuilder();
}
else
_output.Append('{');
}
_TypesWritten = true;
_current_depth++;
if (_current_depth > _MAX_DEPTH)
throw new Exception("Serializer encountered maximum depth of " + _MAX_DEPTH);
Dictionary<string, string> map = new Dictionary<string, string>();
Type t = obj.GetType();
bool append = false;
if (_params.UseExtensions)
{
if (_params.UsingGlobalTypes == false)
WritePairFast("$type", Reflection.Instance.GetTypereplacedemblyName(t));
else
{
int dt = 0;
string ct = Reflection.Instance.GetTypereplacedemblyName(t);
if (_globalTypes.TryGetValue(ct, out dt) == false)
{
dt = _globalTypes.Count + 1;
_globalTypes.Add(ct, dt);
}
WritePairFast("$type", dt.ToString());
}
append = true;
}
Getters[] g = Reflection.Instance.GetGetters(t, _params.IgnoreAttributes);
int c = g.Length;
for (int ii = 0; ii < c; ii++)
{
var p = g[ii];
object o = p.Property.GetValue(obj);
if (_params.SerializeNullValues == false && (o == null || o is DBNull))
{
//append = false;
}
else
{
if (append)
_output.Append(',');
if (p.memberName != null)
WritePair(p.memberName, o);
else
{
WritePair(JsonHelper.SerializaName(_params.JsonFormatting, p.Name), o);
}
if (o != null && _params.UseExtensions)
{
Type tt = o.GetType();
if (tt == typeof(System.Object))
map.Add(p.Name, tt.ToString());
}
append = true;
}
}
if (map.Count > 0 && _params.UseExtensions)
{
_output.Append(",\"$map\":");
WriteStringDictionary(map);
}
_output.Append('}');
_current_depth--;
}
19
View Source File : PatreonCrawledUrlProcessor.cs
License : MIT License
Project Creator : AlexCSDev
License : MIT License
Project Creator : AlexCSDev
public async Task<bool> ProcessCrawledUrl(ICrawledUrl udpCrawledUrl, string downloadDirectory)
{
PatreonCrawledUrl crawledUrl = (PatreonCrawledUrl)udpCrawledUrl;
bool skipChecks = false; //skip sanitization, duplicate and other checks, do not preplaced filename to download path
if (crawledUrl.Url.IndexOf("dropbox.com/", StringComparison.Ordinal) != -1)
{
if (!crawledUrl.Url.EndsWith("?dl=1"))
{
if (crawledUrl.Url.EndsWith("?dl=0"))
crawledUrl.Url = crawledUrl.Url.Replace("?dl=0", "?dl=1");
else
crawledUrl.Url = $"{crawledUrl.Url}?dl=1";
}
_logger.Debug($"[{crawledUrl.PostId}] This is a dropbox entry: {crawledUrl.Url}");
}
else if (crawledUrl.Url.StartsWith("https://mega.nz/"))
{
_logger.Debug($"[{crawledUrl.PostId}] mega found: {crawledUrl.Url}");
skipChecks = true; //mega plugin expects to see only path to the folder where everything will be saved
}
else if (_googleDriveRegex.Match(crawledUrl.Url).Success)
{
_logger.Debug($"[{crawledUrl.PostId}] google drive found: {crawledUrl.Url}");
skipChecks = true; //no need for checks if we use google drive plugin
}
else if (crawledUrl.Url.IndexOf("youtube.com/watch?v=", StringComparison.Ordinal) != -1 ||
crawledUrl.Url.IndexOf("youtu.be/", StringComparison.Ordinal) != -1)
{
//TODO: YOUTUBE SUPPORT?
_logger.Fatal($"[{crawledUrl.PostId}] [NOT SUPPORTED] YOUTUBE link found: {crawledUrl.Url}");
}
else if (crawledUrl.Url.IndexOf("imgur.com/", StringComparison.Ordinal) != -1)
{
//TODO: IMGUR SUPPORT
_logger.Fatal($"[{crawledUrl.PostId}] [NOT SUPPORTED] IMGUR link found: {crawledUrl.Url}");
}
string filename = crawledUrl.Filename;
if (!skipChecks)
{
if (!_patreonDownloaderSettings.UseSubDirectories)
filename = $"{crawledUrl.PostId}_";
else
filename = "";
switch (crawledUrl.UrlType)
{
case PatreonCrawledUrlType.PostFile:
filename += "post";
break;
case PatreonCrawledUrlType.PostAttachment:
filename += "attachment";
break;
case PatreonCrawledUrlType.PostMedia:
filename += "media";
break;
case PatreonCrawledUrlType.AvatarFile:
filename += "avatar";
break;
case PatreonCrawledUrlType.CoverFile:
filename += "cover";
break;
case PatreonCrawledUrlType.ExternalUrl:
filename += "external";
break;
default:
throw new ArgumentException($"Invalid url type: {crawledUrl.UrlType}");
}
if (crawledUrl.Filename == null)
{
_logger.Debug($"No filename for {crawledUrl.Url}, trying to retrieve...");
string remoteFilename =
await _remoteFilenameRetriever.RetrieveRemoteFileName(crawledUrl.Url);
if (remoteFilename == null)
{
throw new DownloadException(
$"[{crawledUrl.PostId}] Unable to retrieve name for external entry of type {crawledUrl.UrlType}: {crawledUrl.Url}");
}
filename += $"_{remoteFilename}";
}
else
{
filename += $"_{crawledUrl.Filename}";
}
_logger.Debug($"Filename for {crawledUrl.Url} is {filename}");
_logger.Debug($"Sanitizing filename: {filename}");
filename = PathSanitizer.SanitizePath(filename);
_logger.Debug($"Sanitized filename: {filename}");
if (filename.Length > _patreonDownloaderSettings.MaxFilenameLength)
{
_logger.Debug($"Filename is too long, will be truncated: {filename}");
string extension = Path.GetExtension(filename);
if (extension.Length > 4)
{
_logger.Warn($"File extension for file {filename} is longer 4 characters and won't be appended to truncated filename!");
extension = "";
}
filename = filename.Substring(0, _patreonDownloaderSettings.MaxFilenameLength) + extension;
_logger.Debug($"Truncated filename: {filename}");
}
string key = $"{crawledUrl.PostId}_{filename.ToLowerInvariant()}";
if (!_fileCountDict.ContainsKey(key))
_fileCountDict.Add(key, 0);
_fileCountDict[key]++;
if (_fileCountDict[key] > 1)
{
_logger.Warn($"Found more than a single file with the name {filename} in the same folder in post {crawledUrl.PostId}, sequential number will be appended to its name.");
string appendStr = _fileCountDict[key].ToString();
if (crawledUrl.UrlType != PatreonCrawledUrlType.ExternalUrl)
{
MatchCollection matches = _fileIdRegex.Matches(crawledUrl.Url);
if (matches.Count == 0)
throw new DownloadException($"[{crawledUrl.PostId}] Unable to retrieve file id for {crawledUrl.Url}, contact developer!");
if (matches.Count > 1)
throw new DownloadException($"[{crawledUrl.PostId}] More than 1 media found in URL {crawledUrl.Url}");
appendStr = matches[0].Groups[5].Value;
}
filename = $"{Path.GetFileNameWithoutExtension(filename)}_{appendStr}{Path.GetExtension(filename)}";
}
}
if (_patreonDownloaderSettings.UseSubDirectories &&
crawledUrl.UrlType != PatreonCrawledUrlType.AvatarFile &&
crawledUrl.UrlType != PatreonCrawledUrlType.CoverFile)
downloadDirectory = Path.Combine(downloadDirectory, PostSubdirectoryHelper.CreateNameFromPattern(crawledUrl, _patreonDownloaderSettings.SubDirectoryPattern));
crawledUrl.DownloadPath = !skipChecks ? Path.Combine(downloadDirectory, filename) : downloadDirectory + Path.DirectorySeparatorChar;
return true;
}
19
View Source File : CategoryAxis.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
internal override void UpdateFromSeries(IEnumerable<Series> series)
{
if (this.Labels.Count == 0)
{
this.TotalWidthPerCategory = null;
this.MaxWidth = double.NaN;
this.BarOffset = null;
this.StackedBarOffset = null;
this.StackIndexMapping = null;
this.PositiveBaseValues = null;
this.NegativeBaseValues = null;
this.MaxValue = null;
this.MinValue = null;
return;
}
this.TotalWidthPerCategory = new double[this.Labels.Count];
var usedSeries = series.Where(s => s.IsUsing(this)).ToList();
// Add width of stacked series
var categorizedSeries = usedSeries.OfType<CategorizedSeries>().ToList();
var stackedSeries = categorizedSeries.OfType<IStackableSeries>().Where(s => s.IsStacked).ToList();
var stackIndices = stackedSeries.Select(s => s.StackGroup).Distinct().ToList();
var stackRankBarWidth = new Dictionary<int, double>();
for (var j = 0; j < stackIndices.Count; j++)
{
var maxBarWidth =
stackedSeries.Where(s => s.StackGroup == stackIndices[j]).Select(
s => ((CategorizedSeries)s).GetBarWidth()).Concat(new[] { 0.0 }).Max();
for (var i = 0; i < this.Labels.Count; i++)
{
int k = 0;
if (
stackedSeries.SelectMany(s => ((CategorizedSeries)s).Gereplacedems()).Any(
item => item.GetCategoryIndex(k++) == i))
{
this.TotalWidthPerCategory[i] += maxBarWidth;
}
}
stackRankBarWidth[j] = maxBarWidth;
}
// Add width of unstacked series
var unstackedBarSeries =
categorizedSeries.Where(s => !(s is IStackableSeries) || !((IStackableSeries)s).IsStacked).ToList();
foreach (var s in unstackedBarSeries)
{
for (var i = 0; i < this.Labels.Count; i++)
{
int j = 0;
var numberOfItems = s.Gereplacedems().Count(item => item.GetCategoryIndex(j++) == i);
this.TotalWidthPerCategory[i] += s.GetBarWidth() * numberOfItems;
}
}
this.MaxWidth = this.TotalWidthPerCategory.Max();
// Calculate BarOffset and StackedBarOffset
this.BarOffset = new double[this.Labels.Count];
this.StackedBarOffset = new double[stackIndices.Count + 1, this.Labels.Count];
var factor = 0.5 / (1 + this.GapWidth) / this.MaxWidth;
for (var i = 0; i < this.Labels.Count; i++)
{
this.BarOffset[i] = 0.5 - (this.TotalWidthPerCategory[i] * factor);
}
for (var j = 0; j <= stackIndices.Count; j++)
{
for (var i = 0; i < this.Labels.Count; i++)
{
int k = 0;
if (
stackedSeries.SelectMany(s => ((CategorizedSeries)s).Gereplacedems()).All(
item => item.GetCategoryIndex(k++) != i))
{
continue;
}
this.StackedBarOffset[j, i] = this.BarOffset[i];
if (j < stackIndices.Count)
{
this.BarOffset[i] += stackRankBarWidth[j] / (1 + this.GapWidth) / this.MaxWidth;
}
}
}
stackIndices.Sort();
this.StackIndexMapping = new Dictionary<string, int>();
for (var i = 0; i < stackIndices.Count; i++)
{
this.StackIndexMapping.Add(stackIndices[i], i);
}
this.PositiveBaseValues = new double[stackIndices.Count, this.Labels.Count];
Fill(this.PositiveBaseValues, double.NaN);
this.NegativeBaseValues = new double[stackIndices.Count, this.Labels.Count];
Fill(this.NegativeBaseValues, double.NaN);
this.MaxValue = new double[stackIndices.Count, this.Labels.Count];
Fill(this.MaxValue, double.NaN);
this.MinValue = new double[stackIndices.Count, this.Labels.Count];
Fill(this.MinValue, double.NaN);
}
19
View Source File : DuplicatePreventionBuffer.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
public bool RegisterLocalVariableName( int nodeId, string name )
{
if ( name.Length == 0 )
return false;
if ( m_availableLocalVariableNames.ContainsKey( name ) )
{
if ( m_availableLocalVariableNames[ name ] > -1 )
{
return false;
}
else
{
m_availableLocalVariableNames[ name ] = nodeId;
return true;
}
}
m_availableLocalVariableNames.Add( name, nodeId );
return true;
}
19
View Source File : DuplicatePreventionBuffer.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
public bool RegisterUniformName( int nodeId, string name )
{
if ( name.Length == 0 )
return false;
if ( m_availableUniformNames.ContainsKey( name ) )
{
if ( m_availableUniformNames[ name ] > -1 )
{
return false;
}
else
{
m_availableUniformNames[ name ] = nodeId;
return true;
}
}
m_availableUniformNames.Add( name, nodeId );
return true;
}
19
View Source File : DuplicatePreventionBuffer.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
public bool GetPropertyName( int nodeId, string name )
{
if ( m_availablePropertyNames.ContainsKey( name ) )
{
if ( m_availablePropertyNames[ name ] > -1 )
{
return false;
}
else
{
m_availablePropertyNames[ name ] = nodeId;
return true;
}
}
m_availablePropertyNames.Add( name, nodeId );
return true;
}
19
View Source File : TemplateOptionsData.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
public static TemplateOptionsContainer GenerateOptionsContainer( bool isSubShader, string data )
{
TemplateOptionsContainer optionsContainer = new TemplateOptionsContainer();
Match match = Regex.Match( data, isSubShader ? SubShaderOptionsMainPattern : PreplacedOptionsMainPattern );
optionsContainer.Enabled = match.Success;
if( match.Success )
{
try
{
optionsContainer.Body = match.Value;
optionsContainer.Index = match.Index;
List<TemplateOptionsItem> optionItemsList = new List<TemplateOptionsItem>();
List<List<TemplateActionItem>> actionItemsList = new List<List<TemplateActionItem>>();
Dictionary<string, int> optionItemToIndex = new Dictionary<string, int>();
TemplateOptionsItem currentOption = null;
//OPTIONS OVERALL SETUP
string[] setupLines = match.Groups[ 1 ].Value.Split( ':' );
for( int i = 0; i < setupLines.Length; i++ )
{
if( AseOptionsSetupDict.ContainsKey( setupLines[ i ] ) )
{
AseOptionsSetup setup = AseOptionsSetupDict[ setupLines[ i ] ];
switch( setup )
{
case AseOptionsSetup.CopyOptionsFromMainPreplaced: optionsContainer.CopyOptionsFromMainPreplaced = true; break;
}
}
else
{
string[] args = setupLines[ i ].Split( '=' );
if( args.Length > 1 && AseOptionsSetupDict.ContainsKey( args[ 0 ] ) )
{
AseOptionsSetup setup = AseOptionsSetupDict[ args[ 0 ] ];
switch( setup )
{
case AseOptionsSetup.Id: if( !int.TryParse( args[ 1 ], out optionsContainer.Id ) ) optionsContainer.Id = -1; break;
case AseOptionsSetup.Name: optionsContainer.Name = args[ 1 ]; break;
}
}
}
}
//AVAILABLE OPTIONS
string body = match.Groups[ 2 ].Value.Replace( "\t", string.Empty );
string[] optionLines = body.Split( '\n' );
for( int oL = 0; oL < optionLines.Length; oL++ )
{
string[] optionItems = optionLines[ oL ].Split( ':' );
if( optionItems.Length > 0 )
{
string[] itemIds = optionItems[ 0 ].Split( OptionsDataSeparator );
switch( itemIds[ 0 ] )
{
case "Option":
{
//Fills previous option with its actions
//actionItemsList is cleared over here
FillOptionAction( currentOption, ref actionItemsList );
optionItemToIndex.Clear();
currentOption = new TemplateOptionsItem();
currentOption.Type = AseOptionsType.Option;
string[] optionItemSetup = optionItems[ 1 ].Split( OptionsDataSeparator );
currentOption.Name = optionItemSetup[ 0 ];
if( optionItemSetup.Length > 1 )
{
if( AseOptionItemSetupDict.ContainsKey( optionItemSetup[ 1 ] ) )
currentOption.Setup = AseOptionItemSetupDict[ optionItemSetup[ 1 ] ];
}
currentOption.Id = itemIds.Length > 1 ? itemIds[ 1 ] : optionItems[ 1 ];
currentOption.Options = optionItems[ 2 ].Split( OptionsDataSeparator );
currentOption.Count = currentOption.Options.Length;
for( int opIdx = 0; opIdx < currentOption.Options.Length; opIdx++ )
{
optionItemToIndex.Add( currentOption.Options[ opIdx ], opIdx );
actionItemsList.Add( new List<TemplateActionItem>() );
}
if( optionItems.Length > 3 )
{
currentOption.DefaultOption = optionItems[ 3 ];
}
else
{
currentOption.DefaultOption = currentOption.Options[ 0 ];
}
if( currentOption.Options.Length > 2 )
{
currentOption.UIWidget = AseOptionsUIWidget.Dropdown;
}
else if( currentOption.Options.Length == 2 )
{
if( ( currentOption.Options[ 0 ].Equals( "true" ) && currentOption.Options[ 1 ].Equals( "false" ) ) ||
( currentOption.Options[ 0 ].Equals( "false" ) && currentOption.Options[ 1 ].Equals( "true" ) ) )
{
// Toggle 0 is false and 1 is true
currentOption.Options[ 0 ] = "false";
currentOption.Options[ 1 ] = "true";
currentOption.UIWidget = AseOptionsUIWidget.Toggle;
}
}
else
{
Debug.LogWarning( "Detected an option with less than two items:" + optionItems[ 1 ] );
}
optionItemsList.Add( currentOption );
}
break;
case "Port":
{
//Fills previous option with its actions
//actionItemsList is cleared over here
FillOptionAction( currentOption, ref actionItemsList );
optionItemToIndex.Clear();
currentOption = new TemplateOptionsItem();
currentOption.Type = AseOptionsType.Port;
if( isSubShader && optionItems.Length > 2 )
{
currentOption.Id = optionItems[ 1 ];
currentOption.Name = optionItems[ 2 ];
}
else
{
currentOption.Name = optionItems[ 1 ];
}
currentOption.Options = new string[] { "On", "Off" };
optionItemToIndex.Add( currentOption.Options[ 0 ], 0 );
optionItemToIndex.Add( currentOption.Options[ 1 ], 1 );
actionItemsList.Add( new List<TemplateActionItem>() );
actionItemsList.Add( new List<TemplateActionItem>() );
optionItemsList.Add( currentOption );
}
break;
default:
{
if( optionItemToIndex.ContainsKey( optionItems[ 0 ] ) )
{
int idx = 0;
if( currentOption != null && currentOption.UIWidget == AseOptionsUIWidget.Toggle )
{
idx = ( optionItems[ 0 ].Equals( "true" ) ) ? 1 : 0;
}
else
{
idx = optionItemToIndex[ optionItems[ 0 ] ];
}
actionItemsList[ idx ].Add( CreateActionItem( isSubShader, optionItems ) );
}
else
{
//string[] ids = optionItems[ 0 ].Split( ',' );
if( itemIds.Length > 1 )
{
for( int i = 0; i < itemIds.Length; i++ )
{
if( optionItemToIndex.ContainsKey( itemIds[ i ] ) )
{
int idx = optionItemToIndex[ itemIds[ i ] ];
actionItemsList[ idx ].Add( CreateActionItem( isSubShader, optionItems ) );
}
}
}
}
}
break;
}
}
}
//Fills last option with its actions
FillOptionAction( currentOption, ref actionItemsList );
actionItemsList.Clear();
actionItemsList = null;
optionsContainer.Options = optionItemsList.ToArray();
optionItemsList.Clear();
optionItemsList = null;
optionItemToIndex.Clear();
optionItemToIndex = null;
}
catch( Exception e )
{
Debug.LogException( e );
}
}
return optionsContainer;
}
19
View Source File : CustomExpressionNode.cs
License : GNU General Public License v3.0
Project Creator : alexismorin
License : GNU General Public License v3.0
Project Creator : alexismorin
public override void OnNodeLogicUpdate( DrawInfo drawInfo )
{
base.OnNodeLogicUpdate( drawInfo );
if( m_nameModified )
{
if( ( EditorApplication.timeSinceStartup - m_lastTimeNameModified ) > MaxTimestamp )
{
m_nameModified = false;
m_repopulateNameDictionary = true;
}
}
if( m_repopulateNameDictionary )
{
m_repopulateNameDictionary = false;
m_usedNames.Clear();
for( int i = 0; i < m_inputPorts.Count; i++ )
{
m_usedNames.Add( m_inputPorts[ i ].Name, i );
}
}
if( m_codeModified )
{
if( ( EditorApplication.timeSinceStartup - m_lastTimeCodeModified ) > MaxTimestamp )
{
m_codeModified = false;
bool functionMode = m_code.Contains( ReturnHelper );
if( functionMode != m_functionMode )
{
//if( m_functionMode )
//{
// while( m_outputPorts.Count > 1 )
// {
// RemoveOutputPort( m_outputPorts.Count - 1 );
// }
//}
m_functionMode = functionMode;
CheckCallMode();
}
}
}
}
19
View Source File : BitfinexClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public void Converter()
{
while (true)
{
try
{
if (_isDisposed)
{
return;
}
if (!_newMessage.IsEmpty)
{
string mes;
if (_newMessage.TryDequeue(out mes))
{
if (mes.Contains("\"event\":\"error\""))
{
lock (_senderLocker)
{
SendLogMessage(mes, LogMessageType.Error);
}
}
else if (mes.StartsWith("{\"event\":\"info\""))
{
lock (_senderLocker)
{
if (mes.Contains("\"code\":20051") || mes.Contains("\"code\":20060"))
{
SendLogMessage("остановка/перезапуск сервера Websocket", LogMessageType.Error);
if (Disconnected != null)
{
Disconnected();
}
}
}
}
else if (mes.Contains("\"event\":\"auth\""))
{
}
else if (mes.Contains("\"os\"")) // снимок моих ордеров
{
}
else if(mes.Contains("\"on\""))
{
}
else if ( mes.Contains("\"ou\"") || mes.Contains("\"oc\"")) // обновление или закрытие моего ордера
{
lock (_senderLocker)
{
Thread.Sleep(300);
var values = ParseData(mes);
int numUser = _osOrders[values[0]];
var order = new Order();
order.NumberUser = numUser;
order.SecurityNameCode = values[1];
order.PortfolioNumber = values[1].Substring(3);
order.Side = values[2].ToDecimal() > 0 ? Side.Buy : Side.Sell;
order.NumberMarket = values[0];
order.Price = values[6].ToDecimal();
order.Volume = Math.Abs(values[2].ToDecimal());
order.TimeCallBack = DateTime.Parse(values[8].TrimEnd('Z'));
if (values[5].Contains("EXECUTED"))
{
order.State = OrderStateType.Done;
}
else
{
switch (values[5])
{
case "ACTIVE":
order.State = OrderStateType.Activ;
break;
case "PARTIALLY FILLED":
order.State = OrderStateType.Patrial;
break;
case "CANCELED":
order.TimeCancel = order.TimeCallBack;
order.State = OrderStateType.Cancel;
_osOrders.Remove(order.NumberMarket);
break;
default:
order.State = OrderStateType.None;
break;
}
}
if (MyOrderEvent != null)
{
MyOrderEvent(order);
}
}
}
else if (mes.Contains("[0,\"tu\",[")) // my new trade / новая моя сделка
{
lock (_senderLocker)
{
// [0,"tu",["5809001-IOTBTC",275774974,"IOTBTC",1533415991,15073784940,13,0.00012184,"EXCHANGE LIMIT",0.00012184,-0.026,"IOT"]] моя сделка
var valuesMyTrade = ParseData(mes);
Thread.Sleep(300);
MyTrade myTrade = new MyTrade();
myTrade.Price = valuesMyTrade[6].ToDecimal();
myTrade.NumberTrade = valuesMyTrade[1];
myTrade.SecurityNameCode = valuesMyTrade[2];
myTrade.Side = valuesMyTrade[5].Contains("-") ? Side.Sell : Side.Buy;
myTrade.Volume = Math.Abs(valuesMyTrade[5].ToDecimal());
myTrade.Time = new DateTime(1970, 01, 01) + TimeSpan.FromSeconds(Convert.ToDouble(valuesMyTrade[3]));
myTrade.NumberOrderParent = valuesMyTrade[4];
if (MyTradeEvent != null)
{
MyTradeEvent(myTrade);
}
}
}
else if (mes.Contains("\"ws\"")) // snapshot of portfolios / снимок портфелей
{
lock (_senderLocker)
{
var res = Walets.FromJson(mes)[2].AllWallets;
if (NewPortfolio != null)
{
NewPortfolio(res);
}
}
}
else if (mes.Contains("\"wu\"")) // portfolio update / обновление портфеля
{
lock (_senderLocker)
{
var res = WalletUpdate.FromJson(mes)[2].UpdatedWallet; ;
if (UpdatePortfolio != null)
{
UpdatePortfolio(res);
}
}
}
else if (mes.Contains("[0,\"ps\",[")) // shapshot of position / снимок позиций
{
}
else if (mes.Contains("\"pn\"")|| mes.Contains("\"pu\"")|| mes.Contains("\"pc\"")) // снимок позиций
{
}
else if (mes.Contains("\"event\":\"subscribed\"") && mes.Contains("\"chanId\""))
{
lock (_senderLocker)
{
// inform about successful subscription / информируем об успешной подписке
var info = JsonConvert.DeserializeAnonymousType(mes, new SubscriptionInformation());
if (info.channel == "trades")
{
_subscribedTradesSecurity.Add(info.pair, info.chanId);
}
if (info.channel == "book")
{
_subscribedBooksSecurity.Add(info.pair, info.chanId);
}
string msgInfo =
string.Format(
"Инструмент {0} успешно подписан на канал : {1}, Id канала = {2}", info.pair,
info.channel, info.chanId);
SendLogMessage(msgInfo, LogMessageType.System);
}
}
else if (mes.Contains("\"tu\"")) // new tick / новый тик
{
lock (_senderLocker)
{
var bitfinexTick = UpdateDataBitfinex.FromJson(mes);
// find the security that owns this snapshot / находим бумагу которой принадлежит этот снимок
var namePair =
_subscribedTradesSecurity.FirstOrDefault(
dic => dic.Value == Convert.ToInt32(bitfinexTick[0].Double));
if (NewTradesEvent != null)
{
NewTradesEvent(bitfinexTick, namePair.Key);
}
}
}
else if (mes.Contains("[["))
{
lock (_senderLocker)
{
var countParams = NumberParametersSnapshot(mes);
if (countParams == 3)
{
// process a shapshot of depth / обрабатываем снимок стакана
var orderBook = BitfinexSnapshotParser.FromJson(mes);
// find the security that owns this snapshot / находим бумагу которой принадлежит этот снимок
var namePair =
_subscribedBooksSecurity.FirstOrDefault(
dic => dic.Value == Convert.ToInt32(orderBook[0].IdChanel));
if (NewMarketDepth != null)
{
NewMarketDepth(orderBook, namePair.Key);
}
}
}
}
else if (mes.Contains("hb"))
{
// heartbeat message came / пришло сообщение серцебиения
}
else if (!mes.Contains("[[") && !mes.Contains("\"te\"") && !mes.Contains("\"ws\""))
{
lock (_senderLocker)
{
var bitfinexChangeOrderBook = UpdateDataBitfinex.FromJson(mes);
// find the security that owns this snapshot / находим бумагу которой принадлежит этот снимок
var namePair =
_subscribedBooksSecurity.FirstOrDefault(
dic => dic.Value == Convert.ToInt32(bitfinexChangeOrderBook[0].Double));
if (UpdateMarketDepth != null)
{
UpdateMarketDepth(bitfinexChangeOrderBook, namePair.Key);
}
}
}
}
}
else
{
Thread.Sleep(1);
}
}
catch (Exception exception)
{
SendLogMessage(exception.Message, LogMessageType.Connect);
}
}
}
See More Examples