content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Assets.Scripts.Missions; using Assets.Scripts.Props; using UnityEngine; /// <summary>Encapsulates an ongoing game, with all its bombs, module cameras, HUDs etc.</summary> public class TwitchGame : MonoBehaviour { public TwitchBomb twitchBombPrefab; public TwitchModule twitchModulePrefab; public ModuleCameras moduleCamerasPrefab; public TwitchPlaysService ParentService; public List<TwitchBomb> Bombs = new List<TwitchBomb>(); public List<TwitchModule> Modules = new List<TwitchModule>(); public int _currentBomb = -1; public TwitchBomb CurrentBomb => Bombs[_currentBomb == -1 ? 0 : _currentBomb]; public AudioSource alertSound = null; public readonly Dictionary<int, string> NotesDictionary = new Dictionary<int, string>(); public Dictionary<string, Dictionary<string, double>> LastClaimedModule = new Dictionary<string, Dictionary<string, double>>(); public bool VoteDetonateAttempted = false; public int VoteSolveCount; public int TrainingModeRemainingTime = -1; public int[] TrainingModeAlertTimes = new int[9] { 1, 2, 5, 10, 20, 30, 45, 60, 90 }; public readonly List<CommandQueueItem> CommandQueue = new List<CommandQueueItem>(); public bool QueueEnabled; public int callsNeeded = 1; public Dictionary<string, string> CallingPlayers = new Dictionary<string, string>(); public bool callWaiting; public string commandToCall = ""; public CommandQueueItem callSend; public bool VSSetFlag = false; public SortedDictionary<int, string> VSModePlayers = new SortedDictionary<int, string>(); public List<string> GoodPlayers = new List<string>(); public List<string> EvilPlayers = new List<string>(); public int FindClaimUse = 0; public bool FindClaimEnabled; public Dictionary<string, int> FindClaimPlayers = new Dictionary<string, int>(); #pragma warning disable 169 // ReSharper disable once InconsistentNaming private readonly AlarmClock alarmClock; #pragma warning restore 169 public static ModuleCameras ModuleCameras; public static bool BombActive { get; private set; } = false; public static TwitchGame Instance; public static bool RetryAllowed = true; public bool ClaimCooldown = true; public bool ProcessingClaimQueue; public IEnumerator ProcessClaimQueue() { if (ProcessingClaimQueue) yield break; ProcessingClaimQueue = true; // Cause the modules on the bomb to process their claim queues in random order. // This way, !claimall doesn’t give players all the modules in the same order every time. var shuffledModules = Modules.Shuffle(); while (Modules.Any(module => module.ClaimQueue.Count > 0)) { foreach (var module in shuffledModules) { module.ProcessClaimQueue(); } yield return new WaitForSeconds(0.1f); } ProcessingClaimQueue = false; } public static bool EnableDisableInput() { if (IRCConnection.Instance.State == IRCConnectionState.Connected && !TwitchPlaySettings.data.EnableInteractiveMode && BombActive) { InputInterceptor.DisableInput(); return true; } else { InputInterceptor.EnableInput(); return false; } } public void SetCurrentBomb() { if (BombActive) _currentBomb = TwitchPlaysService.Instance.CoroutineQueue.CurrentBombID; } private bool _bombStarted; public void OnLightsChange(bool on) { if (_bombStarted || !on) return; _bombStarted = true; if (TwitchPlaySettings.data.BombLiveMessageDelay > 0) { System.Threading.Thread.Sleep(TwitchPlaySettings.data.BombLiveMessageDelay * 1000); } StartCoroutine(TwitchPlaysService.Instance.AnimateHeaderVisibility(true)); StartCoroutine(new WaitForSeconds(TwitchPlaySettings.data.FindClaimDelay).Yield(() => FindClaimEnabled = true)); IRCConnection.SendMessage(Bombs.Count == 1 ? TwitchPlaySettings.data.BombLiveMessage : TwitchPlaySettings.data.MultiBombLiveMessage); StartCoroutine(AutoFillEdgework()); GameRoom.InitializeGameModes(GameRoom.Instance.InitializeOnLightsOn); } private void OnEnable() { Instance = this; BombActive = true; EnableDisableInput(); Leaderboard.Instance.ClearSolo(); LogUploader.Instance.Clear(); callsNeeded = 1; CallingPlayers.Clear(); callWaiting = false; VoteDetonateAttempted = false; ProcessingClaimQueue = false; VoteSolveCount = 0; FindClaimPlayers.Clear(); MysteryModuleShim.CoveredModules.Clear(); RetryAllowed = true; _bombStarted = false; ParentService.GetComponent<KMGameInfo>().OnLightsChange += OnLightsChange; StartCoroutine(CheckForBomb()); StartCoroutine(new WaitForSeconds(TwitchPlaySettings.data.InstantModuleClaimCooldown).Yield(() => ClaimCooldown = false)); FindClaimUse = TwitchPlaySettings.data.FindClaimLimit; alertSound = gameObject.Traverse<AudioSource>("AlertSound"); StartCoroutine(AdjustFindClaimLimit()); if (OtherModes.TrainingModeOn) StartCoroutine(EndTrainingModeBomb()); try { string path = Path.Combine(Application.persistentDataPath, "TwitchPlaysLastClaimed.json"); LastClaimedModule = SettingsConverter.Deserialize<Dictionary<string, Dictionary<string, double>>>(File.ReadAllText(path)); } catch (Exception ex) { DebugHelper.LogException(ex, "Couldn't read TwitchPlaysLastClaimed.json:"); LastClaimedModule = new Dictionary<string, Dictionary<string, double>>(); } } public string GetBombResult(bool lastBomb = true) { bool hasDetonated = false; bool hasBeenSolved = true; float timeStarting = float.MaxValue; float timeRemaining = float.MaxValue; string timeRemainingFormatted = ""; foreach (TwitchBomb bomb in Bombs) { if (bomb == null) continue; hasDetonated |= bomb.Bomb.HasDetonated; hasBeenSolved &= bomb.IsSolved; if (timeRemaining > bomb.CurrentTimer) { timeStarting = bomb.BombStartingTimer; timeRemaining = bomb.CurrentTimer; } if (!string.IsNullOrEmpty(timeRemainingFormatted)) { timeRemainingFormatted += ", " + bomb.GetFullFormattedTime; } else { timeRemainingFormatted = bomb.GetFullFormattedTime; } } string bombMessage = ""; if (OtherModes.VSModeOn && (hasDetonated || hasBeenSolved)) { OtherModes.Team winner = OtherModes.Team.Good; if (OtherModes.GetGoodHealth() == 0) { winner = OtherModes.Team.Evil; bombMessage = TwitchPlaySettings.data.VersusEvilHeader; } else if (OtherModes.GetEvilHealth() == 0) { winner = OtherModes.Team.Good; bombMessage = TwitchPlaySettings.data.VersusGoodHeader; } bombMessage += string.Format(TwitchPlaySettings.data.VersusEndMessage, winner == OtherModes.Team.Good ? "good" : "evil", timeRemainingFormatted); bombMessage += TwitchPlaySettings.GiveBonusPoints(); if (winner == OtherModes.Team.Good) bombMessage += TwitchPlaySettings.data.VersusGoodFooter; else if (winner == OtherModes.Team.Evil) bombMessage += TwitchPlaySettings.data.VersusEvilFooter; if (lastBomb && hasBeenSolved) Leaderboard.Instance.Success = true; } else if (hasDetonated) { bombMessage = string.Format(TwitchPlaySettings.data.BombExplodedMessage, timeRemainingFormatted); Leaderboard.Instance.BombsExploded += Bombs.Count; if (!lastBomb) return bombMessage; Leaderboard.Instance.Success = false; TwitchPlaySettings.ClearPlayerLog(); } else if (hasBeenSolved) { bombMessage = string.Format(TwitchPlaySettings.data.BombDefusedMessage, timeRemainingFormatted); Leaderboard.Instance.BombsCleared += Bombs.Count; bombMessage += TwitchPlaySettings.GiveBonusPoints(); if (lastBomb) { Leaderboard.Instance.Success = true; } if (Leaderboard.Instance.CurrentSolvers.Count != 1) return bombMessage; float elapsedTime = timeStarting - timeRemaining; string userName = ""; foreach (string uName in Leaderboard.Instance.CurrentSolvers.Keys) { userName = uName; break; } if (Leaderboard.Instance.CurrentSolvers[userName] == Leaderboard.RequiredSoloSolves * Bombs.Count && OtherModes.currentMode == TwitchPlaysMode.Normal) { Leaderboard.Instance.AddSoloClear(userName, elapsedTime, out float previousRecord); if (TwitchPlaySettings.data.EnableSoloPlayMode) { //Still record solo information, should the defuser be the only one to actually defuse a 11 * bomb-count bomb, but display normal leaderboards instead if //solo play is disabled. TimeSpan elapsedTimeSpan = TimeSpan.FromSeconds(elapsedTime); string soloMessage = string.Format(TwitchPlaySettings.data.BombSoloDefusalMessage, Leaderboard.Instance.SoloSolver.UserName, (int) elapsedTimeSpan.TotalMinutes, elapsedTimeSpan.Seconds); if (elapsedTime < previousRecord) { TimeSpan previousTimeSpan = TimeSpan.FromSeconds(previousRecord); soloMessage += string.Format(TwitchPlaySettings.data.BombSoloDefusalNewRecordMessage, (int) previousTimeSpan.TotalMinutes, previousTimeSpan.Seconds); } soloMessage += TwitchPlaySettings.data.BombSoloDefusalFooter; IRCConnection.SendDelayedMessage(soloMessage, 1); } else { Leaderboard.Instance.ClearSolo(); } } else { Leaderboard.Instance.ClearSolo(); } } else { bombMessage = string.Format(TwitchPlaySettings.data.BombAbortedMessage, timeRemainingFormatted); Leaderboard.Instance.Success = false; TwitchPlaySettings.ClearPlayerLog(); } return bombMessage; } private void OnDisable() { GameRoom.ShowCamera(); BombActive = false; EnableDisableInput(); bool claimsEnabled = TwitchModule.ClaimsEnabled; TwitchModule.ClearUnsupportedModules(); if (!claimsEnabled) TwitchModule.ClaimsEnabled = true; StopAllCoroutines(); GoodPlayers.Clear(); EvilPlayers.Clear(); VSSetFlag = false; QueueEnabled = false; FindClaimEnabled = false; Leaderboard.Instance.BombsAttempted++; // ReSharper disable once DelegateSubtraction ParentService.GetComponent<KMGameInfo>().OnLightsChange -= OnLightsChange; ParentService.AddStateCoroutine(ParentService.AnimateHeaderVisibility(false)); ParentService.AddStateCoroutine(DelayBombResult()); if (!claimsEnabled) IRCConnection.SendDelayedMessage("Claims have been enabled.", 1.1f); if (ModuleCameras != null) ModuleCameras.StartCoroutine(ModuleCameras.DisableCameras()); // Award users who maintained modules. var methods = Modules.SelectMany(module => module.ScoreMethods).Where(method => method.Players.Count != 0); var awardedPoints = new Dictionary<string, int>(); foreach (var player in methods.SelectMany(method => method.Players).Distinct()) { int points = (methods.Sum(method => method.CalculateScore(player)) * OtherModes.ScoreMultiplier).RoundToInt(); if (points != 0) { awardedPoints[player] = points; Leaderboard.Instance.AddScore(player, points); } } if (awardedPoints.Count > 0) IRCConnection.SendMessage($"These players have been awarded points for managing a needy: {awardedPoints.Select(pair => $"{pair.Key} ({pair.Value})").Join(", ")}"); GameCommands.unclaimedModules = null; DestroyComponentHandles(); MusicPlayer.StopAllMusic(); GameRoom.Instance?.OnDisable(); try { string path = Path.Combine(Application.persistentDataPath, "TwitchPlaysLastClaimed.json"); File.WriteAllText(path, SettingsConverter.Serialize(LastClaimedModule)); } catch (Exception ex) { DebugHelper.LogException(ex, "Couldn't write TwitchPlaysLastClaimed.json:"); } } // We need to delay the bomb result by one frame so we don't award the solve bonus before the person who solved the last module is added to the Players list. // Delaying the log being uploaded by one frame also captures module that log after calling HandleStrike(). public IEnumerator DelayBombResult() { yield return null; LogUploader.Instance.GetBombUrl(); IRCConnection.SendDelayedMessage(GetBombResult(), 1, SendAnalysisLink); foreach (var bomb in Bombs.Where(x => x != null)) Destroy(bomb.gameObject, 2.0f); Bombs.Clear(); } public void DestroyComponentHandles() { if (Modules == null) return; foreach (TwitchModule handle in Modules) { if (handle != null) { handle.ClaimQueue.Clear(); // Prevent any claims from going through. Destroy(handle.gameObject, 2.0f); } } Modules.Clear(); } public void CallUpdate(bool response) { var callResponse = CheckIfCall(true, false, "", commandToCall, out _); if (callResponse == CallResponse.Success) GameCommands.CallQueuedCommand("", true, commandToCall); else if (callResponse == CallResponse.NotPresent) IRCConnection.SendMessageFormat("Waiting for {0} to be queued.", string.IsNullOrEmpty(commandToCall) ? "the next unnamed queued command" : commandToCall.StartsWith("!") ? "module " + commandToCall : "the command named “" + commandToCall + "”"); else callWaiting = false; if (response) GameCommands.CallCountCommand(); } public enum CallResponse { Success, AlreadyCalled, NotEnoughCalls, UncommonCalls, DifferentName, NotPresent } public CallResponse CheckIfCall(bool check, bool now, string user, string name, out bool callChanged) { /* THIS IS THE ORDERING OF THE CALL CHECKING SYSTEM * 1. Prevent user from being added / add them if necessary* * 2. Check if enough calls were made** * 3. Remove all empty sets and check if calls are all now common. This will also set the correct call to be made if necessary** * 4. Make sure that the correct call exists in the queue. If not, set it to be made when possible * * * This section is skipped if "bool check" or "bool now" is true * ** These sections are skipped if "bool now" is true */ callChanged = false; if (!now) { //section 1 start if (!check) { if (CallingPlayers.Keys.Contains(user)) { if (name == CallingPlayers[user]) return CallResponse.AlreadyCalled; callChanged = true; CallingPlayers.Remove(user); } CallingPlayers.Add(user, name); } //section 2 start if (callsNeeded > CallingPlayers.Count) return CallResponse.NotEnoughCalls; //section 3 start string[] _calls = CallingPlayers.Values.Where(x => x.Length != 0).ToArray(); if (_calls.Length != 0) { for (int i = 0; i < _calls.Length; i++) { if (!_calls[0].EqualsIgnoreCase(_calls[i])) return CallResponse.UncommonCalls; } name = _calls[0]; } } commandToCall = name; //section 4 start CommandQueueItem call = null; if (string.IsNullOrEmpty(name)) //call any unnamed command { call = CommandQueue.Find(item => item.Name == null); } else if (name.StartsWith("!")) //call a specific module { name += ' '; call = CommandQueue.Find(item => item.Message.Text.StartsWith(name) && item.Name == null); if (call == null) { call = CommandQueue.Find(item => item.Message.Text.StartsWith(name)); if (call != null) return CallResponse.DifferentName; } } else //call a named command { call = CommandQueue.Find(item => name.EqualsIgnoreCase(item.Name)); } if (call == null) return CallResponse.NotPresent; callSend = call; return CallResponse.Success; } public void SendCallResponse(string user, string name, CallResponse response, bool callChanged) { bool unnamed = string.IsNullOrEmpty(name); if (response == CallResponse.AlreadyCalled) { IRCConnection.SendMessageFormat("@{0}, you already called!", user); return; } else if (response == CallResponse.NotEnoughCalls) { if (callChanged) IRCConnection.SendMessageFormat("@{0}, your call has been updated to {1}.", user, unnamed ? "the next queued command" : name); GameCommands.CallCountCommand(); return; } else if (response == CallResponse.UncommonCalls) { if (callChanged) IRCConnection.SendMessageFormat("@{0}, your call has been updated to {1}. Uncommon calls still present.", user, unnamed ? "the next queued command" : name); else { IRCConnection.SendMessageFormat("Sorry, uncommon calls were made. Please either correct your call(s) or use “!callnow” followed by the correct command to call."); GameCommands.ListCalledPlayers(); } return; } else if (response == CallResponse.DifferentName) { CommandQueueItem call = CommandQueue.Find(item => item.Message.Text.StartsWith(name)); IRCConnection.SendMessageFormat("@{0}, module {1} is queued with the name “{2}”, please use “!call {2}” to call it.", user, name, call.Name); return; } else { unnamed = string.IsNullOrEmpty(commandToCall); if (callWaiting) IRCConnection.SendMessageFormat("Waiting for {0} to be queued.", unnamed ? "the next unnamed queued command" : commandToCall.StartsWith("!") ? "module " + commandToCall : "the command named “" + commandToCall + "”"); else { IRCConnection.SendMessageFormat("No {0} in the queue. Calling {1} when it is queued.", unnamed ? "unnamed commands" : commandToCall.StartsWith("!") ? "command for module " + commandToCall : "command named “" + commandToCall + "”", unnamed ? "the next unnamed queued command" : commandToCall.StartsWith("!") ? "module " + commandToCall : "the command named “" + commandToCall + "”"); callWaiting = true; } } } #region Protected/Private Methods private IEnumerator AutoFillEdgework() { while (BombActive) { if (TwitchPlaySettings.data.EnableAutomaticEdgework) foreach (TwitchBomb bomb in Bombs) bomb.FillEdgework(); yield return new WaitForSeconds(0.1f); } } private IEnumerator CheckForBomb() { yield return new WaitUntil(() => SceneManager.Instance.GameplayState.Bombs != null && SceneManager.Instance.GameplayState.Bombs.Count > 0); yield return null; var bombs = SceneManager.Instance.GameplayState.Bombs; try { ModuleCameras = Instantiate(moduleCamerasPrefab); } catch (Exception ex) { DebugHelper.LogException(ex, "Failed to instantiate the module camera system due to an exception:"); ModuleCameras = null; } if (GameRoom.GameRoomTypes.Where((t, i) => t() != null && GameRoom.CreateRooms[i](FindObjectsOfType(t()), out GameRoom.Instance)).Any()) { GameRoom.Instance.InitializeBombs(bombs); } ModuleCameras?.ChangeBomb(Bombs[0]); try { GameRoom.Instance.InitializeBombNames(); } catch (Exception ex) { DebugHelper.LogException(ex, "An exception has occurred while setting the bomb names"); } StartCoroutine(GameRoom.Instance.ReportBombStatus()); StartCoroutine(GameRoom.Instance.InterruptLights()); try { if (GameRoom.Instance.HoldBomb) StartCoroutine(BombCommands.Hold(Bombs[0])); } catch (Exception ex) { DebugHelper.LogException(ex, "An exception has occurred attempting to hold the bomb."); } NotesDictionary.Clear(); CommandQueue.Clear(); ModuleCameras?.SetNotes(); if (EnableDisableInput()) { TwitchModule.SolveUnsupportedModules(true); } // Set up some stuff for the !unclaimed command. GameCommands.unclaimedModules = Modules.Where(h => h.CanBeClaimed).Shuffle().ToList(); GameCommands.unclaimedModuleIndex = 0; while (OtherModes.Unexplodable) { foreach (var bomb in Bombs) if (bomb.Bomb.GetTimer() != null && bomb.Bomb.GetTimer().GetRate() > 0) bomb.Bomb.GetTimer().SetRateModifier(-bomb.Bomb.GetTimer().GetRate()); yield return null; } TwitchPlaysService.Instance.UpdateUiHue(); } internal void InitializeModuleCodes() { // This method assigns a unique code to each module. if (TwitchPlaySettings.data.EnableLetterCodes) { // Ignore initial “the” in module names string SanitizedName(TwitchModule handle) => Regex.Replace(handle.BombComponent.GetModuleDisplayName(), @"^the\s+", "", RegexOptions.IgnoreCase); // First, assign codes “naively” var dic1 = new Dictionary<string, List<TwitchModule>>(); var numeric = 0; foreach (var handle in Modules) { if (handle.BombComponent == null || handle.BombComponent.ComponentType == ComponentTypeEnum.Timer || handle.BombComponent.ComponentType == ComponentTypeEnum.Empty) continue; string moduleName = SanitizedName(handle); if (moduleName != null) { string code = moduleName.Where(ch => (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z' && ch != 'O')).Take(2).Join(""); if (code.Length < 2 && moduleName.Length >= 2) code = moduleName.Where(char.IsLetterOrDigit).Take(2).Join("").ToUpperInvariant(); if (code.Length == 0) code = (++numeric).ToString(); handle.Code = code; dic1.AddSafe(code, handle); } else { handle.Code = (++numeric).ToString(); dic1.AddSafe(handle.Code, handle); } } // If this assignment succeeded in generating unique codes, use it if (dic1.Values.All(list => list.Count < 2)) return; // See if we can make them all unique by just changing some non-unique ones to different letters in the module name var dic2 = dic1.Where(kvp => kvp.Value.Count < 2).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); foreach (var kvp in dic1) { if (kvp.Value.Count < 2) continue; dic2.AddSafe(kvp.Key, kvp.Value[0]); for (int i = 1; i < kvp.Value.Count; i++) { var moduleName = SanitizedName(kvp.Value[i]); for (int chIx = 1; chIx < moduleName.Length; chIx++) { string newCode = (moduleName[0] + "" + moduleName[chIx]).ToUpperInvariant(); if (moduleName[chIx] == 'O' || !char.IsLetter(moduleName[chIx]) || dic2.ContainsKey(newCode)) continue; kvp.Value[i].Code = newCode; dic2.AddSafe(newCode, kvp.Value[i]); goto processed; } dic2.AddSafe(kvp.Key, kvp.Value[i]); processed:; } } // If this assignment succeeded in generating unique codes, use it if (dic2.Values.All(list => list.Count < 2)) return; var globalNumber = 1; // If still no success, gonna have to use numbers while (true) { var tooMany = dic2.FirstOrDefault(kvp => kvp.Value.Count > 1); // We did it — all unique if (tooMany.Key == null) break; // Find other non-unique modules with the same first letter var all = dic2.Where(kvp => kvp.Key[0] == tooMany.Key[0] && kvp.Value.Count > 1).SelectMany(kvp => kvp.Value.Skip(1)).ToList(); var number = 1; foreach (TwitchModule module in all) { dic2[module.Code].Remove(module); while (dic2.ContainsKey(module.Code[0] + number.ToString())) number++; if (number < 10) module.Code = module.Code[0] + (number++).ToString(); else { while (dic2.ContainsKey(globalNumber.ToString())) globalNumber++; module.Code = (globalNumber++).ToString(); } dic2.AddSafe(module.Code, module); } } } else { int num = 1; foreach (var handle in Modules) handle.Code = num++.ToString(); } } public void SetBomb(Bomb bomb, int id) { if (Bombs.Count == 0) _currentBomb = id == -1 ? -1 : 0; var tb = CreateBombHandleForBomb(bomb, id); Bombs.Add(tb); CreateComponentHandlesForBomb(tb); } private TwitchBomb CreateBombHandleForBomb(Bomb bomb, int id) { TwitchBomb twitchBomb = Instantiate(twitchBombPrefab); twitchBomb.Bomb = bomb; twitchBomb.BombID = id; twitchBomb.BombTimeStamp = DateTime.Now; twitchBomb.BombStartingTimer = bomb.GetTimer().TimeRemaining; return twitchBomb; } public void CreateComponentHandlesForBomb(TwitchBomb bomb) { foreach (var component in bomb.Bomb.BombComponents) { if (component.ComponentType.EqualsAny(ComponentTypeEnum.Empty, ComponentTypeEnum.Timer)) continue; TwitchModule module = Instantiate(twitchModulePrefab, component.transform, false); module.Bomb = bomb; module.BombComponent = component; module.BombID = _currentBomb == -1 ? -1 : Bombs.Count - 1; module.transform.SetParent(component.transform.parent, true); module.BasePosition = module.transform.localPosition; Modules.Add(module); } } public double? GetLastClaimedTime(string moduleID, string userNickName) { if (LastClaimedModule == null) LastClaimedModule = new Dictionary<string, Dictionary<string, double>>(); if (!LastClaimedModule.TryGetValue(moduleID, out var lastClaimedTimes) || lastClaimedTimes == null) lastClaimedTimes = LastClaimedModule[moduleID] = new Dictionary<string, double>(); return lastClaimedTimes.TryGetValue(userNickName, out var time) ? time : (double?) null; } public void SetLastClaimedTime(string moduleID, string userNickName, double timestamp) { // Ensures that the relevant dictionaries exist GetLastClaimedTime(moduleID, userNickName); LastClaimedModule[moduleID][userNickName] = timestamp; } private IEnumerator AdjustFindClaimLimit() { if (TwitchPlaySettings.data.FindClaimAddTime < 1) yield break; var _time = TwitchPlaySettings.data.FindClaimAddTime * 60; while (true) { yield return new WaitForSeconds(_time); FindClaimUse++; } } private IEnumerator EndTrainingModeBomb() { TrainingModeRemainingTime = TwitchPlaySettings.data.TrainingModeDetonationTime; if (TrainingModeRemainingTime < 1) yield break; while (true) { if (TrainingModeAlertTimes.Contains(TrainingModeRemainingTime)) { if (alertSound != null) alertSound.Play(); IRCConnection.SendMessageFormat("Warning: This bomb will be automatically detonated in {0} minute{1}.", TrainingModeRemainingTime.ToString(), TrainingModeRemainingTime == 1 ? "" : "s"); } yield return new WaitForSecondsRealtime(60.0f); TrainingModeRemainingTime--; if (BombActive) ModuleCameras.SetNotes(); if (TrainingModeRemainingTime < 1) Bombs[0].CauseExplosionByTrainingModeTimeout(); } } private void SendAnalysisLink() { if (LogUploader.Instance.previousUrl != null) LogUploader.PostToChat(LogUploader.Instance.previousUrl); else LogUploader.Instance.postOnComplete = true; } public static bool IsAuthorizedDefuser(string userNickName, bool isWhisper, bool silent = false) { if (userNickName.EqualsAny("Bomb Factory", TwitchPlaySettings.data.TwitchPlaysDebugUsername) || Instance.Bombs.Any(x => x.BombName == userNickName)) return true; bool result = !TwitchPlaySettings.data.EnableWhiteList || UserAccess.HasAccess(userNickName, AccessLevel.Defuser, true); if (!result && !silent) IRCConnection.SendMessage(string.Format(TwitchPlaySettings.data.TwitchPlaysDisabled, userNickName), userNickName, !isWhisper); return result; } public void StopCommands() { CoroutineCanceller.SetCancel(); TwitchPlaysService.Instance.CoroutineQueue.CancelFutureSubcoroutines(); SetCurrentBomb(); } private static readonly string[] solveBased = { "MemoryV2", "SouvenirModule", "TurnTheKeyAdvanced", "HexiEvilFMN", "simonsStages", "forgetThemAll", "tallorderedKeys", "forgetEnigma", "forgetUsNot", "qkForgetPerspective", "organizationModule", "ForgetMeNow" }; private bool removedSolveBasedModules = false; public void RemoveSolveBasedModules() { if (removedSolveBasedModules) return; removedSolveBasedModules = true; foreach (var module in Modules.Where(x => !x.Solved && solveBased.Contains(x.BombComponent.GetModuleDisplayName()))) { ComponentSolver.HandleForcedSolve(module); module.Unsupported = true; if (module.Solver != null) module.Solver.UnsupportedModule = true; } } #endregion }
32.153937
386
0.717867
[ "MIT" ]
samfun123/KtaneTwitchPlays
TwitchPlaysAssembly/Src/TwitchGame.cs
27,403
C#
// // asmr: Coffee Beans Management Solution // © 2021 Pandora Karya Digital. All right reserved. // // Written by Danang Galuh Tegar Prasetyo [connect@danang.id] // // JsonContent.cs // using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; using System.Threading.Tasks; using ASMR.Common.Constants; namespace ASMR.Common.Net.Http; public class JsonContent<TContent> : HttpContent { private readonly TContent _value; public JsonContent(TContent value) { _value = value; Headers.ContentType = new MediaTypeHeaderValue("application/json"); } protected override bool TryComputeLength(out long length) { length = -1; return false; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { return JsonSerializer.SerializeAsync(stream, _value, JsonConstants.DefaultJsonSerializerOptions); } }
22.625
99
0.770166
[ "BSD-3-Clause" ]
danang-id/ASMR
ASMR.Common/Net/Http/JsonContent.cs
906
C#
using System.Collections.Generic; using ESRI.ArcGIS.Geodatabase; using ProSuite.QA.Container; using ProSuite.QA.Tests.Test.TestRunners; using NUnit.Framework; using ProSuite.Commons.AO.Geodatabase; using ProSuite.Commons.AO.Licensing; using ProSuite.Commons.Essentials.CodeAnnotations; using ProSuite.QA.Tests.Test.TestData; namespace ProSuite.QA.Tests.Test { [TestFixture] public class QaSchemaFieldDomainNameRegexTest { private readonly ArcGISLicenses _lic = new ArcGISLicenses(); private const string _pattern = @"^[A-Z]{3}[_][A-Z0-9_]*$"; private const string _patternDescription = "Gültige Zeichen für Domaenennamen sind A-Z (ohne Umlaute), 0-9 sowie '_'. " + "Domaenennamen muessen mit einer dreistelligen Buchstabenfolge gefolgt von einem Underscore beginnen."; [OneTimeSetUp] public void SetupFixture() { _lic.Checkout(); } [OneTimeTearDown] public void TeardownFixture() { _lic.Release(); } [Test] public void InvalidValidTable1() { IList<QaError> errors = GetErrors("GEO_00100004001", _pattern, false, _patternDescription); Assert.AreEqual(1, errors.Count); Assert.AreEqual( string.Format("The domain name 'ZONENTYP' does not match the pattern for '{0}'", _patternDescription), errors[0].Description); } [Test] public void ValidTable1() { Assert.AreEqual(0, GetErrors("GEO_00100024004", _pattern, false, _patternDescription).Count); } [Test] public void ValidTable2() { Assert.AreEqual(0, GetErrors("GEO_00100059002", _pattern, false, _patternDescription).Count); } [Test] public void ValidTable3() { Assert.AreEqual(0, GetErrors("GEO_00100436001", _pattern, false, _patternDescription).Count); } [Test] public void InvalidTable2() { IList<QaError> errors = GetErrors("GEO_00100510001", _pattern, false, _patternDescription); Assert.AreEqual(10, errors.Count); Assert.AreEqual( string.Format( "The domain name 'A_GZB_OBJART' does not match the pattern for '{0}'", _patternDescription), errors[0].Description); Assert.AreEqual( string.Format("The domain name 'A_GZB_BEZ' does not match the pattern for '{0}'", _patternDescription), errors[1].Description); Assert.AreEqual( string.Format( "The domain name 'A_GZB_BEZZUS' does not match the pattern for '{0}'", _patternDescription), errors[2].Description); Assert.AreEqual( string.Format( "The domain name 'A_GZB_BEZANG' does not match the pattern for '{0}'", _patternDescription), errors[3].Description); Assert.AreEqual( string.Format( "The domain name 'A_GWS_NITRAT' does not match the pattern for '{0}'", _patternDescription), errors[4].Description); Assert.AreEqual( string.Format("The domain name 'A_ERF_VORL' does not match the pattern for '{0}'", _patternDescription), errors[5].Description); Assert.AreEqual( string.Format("The domain name 'A_VORL_ART' does not match the pattern for '{0}'", _patternDescription), errors[6].Description); Assert.AreEqual( string.Format( "The domain name 'A_VORL_MSTAB' does not match the pattern for '{0}'", _patternDescription), errors[7].Description); Assert.AreEqual( string.Format( "The domain name 'A_VORL_HERK' does not match the pattern for '{0}'", _patternDescription), errors[8].Description); Assert.AreEqual( string.Format( "The domain name 'a_erf_genau' does not match the pattern for '{0}'", _patternDescription), errors[9].Description); } [Test] public void ValidTable4() { Assert.AreEqual(0, GetErrors("GEO_00100633001", _pattern, false, _patternDescription).Count); } [NotNull] private static IList<QaError> GetErrors([NotNull] string tableName, [NotNull] string pattern, bool matchIsError, [CanBeNull] string patternDescription) { var locator = TestDataUtils.GetTestDataLocator(); string path = locator.GetPath("QaSchemaTests.mdb"); IFeatureWorkspace workspace = WorkspaceUtils.OpenPgdbFeatureWorkspace(path); ITable table = workspace.OpenTable(tableName); var test = new QaSchemaFieldDomainNameRegex(table, pattern, matchIsError, patternDescription); var runner = new QaTestRunner(test); runner.Execute(); return runner.Errors; } } }
32.666667
106
0.655187
[ "MIT" ]
ProSuite/ProSuite
src/ProSuite.QA.Tests.Test/QaSchemaFieldNameRegexTest.cs
4,706
C#
using UIKit; namespace TestAppNative.iOS { public class Application { static void Main(string[] args) { UIApplication.Main(args, null, nameof(AppDelegate)); } } }
17.666667
64
0.580189
[ "MIT" ]
FabriBertani/Plugin.XamarinAppRating
TestAppNative/TestAppNative.iOS/Main.cs
214
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MinecraftClient.ChatBots { /// <summary> /// In-Chat Hangman game /// </summary> public class HangmanGame : ChatBot { private int vie = 0; private int vie_param = 10; private int compteur = 0; private int compteur_param = 3000; //5 minutes private bool running = false; private bool[] discovered; private string word = ""; private string letters = ""; private bool English; /// <summary> /// Le jeu du Pendu / Hangman Game /// </summary> /// <param name="english">if true, the game will be in english. If false, the game will be in french.</param> public HangmanGame(bool english) { English = english; } public override void Update() { if (running) { if (compteur > 0) { compteur--; } else { SendText(English ? "You took too long to try a letter." : "Temps imparti écoulé !"); SendText(English ? "Game canceled." : "Partie annulée."); running = false; } } } public override void GetText(string text) { string message = ""; string username = ""; text = GetVerbatim(text); if (IsPrivateMessage(text, ref message, ref username)) { if (Settings.Bots_Owners.Contains(username.ToLower())) { switch (message) { case "start": start(); break; case "stop": running = false; break; default: break; } } } else { if (running && IsChatMessage(text, ref message, ref username)) { if (message.Length == 1) { char letter = message.ToUpper()[0]; if (letter >= 'A' && letter <= 'Z') { if (letters.Contains(letter)) { SendText(English ? ("Letter " + letter + " has already been tried.") : ("Le " + letter + " a déjà été proposé.")); } else { letters += letter; compteur = compteur_param; if (word.Contains(letter)) { for (int i = 0; i < word.Length; i++) { if (word[i] == letter) { discovered[i] = true; } } SendText(English ? ("Yes, the word contains a " + letter + '!') : ("Le " + letter + " figurait bien dans le mot :)")); } else { vie--; if (vie == 0) { SendText(English ? "Game Over! :]" : "Perdu ! Partie terminée :]"); SendText(English ? ("The word was: " + word) : ("Le mot était : " + word)); running = false; } else SendText(English ? ("The " + letter + "? No.") : ("Le " + letter + " ? Non.")); } if (running) { SendText(English ? ("Mysterious word: " + word_cached + " (lives : " + vie + ")") : ("Mot mystère : " + word_cached + " (vie : " + vie + ")")); } if (winner) { SendText(English ? ("Congrats, " + username + '!') : ("Félicitations, " + username + " !")); running = false; } } } } } } } private void start() { vie = vie_param; running = true; letters = ""; word = chooseword(); compteur = compteur_param; discovered = new bool[word.Length]; SendText(English ? "Hangman v1.0 - By ORelio" : "Pendu v1.0 - Par ORelio"); SendText(English ? ("Mysterious word: " + word_cached + " (lives : " + vie + ")") : ("Mot mystère : " + word_cached + " (vie : " + vie + ")")); SendText(English ? ("Try some letters ... :)") : ("Proposez une lettre ... :)")); } private string chooseword() { if (System.IO.File.Exists(English ? Settings.Hangman_FileWords_EN : Settings.Hangman_FileWords_FR)) { string[] dico = System.IO.File.ReadAllLines(English ? Settings.Hangman_FileWords_EN : Settings.Hangman_FileWords_FR, Encoding.UTF8); return dico[new Random().Next(dico.Length)]; } else { LogToConsole(English ? "File not found: " + Settings.Hangman_FileWords_EN : "Fichier introuvable : " + Settings.Hangman_FileWords_FR); return English ? "WORDSAREMISSING" : "DICOMANQUANT"; } } private string word_cached { get { string printed = ""; for (int i = 0; i < word.Length; i++) { if (discovered[i]) { printed += word[i]; } else printed += '_'; } return printed; } } private bool winner { get { for (int i = 0; i < discovered.Length; i++) { if (!discovered[i]) { return false; } } return true; } } } }
35.777778
154
0.363946
[ "MIT" ]
IsaacJuracich/Replay-MCBot
ChatBots/HangmanGame.cs
6,777
C#
/// <summary> /// This class is responsible for the creation of HR_Monitors. /// </summary> public sealed class HR_Factory { private static HR_Factory _instance = null; private HR_Factory() { } public static HR_Factory Instance() { if (_instance == null) { _instance = new HR_Factory(); } return _instance; } /// <summary> /// Returns an instance of a HR_Monitor according to the build parameters passed. /// </summary> /// <param name="UDP_PORT"></param> /// <param name="IPAddress"></param> /// <param name="type"></param> /// <returns></returns> public HR_Monitor createHR_Monitor(int UDP_PORT, string type) { HR_Monitor hrm; switch (type) { case "Generic": hrm = new HR_Monitor_Generic(); break; case "BWATCH": hrm = new HR_Monitor_BWATCH(); break; default: hrm = new HR_Monitor_Generic(); break; } hrm.UDP_PORT = UDP_PORT; hrm.Initialize(); return hrm; } }
23.24
85
0.526678
[ "MIT" ]
kingfreir/tenumbra
Assets/Scripts/Connectors/Heart Rate/HR_Factory.cs
1,164
C#
/* * Copyright (c) 2019-2021 Angouri. * AngouriMath is licensed under MIT. * Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. * Website: https://am.angouri.org. */ using static AngouriMath.Entity.Boolean; namespace AngouriMath { partial record Entity { partial record Boolean { /// <inheritdoc/> protected override Entity InnerEval() => this; /// <inheritdoc/> protected override Entity InnerSimplify() => this; } partial record Notf { /// <inheritdoc/> protected override Entity InnerEval() => ExpandOnOneArgument(Argument.Evaled, a => a switch { Boolean b => !(bool)b, _ => null }, (@this, a) => ((Notf)@this).New(a) ); /// <inheritdoc/> protected override Entity InnerSimplify() => Evaled is Boolean b ? b : New(Argument.InnerSimplified); } partial record Andf { private static bool GoodResult(Entity left, Entity right, Entity leftEvaled, Entity rightEvaled, out Entity res) { if (leftEvaled is Boolean leftBool && rightEvaled is Boolean rightBool) { res = (bool)leftBool && (bool)rightBool; // there's no cost in casting return true; } else if (leftEvaled == False || rightEvaled == False) { res = False; return true; } else if (leftEvaled == True) { res = right; return true; } else if (rightEvaled == True) { res = left; return true; } else { res = False; return false; } } /// <inheritdoc/> protected override Entity InnerEval() => ExpandOnTwoArguments(Left.Evaled, Right.Evaled, (a, b) => (a, b) switch { (var left, var right) when GoodResult(left, right, left, right, out var res) => res, _ => null }, (@this, a, b) => ((Andf)@this).New(a, b) ); /// <inheritdoc/> protected override Entity InnerSimplify() => ExpandOnTwoArguments(Left.InnerSimplified, Right.InnerSimplified, (a, b) => (a, b) switch { (var left, var right) when GoodResult(left, right, left.Evaled, right.Evaled, out var res) => res, _ => null }, (@this, a, b) => ((Andf)@this).New(a, b) ); } partial record Orf { private static bool GoodResult(Entity left, Entity right, Entity leftEvaled, Entity rightEvaled, out Entity res) { if (leftEvaled is Boolean leftBool && rightEvaled is Boolean rightBool) { res = (bool)leftBool || (bool)rightBool; // there's no cost in casting return true; } else if (leftEvaled == True || rightEvaled == True) { res = True; return true; } else if (leftEvaled == False) { res = right; return true; } else if (rightEvaled == False) { res = left; return true; } else { res = False; return false; } } /// <inheritdoc/> protected override Entity InnerEval() => ExpandOnTwoArguments(Left.Evaled, Right.Evaled, (a, b) => (a, b) switch { (var left, var right) when GoodResult(left, right, left, right, out var res) => res, _ => null }, (@this, a, b) => ((Orf)@this).New(a, b) ); /// <inheritdoc/> protected override Entity InnerSimplify() => ExpandOnTwoArguments(Left.InnerSimplified, Right.InnerSimplified, (a, b) => (a, b) switch { (var left, var right) when GoodResult(left, right, left.Evaled, right.Evaled, out var res) => res, _ => null }, (@this, a, b) => ((Orf)@this).New(a, b) ); } partial record Xorf { private static bool GoodResult(Entity left, Entity right, Entity leftEvaled, Entity rightEvaled, out Entity res) { if (leftEvaled is Boolean leftBool && rightEvaled is Boolean rightBool) { res = (bool)leftBool ^ (bool)rightBool; // there's no cost in casting return true; } else if (leftEvaled is Boolean leftBoolOnly) { res = leftBoolOnly ? !right : right; return true; } else if (rightEvaled is Boolean rightBoolOnly) { res = rightBoolOnly ? !left : left; return true; } else { res = False; return false; } } /// <inheritdoc/> protected override Entity InnerEval() => ExpandOnTwoArguments(Left.Evaled, Right.Evaled, (a, b) => (a, b) switch { (var left, var right) when GoodResult(left, right, left, right, out var res) => res, _ => null }, (@this, a, b) => ((Xorf)@this).New(a, b) ); /// <inheritdoc/> protected override Entity InnerSimplify() => ExpandOnTwoArguments(Left.InnerSimplified, Right.InnerSimplified, (a, b) => (a, b) switch { (var left, var right) when GoodResult(left, right, left.Evaled, right.Evaled, out var res) => res, _ => null }, (@this, a, b) => ((Xorf)@this).New(a, b) ); } partial record Impliesf { private static bool GoodResult(Entity left, Entity right, Entity leftEvaled, Entity rightEvaled, out Entity res) { if (leftEvaled is Boolean leftBool && rightEvaled is Boolean rightBool) { res = !(bool)leftBool || (bool)rightBool; // there's no cost in casting return true; } else if (leftEvaled == False || rightEvaled == True) { res = True; return true; } else if (leftEvaled == True) { res = right; return true; } else if (rightEvaled == False) { res = !left; return true; } else { res = False; return false; } } /// <inheritdoc/> protected override Entity InnerEval() => ExpandOnTwoArguments(Assumption.Evaled, Conclusion.Evaled, (a, b) => (a, b) switch { (var left, var right) when GoodResult(left, right, left, right, out var res) => res, _ => null }, (@this, a, b) => ((Impliesf)@this).New(a, b) ); /// <inheritdoc/> protected override Entity InnerSimplify() => ExpandOnTwoArguments(Assumption.InnerSimplified, Conclusion.InnerSimplified, (a, b) => (a, b) switch { (var left, var right) when GoodResult(left, right, left.Evaled, right.Evaled, out var res) => res, _ => null }, (@this, a, b) => ((Impliesf)@this).New(a, b) ); } partial record Equalsf { /// <inheritdoc/> protected override Entity InnerEval() => (Left.Evaled, Right.Evaled) switch { (var left, var right) when left == right => true, (var left, var right) when left.IsConstant && right.IsConstant => left == right, (var left, var right) => MathS.Equality(left, right) }; /// <inheritdoc/> protected override Entity InnerSimplify() => Evaled is Boolean b ? b : MathS.Equality(Left.InnerSimplified, Right.InnerSimplified); } partial record Greaterf { /// <inheritdoc/> protected override Entity InnerEval() => ExpandOnTwoArguments(Left.Evaled, Right.Evaled, (a, b) => (a, b) switch { (Real reLeft, Real reRight) => reLeft > reRight, (Number numLeft, Number numRight) => MathS.NaN, _ => null }, (@this, a, b) => ((Greaterf)@this).New(a, b) ); /// <inheritdoc/> protected override Entity InnerSimplify() => Evaled is Boolean b ? b : ExpandOnTwoArguments(Left.InnerSimplified, Right.InnerSimplified, (a, b) => (a, b) switch { _ => null }, (@this, a, b) => ((Greaterf)@this).New(a, b) ); } partial record GreaterOrEqualf { /// <inheritdoc/> protected override Entity InnerEval() => ExpandOnTwoArguments(Left.Evaled, Right.Evaled, (a, b) => (a, b) switch { (Real reLeft, Real reRight) => reLeft >= reRight, (Number numLeft, Number numRight) => MathS.NaN, _ => null }, (@this, a, b) => ((GreaterOrEqualf)@this).New(a, b) ); /// <inheritdoc/> protected override Entity InnerSimplify() => Evaled is Boolean b ? b : ExpandOnTwoArguments(Left.InnerSimplified, Right.InnerSimplified, (a, b) => (a, b) switch { _ => null }, (@this, a, b) => ((GreaterOrEqualf)@this).New(a, b) ); } partial record Lessf { /// <inheritdoc/> protected override Entity InnerEval() => ExpandOnTwoArguments(Left.Evaled, Right.Evaled, (a, b) => (a, b) switch { (Real reLeft, Real reRight) => reLeft < reRight, (Number numLeft, Number numRight) => MathS.NaN, _ => null }, (@this, a, b) => ((Lessf)@this).New(a, b) ); /// <inheritdoc/> protected override Entity InnerSimplify() => Evaled is Boolean b ? b : ExpandOnTwoArguments(Left.InnerSimplified, Right.InnerSimplified, (a, b) => (a, b) switch { _ => null }, (@this, a, b) => ((Lessf)@this).New(a, b) ); } partial record LessOrEqualf { /// <inheritdoc/> protected override Entity InnerEval() => ExpandOnTwoArguments(Left.Evaled, Right.Evaled, (a, b) => (a, b) switch { (Real reLeft, Real reRight) => reLeft <= reRight, (Number numLeft, Number numRight) => MathS.NaN, _ => null }, (@this, a, b) => ((LessOrEqualf)@this).New(a, b) ); /// <inheritdoc/> protected override Entity InnerSimplify() => Evaled is Boolean b ? b : ExpandOnTwoArguments(Left.InnerSimplified, Right.InnerSimplified, (a, b) => (a, b) switch { _ => null }, (@this, a, b) => ((LessOrEqualf)@this).New(a, b) ); } partial record Set { partial record Inf { /// <inheritdoc/> protected override Entity InnerEval() => ExpandOnTwoArguments(Element.Evaled, SupSet.Evaled, (a, b) => (a, b) switch { (var el, Set set) when set.TryContains(el, out var contains) => contains, _ => null }, (@this, a, b) => ((Inf)@this).New(a, b) ); /// <inheritdoc/> protected override Entity InnerSimplify() => ExpandOnTwoArguments(Element.InnerSimplified, SupSet.InnerSimplified, (a, b) => (a, b) switch { (var el, Set set) when set.TryContains(el, out var contains) => contains, _ => null }, (@this, a, b) => ((Inf)@this).New(a, b) ); } } partial record Phif { /// <inheritdoc/> protected override Entity InnerEval() => ExpandOnOneArgument(Argument.Evaled, a => a switch { Integer integer => integer.Phi(), _ => null }, (@this, a) => ((Phif)@this).New(a) ); /// <inheritdoc/> protected override Entity InnerSimplify() => ExpandOnOneArgument(Argument.InnerSimplified, a => a switch { Integer integer => integer.Phi(), _ => null }, (@this, a) => ((Phif)@this).New(a) ); } } }
36.870588
124
0.39515
[ "MIT" ]
jclapis/AngouriMath
Sources/AngouriMath/Functions/Evaluation/Evaluation.Discrete/Evaluation.Discrete.Classes.cs
15,672
C#
 namespace BookShop.Data { using BookShop.Data.Models; using Microsoft.EntityFrameworkCore; public class BookShopDbContext : DbContext { public BookShopDbContext(DbContextOptions<BookShopDbContext> options) : base(options) { } public DbSet<Book> Books { get; set; } public DbSet<Author> Authors{ get; set; } public DbSet<Category> Categories{ get; set; } public DbSet<BookCategory> BooksInCategories { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<Book>() .HasOne(b => b.Author) .WithMany(a => a.Books) .HasForeignKey(b => b.AuthorId); builder .Entity<BookCategory>() .HasKey(dc => new { dc.BookId, dc.CategoryId }); builder .Entity<BookCategory>() .HasOne(bc => bc.Book) .WithMany(b => b.Categories) .HasForeignKey(bc => bc.BookId); builder .Entity<BookCategory>() .HasOne(bc => bc.Category) .WithMany(c => c.Books) .HasForeignKey(bc => bc.CategoryId); } } }
27.319149
78
0.523364
[ "MIT" ]
LuGeorgiev/CSharpSelfLearning
ASP.Core.SelfLearning/BookShop/BookShop.Data/BookShopDbContext.cs
1,286
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using CommandLine; #if NET40Plus using System.Threading.Tasks; #endif namespace System.Doors.Drive { class Program { class AppArguments { [Argument(ArgumentType.AtMostOnce, ShortName = "b", DefaultValue = 1048576, HelpText = "The buffer size.")] public int bufferSize = 0; [Argument(ArgumentType.AtMostOnce, ShortName = "n", DefaultValue = 50, HelpText = "The number of nodes.")] public int nodeCount = 0; [Argument(ArgumentType.Required, ShortName = "w", HelpText = "The number of writers.")] public int writers = 0; [Argument(ArgumentType.Required, ShortName = "r", HelpText = "The number of readers.")] public int readers = 0; [Argument(ArgumentType.AtMostOnce, ShortName = "e", DefaultValue = 100000, HelpText = "The number of elements to process.")] public int elements = 0; } static void Main(string[] args) { int elements = 100000; int writeCount = 0; int clientWaitCount = 0; int readCount = 0; int serverWaitCount = 0; long lastTick = 0; int bufferSize = 1048576; int size = sizeof(byte) * bufferSize; int count = 50; // node count within buffer int serverCount = 0; int clientCount = 0; // Process command line AppArguments parsedArgs = new AppArguments(); var validArgs = Parser.ParseArgumentsWithUsage(args, parsedArgs); if (!validArgs) { return; } else { elements = parsedArgs.elements; bufferSize = parsedArgs.bufferSize; serverCount = parsedArgs.writers; clientCount = parsedArgs.readers; size = sizeof(byte) * bufferSize; count = parsedArgs.nodeCount; } Console.WriteLine("Node buffer size: {0}, count: {1}, writers: {2}, readers {3}, elements: {4}", size, count, serverCount, clientCount, elements); int dataListCount = 256; // Generate random data to be written Random random = new Random(); byte[][] dataList = new byte[dataListCount][]; for (var j = 0; j < dataListCount; j++) { var data = new byte[size]; random.NextBytes(data); dataList[j] = data; } long bytesWritten = 0; long bytesRead = 0; string name = Guid.NewGuid().ToString(); var server = new DriveCircular("E:\\MAPTEST.TREL", name, count, size); Stopwatch sw = Stopwatch.StartNew(); Action clientAction = () => { byte[] testData = new byte[size]; var client = new DriveCircular("E:\\MAPTEST.TREL", name); Stopwatch clientTime = new Stopwatch(); clientTime.Start(); long startTick = 0; long stopTick = 0; for (; ; ) { startTick = clientTime.ElapsedTicks; int amount = client.Read(testData, 100); bytesRead += amount; if (amount == 0) Interlocked.Increment(ref clientWaitCount); else Interlocked.Increment(ref readCount); stopTick = clientTime.ElapsedTicks; if (writeCount > elements && writeCount - readCount == 0) break; } }; for (int c = 0; c < clientCount; c++) { #if NET40Plus Task c1 = Task.Factory.StartNew(clientAction); #else ThreadPool.QueueUserWorkItem(o => { clientAction(); }); #endif } bool wait = true; int index = 0; Action serverWrite = () => { int serverIndex = Interlocked.Increment(ref index); var writer = (serverIndex == 1 ? server : new DriveCircular("C:\\MAPTEST.TREL", name)); bool done = false; TimeSpan doneTime = TimeSpan.MinValue; for (; ; ) { if (writeCount <= elements) { int amount = writer.Write(dataList[random.Next(0, dataListCount)], 100); bytesWritten += amount; if (amount == 0) Interlocked.Increment(ref serverWaitCount); else Interlocked.Increment(ref writeCount); } else { if (!done && serverIndex == 1) { doneTime = sw.Elapsed; done = true; } } if (serverIndex == 1 && sw.ElapsedTicks - lastTick > 1000000) { Console.WriteLine("Write: {0}, Read: {1}, Diff: {5}, Wait(cli/svr): {3}/{2}, {4}MB/s", writeCount, readCount, serverWaitCount, clientWaitCount, (int)((((bytesWritten + bytesRead) / 1048576.0) / sw.ElapsedMilliseconds) * 1000), writeCount - readCount); lastTick = sw.ElapsedTicks; if (writeCount > elements && writeCount - readCount == 0) { Console.WriteLine("Total Time: " + doneTime); wait = false; break; } } } }; for (int s = 0; s < serverCount; s++) { #if NET40Plus Task s1 = Task.Factory.StartNew(serverWrite); #else ThreadPool.QueueUserWorkItem(o => { serverWrite(); }); #endif } while (wait) Thread.Sleep(100); } } }
36.565714
275
0.475543
[ "MIT" ]
undersoft-org/NET.Undersoft.Doors.Fwk.Devel
Undersoft.Doors.Fwk/Drive/Examples/SingleProcess/Program.cs
6,401
C#
using Sitecore.Globalization; using Sitecore.Web.UI.HtmlControls; using Sitecore.Web.UI.Sheer; namespace Cognifide.PowerShell.Client.Controls { public class EditExtended : Edit { public string PlaceholderText { get { return GetViewStateString("Placeholder"); } set { if (PlaceholderText == value) { return; } Attributes["placeholder"] = value; SetViewStateString("Placeholder", value); SheerResponse.SetAttribute(this.ID, "placeholder", Translate.Text(value)); } } } }
26.36
90
0.552352
[ "MIT" ]
dsolovay/Console
Cognifide.PowerShell/Client/Controls/EditExtended.cs
661
C#
using MercadoLivre.Domain.Entities; namespace MercadoLivre.Domain.Interfaces { public interface IProdutoPerguntaRepository : IBaseRepository<ProdutoPergunta> { } }
22.125
82
0.785311
[ "Apache-2.0" ]
YatoEbisu/Desafio-MercadoLivreAPI
MercadoLivre/src/MercadoLivre.Domain/Interfaces/IProdutoPerguntaRepository.cs
179
C#
// *********************************************************************** // Copyright (c) 2011 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System.IO; using System.Text; using NUnit.Framework.Interfaces; namespace NUnitLite.Runner { /// <summary> /// OutputWriter is an abstract class used to write test /// results to a file in various formats. Specific /// OutputWriters are derived from this class. /// </summary> public abstract class OutputWriter { /// <summary> /// Writes a test result to a file /// </summary> /// <param name="result">The result to be written</param> /// <param name="outputPath">Path to the file to which the result is written</param> public void WriteResultFile(ITestResult result, string outputPath) { using (StreamWriter writer = new StreamWriter(outputPath, false, Encoding.UTF8)) { WriteResultFile(result, writer); } } /// <summary> /// Writes test info to a file /// </summary> /// <param name="test">The test to be written</param> /// <param name="outputPath">Path to the file to which the test info is written</param> public void WriteTestFile(ITest test, string outputPath) { using (StreamWriter writer = new StreamWriter(outputPath, false, Encoding.UTF8)) { WriteTestFile(test, writer); } } /// <summary> /// Abstract method that writes a test result to a TextWriter /// </summary> /// <param name="result">The result to be written</param> /// <param name="writer">A TextWriter to which the result is written</param> public abstract void WriteResultFile(ITestResult result, TextWriter writer); /// <summary> /// Abstract method that writes test info to a TextWriter /// </summary> /// <param name="test">The test to be written</param> /// <param name="writer">A TextWriter to which the test info is written</param> public abstract void WriteTestFile(ITest test, TextWriter writer); } }
42.576923
95
0.629329
[ "MIT" ]
Schumix/nunit-framework
src/NUnitFramework/nunitlite.runner/Runner/OutputWriters/OutputWriter.cs
3,323
C#
using PPDCoreModel; using PPDCoreModel.Data; using PPDFramework; using PPDFramework.PPDStructure; using PPDFramework.PPDStructure.EVDData; using PPDFrameworkCore; using System.Collections.Generic; using System.IO; namespace PPDCore { public class EventManager : UpdatableGameComponent, IEventManager { public delegate void VolumeHandler(int volume); public event VolumeHandler ChangeMovieVolume; IEVDData[] data; bool initialized; int iter; int[] volumePercents = new int[10]; bool[] keepPlayings = new bool[10]; bool[] releaseSounds = new bool[10]; float defaultbpm; FlowScriptManager scriptManager; List<float[]> stoplist = new List<float[]>(); SortedList<float, DisplayState> displayStateCache; SortedList<float, NoteType> noteTypeCache; SortedList<float, ButtonType[]> initializeOrderCache; SortedList<float, float> slideScaleCache; ButtonType[] defaultInitializeOrder; MainGameConfigBase config; private BPMManager BPMManager { get { return scriptManager.BPMManager; } } public EventManager(PPDGameUtility ppdgameutility, MainGameConfigBase config, FlowScriptManager scriptManager) { LoadData(ppdgameutility.SongInformation.DirectoryPath, ppdgameutility.Difficulty); InnerStruct(ppdgameutility, config, scriptManager); } public EventManager(PPDGameUtility ppdgameutility, Stream stream, MainGameConfigBase config, FlowScriptManager scriptManager) { LoadData(stream); InnerStruct(ppdgameutility, config, scriptManager); } private void InnerStruct(PPDGameUtility ppdgameutility, MainGameConfigBase config, FlowScriptManager scriptManager) { this.config = config; this.defaultbpm = ppdgameutility.SongInformation.BPM; this.scriptManager = scriptManager; BPMManager.CurrentBPM = defaultbpm; BPMManager.TargetBPM = defaultbpm; displayStateCache = new SortedList<float, DisplayState>(); noteTypeCache = new SortedList<float, NoteType>(); initializeOrderCache = new SortedList<float, ButtonType[]>(); slideScaleCache = new SortedList<float, float>(); defaultInitializeOrder = new ButtonType[10]; for (int i = 0; i < 10; i++) { defaultInitializeOrder[i] = (ButtonType)i; } for (int i = 0; i < volumePercents.Length; i++) { volumePercents[i] = 90; keepPlayings[i] = false; } if (initialized) { InitializeState(); } } private void InitializeState() { float stopstarttime = -1; foreach (IEVDData evddata in data) { switch (evddata.EventType) { case EventType.ChangeDisplayState: var cdse = evddata as ChangeDisplayStateEvent; displayStateCache.Add(cdse.Time, cdse.DisplayState); break; case EventType.ChangeMoveState: var cmse = evddata as ChangeMoveStateEvent; if (stopstarttime < 0) { if (cmse.MoveState == MoveState.Stop) { stopstarttime = cmse.Time; } } else { if (cmse.MoveState == MoveState.Normal) { var temp = new float[] { stopstarttime, cmse.Time }; stoplist.Add(temp); stopstarttime = -1; } } break; case EventType.ChangeNoteType: var cace = evddata as ChangeNoteTypeEvent; noteTypeCache.Add(cace.Time, cace.NoteType); break; case EventType.ChangeInitializeOrder: var cioe = evddata as ChangeInitializeOrderEvent; initializeOrderCache.Add(cioe.Time, cioe.InitializeOrder); break; case EventType.ChangeSlideScale: var csse = evddata as ChangeSlideScaleEvent; slideScaleCache.Add(csse.Time, csse.SlideScale); break; } } } private void LoadData(string dir, Difficulty difficulty) { string filename = DifficultyUtility.ConvertDifficulty(difficulty) + ".evd"; string path = dir + "\\" + filename; if (File.Exists(path)) { data = EVDReader.Read(path); initialized = true; } else { initialized = false; } } private void LoadData(Stream stream) { try { data = EVDReader.Read(stream); initialized = true; } catch { initialized = false; } } public void Retry() { iter = 0; if (ChangeMovieVolume != null) ChangeMovieVolume.Invoke(-1000); for (int i = 0; i < volumePercents.Length; i++) { volumePercents[i] = 90; keepPlayings[i] = false; releaseSounds[i] = false; } BPMManager.CurrentBPM = defaultbpm; BPMManager.TargetBPM = defaultbpm; } public void Seek(float time) { Retry(); if (!initialized) return; ChangeEvent(time); } private void ChangeEvent(float time) { if (iter >= data.Length) return; IEVDData evddata = data[iter]; while (time >= evddata.Time) { switch (evddata.EventType) { case EventType.ChangeBPM: var cbe = evddata as ChangeBPMEvent; BPMManager.TargetBPM = cbe.BPM; break; case EventType.ChangeSoundPlayMode: var cspme = evddata as ChangeSoundPlayModeEvent; keepPlayings[cspme.Channel - 1] = cspme.KeepPlaying; break; case EventType.ChangeVolume: var cve = evddata as ChangeVolumeEvent; if (cve.Channel == 0) { if (ChangeMovieVolume != null) ChangeMovieVolume.Invoke(-100 * (100 - cve.Volume)); } else if (cve.Channel > 0 && cve.Channel <= 10) { volumePercents[cve.Channel - 1] = cve.Volume; } break; case EventType.RapidChangeBPM: var rcbe = evddata as RapidChangeBPMEvent; if (rcbe.Rapid) { BPMManager.CurrentBPM = rcbe.BPM; } BPMManager.TargetBPM = rcbe.BPM; break; case EventType.ChangeReleaseSound: var crse = evddata as ChangeReleaseSoundEvent; releaseSounds[crse.Channel - 1] = crse.ReleaseSound; break; } iter++; if (iter >= data.Length) return; evddata = data[iter]; } } public float GetSlideScale(float markTime) { float ret = 1; foreach (KeyValuePair<float, float> data in slideScaleCache) { if (markTime < data.Key) break; ret = data.Value; } return ret; } public DisplayState GetCorrectDisplaystate(float markTime) { if (config.DisplayState == DisplayState.Normal) { DisplayState ret = DisplayState.Normal; foreach (KeyValuePair<float, DisplayState> data in displayStateCache) { if (markTime < data.Key) break; ret = data.Value; } return ret; } else { return config.DisplayState; } } public NoteType GetNoteType(float markTime) { NoteType ret = NoteType.Normal; foreach (KeyValuePair<float, NoteType> data in noteTypeCache) { if (markTime < data.Key) break; ret = data.Value; } return ret; } public float GetCorrectTime(float currentTime, float markTime) { float ret = currentTime; for (int i = 0; i < stoplist.Count; i++) { float[] temp = stoplist[i]; if (markTime <= temp[1]) break; if (currentTime >= temp[1]) continue; if (currentTime >= temp[0] && currentTime <= temp[1]) { ret = temp[1]; } if (currentTime < temp[0]) { ret += temp[1] - temp[0]; } } return ret; } public ButtonType[] GetInitlaizeOrder(float markTime) { ButtonType[] ret = defaultInitializeOrder; foreach (KeyValuePair<float, ButtonType[]> data in initializeOrderCache) { if (markTime < data.Key) break; ret = data.Value; } return ret; } public void Update(float time) { if (initialized) { ChangeEvent(time); BPMManager.Step(); } } public float BPM { get { return BPMManager.CurrentBPM; } } public int GetVolPercent(int i) { if (i >= 0 && i < 10) { return volumePercents[i]; } return 0; } public bool GetReleaseSound(int i) { if (i >= 0 && i < 10) { return releaseSounds[i]; } return false; } public int[] VolumePercents { get { return volumePercents; } } public bool[] KeepPlayings { get { return keepPlayings; } } public bool[] ReleaseSounds { get { return releaseSounds; } } public bool SetVolumePercent(MarkType button, int volPercent) { if (0 <= button && button <= MarkType.L) { volumePercents[(int)button] = volPercent; return true; } return false; } public bool SetKeepPlaying(MarkType button, bool keepPlaying) { if (0 <= button && button <= MarkType.L) { this.keepPlayings[(int)button] = keepPlaying; return true; } return false; } public bool SetReleaseSound(MarkType button, bool releaseSound) { if (0 <= button && button <= MarkType.L) { releaseSounds[(int)button] = releaseSound; return true; } return false; } public int GetVolumePercent(MarkType button) { return volumePercents[(int)button]; } public bool GetKeepPlaying(MarkType button) { return keepPlayings[(int)button]; } public bool GetReleaseSound(MarkType button) { return releaseSounds[(int)button]; } } }
33.012987
133
0.464359
[ "Apache-2.0" ]
KHCmaster/PPD
Win/PPDCore/EventManager.cs
12,712
C#
namespace Lazy.Core.Enums { public enum ElementType { Assignment = 1, Fix = 2, Bug = 3, Other = 4, } }
13.454545
27
0.459459
[ "Apache-2.0" ]
MarioZisov/Lazy
Lazy.Core/Enums/ElementType.cs
150
C#
#region Copyright & License // Copyright © 2012 - 2021 François Chabot // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Diagnostics.CodeAnalysis; using Be.Stateless.BizTalk.Message.Extensions; using Be.Stateless.BizTalk.Stream; using Be.Stateless.Extensions; using log4net; using Microsoft.BizTalk.Component.Interop; using Microsoft.BizTalk.Message.Interop; namespace Be.Stateless.BizTalk.MicroComponent { /// <summary> /// Wraps the original message stream by a <see cref="MultipartFormDataContentStream"/>. /// </summary> public class MultipartFormDataContentEncoder : IMicroComponent { #region IMicroComponent Members public IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage message) { if (pipelineContext == null) throw new ArgumentNullException(nameof(pipelineContext)); if (message == null) throw new ArgumentNullException(nameof(message)); message.BodyPart.WrapOriginalDataStream( originalStream => { if (_logger.IsDebugEnabled) _logger.Debug("Wrapping message stream in a MultipartFormDataContentStream."); var multipartFormDataContentStream = ContentName.IsNullOrEmpty() ? UseBodyPartNameAsContentName ? new(originalStream, message.BodyPartName) : new MultipartFormDataContentStream(originalStream) : new(originalStream, ContentName); message.BodyPart.ContentType = multipartFormDataContentStream.ContentType; return multipartFormDataContentStream; }, pipelineContext.ResourceTracker); return message; } #endregion [SuppressMessage("ReSharper", "MemberCanBePrivate.Global", Justification = "Public API")] [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global", Justification = "Public API")] public string ContentName { get; set; } [SuppressMessage("ReSharper", "MemberCanBePrivate.Global", Justification = "Public API")] [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global", Justification = "Public API")] public bool UseBodyPartNameAsContentName { get; set; } private static readonly ILog _logger = LogManager.GetLogger(typeof(MultipartFormDataContentEncoder)); } }
38.768116
111
0.770093
[ "Apache-2.0" ]
icraftsoftware/Be.Stateless.BizTalk.Pipeline.MicroComponents
src/Be.Stateless.BizTalk.Pipeline.MicroComponents/MicroComponent/MultipartFormDataContentEncoder.cs
2,679
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using LuaInterface; namespace CSharpLua { [LuaAutoWrap] public sealed class BridgeMonoBehaviour : MonoBehaviour { private static readonly YieldInstruction[] updateYieldInstructions_ = new YieldInstruction[] { null, new WaitForFixedUpdate(), new WaitForEndOfFrame() }; public LuaTable Table { get; private set; } public string LuaClass; public string SerializeData; public UnityEngine.Object[] SerializeObjects; public void Bind(LuaTable table, string luaClass) { Table = table; LuaClass = luaClass; } public void Bind(LuaTable table) { Table = table; } internal void Bind(string luaClass, string serializeData, UnityEngine.Object[] serializeObjects) { LuaClass = luaClass; SerializeData = serializeData; SerializeObjects = serializeObjects; } public void RegisterUpdate(int instructionIndex, LuaFunction updateFn) { StartCoroutine(StartUpdate(updateFn, updateYieldInstructions_[instructionIndex])); } private IEnumerator StartUpdate(LuaFunction updateFn, YieldInstruction yieldInstruction) { while (true) { yield return yieldInstruction; updateFn.Call(Table); } } private void Awake() { if (!string.IsNullOrEmpty(LuaClass)) { if (Table == null) { Table = CSharpLuaClient.Instance.BindLua(this); } else { using (var fn = Table.GetLuaFunction("Awake")) { fn.Call(Table); } } } } private void Start() { using (var fn = Table.GetLuaFunction("Start")) { fn.Call(Table); } } } internal sealed class LuaIEnumerator : IEnumerator, IDisposable { private LuaTable table_; private LuaFunction current_; private LuaFunction moveNext_; private LuaIEnumerator(LuaTable table) { table_ = table; current_ = table.GetLuaFunction("getCurrent"); if (current_ == null) { throw new ArgumentNullException(); } moveNext_ = table.GetLuaFunction("MoveNext"); if (moveNext_ == null) { throw new ArgumentNullException(); } } public static LuaIEnumerator Create(LuaTable table) { var ret = table.GetTable<LuaIEnumerator>("ref"); if (ret == null) { ret = new LuaIEnumerator(table); table.SetTable("ref", ret); } return ret; } public void Push(IntPtr L) { table_.Push(); } public object Current { get { return current_.Invoke<LuaTable, object>(table_); } } public void Dispose() { if (current_ != null) { current_.Dispose(); current_ = null; } if (moveNext_ != null) { moveNext_.Dispose(); moveNext_ = null; } if (table_ != null) { table_.Dispose(); table_ = null; } } public bool MoveNext() { bool hasNext = moveNext_.Invoke<LuaTable, bool>(table_); if (!hasNext) { Dispose(); } return hasNext; } public void Reset() { throw new NotSupportedException(); } } #pragma warning disable 0162 public class CSharpLuaClient : LuaClient, IProvider { public string[] Components; private LuaFunction bindFn_; public static new CSharpLuaClient Instance { get { return (CSharpLuaClient)LuaClient.Instance; } } protected override void OpenLibs() { base.OpenLibs(); OpenCJson(); OpenPBC(); } private void OpenPBC() { luaState.OpenLibs(LuaDLL.luaopen_protobuf_c); } public override void Destroy() { if (bindFn_ != null) { bindFn_.Dispose(); bindFn_ = null; } base.Destroy(); BaseUtility.Provider = null; } protected override void StartMain() { BaseUtility.Provider = this; if (Settings.kIsRunFromLua) { base.StartMain(); bindFn_ = luaState.GetFunction("UnityEngine.bind"); if (bindFn_ == null) { throw new ArgumentNullException(); } if (Components != null && Components.Length > 0) { using (var fn = luaState.GetFunction("UnityEngine.addComponent")) { foreach (string type in Components) { fn.Call(gameObject, type); } } } } else { if (Components != null) { foreach (string type in Components) { Type componentType = Type.GetType(type, true, false); gameObject.AddComponent(componentType); } } } } internal LuaTable BindLua(BridgeMonoBehaviour bridgeMonoBehaviour) { return bindFn_.Invoke<BridgeMonoBehaviour, string, string, UnityEngine.Object[], LuaTable>( bridgeMonoBehaviour, bridgeMonoBehaviour.LuaClass, bridgeMonoBehaviour.SerializeData, bridgeMonoBehaviour.SerializeObjects); } public void ConvertCustomMonoBehaviour(ref GameObject prefab) { #if UNITY_EDITOR if (Settings.kIsRunFromLua) { UserMonoBehaviourConverter.Default.Do(ref prefab); } #endif } #pragma warning restore 0162 } }
25.931034
157
0.621201
[ "MIT" ]
DukeChiang/CSharpLuaForUnity
Assets/LuaRuntime/CSharpLua/CSharpLuaClient.cs
5,266
C#
using System; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using Jetsons.JSON.Internal; using Jetsons.JSON.Internal.Emit; namespace Jetsons.JSON { // NonGeneric API public static partial class JsonSerializer { public static class NonGeneric { static readonly Func<Type, CompiledMethods> CreateCompiledMethods; static readonly ThreadsafeTypeKeyHashTable<CompiledMethods> serializes = new ThreadsafeTypeKeyHashTable<CompiledMethods>(capacity: 64); delegate void SerializeJsonWriter(ref JsonWriter writer, object value, IJsonFormatterResolver resolver); delegate object DeserializeJsonReader(ref JsonReader reader, IJsonFormatterResolver resolver); static NonGeneric() { CreateCompiledMethods = t => new CompiledMethods(t); } static CompiledMethods GetOrAdd(Type type) { return serializes.GetOrAdd(type, CreateCompiledMethods); } /// <summary> /// Serialize to binary with default resolver. /// </summary> public static byte[] Serialize(object value) { if (value == null) return Serialize<object>(value); return Serialize(value.GetType(), value, defaultResolver); } /// <summary> /// Serialize to binary with default resolver. /// </summary> public static byte[] Serialize(Type type, object value) { return Serialize(type, value, defaultResolver); } /// <summary> /// Serialize to binary with specified resolver. /// </summary> public static byte[] Serialize(object value, IJsonFormatterResolver resolver) { if (value == null) return Serialize<object>(value, resolver); return Serialize(value.GetType(), value, resolver); } /// <summary> /// Serialize to binary with specified resolver. /// </summary> public static byte[] Serialize(Type type, object value, IJsonFormatterResolver resolver) { return GetOrAdd(type).serialize1.Invoke(value, resolver); } /// <summary> /// Serialize to stream. /// </summary> public static void Serialize(Stream stream, object value) { if (value == null) { Serialize<object>(stream, value); return; } Serialize(value.GetType(), stream, value, defaultResolver); } /// <summary> /// Serialize to stream. /// </summary> public static void Serialize(Type type, Stream stream, object value) { Serialize(type, stream, value, defaultResolver); } /// <summary> /// Serialize to stream with specified resolver. /// </summary> public static void Serialize(Stream stream, object value, IJsonFormatterResolver resolver) { if (value == null) { Serialize<object>(stream, value, resolver); return; } Serialize(value.GetType(), stream, value, resolver); } /// <summary> /// Serialize to stream with specified resolver. /// </summary> public static void Serialize(Type type, Stream stream, object value, IJsonFormatterResolver resolver) { GetOrAdd(type).serialize2.Invoke(stream, value, resolver); } #if NETSTANDARD /// <summary> /// Serialize to stream. /// </summary> public static System.Threading.Tasks.Task SerializeAsync(Stream stream, object value) { if (value == null) { return SerializeAsync<object>(stream, value); } return SerializeAsync(value.GetType(), stream, value, defaultResolver); } /// <summary> /// Serialize to stream. /// </summary> public static System.Threading.Tasks.Task SerializeAsync(Type type, Stream stream, object value) { return SerializeAsync(type, stream, value, defaultResolver); } /// <summary> /// Serialize to stream with specified resolver. /// </summary> public static System.Threading.Tasks.Task SerializeAsync(Stream stream, object value, IJsonFormatterResolver resolver) { if (value == null) { return SerializeAsync<object>(stream, value, resolver); } return SerializeAsync(value.GetType(), stream, value, resolver); } /// <summary> /// Serialize to stream with specified resolver. /// </summary> public static System.Threading.Tasks.Task SerializeAsync(Type type, Stream stream, object value, IJsonFormatterResolver resolver) { return GetOrAdd(type).serializeAsync.Invoke(stream, value, resolver); } #endif public static void Serialize(ref JsonWriter writer, object value, IJsonFormatterResolver resolver) { if (value == null) { writer.WriteNull(); return; } else { Serialize(value.GetType(), ref writer, value, resolver); } } public static void Serialize(Type type, ref JsonWriter writer, object value) { Serialize(type, ref writer, value, defaultResolver); } public static void Serialize(Type type, ref JsonWriter writer, object value, IJsonFormatterResolver resolver) { GetOrAdd(type).serialize3.Invoke(ref writer, value, resolver); } /// <summary> /// Serialize to binary. Get the raw memory pool byte[]. The result can not share across thread and can not hold, so use quickly. /// </summary> public static ArraySegment<byte> SerializeUnsafe(object value) { if (value == null) return SerializeUnsafe<object>(value); return SerializeUnsafe(value.GetType(), value); } /// <summary> /// Serialize to binary. Get the raw memory pool byte[]. The result can not share across thread and can not hold, so use quickly. /// </summary> public static ArraySegment<byte> SerializeUnsafe(Type type, object value) { return SerializeUnsafe(type, value, defaultResolver); } /// <summary> /// Serialize to binary with specified resolver. Get the raw memory pool byte[]. The result can not share across thread and can not hold, so use quickly. /// </summary> public static ArraySegment<byte> SerializeUnsafe(object value, IJsonFormatterResolver resolver) { if (value == null) return SerializeUnsafe<object>(value); return SerializeUnsafe(value.GetType(), value, resolver); } /// <summary> /// Serialize to binary with specified resolver. Get the raw memory pool byte[]. The result can not share across thread and can not hold, so use quickly. /// </summary> public static ArraySegment<byte> SerializeUnsafe(Type type, object value, IJsonFormatterResolver resolver) { return GetOrAdd(type).serializeUnsafe.Invoke(value, resolver); } /// <summary> /// Serialize to JsonString. /// </summary> public static string ToJsonString(object value) { if (value == null) return "null"; return ToJsonString(value.GetType(), value); } /// <summary> /// Serialize to JsonString. /// </summary> public static string ToJsonString(Type type, object value) { return ToJsonString(type, value, defaultResolver); } /// <summary> /// Serialize to JsonString with specified resolver. /// </summary> public static string ToJsonString(object value, IJsonFormatterResolver resolver) { if (value == null) return "null"; return ToJsonString(value.GetType(), value, resolver); } /// <summary> /// Serialize to JsonString with specified resolver. /// </summary> public static string ToJsonString(Type type, object value, IJsonFormatterResolver resolver) { return GetOrAdd(type).toJsonString.Invoke(value, resolver); } public static object Deserialize(Type type, string json) { return Deserialize(type, json, defaultResolver); } public static object Deserialize(Type type, string json, IJsonFormatterResolver resolver) { return GetOrAdd(type).deserialize1.Invoke(json, resolver); } public static object Deserialize(Type type, byte[] bytes) { return Deserialize(type, bytes, defaultResolver); } public static object Deserialize(Type type, byte[] bytes, IJsonFormatterResolver resolver) { return Deserialize(type, bytes, 0, defaultResolver); } public static object Deserialize(Type type, byte[] bytes, int offset) { return Deserialize(type, bytes, offset, defaultResolver); } public static object Deserialize(Type type, byte[] bytes, int offset, IJsonFormatterResolver resolver) { return GetOrAdd(type).deserialize2.Invoke(bytes, offset, resolver); } public static object Deserialize(Type type, Stream stream) { return Deserialize(type, stream, defaultResolver); } public static object Deserialize(Type type, Stream stream, IJsonFormatterResolver resolver) { return GetOrAdd(type).deserialize3.Invoke(stream, resolver); } public static object Deserialize(Type type, ref JsonReader reader) { return Deserialize(type, ref reader, defaultResolver); } public static object Deserialize(Type type, ref JsonReader reader, IJsonFormatterResolver resolver) { return GetOrAdd(type).deserialize4.Invoke(ref reader, resolver); } #if NETSTANDARD public static System.Threading.Tasks.Task<object> DeserializeAsync(Type type, Stream stream) { return DeserializeAsync(type, stream, defaultResolver); } public static System.Threading.Tasks.Task<object> DeserializeAsync(Type type, Stream stream, IJsonFormatterResolver resolver) { return GetOrAdd(type).deserializeAsync.Invoke(stream, resolver); } #endif class CompiledMethods { public readonly Func<object, IJsonFormatterResolver, byte[]> serialize1; public readonly Action<Stream, object, IJsonFormatterResolver> serialize2; public readonly SerializeJsonWriter serialize3; public readonly Func<object, IJsonFormatterResolver, ArraySegment<byte>> serializeUnsafe; public readonly Func<object, IJsonFormatterResolver, string> toJsonString; public readonly Func<string, IJsonFormatterResolver, object> deserialize1; public readonly Func<byte[], int, IJsonFormatterResolver, object> deserialize2; public readonly Func<Stream, IJsonFormatterResolver, object> deserialize3; public readonly DeserializeJsonReader deserialize4; #if NETSTANDARD public readonly Func<Stream, object, IJsonFormatterResolver, System.Threading.Tasks.Task> serializeAsync; public readonly Func<Stream, IJsonFormatterResolver, System.Threading.Tasks.Task<object>> deserializeAsync; #endif public CompiledMethods(Type type) { { var dm = new DynamicMethod("serialize1", typeof(byte[]), new[] { typeof(object), typeof(IJsonFormatterResolver) }, type.Module, true); var il = dm.GetILGenerator(); il.EmitLdarg(0); // obj il.EmitUnboxOrCast(type); il.EmitLdarg(1); il.EmitCall(GetMethod(type, "Serialize", new[] { null, typeof(IJsonFormatterResolver) })); il.Emit(OpCodes.Ret); serialize1 = CreateDelegate<Func<object, IJsonFormatterResolver, byte[]>>(dm); } { var dm = new DynamicMethod("serialize2", null, new[] { typeof(Stream), typeof(object), typeof(IJsonFormatterResolver) }, type.Module, true); var il = dm.GetILGenerator(); il.EmitLdarg(0); // stream il.EmitLdarg(1); il.EmitUnboxOrCast(type); il.EmitLdarg(2); il.EmitCall(GetMethod(type, "Serialize", new[] { typeof(Stream), null, typeof(IJsonFormatterResolver) })); il.Emit(OpCodes.Ret); serialize2 = CreateDelegate<Action<Stream, object, IJsonFormatterResolver>>(dm); } { var dm = new DynamicMethod("serialize3", null, new[] { typeof(JsonWriter).MakeByRefType(), typeof(object), typeof(IJsonFormatterResolver) }, type.Module, true); var il = dm.GetILGenerator(); il.EmitLdarg(0); // ref writer il.EmitLdarg(1); il.EmitUnboxOrCast(type); il.EmitLdarg(2); il.EmitCall(GetMethod(type, "Serialize", new[] { typeof(JsonWriter).MakeByRefType(), null, typeof(IJsonFormatterResolver) })); il.Emit(OpCodes.Ret); serialize3 = CreateDelegate<SerializeJsonWriter>(dm); } { var dm = new DynamicMethod("serializeUnsafe", typeof(ArraySegment<byte>), new[] { typeof(object), typeof(IJsonFormatterResolver) }, type.Module, true); var il = dm.GetILGenerator(); il.EmitLdarg(0); // obj il.EmitUnboxOrCast(type); il.EmitLdarg(1); il.EmitCall(GetMethod(type, "SerializeUnsafe", new[] { null, typeof(IJsonFormatterResolver) })); il.Emit(OpCodes.Ret); serializeUnsafe = CreateDelegate<Func<object, IJsonFormatterResolver, ArraySegment<byte>>>(dm); } { var dm = new DynamicMethod("toJsonString", typeof(string), new[] { typeof(object), typeof(IJsonFormatterResolver) }, type.Module, true); var il = dm.GetILGenerator(); il.EmitLdarg(0); // obj il.EmitUnboxOrCast(type); il.EmitLdarg(1); il.EmitCall(GetMethod(type, "ToJsonString", new[] { null, typeof(IJsonFormatterResolver) })); il.Emit(OpCodes.Ret); toJsonString = CreateDelegate<Func<object, IJsonFormatterResolver, string>>(dm); } { var dm = new DynamicMethod("Deserialize", typeof(object), new[] { typeof(string), typeof(IJsonFormatterResolver) }, type.Module, true); var il = dm.GetILGenerator(); il.EmitLdarg(0); il.EmitLdarg(1); il.EmitCall(GetMethod(type, "Deserialize", new[] { typeof(string), typeof(IJsonFormatterResolver) })); il.EmitBoxOrDoNothing(type); il.Emit(OpCodes.Ret); deserialize1 = CreateDelegate<Func<string, IJsonFormatterResolver, object>>(dm); } { var dm = new DynamicMethod("Deserialize", typeof(object), new[] { typeof(byte[]), typeof(int), typeof(IJsonFormatterResolver) }, type.Module, true); var il = dm.GetILGenerator(); il.EmitLdarg(0); il.EmitLdarg(1); il.EmitLdarg(2); il.EmitCall(GetMethod(type, "Deserialize", new[] { typeof(byte[]), typeof(int), typeof(IJsonFormatterResolver) })); il.EmitBoxOrDoNothing(type); il.Emit(OpCodes.Ret); deserialize2 = CreateDelegate<Func<byte[], int, IJsonFormatterResolver, object>>(dm); } { var dm = new DynamicMethod("Deserialize", typeof(object), new[] { typeof(Stream), typeof(IJsonFormatterResolver) }, type.Module, true); var il = dm.GetILGenerator(); il.EmitLdarg(0); il.EmitLdarg(1); il.EmitCall(GetMethod(type, "Deserialize", new[] { typeof(Stream), typeof(IJsonFormatterResolver) })); il.EmitBoxOrDoNothing(type); il.Emit(OpCodes.Ret); deserialize3 = CreateDelegate<Func<Stream, IJsonFormatterResolver, object>>(dm); } { var dm = new DynamicMethod("Deserialize", typeof(object), new[] { typeof(JsonReader).MakeByRefType(), typeof(IJsonFormatterResolver) }, type.Module, true); var il = dm.GetILGenerator(); il.EmitLdarg(0); // ref reader il.EmitLdarg(1); il.EmitCall(GetMethod(type, "Deserialize", new[] { typeof(JsonReader).MakeByRefType(), typeof(IJsonFormatterResolver) })); il.EmitBoxOrDoNothing(type); il.Emit(OpCodes.Ret); deserialize4 = CreateDelegate<DeserializeJsonReader>(dm); } #if NETSTANDARD { var dm = new DynamicMethod("SerializeAsync", typeof(System.Threading.Tasks.Task), new[] { typeof(Stream), typeof(object), typeof(IJsonFormatterResolver) }, type.Module, true); var il = dm.GetILGenerator(); il.EmitLdarg(0); // stream il.EmitLdarg(1); il.EmitUnboxOrCast(type); il.EmitLdarg(2); il.EmitCall(GetMethod(type, "SerializeAsync", new[] { typeof(Stream), null, typeof(IJsonFormatterResolver) })); il.Emit(OpCodes.Ret); serializeAsync = CreateDelegate<Func<Stream, object, IJsonFormatterResolver, System.Threading.Tasks.Task>>(dm); } { var dm = new DynamicMethod("DeserializeAsync", typeof(System.Threading.Tasks.Task<object>), new[] { typeof(Stream), typeof(IJsonFormatterResolver) }, type.Module, true); var il = dm.GetILGenerator(); il.EmitLdarg(0); il.EmitLdarg(1); il.EmitCall(GetMethod(type, "DeserializeAsync", new[] { typeof(Stream), typeof(IJsonFormatterResolver) })); il.EmitCall(typeof(CompiledMethods).GetMethod("TaskCast", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(type)); il.Emit(OpCodes.Ret); deserializeAsync = CreateDelegate<Func<Stream, IJsonFormatterResolver, System.Threading.Tasks.Task<object>>>(dm); } #endif } #if NETSTANDARD static async System.Threading.Tasks.Task<object> TaskCast<T>(System.Threading.Tasks.Task<T> task) { var t = await task.ConfigureAwait(false); return (object)t; } #endif static T CreateDelegate<T>(DynamicMethod dm) { return (T)(object)dm.CreateDelegate(typeof(T)); } static MethodInfo GetMethod(Type type, string name, Type[] arguments) { return typeof(JsonSerializer).GetMethods(BindingFlags.Static | BindingFlags.Public) .Where(x => x.Name == name) .Single(x => { var ps = x.GetParameters(); if (ps.Length != arguments.Length) return false; for (int i = 0; i < ps.Length; i++) { // null for <T>. if (arguments[i] == null && ps[i].ParameterType.IsGenericParameter) continue; if (ps[i].ParameterType != arguments[i]) return false; } return true; }) .MakeGenericMethod(type); } } } } }
44.987805
199
0.535737
[ "MIT" ]
jetsons/JetPack.Data.Net
JSON/JsonSerializer.NonGeneric.cs
22,136
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Serialization; using System.ServiceModel; namespace WcfService { [ServiceContract(SessionMode = SessionMode.Allowed)] public interface ISessionTestsDefaultService { [OperationContract] int MethodAInitiating(int a); [OperationContract] int MethodBNonInitiating(int b); [OperationContract] SessionTestsCompositeType MethodCTerminating(); } [ServiceContract(SessionMode = SessionMode.Allowed)] public interface ISessionTestsShortTimeoutService : ISessionTestsDefaultService { } } [DataContract] public class SessionTestsCompositeType { [DataMember] public int MethodAValue { get; set; } [DataMember] public int MethodBValue { get; set; } } [ServiceContract(CallbackContract = typeof(ISessionTestsDuplexCallback), SessionMode = SessionMode.Required)] public interface ISessionTestsDuplexService { [OperationContract(IsInitiating = true, IsTerminating = false)] int NonTerminatingMethodCallingDuplexCallbacks( int callsToClientCallbackToMake, int callsToTerminatingClientCallbackToMake, int callsToClientSideOnlyTerminatingClientCallbackToMake, int callsToNonTerminatingMethodToMakeInsideClientCallback, int callsToTerminatingMethodToMakeInsideClientCallback); [OperationContract(IsInitiating = true, IsTerminating = true)] int TerminatingMethodCallingDuplexCallbacks( int callsToClientCallbackToMake, int callsToTerminatingClientCallbackToMake, int callsToClientSideOnlyTerminatingClientCallbackToMake, int callsToNonTerminatingMethodToMakeInsideClientCallback, int callsToTerminatingMethodToMakeInsideClientCallback); [OperationContract] int NonTerminatingMethod(); [OperationContract] int TerminatingMethod(); } [ServiceContract(SessionMode = SessionMode.Required)] public interface ISessionTestsDuplexCallback { [OperationContract(IsInitiating = true, IsTerminating = false)] int ClientCallback(int callsToNonTerminatingMethodToMake, int callsToTerminatingMethodToMake); [OperationContract(IsInitiating = true, IsTerminating = true)] int TerminatingClientCallback(int callsToNonTerminatingMethodToMake, int callsToTerminatingMethodToMake); // note IsTerminating = false while the client callback has IsTerminating = true [OperationContract(IsInitiating = true, IsTerminating = false)] int ClientSideOnlyTerminatingClientCallback(int callsToNonTerminatingMethodToMake, int callsToTerminatingMethodToMake); }
36.207792
123
0.781205
[ "MIT" ]
crummel/dotnet_wcf
src/System.Private.ServiceModel/tools/IISHostedWcfService/App_code/ISessionTests.cs
2,790
C#
using System; using CCompiler.Tokenizer; namespace CCompiler.Parser { public interface IParseResult { public bool IsSuccess { get; } public Node ResultNode { get; } public string ErrorMessage { get; } public bool IsNullStat(); } public class SuccessParseResult : IParseResult { public SuccessParseResult(Node node) { ResultNode = node; } public bool IsSuccess => true; public Node ResultNode { get; } public string ErrorMessage => throw new NullReferenceException("Attempt to get ErrorMessage in success parse result"); public bool IsNullStat() { return ResultNode is NullStat; } } public class FailedParseResult : IParseResult { public FailedParseResult(string errorMessage, Token token) { ErrorMessage = errorMessage; } public bool IsSuccess => false; public Node ResultNode => throw new NullReferenceException("Attempt to get Node in failed parse result"); public string ErrorMessage { get; } public bool IsNullStat() { throw new NullReferenceException("Attempt to check failed parse node"); } } }
26.666667
113
0.6125
[ "MIT" ]
ALMikhai/CCompiler
CCompiler/Parser/ParseResult.cs
1,282
C#
using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace SimpleAPI { public class DataLayer { private readonly ConnectionFactory _connectionFactory; public DataLayer() { _connectionFactory = new ConnectionFactory(); } public SqlDataReader RunStoredProcedure(string storedProcedureName, IList<SqlParameter> parameters) { var connection = (SqlConnection)_connectionFactory.Create(); connection.Open(); var command = connection.CreateCommand(); command.CommandText = storedProcedureName; command.CommandType = CommandType.StoredProcedure; foreach (var parameter in parameters) command.Parameters.Add(parameter); return command.ExecuteReader(); } } }
28
107
0.647465
[ "MIT" ]
CodeUpManchester/SimpleAPI
SimpleAPI/SimpleAPI/DataLayer.cs
870
C#
using Messages.Core; using System.Threading.Tasks; using HouseModel = Make.Magic.Challenge.Domain.House.Models.House; namespace Make.Magic.Challenge.Domain.House.Services.Contracts { public interface IHouseService { Task<Response<HouseModel>> GetHouseAsync(string houseId); } }
25
66
0.76
[ "MIT" ]
leo-oliveira-eng/Make-Magic-Challenge
Make.Magic.Challenge.Domain/House/Services/Contracts/IHouseService.cs
302
C#
using System.Data.Entity; namespace Chapter_1.Core { public class UserContext : DbContext { public DbSet<User> Users { get; set; } public UserContext() : base("DbConnection") { } } }
18.75
56
0.591111
[ "Apache-2.0" ]
verloka/EF6FromZero
src/Chapter_1/Chapter_1/Core/UserContext.cs
227
C#
using System.Text.Json; using System.Threading.Tasks; using Flurl.Http; using Flurl.Http.Configuration; namespace NemligSharp { public class NemligClient : INemligClient { public const string NemligBaseUrl = "https://www.nemlig.com/"; private readonly IFlurlClient _flurlClient; private CookieJar _cookieJar = null; public NemligClient(IFlurlClientFactory flurlClientFactory) { _flurlClient = flurlClientFactory.Get(NemligBaseUrl); } public async Task<ILoginResponse> LoginAsync(string userName, string password) { var payload = new LoginPayload(userName, password); var response = await _flurlClient.Request(new string[] { "webapi", "login" }).WithCookies(out var jar).PostJsonAsync(payload).ConfigureAwait(false); var jsonString = await response.GetStringAsync().ConfigureAwait(false); var deserialized = JsonSerializer.Deserialize<LoginResponse>(jsonString); _cookieJar = jar; return deserialized with { StatusCode = response.StatusCode }; } public async Task<ICurrentUserResponse> GetCurrentUserAsync() { return await DoFlurlGet<CurrentUserResponse, ICurrentUserResponse>(new string[] { "webapi", "user", "GetCurrentUser" }).ConfigureAwait(false); } public async Task<IOrderHistoryResponse> GetOrderHistoryAsync(int skip, int take) { return await DoFlurlGet<OrderHistoryResponse, IOrderHistoryResponse>(new string[] { "webapi", "order", "GetBasicOrderHistory" }, new { skip, take }); } public async Task<IOrderResponse> GetOrderAsync(int orderId) { return await DoFlurlGet<OrderResponse, IOrderResponse>(new string[] { "webapi", "order", "GetOrderHistory" }, new { orderNumber = orderId }); } public async Task<IShoppingListsResponse> GetShoppingListsAsync(int skip, int take) { return await DoFlurlGet<ShoppingListsResponse, IShoppingListsResponse>(new string[] { "webapi", "ShoppingList", "GetShoppingLists" }, new { skip, take }); } public async Task<IShoppingListResponse> GetShoppingListAsync(int shoppingListId) { return await DoFlurlGet<ShoppingListResponse, IShoppingListResponse>(new string[] { "webapi", "ShoppingList", "GetShoppingList" }, new { listId = shoppingListId }); } public async Task<ICurrentBasketResponse> GetCurrentBasketAsync() { return await DoFlurlGet<CurrentBasketResponse, ICurrentBasketResponse>(new string[] { "webapi", "basket", "GetBasket" }); } private async Task<TResponseInterface> DoFlurlGet<TResponseImplementation, TResponseInterface>(string[] pathSegments, object queryParameters = null) where TResponseImplementation : Response, TResponseInterface where TResponseInterface : IResponse { var response = await _flurlClient.Request(pathSegments).SetQueryParams(queryParameters).WithCookies(_cookieJar).GetAsync().ConfigureAwait(false); var jsonString = await response.GetStringAsync().ConfigureAwait(false); var deserialized = JsonSerializer.Deserialize<TResponseImplementation>(jsonString); return deserialized with { StatusCode = response.StatusCode }; } } }
42.166667
167
0.768116
[ "MIT" ]
kimipsen/NemligSharp
src/NemligClient.cs
3,038
C#
namespace ZI.Properties { // 通过此类可以处理设置类上的特定事件: // 在更改某个设置的值之前将引发 SettingChanging 事件。 // 在更改某个设置的值之后将引发 PropertyChanged 事件。 // 在加载设置值之后将引发 SettingsLoaded 事件。 // 在保存设置值之前将引发 SettingsSaving 事件。 internal sealed partial class Settings { public Settings() { // // 若要为保存和更改设置添加事件处理程序,请取消注释下列行: // // this.SettingChanging += this.SettingChangingEventHandler; // // this.SettingsSaving += this.SettingsSavingEventHandler; // } private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) { // 在此处添加用于处理 SettingChangingEvent 事件的代码。 } private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) { // 在此处添加用于处理 SettingsSaving 事件的代码。 } } }
32.62069
115
0.599366
[ "MIT" ]
lymuxh/Price-index-simulation-tool
code/Settings.cs
1,220
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Web.Syndication { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] #endif public enum SyndicationErrorStatus { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ Unknown, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ MissingRequiredElement, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ MissingRequiredAttribute, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ InvalidXml, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ UnexpectedContent, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ UnsupportedFormat, #endif } #endif }
28.5625
63
0.704595
[ "Apache-2.0" ]
06needhamt/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Web.Syndication/SyndicationErrorStatus.cs
914
C#
using AutoMapper; using Synchronization.Application.AutoMapper; using Xunit; namespace Synchronization.Application.Tests.Tests.AutoMapper; public class AutoMapperProfileTests { [Fact] public void ProfileIsValid() { // Arrange var configuration = new MapperConfiguration(cfg => cfg.AddProfile<AutoMapperProfile>()); // Act & Assert configuration.AssertConfigurationIsValid(); } }
22.684211
96
0.714617
[ "MIT" ]
nmshd/bkb-synchronization
Synchronization.Application.Tests/Tests/AutoMapper/AutoMapperProfileTests.cs
433
C#
using Microsoft.Toolkit.Uwp; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FluentHub.Models { public class DefaultLanguageModel { public string ID { get; set; } public string Name { get; set; } public DefaultLanguageModel(string id) { if (!string.IsNullOrEmpty(id)) { var info = new CultureInfo(id); ID = info.Name; Name = info.NativeName; } else { ID = string.Empty; var systemDefaultLanguageOptionStr = "WndowsDefault".GetLocalized(); Name = string.IsNullOrEmpty(systemDefaultLanguageOptionStr) ? "Windows Default" : systemDefaultLanguageOptionStr; } } public override string ToString() => Name; } }
26.194444
129
0.585366
[ "MIT" ]
esibruti/FluentHub
src/FluentHub/Models/DefaultLanguageModel.cs
945
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using CoreUserIdentity._UserIdentity; using CoreUserIdentity.Models; using FridgeServer.Data; using FridgeServer.Helpers; using FridgeServer.Models; using FridgeServer.Models.Dto; using FridgeServer.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; namespace FridgeServer.Controllers { static class setting { public static bool alreadyrun = false; public static SiteStatus siteStatus { get; set; } } [AuthTokenManager] [Route("api/[controller]")] public class AdminController : Controller { private IUserService userService; private IRunOnAppStart<ApplicationUser> runOnAppStart; private AppSettings appSettings; private readonly IHostingEnvironment env; private AppDbContext db; public AdminController(IUserService _userService, IRunOnAppStart<ApplicationUser> _runOnAppStart,IOptions<AppSettings> _options , IHostingEnvironment _hostingEnvironment, AppDbContext _db) { appSettings = _options.Value; userService = _userService; env = _hostingEnvironment; runOnAppStart = _runOnAppStart; db = _db; } [HttpGet] public async Task<IActionResult> Get() { return Ok(new { result = new string[] { "welcome admin", $"Id:{GetTokenId()}",$"name:{GetTokenUsername()}" } }); } //Get all user [HttpGet("users")] public async Task<IActionResult> GetAll() { var users =userService.GetAllUsing_Manager().ToList(); return Ok(new { users }); } //Get by id [HttpGet("{id}")] public async Task<IActionResult> GetById(string Id) { var user = await userService.GetById_Manager(Id); return Ok(user); } //Get all user [HttpGet("FullUsers")] public async Task<IActionResult> GetFullUsers() { var users = await userService.GetAllUsing_Db(); return Ok(new { users }); } //Run for the first time [AllowAnonymous] [HttpGet("runonfirsttime/{code}")] public async Task<IActionResult> RunForFirstTime(string code,[FromQuery(Name ="force")]bool force=false) { // check that the provided code is correct var admincode = appSettings.adminaccesscode; if (admincode != code) return NotFound(); if (setting.alreadyrun==false || force) { setting.alreadyrun = true; if (env.IsProduction() ) { db.Database.Migrate(); } var siteStatus = await runOnAppStart.Start(); var appSettingsFile = appSettings; setting.siteStatus = siteStatus; var results = new { appSettingsFile, siteStatus }; return Ok( ret(results, "admin created") ); } else { var siteStatus = setting.siteStatus; var appSettingsFile = appSettings; var results = new { appSettingsFile, siteStatus }; return Ok(ret(results, "admin already run")); } } #region Response Converter //response value public ResponseDto<T> ret<T>(T value, string statusText) { var response = new ResponseDto<T> { statusText = statusText, value = value }; return response; } //response error public ResponseDto ree(string error) { if (string.IsNullOrEmpty(error)) { error = "error"; } var response = new ResponseDto { errors = error }; return response; } #endregion #region Get User and Claim public string GetTokenUsername() { var name = HttpContext.User.Identity.Name; if (name != null) { return name; } return null; } public string GetTokenId() { var claims = HttpContext.User.Claims; var claim = FindClaimNameIdentifier(claims); if (claim != null) { return claim.Value; } return null; } public Claim FindClaim(IEnumerable<Claim> Eclaims, string ClaimType) { var claims = Eclaims.ToList(); for (int i = 0; i < claims.Count; i++) { var claim = claims[i]; if (claim.Type == ClaimType) { return claim; } } return null; } public Claim FindClaimNameIdentifier(IEnumerable<Claim> Eclaims) { return FindClaim(Eclaims, ClaimTypes.NameIdentifier); } public string GetHost() { return HttpContext.Request.Host.Value; } #endregion } }
29.648649
135
0.545488
[ "MIT" ]
MoustafaMohsen/fridge-notes-Api
FridgeServer/Controllers/AdminController.cs
5,487
C#
using Polyglot; using UnityEngine; using System.Collections.Generic; using IPA.Config.Stores.Converters; using IPA.Config.Stores.Attributes; namespace SiraUtil { public class Config { public virtual int MajorVersion { get; set; } public virtual int MinorVersion { get; set; } public virtual int BuildVersion { get; set; } [NonNullable] public virtual FPFCToggleOptions FPFCToggle { get; set; } = new FPFCToggleOptions(); [NonNullable] public virtual SongControlOptions SongControl { get; set; } = new SongControlOptions(); [NonNullable] public virtual LocalizationOptions Localization { get; set; } = new LocalizationOptions(); public class SongControlOptions { public virtual bool Enabled { get; set; } = false; [UseConverter(typeof(EnumConverter<KeyCode>))] public virtual KeyCode RestartKeyCode { get; set; } = KeyCode.F4; [UseConverter(typeof(EnumConverter<KeyCode>))] public virtual KeyCode ExitKeyCode { get; set; } = KeyCode.Escape; [UseConverter(typeof(EnumConverter<KeyCode>))] public virtual KeyCode PauseToggleKeyCode { get; set; } = KeyCode.F2; } public class FPFCToggleOptions { public virtual bool Enabled { get; set; } = false; public virtual float CameraFOV { get; set; } = 90f; public virtual float MoveSensitivity { get; set; } = 0.1f; [UseConverter(typeof(EnumConverter<KeyCode>))] public virtual KeyCode ToggleKeyCode { get; set; } = KeyCode.G; } public class LocalizationOptions { public virtual bool Enabled { get; set; } = false; [NonNullable, UseConverter(typeof(DictionaryConverter<LocalizationSource>))] public virtual Dictionary<string, LocalizationSource> Sources { get; set; } = new Dictionary<string, LocalizationSource>(); public class LocalizationSource { public bool Enabled { get; set; } public string URL { get; set; } public string IsOnline { get; set; } [UseConverter(typeof(EnumConverter<GoogleDriveDownloadFormat>))] public GoogleDriveDownloadFormat Format { get; set; } } } } }
36.257576
135
0.616799
[ "MIT" ]
ErisApps/SiraUtil
SiraUtil/Config.cs
2,395
C#
using Abp.EntityFrameworkCore.Configuration; using Abp.IdentityServer4; using Abp.Modules; using Abp.Reflection.Extensions; using Abp.Zero.EntityFrameworkCore; using StroudwaterIdentity.EntityFrameworkCore.Seed; namespace StroudwaterIdentity.EntityFrameworkCore { [DependsOn( typeof(StroudwaterIdentityCoreModule), typeof(AbpZeroCoreIdentityServerEntityFrameworkCoreModule), typeof(AbpZeroCoreEntityFrameworkCoreModule))] public class StroudwaterIdentityEntityFrameworkModule : AbpModule { /* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */ public bool SkipDbContextRegistration { get; set; } public bool SkipDbSeed { get; set; } public override void PreInitialize() { if (!SkipDbContextRegistration) { Configuration.Modules.AbpEfCore().AddDbContext<StroudwaterIdentityDbContext>(options => { if (options.ExistingConnection != null) { StroudwaterIdentityDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection); } else { StroudwaterIdentityDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString); } }); } } public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(StroudwaterIdentityEntityFrameworkModule).GetAssembly()); } public override void PostInitialize() { if (!SkipDbSeed) { SeedHelper.SeedHostDb(IocManager); } } } }
34.150943
127
0.623204
[ "MIT" ]
ITconsultants247/StroudwaterIdentity
aspnet-core/src/StroudwaterIdentity.EntityFrameworkCore/EntityFrameworkCore/StroudwaterIdentityEntityFrameworkModule.cs
1,812
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace viva { public partial class PauseMenu : UIMenu { public enum Menu { NONE, ROOT, KB_CONTROLS, VR_CONTROLS, MAP, OPTIONS, ERROR, CHECKLIST, CALIBRATE_HANDS, MANUAL } private List<Button> cycleButtons = new List<Button>(); private int cycleIndex = 0; private Menu lastMenu = Menu.NONE; [SerializeField] private RectTransform rightPageRootPanel; [SerializeField] private RectTransform leftPageRootPanel; [SerializeField] private PageScroller checklistPageScroller; [SerializeField] private GameObject checklistPrefab; [SerializeField] public GameObject fadePanel; [SerializeField] public Text mouseSensitivityText; [SerializeField] private Text musicVolumeText; [SerializeField] private Text dayNightCycleSpeedText; [SerializeField] private GameObject beginnerFriendlyKeyboard; [SerializeField] private GameObject beginnerFriendlyVR; [SerializeField] private Text respawnLoliText; [SerializeField] private Text antiAliasingText; private Coroutine errorCoroutine = null; private Coroutine calibrationCoroutine = null; private Vector3 lastPositionBeforeTutorial = Vector3.zero; [SerializeField] private GameObject calibrateHandGhostPrefab = null; public void ShowFirstLoadInstructions() { if (GameDirector.player.controls == Player.ControlType.KEYBOARD) { beginnerFriendlyKeyboard.SetActive(true); } else { beginnerFriendlyVR.SetActive(true); } } private void Start() { if (tutorialCircle == null) { Debug.LogError("ERROR Tutorial Circle is null!"); } checklistPageScroller.Initialize(OnChecklistManifest, OnChecklistPageUpdate); //parent to page rightPageRootPanel.SetParent(UI_pageL); rightPageRootPanel.localEulerAngles = new Vector3(180.0f, 90.0f, 90.0f); rightPageRootPanel.localPosition = Vector3.zero; //parent to page leftPageRootPanel.SetParent(UI_pageR); leftPageRootPanel.localEulerAngles = new Vector3(0.0f, 90.0f, 90.0f); leftPageRootPanel.localPosition = Vector3.zero; } public void clickStartTutorial() { GameDirector.instance.StopUIInput(); if (tutorialCoroutine != null) { return; } lastPositionBeforeTutorial = GameDirector.player.transform.position; GameDirector.player.transform.position = tutorialCircle.transform.position; menuTutorialPhase = MenuTutorial.NONE; tutorialCoroutine = GameDirector.instance.StartCoroutine(Tutorial()); } public override void OnBeginUIInput() { Debug.Log("[PAUSEMENU] Open"); gameObject.SetActive(true); PlayBookAnimation("open", OnOpenBookFinished); GameDirector.instance.PlayGlobalSound(openSound); OrientPauseBookToPlayer(); } public override void OnExitUIInput() { Debug.Log("[PAUSEMENU] Closed"); PlayBookAnimation("close", OnCloseBookFinished); GameDirector.instance.PlayGlobalSound(closeSound); SetMenuActive(Menu.NONE, false); lastMenu = Menu.NONE; StopCalibration(); } private void UpdateMusicVolumeText() { musicVolumeText.text = "" + (int)(GameDirector.settings.musicVolume * 100) + "%"; } public void clickShiftMusicVolume(float amount) { GameDirector.settings.AdjustMusicVolume(amount); UpdateMusicVolumeText(); } public void clickShiftDayNightCycleSpeedIndex(int indexAmount) { dayNightCycleSpeedText.text = GameDirector.settings.AdjustDayTimeSpeedIndex(indexAmount); } private void UpdateMouseSensitivityText() { mouseSensitivityText.text = "" + (int)(GameDirector.settings.mouseSensitivity) + "%"; } public void IncreaseMouseSensitivity() { GameDirector.settings.AdjustMouseSensitivity(10.0f); UpdateMouseSensitivityText(); } public void DecreaseMouseSensitivity() { GameDirector.settings.AdjustMouseSensitivity(-10.0f); UpdateMouseSensitivityText(); } public void DisplayError(string message) { if (errorCoroutine != null) { GameDirector.instance.StopCoroutine(errorCoroutine); } GameDirector.instance.StartCoroutine(ErrorMessage(message)); } private IEnumerator ErrorMessage(string message) { float timer = 3.0f; GameObject errorPanel = GetRightPageUIByMenu(Menu.ERROR); errorPanel.SetActive(true); Text text = errorPanel.transform.GetChild(1).GetComponent(typeof(Text)) as Text; text.text = message; while (timer > 0.0f) { timer -= Time.deltaTime; yield return null; } errorPanel.SetActive(false); } private GameObject GetRightPageUIByMenu(Menu menu) { if (menu == Menu.NONE) { return null; } return rightPageRootPanel.transform.GetChild((int)menu - 1).gameObject; } private GameObject GetLeftPageUIByMenu(Menu menu) { if (menu == Menu.NONE) { return null; } return leftPageRootPanel.transform.GetChild((int)menu - 1).gameObject; } private void SetMenuActive(Menu menu, bool active) { GameObject lastMenuPanel = GetRightPageUIByMenu(lastMenu); if (lastMenuPanel) { lastMenuPanel.SetActive(false); GetLeftPageUIByMenu(lastMenu).SetActive(false); } GameObject menuPanel = GetRightPageUIByMenu(menu); if (menuPanel) { menuPanel.SetActive(active); GetLeftPageUIByMenu(menu).SetActive(active); if (active) { SetCycleButtonsFrom(menuPanel); lastMenu = menu; } } } public void SetPauseMenu(Menu menu) { switch (menu) { case Menu.NONE: SetMenuActive(menu, false); break; case Menu.VR_CONTROLS: GameDirector.instance.PlayGlobalSound(nextSound); SetMenuActive(menu, true); UpdateVRMovementPrefText(); UpdateDisableGrabToggleText(); UpdatePressToTurnText(); break; case Menu.KB_CONTROLS: case Menu.OPTIONS: GameDirector.instance.PlayGlobalSound(nextSound); SetMenuActive(menu, true); UpdateMusicVolumeText(); UpdateMouseSensitivityText(); clickShiftDayNightCycleSpeedIndex(0); UpdateToggleQualityText(); UpdateAntiAliasingText(); break; case Menu.MAP: GameDirector.instance.PlayGlobalSound(nextSound); SetMenuActive(menu, true); break; case Menu.CHECKLIST: GameDirector.instance.PlayGlobalSound(nextSound); SetMenuActive(menu, true); ContinueTutorial(MenuTutorial.WAIT_TO_ENTER_CHECKLIST); break; case Menu.CALIBRATE_HANDS: case Menu.MANUAL: GameDirector.instance.PlayGlobalSound(nextSound); SetMenuActive(menu, true); SetShowManualRoot(true); UpdateRespawnShinobuText(); break; case Menu.ROOT: if (lastMenu == Menu.ROOT) { //treat as a toggle GameDirector.instance.StopUIInput(); return; } GameDirector.instance.PlayGlobalSound(prevSound); SetMenuActive(menu, true); ContinueTutorial(MenuTutorial.WAIT_TO_OPEN_PAUSE_MENU); break; } } public void OrientPauseBookToPlayer() { Player player = GameDirector.player; if (player.controls == Player.ControlType.KEYBOARD) { transform.localScale = Vector3.one * 0.045f; //make it tiny so it doesn't get occluded by other objects transform.position = player.head.transform.TransformPoint(keyboardOrientPosition); transform.rotation = player.head.rotation * Quaternion.Euler(keyboardOrientRotation); } else { Vector3 forward = player.head.forward; forward.y = 0.0f; forward = forward.normalized; transform.localScale = Vector3.one; transform.position = player.floorPos + forward * 0.8f - Vector3.up * 0.2f; transform.rotation = Quaternion.LookRotation(-forward, Vector3.up); } } private void SetCycleButtonsFrom(GameObject parent) { cycleButtons.Clear(); for (int i = 0; i < parent.transform.childCount; i++) { Button button = parent.transform.GetChild(i).GetComponent(typeof(Button)) as Button; if (button != null) { cycleButtons.Add(button); } } cycleIndex = 0; } public void cycleButton(int dir) { if (cycleButtons.Count == 0) { return; } cycleIndex = Mathf.Max(0, cycleIndex + dir); if (cycleIndex >= cycleButtons.Count) { cycleIndex = 0; } cycleButtons[cycleIndex].Select(); } public void clickCurrentCycledButton() { if (cycleButtons.Count == 0) { return; } cycleButtons[cycleIndex].onClick.Invoke(); } public void clickCycleAntiAliasing() { GameDirector.settings.CycleAntiAliasing(); UpdateAntiAliasingText(); } private void UpdateAntiAliasingText() { switch (GameDirector.settings.antiAliasing) { case 0: antiAliasingText.text = "No Antialiasing"; break; case 2: antiAliasingText.text = "2x Antialiasing"; break; case 4: antiAliasingText.text = "4x Antialiasing"; break; case 8: antiAliasingText.text = "8x Antialiasing"; break; default: antiAliasingText.text = "[ERROR] Bad Antialiasing value"; break; } } private void UpdateRespawnShinobuText() { Button button = respawnLoliText.transform.parent.GetComponent<Button>(); if (GameDirector.characters.Count > 1) { respawnLoliText.text = "Respawn Loli"; button.enabled = true; } else { respawnLoliText.text = "You need to spawn Loli in the Mirror first"; button.enabled = false; } } //TODO Make this work with selected Lolis public void clickRespawnShinobu() { // Loli loli = GameDirector.instance.loli; // if( loli != null ){ // loli.active.SetTask( loli.active.idle, null ); // loli.OverrideBodyState( BodyState.STAND ); // loli.OverrideClearAnimationPriority(); // loli.SetTargetAnimation( loli.GetLastReturnableIdleAnimation() ); // Player player = GameDirector.player; // loli.transform.position = player.head.position+player.head.forward*0.8f; // loli.rigidBody.velocity = Vector3.zero; // } } public void clickDiscord() { Application.OpenURL("https://discord.gg/openviva"); } public void clickSaveAndQuitGame() { GameDirector.instance.Save(); #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit(); System.Diagnostics.Process.GetCurrentProcess().Kill(); #endif } public void clickControls() { if (GameDirector.player.controls == Player.ControlType.KEYBOARD) { SetPauseMenu(Menu.KB_CONTROLS); } else { SetPauseMenu(Menu.VR_CONTROLS); } } public void clickRoot() { SetPauseMenu(Menu.ROOT); } public void clickOptions() { SetPauseMenu(Menu.OPTIONS); } public void toggleMuteMusic() { GameDirector.instance.SetMuteMusic(GameDirector.instance.IsMusicMuted()); } public void clickSwitchVRControlScheme() { Player player = GameDirector.player; Text buttonText = GetRightPageUIByMenu(Menu.VR_CONTROLS).transform.Find("Trackpad").GetChild(0).GetComponent(typeof(Text)) as Text; if (GameDirector.settings.vrControls == Player.VRControlType.TRACKPAD) { GameDirector.settings.SetVRControls(Player.VRControlType.TELEPORT); buttonText.text = "Using Teleport"; OrientPauseBookToPlayer(); } else { GameDirector.settings.SetVRControls(Player.VRControlType.TRACKPAD); buttonText.text = "Using Trackpad"; } UpdateVRMovementPrefText(); } public void clickToggleTrackpadPreferences() { GameDirector.settings.ToggleTrackpadMovementUseRight(); UpdateVRMovementPrefText(); } private void UpdateVRMovementPrefText() { Text buttonText = GetRightPageUIByMenu(Menu.VR_CONTROLS).transform.Find("TrackpadPref").GetChild(0).GetComponent(typeof(Text)) as Text; if (GameDirector.settings.trackpadMovementUseRight) { buttonText.text = "Using Right Handed"; } else { buttonText.text = "Using Left Handed"; } } public void clickSwitchControlScheme() { Player player = GameDirector.player; if (player.controls == Player.ControlType.KEYBOARD) { player.SetControls(Player.ControlType.VR); } else { player.SetControls(Player.ControlType.KEYBOARD); } } public void clickToggleQuality() { GameDirector.settings.CycleQualitySetting(); GameDirector.instance.ApplyAllQualitySettings(); UpdateToggleQualityText(); } public void clickToggleClouds() { bool currentCLD = GameDirector.instance.UseClouds(); Text text = GetRightPageUIByMenu(Menu.OPTIONS).transform.Find("Toggle Clouds").GetChild(0).GetComponent(typeof(Text)) as Text; currentCLD = !currentCLD; if (currentCLD) { text.text = "Turn Off Clouds"; } else { text.text = "Turn On Clouds"; } GameDirector.instance.SetCloud(currentCLD); } private void UpdateToggleQualityText() { Text text = GetRightPageUIByMenu(Menu.OPTIONS).transform.Find("Toggle Quality").GetChild(0).GetComponent(typeof(Text)) as Text; string[] names = QualitySettings.names; text.text = names[QualitySettings.GetQualityLevel()] + " Quality"; } public int OnChecklistManifest() { return System.Enum.GetValues(typeof(Player.ObjectiveType)).Length / 10; } void OnChecklistPageUpdate(int page) { //clear old page items for (int i = 3; i < checklistPageScroller.GetPageContent().childCount; i++) { Destroy(checklistPageScroller.GetPageContent().GetChild(i).gameObject); } int checklistIndex = page * 10; for (int i = 0; i < 10; i++) { if (checklistIndex >= System.Enum.GetValues(typeof(Player.ObjectiveType)).Length) { break; } GameObject newEntry = Instantiate(checklistPrefab, new Vector3(0.0f, -i * 32.0f - 15.0f, 0.0f), Quaternion.identity); RectTransform entryRect = newEntry.transform as RectTransform; newEntry.transform.SetParent(checklistPageScroller.GetPageContent(), false); Text textComponent = entryRect.GetChild(0).GetComponent(typeof(Text)) as Text; Player.ObjectiveType type = (Player.ObjectiveType)checklistIndex; textComponent.text = GameDirector.player.GetAchievementDescription(type); Button button = newEntry.GetComponent(typeof(Button)) as Button; button.interactable = GameDirector.player.IsAchievementComplete(type); checklistIndex++; } } public void clickChecklist() { SetPauseMenu(Menu.CHECKLIST); //setup checklist panel checklistPageScroller.FlipPage(0); //refresh current page } public void BETA_increaseDaylight() { GameDirector.settings.ShiftWorldTime(0.3f); } public void clickToggleDisableGrab() { GameDirector.settings.ToggleDisableGrabToggle(); UpdateDisableGrabToggleText(); } private void UpdateDisableGrabToggleText() { Text buttonText = GetRightPageUIByMenu(Menu.VR_CONTROLS).transform.Find("Disable Grab Toggle").GetChild(0).GetComponent(typeof(Text)) as Text; if (GameDirector.settings.disableGrabToggle) { buttonText.text = "Grab Toggle is off"; } else { buttonText.text = "Grab Toggle is on"; } } private void UpdatePressToTurnText() { Text buttonText = GetRightPageUIByMenu(Menu.VR_CONTROLS).transform.Find("Turning requires press").GetChild(0).GetComponent(typeof(Text)) as Text; if (GameDirector.settings.pressToTurn) { buttonText.text = "Using Press to Turn"; } else { buttonText.text = "Using Touch to Turn"; } } public void clickTogglePressToTurn() { GameDirector.settings.TogglePresstoTurn(); UpdatePressToTurnText(); } public void clickCalibrateHands() { SetPauseMenu(Menu.CALIBRATE_HANDS); StartCalibration(); } public void clickMap() { SetPauseMenu(Menu.MAP); } //TODO: add a smooth transition for this public void clickWaypoint(Transform pos){ GameDirector.player.transform.position = pos.position; } private void StartCalibration() { if (calibrationCoroutine != null) { return; } calibrationCoroutine = GameDirector.instance.StartCoroutine(CalibrateHands()); } private void StopCalibration() { if (calibrationCoroutine == null) { return; } GameDirector.instance.StopCoroutine(calibrationCoroutine); calibrationCoroutine = null; } private void SetPlayerAbsoluteVROffsets(Vector3 position, Vector3 euler, bool relativeToRightHand) { Player player = GameDirector.player; if (player == null) { return; } player.rightPlayerHandState.SetAbsoluteVROffsets(position, euler, relativeToRightHand); player.leftPlayerHandState.SetAbsoluteVROffsets(position, euler, relativeToRightHand); } private IEnumerator CalibrateHands() { PlayerHandState targetHoldState = null; GameObject ghost = null; while (true) { if (ghost == null) { if (GameDirector.player.rightPlayerHandState.gripState.isDown) { targetHoldState = GameDirector.player.rightPlayerHandState; } if (GameDirector.player.leftPlayerHandState.gripState.isDown) { targetHoldState = GameDirector.player.leftPlayerHandState; } if (targetHoldState != null) { GameDirector.player.ApplyVRHandsToAnimation(); GameDirector.player.SetFreezeVRHandTransforms(true); SetPlayerAbsoluteVROffsets(Vector3.zero, Vector3.zero, false); Transform absolute = targetHoldState.absoluteHandTransform; ghost = GameObject.Instantiate(calibrateHandGhostPrefab, Vector3.zero, Quaternion.identity); } } else { //calibrate GameDirector.player.ApplyVRHandsToAnimation(); Transform absolute = targetHoldState.absoluteHandTransform; Transform wrist = targetHoldState.fingerAnimator.wrist; ghost.transform.position = absolute.position; ghost.transform.rotation = absolute.rotation; if (targetHoldState.gripState.isUp) { Transform oldParent = wrist.parent; wrist.SetParent(absolute, true); Vector3 posOffset = wrist.localPosition; //safety position check if (posOffset.sqrMagnitude > 0.4f) { posOffset = Vector3.zero; } Vector3 rotOffset = wrist.localEulerAngles; wrist.SetParent(oldParent, true); SetPlayerAbsoluteVROffsets(posOffset, rotOffset, targetHoldState == GameDirector.player.rightHandState); Destroy(ghost); ghost = null; targetHoldState = null; GameDirector.player.SetFreezeVRHandTransforms(false); } } yield return null; } } } }
34.364407
157
0.53732
[ "MIT" ]
Foxify52/OpenViva
Assets/Scripts/PauseMenu.cs
24,332
C#
using System; namespace demo_15.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
17.166667
70
0.660194
[ "MIT" ]
mahendra-shinde/docker-k8s-july-2020
demos/demo-15/Models/ErrorViewModel.cs
206
C#
using OilStationCoreAPI.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace OilStationCoreAPI.IServices { public interface IAspNetRolesServices { ResponseModel<IEnumerable<RolesViewModel>> Roles_Get(); ResponseModel<bool> Roles_Update(UserRolesViewModel model); ResponseModel<IEnumerable<string>> Claim_Get(string RoleId); ResponseModel<bool> Claim_Update(ClaimViewModel model); } }
24.95
68
0.761523
[ "MIT" ]
Asylumrots/OilStation
OilStationCoreAPI/OilStationCoreAPI/IServices/IAspNetRolesServices.cs
501
C#
using System; namespace Bing.Datas.Sql.Builders { /// <summary> /// From子句 /// </summary> public interface IFromClause { /// <summary> /// 克隆 /// </summary> /// <param name="builder">Sql生成器</param> /// <param name="register">实体别名注册器</param> IFromClause Clone(ISqlBuilder builder, IEntityAliasRegister register); /// <summary> /// 设置表名 /// </summary> /// <param name="table">表名</param> /// <param name="alias">别名</param> void From(string table, string alias = null); /// <summary> /// 设置表名 /// </summary> /// <typeparam name="TEntity">实体类型</typeparam> /// <param name="alias">别名</param> /// <param name="schema">架构名</param> void From<TEntity>(string alias = null, string schema = null) where TEntity : class; /// <summary> /// 设置子查询表 /// </summary> /// <param name="builder">Sql生成器</param> /// <param name="alias">表别名</param> void From(ISqlBuilder builder, string alias); /// <summary> /// 设置子查询表 /// </summary> /// <param name="action">子查询操作</param> /// <param name="alias">表别名</param> void From(Action<ISqlBuilder> action, string alias); /// <summary> /// 添加到From子句 /// </summary> /// <param name="sql">Sql语句</param> void AppendSql(string sql); /// <summary> /// 验证 /// </summary> void Validate(); /// <summary> /// 输出Sql /// </summary> string ToSql(); } }
26.079365
92
0.494218
[ "MIT" ]
brucehu123/Bing.NetCore
framework/src/Bing/Bing/Datas/Sql/Builders/IFromClause.cs
1,789
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ITA.WizardsUITest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ITA")] [assembly: AssemblyProduct("ITA.WizardsUITest")] [assembly: AssemblyCopyright("Copyright © ITA 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("acc49f29-67d8-4adb-bc41-ae5df99de70c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.189189
84
0.746638
[ "Apache-2.0" ]
italabs/ITA.Common
SOURCE/ITA.WizardsUITest/Properties/AssemblyInfo.cs
1,416
C#
/****************************************************************************** * Spine Runtimes Software License * Version 2 * * Copyright (c) 2013, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to install, execute and perform the Spine Runtimes * Software (the "Software") solely for internal use. Without the written * permission of Esoteric Software, you may not (a) modify, translate, adapt or * otherwise create derivative works, improvements of the Software or develop * new applications using the Software or (b) remove, delete, alter or obscure * any trademarks or any copyright, trademark, patent or other intellectual * property or proprietary rights notices on or in the Software, including * any copy thereof. Redistributions in binary or source form must include * this license and terms. THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTARE BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System; namespace Spine { abstract public class Attachment { public String Name { get; private set; } public Attachment (String name) { if (name == null) throw new ArgumentNullException("name cannot be null."); Name = name; } override public String ToString () { return Name; } } }
45.511111
79
0.698242
[ "MIT" ]
herman-rogers/Relic
RelicGame/Assets/spine-csharp/src/Attachments/Attachment.cs
2,048
C#
using COLID.SearchService.Services.Implementation; using COLID.SearchService.Services.Interface; using COLID.MessageQueue.Services; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace COLID.SearchService.Services { public static class ServicesModule { /// <summary> /// This will register all the supported functionality by Services module. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> object for registration.</param> /// <param name="configuration">The <see cref="IConfiguration"/> object for registration.</param> public static IServiceCollection AddServicesModule(this IServiceCollection services, IConfiguration configuration) { services.AddTransient<IStatusService, StatusService>(); services.AddSingleton<Implementation.SearchService>(); services.AddSingleton<ISearchService>(x => x.GetRequiredService<Implementation.SearchService>()); services.AddSingleton<DocumentService>(); services.AddSingleton<IDocumentService>(x => x.GetRequiredService<DocumentService>()); services.AddSingleton<IMessageQueueReceiver>(x => x.GetRequiredService<DocumentService>()); services.AddTransient<IIndexService, IndexService>(); return services; } } }
43.75
122
0.712857
[ "BSD-3-Clause" ]
Bayer-Group/COLID-Search-Service
COLID.SearchService.Services/ServicesModule.cs
1,402
C#
// Copyright (c) 2022 TrakHound Inc., All Rights Reserved. // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. namespace MTConnect.Observations.Events.Values { /// <summary> /// A setting or operator selection that changes the behavior of a piece of equipment. /// </summary> public static class ControllerModeOverrideValueDescriptions { /// <summary> /// The indicator of the ControllerModeOverride is in the OFF state and the mode override is inactive. /// </summary> public const string OFF = "The indicator of the ControllerModeOverride is in the OFF state and the mode override is inactive."; /// <summary> /// The indicator of the ControllerModeOverride is in the ON state and the mode override is active. /// </summary> public const string ON = "The indicator of the ControllerModeOverride is in the ON state and the mode override is active."; public static string Get(ControllerModeOverrideValue value) { switch (value) { case ControllerModeOverrideValue.OFF: return OFF; case ControllerModeOverrideValue.ON: return ON; } return null; } } }
36.777778
135
0.654834
[ "Apache-2.0" ]
TrakHound/MTConnect
src/MTConnect.NET-Common/Observations/Events/Values/ControllerModeOverrideValueDescriptions.cs
1,324
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.WindowsAzure.Commands.Sync; using Microsoft.WindowsAzure.Commands.Sync.Upload; namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Model { public class VhdUploaderModel { public static VhdUploadContext Upload(UploadParameters uploadParameters) { Program.SyncOutput = new PSSyncOutputEvents(uploadParameters.Cmdlet); BlobCreatorBase blobCreator; if (uploadParameters.BaseImageUri != null) { blobCreator = new PatchingBlobCreator(uploadParameters.LocalFilePath, uploadParameters.DestinationUri, uploadParameters.BaseImageUri, uploadParameters.BlobObjectFactory, uploadParameters.OverWrite); } else { blobCreator = new BlobCreator(uploadParameters.LocalFilePath, uploadParameters.DestinationUri, uploadParameters.BlobObjectFactory, uploadParameters.OverWrite); } using (var uploadContext = blobCreator.Create()) { var synchronizer = new BlobSynchronizer(uploadContext, uploadParameters.NumberOfUploaderThreads); if (synchronizer.Synchronize()) { return new VhdUploadContext {LocalFilePath = uploadParameters.LocalFilePath, DestinationUri = uploadParameters.DestinationUri.Uri}; } return null; } } } }
47.382979
215
0.627301
[ "MIT" ]
Andrean/azure-powershell
src/ServiceManagement/Compute/Commands.ServiceManagement/Model/VhdUploaderModel.cs
2,183
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using Nwc.XmlRpc; using OpenMetaverse; namespace OpenSim.Framework.Communications.Clients { public class AuthClient { public static string GetNewKey(string authurl, UUID userID, UUID authToken) { //Hashtable keyParams = new Hashtable(); //keyParams["user_id"] = userID; //keyParams["auth_token"] = authKey; List<string> SendParams = new List<string>(); SendParams.Add(userID.ToString()); SendParams.Add(authToken.ToString()); XmlRpcRequest request = new XmlRpcRequest("hg_new_auth_key", SendParams); XmlRpcResponse reply; try { reply = request.Send(authurl, 6000); } catch (Exception e) { System.Console.WriteLine("[HGrid]: Failed to get new key. Reason: " + e.Message); return string.Empty; } if (!reply.IsFault) { string newKey = string.Empty; if (reply.Value != null) newKey = (string)reply.Value; return newKey; } else { System.Console.WriteLine("[HGrid]: XmlRpc request to get auth key failed with message {0}" + reply.FaultString + ", code " + reply.FaultCode); return string.Empty; } } public static bool VerifyKey(string authurl, UUID userID, string authKey) { List<string> SendParams = new List<string>(); SendParams.Add(userID.ToString()); SendParams.Add(authKey); System.Console.WriteLine("[HGrid]: Verifying user key with authority " + authurl); XmlRpcRequest request = new XmlRpcRequest("hg_verify_auth_key", SendParams); XmlRpcResponse reply; try { reply = request.Send(authurl, 10000); } catch (Exception e) { System.Console.WriteLine("[HGrid]: Failed to verify key. Reason: " + e.Message); return false; } if (reply != null) { if (!reply.IsFault) { bool success = false; if (reply.Value != null) success = (bool)reply.Value; return success; } else { System.Console.WriteLine("[HGrid]: XmlRpc request to verify key failed with message {0}" + reply.FaultString + ", code " + reply.FaultCode); return false; } } else { System.Console.WriteLine("[HGrid]: XmlRpc request to verify key returned null reply"); return false; } } public static bool VerifySession(string authurl, UUID userID, UUID sessionID) { Hashtable requestData = new Hashtable(); requestData["avatar_uuid"] = userID.ToString(); requestData["session_id"] = sessionID.ToString(); ArrayList SendParams = new ArrayList(); SendParams.Add(requestData); XmlRpcRequest UserReq = new XmlRpcRequest("check_auth_session", SendParams); XmlRpcResponse UserResp = UserReq.Send(authurl, 3000); Hashtable responseData = (Hashtable)UserResp.Value; if (responseData.ContainsKey("auth_session") && responseData["auth_session"].ToString() == "TRUE") { //System.Console.WriteLine("[Authorization]: userserver reported authorized session for user " + userID); return true; } else { //System.Console.WriteLine("[Authorization]: userserver reported unauthorized session for user " + userID); return false; } } } }
39.783217
160
0.590438
[ "BSD-3-Clause" ]
WhiteCoreSim/WhiteCore-Merger
OpenSim/Framework/Communications/Clients/AuthClient.cs
5,691
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.RecoveryServices.Backup { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// BackupResourceVaultConfigsOperations operations. /// </summary> internal partial class BackupResourceVaultConfigsOperations : IServiceOperations<RecoveryServicesBackupClient>, IBackupResourceVaultConfigsOperations { /// <summary> /// Initializes a new instance of the BackupResourceVaultConfigsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BackupResourceVaultConfigsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Fetches resource vault config. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="NewErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BackupResourceVaultConfigResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2021-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupconfig/vaultconfig").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new NewErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); NewErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<NewErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BackupResourceVaultConfigResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BackupResourceVaultConfigResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates vault security config. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='parameters'> /// resource config request /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="NewErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BackupResourceVaultConfigResource>> UpdateWithHttpMessagesAsync(string vaultName, string resourceGroupName, BackupResourceVaultConfigResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } string apiVersion = "2021-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupconfig/vaultconfig").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new NewErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); NewErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<NewErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BackupResourceVaultConfigResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BackupResourceVaultConfigResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates vault security config. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='parameters'> /// resource config request /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="NewErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BackupResourceVaultConfigResource>> PutWithHttpMessagesAsync(string vaultName, string resourceGroupName, BackupResourceVaultConfigResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } string apiVersion = "2021-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Put", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupconfig/vaultconfig").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new NewErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); NewErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<NewErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BackupResourceVaultConfigResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<BackupResourceVaultConfigResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
46.387443
323
0.574428
[ "MIT" ]
Cardsareus/azure-sdk-for-net
sdk/recoveryservices-backup/Microsoft.Azure.Management.RecoveryServices.Backup/src/Generated/BackupResourceVaultConfigsOperations.cs
30,291
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using MediatR; using OasysNet.Application.Weather.Queries; using OasysNet.Domain.Models; namespace OasysNet.Application.Weather.Handlers { public class GetAllWeatherForecastQueryHandler : IRequestHandler<GetAllWeatherForecastQuery, IEnumerable<WeatherForecast>> { public GetAllWeatherForecastQueryHandler() { } private static readonly string[] _summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; public Task<IEnumerable<WeatherForecast>> Handle(GetAllWeatherForecastQuery request, CancellationToken cancellationToken) { var rng = new Random(); var result = Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = _summaries[rng.Next(_summaries.Length)] }) .ToArray(); return new ValueTask<IEnumerable<WeatherForecast>>(result).AsTask(); } } }
33.513514
129
0.645161
[ "MIT" ]
Dakianth/OasysNet
OasysNet.Application/Weather/Handlers/GetAllWeatherForecastQueryHandler.cs
1,242
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IDEG_DiaTrainer.Messages { /// <summary> /// Signal message for injecting carbohydrates into simulation /// </summary> public class InjectCarbsMessage { public static readonly string Name = "InjectCarbsMessage"; // amount of carbohydrates public double CarbAmount { get; set; } = 0; // when to inject - if null, current simulation time is used public DateTime? When { get; set; } = null; // is this a rescue carbohydrate dosage? public Boolean IsRescue { get; set; } = false; } }
27.538462
69
0.636872
[ "MIT" ]
MartinUbl/IDEG-DiaTrainer
App/IDEG-DiaTrainer/Messages/InjectCarbsMessage.cs
718
C#
using System; using System.ComponentModel.DataAnnotations; using System.Linq; namespace vueAdminAPI.Models { public class Base_metadata_base { [Newtonsoft.Json.JsonIgnore] public int isid { get; set; } [Newtonsoft.Json.JsonProperty(Order = 1)] //[Required(ErrorMessage = "主键不能为空")] public string rowID { get; set; } } }
22.058824
49
0.653333
[ "MIT" ]
GarsonZhang/GZAdmin_API
GZAdminAPI/Models/Base_metadata_base.cs
389
C#
//************************************************************************************************ // Copyright © 2021 Steven M Cohn. All rights reserved. //************************************************************************************************ namespace River.OneMoreAddIn.Commands { using OneMoreAddIn.Models; using System; using System.Drawing; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; using Resx = River.OneMoreAddIn.Properties.Resources; internal class AnalyzeCommand : Command { private const string HeaderShading = "#DEEBF6"; private const string Header2Shading = "#F2F2F2"; private const string HeaderCss = "font-family:'Segoe UI Light';font-size:10.0pt"; private const string LineCss = "font-family:'Courier New';font-size:10.0pt"; private const string Cloud = "<span style='font-family:\"Segoe UI Emoji\"'>\u2601</span>"; private const string RecycleBin = "OneNote_RecycleBin"; private bool showNotebookSummary; private bool showSectionSummary; private AnalysisDetail pageDetail; private bool shownPageSummary; private int thumbnailSize; private OneNote one; private XNamespace ns; private string backupPath; private string defaultPath; private string divider; private int heading1Index; private int heading2Index; private UI.ProgressDialog progress; public AnalyzeCommand() { // prevent replay IsCancelled = true; } public override async Task Execute(params object[] args) { using (one = new OneNote()) { (backupPath, defaultPath, _) = one.GetFolders(); if (!Directory.Exists(backupPath)) { UIHelper.ShowError(owner, Resx.AnalyzeCommand_NoBackups); return; } using (var dialog = new AnalyzeDialog()) { if (dialog.ShowDialog(owner) != DialogResult.OK) { return; } showNotebookSummary = dialog.IncludeNotebookSummary; showSectionSummary = dialog.IncludeSectionSummary; pageDetail = dialog.Detail; thumbnailSize = dialog.ThumbnailSize; } one.CreatePage(one.CurrentSectionId, out var pageId); var page = one.GetPage(pageId); page.Title = Resx.AnalyzeCommand_Title; page.SetMeta(Page.AnalysisMetaName, "true"); ns = page.Namespace; heading1Index = page.GetQuickStyle(Styles.StandardStyles.Heading1).Index; heading2Index = page.GetQuickStyle(Styles.StandardStyles.Heading2).Index; using (progress = new UI.ProgressDialog()) { progress.SetMaximum(5); progress.Show(owner); var container = page.EnsureContentContainer(); var notebooks = one.GetNotebooks(); var prev = false; if (showNotebookSummary) { ReportNotebooks(container, notebooks); ReportOrphans(container, notebooks); ReportCache(container); prev = true; } if (showSectionSummary) { if (prev) { WriteHorizontalLine(page, container); } ReportSections(container, notebooks); prev = true; } if (pageDetail == AnalysisDetail.Current) { if (prev) { WriteHorizontalLine(page, container); } ReportPages(container, one.GetSection(), null, pageId); } else if (pageDetail == AnalysisDetail.All) { if (prev) { WriteHorizontalLine(page, container); } ReportAllPages(container, one.GetNotebook(), null, pageId); } progress.SetMessage("Updating report..."); await one.Update(page); } await one.NavigateTo(pageId); } } private void ReportNotebooks(XElement container, XElement notebooks) { progress.SetMessage("Notebooks..."); progress.Increment(); var backupUri = new Uri(backupPath).AbsoluteUri; var folderUri = new Uri(defaultPath).AbsoluteUri; container.Add( new Paragraph(ns, "Summary").SetQuickStyle(heading1Index), new Paragraph(ns, Resx.AnalyzeCommand_SummarySummary), new Paragraph(ns, new ContentList(ns, new Bullet(ns, $"<span style='font-style:italic'>Default location</span>: <a href=\"{folderUri}\">{defaultPath}</a>"), new Bullet(ns, $"<span style='font-style:italic'>Backup location</span>: <a href=\"{backupUri}\">{backupPath}</a>") )), new Paragraph(ns, string.Empty) ); var table = new Table(ns, 1, 4) { HasHeaderRow = true, BordersVisible = true }; table.SetColumnWidth(0, 120); table.SetColumnWidth(1, 70); table.SetColumnWidth(2, 70); table.SetColumnWidth(3, 70); var row = table[0]; row.SetShading(HeaderShading); row[0].SetContent(new Paragraph(ns, "Notebook").SetStyle(HeaderCss)); row[1].SetContent(new Paragraph(ns, "Backups").SetStyle(HeaderCss).SetAlignment("center")); row[2].SetContent(new Paragraph(ns, "RecycleBin").SetStyle(HeaderCss).SetAlignment("center")); row[3].SetContent(new Paragraph(ns, "Total").SetStyle(HeaderCss).SetAlignment("center")); long total = 0; foreach (var notebook in notebooks.Elements(ns + "Notebook")) { row = table.AddRow(); var name = notebook.Attribute("name").Value; var remote = notebook.Attribute("path").Value.Contains("https://"); row[0].SetContent(remote ? $"{name} {Cloud}" : name); var path = Path.Combine(remote ? backupPath : defaultPath, name); if (Directory.Exists(path)) { var dir = new DirectoryInfo(path); var size = dir.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(f => f.Length); var repath = Path.Combine(path, RecycleBin); if (Directory.Exists(repath)) { dir = new DirectoryInfo(repath); var relength = dir.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(f => f.Length); row[1].SetContent(new Paragraph(ns, (size - relength).ToBytes(1)).SetAlignment("right")); row[2].SetContent(new Paragraph(ns, relength.ToBytes(1)).SetAlignment("right")); row[3].SetContent(new Paragraph(ns, size.ToBytes(1)).SetAlignment("right")); } total += size; } } if (total > 0) { row = table.AddRow(); row[3].SetContent(new Paragraph(ns, total.ToBytes(1)).SetAlignment("right")); } container.Add( new Paragraph(ns, table.Root), new Paragraph(ns, string.Empty) ); } private void ReportOrphans(XElement container, XElement notebooks) { // orphaned backup folders... progress.SetMessage("Orphans..."); progress.Increment(); var knowns = notebooks.Elements(ns + "Notebook") .Select(e => e.Attribute("name").Value) .ToList(); knowns.Add(Resx.AnalyzeCommand_OpenSections); knowns.Add(Resx.AnalyzeCommand_QuickNotes); var orphans = Directory.GetDirectories(backupPath) .Select(d => Path.GetFileNameWithoutExtension(d)) .Except(knowns); container.Add( new Paragraph(ns, "Orphans").SetQuickStyle(heading2Index), new Paragraph(ns, Resx.AnalyzeCommand_OrphanSummary) ); if (!orphans.Any()) { container.Add( new Paragraph(ns, string.Empty), new Paragraph(ns, Resx.AnalyzeCommand_NoOrphans), new Paragraph(ns, string.Empty) ); return; } var list = new ContentList(ns); container.Add( new Paragraph(ns, new XElement(ns + "T", new XCData(string.Empty)), list) ); foreach (var orphan in orphans) { var dir = new DirectoryInfo(Path.Combine(backupPath, orphan)); var size = dir.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(f => f.Length); list.Add(new Bullet(ns, $"{orphan} ({size.ToBytes(1)})")); } container.Add(new Paragraph(ns, string.Empty)); } private void ReportCache(XElement container) { // internal cache folder... progress.SetMessage("Cache..."); progress.Increment(); container.Add( new Paragraph(ns, "Cache").SetQuickStyle(heading2Index), new Paragraph(ns, Resx.AnalyzeCommand_CacheSummary) ); var cachePath = Path.Combine(Path.GetDirectoryName(backupPath), "cache"); if (!Directory.Exists(cachePath)) { container.Add( new Paragraph(ns, string.Empty), new Paragraph(ns, Resx.AnalyzeCommand_NoCache), new Paragraph(ns, string.Empty) ); return; } var dir = new DirectoryInfo(cachePath); var total = dir.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(f => f.Length); var cacheUri = new Uri(cachePath).AbsoluteUri; container.Add( new Paragraph(ns, new ContentList(ns, new Bullet(ns, $"<span style='font-style:italic'>Cache size</span>: {total.ToBytes(1)}"), new Bullet(ns, $"<span style='font-style:italic'>Cache location</span>: <a href=\"{cacheUri}\">{cachePath}</a>") ) ), new Paragraph(ns, string.Empty) ); } private void WriteHorizontalLine(Page page, XElement container) { if (divider == null) { divider = string.Empty.PadRight(80, '═'); page.EnsurePageWidth(divider, "Courier new", 11f, one.WindowHandle); } container.Add(new Paragraph(ns, new XElement(ns + "T", new XAttribute("style", LineCss), new XCData($"{divider}<br/>") ))); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - private void ReportSections(XElement container, XElement notebooks) { progress.SetMessage("Sections..."); progress.Increment(); container.Add( new Paragraph(ns, "Sections").SetQuickStyle(heading1Index), new Paragraph(ns, Resx.AnalyzeCommand_SectionSummary), new Paragraph(ns, string.Empty) ); // discover hierarchy bit by bit to avoid loading huge amounts of memory at once foreach (var book in notebooks.Elements(ns + "Notebook")) { container.Add( new Paragraph(ns, $"{book.Attribute("name").Value} Notebook") .SetQuickStyle(heading2Index)); var table = new Table(ns, 1, 4) { HasHeaderRow = true, BordersVisible = true }; table.SetColumnWidth(0, 200); table.SetColumnWidth(1, 70); table.SetColumnWidth(2, 70); table.SetColumnWidth(3, 70); var row = table[0]; row.SetShading(HeaderShading); row[0].SetContent(new Paragraph(ns, "Section").SetStyle(HeaderCss)); row[1].SetContent(new Paragraph(ns, "Size on Disk").SetStyle(HeaderCss).SetAlignment("center")); row[2].SetContent(new Paragraph(ns, "# of Copies").SetStyle(HeaderCss).SetAlignment("center")); row[3].SetContent(new Paragraph(ns, "Total Size").SetStyle(HeaderCss).SetAlignment("center")); var notebook = one.GetNotebook(book.Attribute("ID").Value); var total = ReportSections(table, notebook, null); row = table.AddRow(); row[3].SetContent(new Paragraph(ns, total.ToBytes(1)).SetAlignment("right")); container.Add( new Paragraph(ns, table.Root), new Paragraph(ns, string.Empty) ); } } private long ReportSections(Table table, XElement folder, string folderPath) { long total = 0; var folderName = folder.Attribute("name").Value; var sections = folder.Elements(ns + "Section") .Where(e => e.Attribute("isInRecycleBin") == null && e.Attribute("locked") == null); foreach (var section in sections) { var name = section.Attribute("name").Value; progress.SetMessage($"Section {name}"); progress.Increment(); var title = folderPath == null ? name : Path.Combine(folderPath, name); var subp = folderPath == null ? folderName : Path.Combine(folderPath, folderName); var remote = section.Attribute("path").Value.Contains("https://"); var path = Path.Combine(remote ? backupPath : defaultPath, subp); var row = table.AddRow(); if (Directory.Exists(path)) { row[0].SetContent(new Paragraph(ns, title)); var filter = remote ? $"{name}.one (On *).one" : $"{name}.one"; var files = Directory.EnumerateFiles(path, filter).ToList(); if (files.Count > 0) { long first = 0; long all = 0; foreach (var file in files) { if (File.Exists(file)) { var size = new FileInfo(file).Length; if (first == 0) first = size; all += size; } } if (all > 0) { row[1].SetContent(new Paragraph(ns, first.ToBytes(1)).SetAlignment("right")); if (remote) { row[2].SetContent(new Paragraph(ns, files.Count.ToString()).SetAlignment("right")); } row[3].SetContent(new Paragraph(ns, all.ToBytes(1)).SetAlignment("right")); total += all; } } else { logger.WriteLine($"empty section {name} in {path}"); } } else { row[0].SetContent(new Paragraph(ns, $"{title} <span style='font-style:italic'>(backup not found)</span>")); } } // section groups... var groups = folder.Elements(ns + "SectionGroup") .Where(e => e.Attribute("isRecycleBin") == null); foreach (var group in groups) { var path = folderPath == null ? folderName : Path.Combine(folderPath, folderName); total += ReportSections(table, group, path); } return total; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - private void ReportAllPages(XElement container, XElement folder, string folderPath, string skipId) { var sections = folder.Elements(ns + "Section") .Where(e => e.Attribute("isInRecycleBin") == null && e.Attribute("locked") == null); foreach (var section in sections) { ReportPages(container, one.GetSection(section.Attribute("ID").Value), folderPath, skipId); } var groups = folder.Elements(ns + "SectionGroup") .Where(e => e.Attribute("isRecycleBin") == null); foreach (var group in groups) { var name = group.Attribute("name").Value; folderPath = folderPath == null ? name : Path.Combine(folderPath, name); ReportAllPages(container, group, folderPath, skipId); } } private void ReportPages(XElement container, XElement section, string folderPath, string skipId) { var name = section.Attribute("name").Value; var title = folderPath == null ? name : Path.Combine(folderPath, name); progress.SetMessage($"{title} pages..."); container.Add(new Paragraph(ns, $"{title} Section Pages").SetQuickStyle(heading1Index)); if (!shownPageSummary) { container.Add(new Paragraph(ns, Resx.AnalyzeCommand_PageSummary)); shownPageSummary = true; } container.Add(new Paragraph(ns, string.Empty)); var table = new Table(ns, 0, 1) { HasHeaderRow = true, BordersVisible = true }; table.SetColumnWidth(0, 450); var pages = section.Elements(ns + "Page") .Where(e => e.Attribute("ID").Value != skipId); progress.SetMaximum(pages.Count()); foreach (var page in pages) { ReportPage(table, page.Attribute("ID").Value); } container.Add( new Paragraph(ns, table.Root), new Paragraph(ns, string.Empty) ); } private void ReportPage(Table table, string pageId) { var page = one.GetPage(pageId, OneNote.PageDetail.All); if (page.GetMetaContent(Page.AnalysisMetaName) == "true") { // skip a previously generated analysis report return; } progress.SetMessage(page.Title); progress.Increment(); var xml = page.Root.ToString(SaveOptions.DisableFormatting); long length = xml.Length; var row = table.AddRow(); row.SetShading(HeaderShading); var link = one.GetHyperlink(pageId, string.Empty); row[0].SetContent(new Paragraph(ns, $"<a href='{link}'>{page.Title}</a> ({length.ToBytes(1)})").SetStyle(HeaderCss)); var images = page.Root.Descendants(ns + "Image") .Where(e => e.Attribute("xpsFileIndex") == null && e.Attribute("sourceDocument") == null) .ToList(); var files = page.Root.Descendants(ns + "InsertedFile") .ToList(); if (images.Count == 0 && files.Count == 0) { return; } var detail = new Table(ns, 1, 3) { BordersVisible = true, HasHeaderRow = true }; detail.SetColumnWidth(0, 250); detail.SetColumnWidth(1, 70); detail.SetColumnWidth(2, 70); row = detail[0]; row.SetShading(Header2Shading); row[0].SetContent(new Paragraph(ns, "Image/File").SetStyle(HeaderCss)); row[1].SetContent(new Paragraph(ns, "XML Size").SetStyle(HeaderCss).SetAlignment("center")); row[2].SetContent(new Paragraph(ns, "Native Size").SetStyle(HeaderCss).SetAlignment("center")); foreach (var image in images) { ReportImage(detail, image); } foreach (var file in files) { row = detail.AddRow(); var name = file.Attribute("preferredName").Value; var path = file.Attribute("pathSource")?.Value; var original = path != null; if (!original) { path = file.Attribute("pathCache")?.Value; } if (path == null) { row[0].SetContent(name); } else { var uri = new Uri(path).AbsoluteUri; var exists = File.Exists(path); if (original && exists) { row[0].SetContent( $"<a href='{uri}'>{name}</a>"); } else { row[0].SetContent( $"<a href='{uri}'>{name}</a> <span style='font-style:italic'>(orphaned)</span>"); } if (exists) { var size = new FileInfo(path).Length; row[2].SetContent(new Paragraph(ns, size.ToBytes(1)).SetAlignment("right")); } } var key = "xpsFileIndex"; var index = file.Element(ns + "Printout")?.Attribute(key)?.Value; if (string.IsNullOrEmpty(index)) { key = "sourceDocument"; index = file.Element(ns + "Previews")?.Attribute(key).Value; } if (!string.IsNullOrEmpty(index)) { var printouts = page.Root.Descendants(ns + "Image") .Where(e => e.Attribute(key)?.Value == index); foreach (var printout in printouts) { ReportImage(detail, printout, true); } } } row = table.AddRow(); row[0].SetContent(new XElement(ns + "OEChildren", new XElement(ns + "OE", new XElement(ns + "T", new XCData(string.Empty)), new XElement(ns + "OEChildren", new XElement(ns + "OE", detail.Root) )), new Paragraph(ns, string.Empty) )); } private void ReportImage(Table detail, XElement image, bool printout = false) { var row = detail.AddRow(); var data = image.Element(ns + "Data").Value; var bytes = Convert.FromBase64String(image.Element(ns + "Data").Value); using (var stream = new MemoryStream(bytes, 0, bytes.Length)) { using (var raw = Image.FromStream(stream)) { XElement img; if (raw.Width > thumbnailSize || raw.Height > thumbnailSize) { // maintain aspect ratio of image thumbnails var zoom = raw.Width - thumbnailSize > raw.Height - thumbnailSize ? ((float)thumbnailSize) / raw.Width : ((float)thumbnailSize) / raw.Height; // callback is a required argument but is never used var callback = new Image.GetThumbnailImageAbort(() => { return false; }); using (var thumbnail = raw.GetThumbnailImage( (int)(raw.Width * zoom), (int)(raw.Height * zoom), callback, IntPtr.Zero)) { img = MakeImage(thumbnail); } } else { img = MakeImage(raw); } if (printout) { var print = new Table(ns, 1, 2); print[0][0].SetContent("Printout:"); print[0][1].SetContent(img); row[0].SetContent(print); } else { row[0].SetContent(img); } } } row[1].SetContent(new Paragraph(ns, data.Length.ToBytes(1)).SetAlignment("right")); row[2].SetContent(new Paragraph(ns, bytes.Length.ToBytes(1)).SetAlignment("right")); } private XElement MakeImage(Image image) { var bytes = (byte[])new ImageConverter().ConvertTo(image, typeof(byte[])); return new XElement(ns + "Image", new XAttribute("format", "png"), new XElement(ns + "Size", new XAttribute("width", $"{image.Width}.0"), new XAttribute("height", $"{image.Height}.0")), new XElement(ns + "Data", Convert.ToBase64String(bytes)) ); } /* <one:Image format="png"> <one:Size width="140.0" height="38.0" /> <one:Data>iVBORw0KGgoAAAANSUhEUgAAAIwAAAAmCAYAAAAWR3O2AAAAAXNSR0IArs4c6QAAAARnQU1BAACx <one:InsertedFile pathCache="C:\Users\steve\AppData\Local\Temp\{569D95EA-50FE-4C04-BBD9-351BB06B49B0}.bin" pathSource="C:\Users\steve\Downloads\Report_Cards_FHS.pdf" preferredName="Report_Cards_FHS.pdf" lastModifiedTime="2021-08-17T19:28:44.000Z" objectID="{7CA7CD12-44EE-4197-9E96-283E7CD967C9}{109}{B0}"> <one:Position x="36.0" y="237.9003143310547" z="2" /> <one:Size width="338.2500305175781" height="64.80000305175781" /> <one:Printout xpsFileIndex="0" /> </one:InsertedFile> <one:Image format="png" xpsFileIndex="0" originalPageNumber="0" isPrintOut="true" lastModifiedTime="2021-08-17T19:28:45.000Z" objectID="{7CA7CD12-44EE-4197-9E96-283E7CD967C9}{116}{B0}"> <one:Position x="36.0" y="313.5003051757812" z="0" /> <one:Size width="613.4400024414062" height="793.4400024414062" isSetByUser="true" /> <one:Data>iVBORw0KGgoAAAANSUhEUgAAAzAAAAQgCAIAAAC2Gy5ZAAAAAXNSR0IArs4c6QAAAARnQU1BAACx <one:InsertedFile selected="all" pathCache="C:\Users\steve\AppData\Local\Microsoft\OneNote\16.0\cache\00000065.bin" pathSource="C:\Users\cohns\SkyDrive\Personal\Life\Color Assignments.xlsx" preferredName="Color Assignments.xlsx"> <one:Previews sourceDocument="{B35B7C0A-A50F-40FF-9052-EDE826112A46}" displayAll="true"> <one:Preview page="Sheet1" /> </one:Previews> </one:InsertedFile> </one:OE> <one:OE alignment="left"> <one:Image format="emf" sourceDocument="{B35B7C0A-A50F-40FF-9052-EDE826112A46}"> <one:Size width="613.5" height="481.5" isSetByUser="true" /> */ } }
28.630607
308
0.638052
[ "MIT" ]
stevencohn/OneMore
OneMore/Commands/Tools/AnalyzeCommand.cs
21,707
C#
/// <summary> /// Creates a deck of 52 cards and places them on the screen in random /// positions. /// </summary> using System.Collections; using System.Collections.Generic; using UnityEngine; public class Deck : MonoBehaviour { #region Variables public List<Card> myDeck = new List<Card>(); private Rules myRules; #endregion // Start is called before the first frame update void Start() { // Make each card BuildDeck(); // Throw the deck on screen InstantiateDeck(); } /// <summary> /// Builds a deck with random rules at runtime /// </summary> void BuildDeck() { // Get instance of our Rules script myRules = GetComponent<Rules>(); // For each value in a deck of cards for (int i = 2; i <= 14; i++) { // Grab one of the rules for that value string myRule = myRules.GetRule(i); // Cards that are not face cards if (i <= 10) { myDeck.Add(new Card("H", i.ToString(), myRule)); myDeck.Add(new Card("D", i.ToString(), myRule)); myDeck.Add(new Card("S", i.ToString(), myRule)); myDeck.Add(new Card("C", i.ToString(), myRule)); } // Jacks else if (i == 11) { myDeck.Add(new Card("H", "J", myRule)); myDeck.Add(new Card("D", "J", myRule)); myDeck.Add(new Card("S", "J", myRule)); myDeck.Add(new Card("C", "J", myRule)); } // Queens else if (i == 12) { myDeck.Add(new Card("H", "Q", myRule)); myDeck.Add(new Card("D", "Q", myRule)); myDeck.Add(new Card("S", "Q", myRule)); myDeck.Add(new Card("C", "Q", myRule)); } // Kings else if (i == 13) { myDeck.Add(new Card("H", "K", myRule)); myDeck.Add(new Card("D", "K", myRule)); myDeck.Add(new Card("S", "K", myRule)); myDeck.Add(new Card("C", "K", myRule)); } // Aces else { myDeck.Add(new Card("H", "A", myRule)); myDeck.Add(new Card("D", "A", myRule)); myDeck.Add(new Card("S", "A", myRule)); myDeck.Add(new Card("C", "A", myRule)); } } } void InstantiateDeck() { // Go through each card foreach (Card card in myDeck) { /* // Get random Y-pos within the boundaries of the main camera float spawnY = Random.Range( Camera.main.ScreenToWorldPoint( new Vector2(0, 0)).y, Camera.main.ScreenToWorldPoint( new Vector2(0, Screen.height)).y ); // Get random X-pos within the boundaries of the main camera float spawnX = Random.Range( Camera.main.ScreenToWorldPoint( new Vector2(0, 0)).x, Camera.main.ScreenToWorldPoint( new Vector2(Screen.width, 0)).x ); // Create a vector two based on the above X and Y values Vector2 spawnPosition = new Vector2(spawnX, spawnY); */ // Instantiate the card on screen at our random position GameObject newCard = (GameObject)Instantiate( Resources.Load( "Cards/Card" ), new Vector2(0,0), Quaternion.Euler(0, 0, Random.Range(0, 360)) ); CardInteraction newCardValues = newCard.GetComponentInChildren<CardInteraction>(); newCardValues.mySuit = card.mySuit; newCardValues.myRule = card.myRule; newCardValues.myValue = card.myValue; } } }
31.890625
94
0.471093
[ "MIT" ]
crav12345/Quack-Studios
Queens Cup/Assets/Scripts/Deck.cs
4,084
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using StarkPlatform.CodeAnalysis; using StarkPlatform.CodeAnalysis.Editor.Shared.Utilities; using StarkPlatform.CodeAnalysis.Host; using StarkPlatform.VisualStudio.LanguageServices.Implementation.Interop; using StarkPlatform.VisualStudio.LanguageServices.Implementation.Utilities; namespace StarkPlatform.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Cache FileCodeModel instances for a given project (we are using WeakReference for now, /// so that we can more or less match the semantics of the former native implementation, which /// offered reference equality until all instances were collected by the GC) /// </summary> internal sealed partial class CodeModelProjectCache { private readonly CodeModelState _state; private readonly ProjectId _projectId; private readonly ICodeModelInstanceFactory _codeModelInstanceFactory; private readonly Dictionary<string, CacheEntry> _cache = new Dictionary<string, CacheEntry>(StringComparer.OrdinalIgnoreCase); private readonly object _cacheGate = new object(); private EnvDTE.CodeModel _rootCodeModel; private bool _zombied; internal CodeModelProjectCache(IThreadingContext threadingContext, ProjectId projectId, ICodeModelInstanceFactory codeModelInstanceFactory, ProjectCodeModelFactory projectFactory, IServiceProvider serviceProvider, HostLanguageServices languageServices, VisualStudioWorkspace workspace) { _state = new CodeModelState(threadingContext, serviceProvider, languageServices, workspace, projectFactory); _projectId = projectId; _codeModelInstanceFactory = codeModelInstanceFactory; } private bool IsZombied { get { return _zombied; } } /// <summary> /// Look for an existing instance of FileCodeModel in our cache. /// Return null if there is no active FCM for "fileName". /// </summary> private CacheEntry? GetCacheEntry(string fileName) { lock (_cacheGate) { if (_cache.TryGetValue(fileName, out var cacheEntry)) { return cacheEntry; } } return null; } public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath) { // First try { var cacheEntry = GetCacheEntry(filePath); if (cacheEntry != null) { var comHandle = cacheEntry.Value.ComHandle; if (comHandle != null) { return comHandle.Value; } } } // This ultimately ends up calling GetOrCreateFileCodeModel(fileName, parent) with the correct "parent" object // through the project system. var newFileCodeModel = (EnvDTE80.FileCodeModel2)_codeModelInstanceFactory.TryCreateFileCodeModelThroughProjectSystem(filePath); return new ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(newFileCodeModel); } public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? GetComHandleForFileCodeModel(string filePath) { var cacheEntry = GetCacheEntry(filePath); return cacheEntry != null ? cacheEntry.Value.ComHandle : null; } public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> GetOrCreateFileCodeModel(string filePath, object parent) { // First try { var cacheEntry = GetCacheEntry(filePath); if (cacheEntry != null) { var comHandle = cacheEntry.Value.ComHandle; if (comHandle != null) { return comHandle.Value; } } } // Check that we know about this file! var documentId = _state.Workspace.CurrentSolution.GetDocumentIdsWithFilePath(filePath).Where(id => id.ProjectId == _projectId).FirstOrDefault(); if (documentId == null) { // Matches behavior of native (C#) implementation throw Exceptions.ThrowENotImpl(); } // Create object (outside of lock) var newFileCodeModel = FileCodeModel.Create(_state, parent, documentId, new TextManagerAdapter()); var newCacheEntry = new CacheEntry(newFileCodeModel); // Second try (object might have been added by another thread at this point!) lock (_cacheGate) { var cacheEntry = GetCacheEntry(filePath); if (cacheEntry != null) { var comHandle = cacheEntry.Value.ComHandle; if (comHandle != null) { return comHandle.Value; } } // Note: Using the indexer here (instead of "Add") is relevant since the old // WeakReference entry is likely still in the cache (with a Null target, of course) _cache[filePath] = newCacheEntry; return newFileCodeModel; } } public EnvDTE.CodeModel GetOrCreateRootCodeModel(EnvDTE.Project parent) { if (this.IsZombied) { Debug.Fail("Cannot access root code model after code model was shutdown!"); throw Exceptions.ThrowEUnexpected(); } if (_rootCodeModel == null) { _rootCodeModel = RootCodeModel.Create(_state, parent, _projectId); } return _rootCodeModel; } public IEnumerable<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>> GetFileCodeModelInstances() { var result = new List<ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>>(); lock (_cacheGate) { foreach (var cacheEntry in _cache.Values) { var comHandle = cacheEntry.ComHandle; if (comHandle != null) { result.Add(comHandle.Value); } } } return result; } public void OnProjectClosed() { var instances = GetFileCodeModelInstances(); lock (_cacheGate) { _cache.Clear(); } foreach (var instance in instances) { instance.Object.Shutdown(); } _zombied = false; } public void OnSourceFileRemoved(string fileName) { ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandle = null; lock (_cacheGate) { if (_cache.TryGetValue(fileName, out var cacheEntry)) { comHandle = cacheEntry.ComHandle; _cache.Remove(fileName); } } if (comHandle != null) { comHandle.Value.Object.Shutdown(); } } public void OnSourceFileRenaming(string oldFileName, string newFileName) { ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandleToRename = null; ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? comHandleToShutDown = null; lock (_cacheGate) { if (_cache.TryGetValue(oldFileName, out var cacheEntry)) { comHandleToRename = cacheEntry.ComHandle; _cache.Remove(oldFileName); if (comHandleToRename != null) { // We might already have a code model for this new filename. This can happen if // we were to rename Goo.cs to Goocs, which will call this method, and then rename // it back, which does not call this method. This results in both Goo.cs and Goocs // being in the cache. We could fix that "correctly", but the zombied Goocs code model // is pretty broken, so there's no point in trying to reuse it. if (_cache.TryGetValue(newFileName, out cacheEntry)) { comHandleToShutDown = cacheEntry.ComHandle; } _cache.Add(newFileName, cacheEntry); } } } comHandleToShutDown?.Object.Shutdown(); comHandleToRename?.Object.OnRename(newFileName); } } }
37.685714
293
0.567746
[ "Apache-2.0" ]
stark-lang/stark-roslyn
src/VisualStudio/Core/Impl/CodeModel/CodeModelProjectCache.cs
9,235
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using NUnit.Framework; using QuantConnect.Brokerages.Backtesting; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine; using QuantConnect.Lean.Engine.Alpha; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Lean.Engine.RealTime; using QuantConnect.Lean.Engine.Results; using QuantConnect.Lean.Engine.Server; using QuantConnect.Lean.Engine.Setup; using QuantConnect.Lean.Engine.TransactionHandlers; using QuantConnect.Orders; using QuantConnect.Packets; using QuantConnect.Scheduling; using QuantConnect.Securities; using QuantConnect.Statistics; using Log = QuantConnect.Logging.Log; namespace QuantConnect.Tests.Engine { [TestFixture, Category("TravisExclude")] public class AlgorithmManagerTests { [Test] public void TestAlgorithmManagerSpeed() { var algorithmManager = new AlgorithmManager(false); var algorithm = PerformanceBenchmarkAlgorithms.SingleSecurity_Second; var job = new BacktestNodePacket(1, 2, "3", null, 9m, $"{nameof(AlgorithmManagerTests)}.{nameof(TestAlgorithmManagerSpeed)}"); var feed = new MockDataFeed(); var marketHoursDatabase = MarketHoursDatabase.FromDataFolder(); var symbolPropertiesDataBase = SymbolPropertiesDatabase.FromDataFolder(); var dataManager = new DataManager(feed, new UniverseSelection( algorithm, new SecurityService(algorithm.Portfolio.CashBook, marketHoursDatabase, symbolPropertiesDataBase, algorithm)), algorithm, algorithm.TimeKeeper, marketHoursDatabase, false); algorithm.SubscriptionManager.SetDataManager(dataManager); var transactions = new BacktestingTransactionHandler(); var results = new BacktestingResultHandler(); var realtime = new BacktestingRealTimeHandler(); var leanManager = new NullLeanManager(); var alphas = new NullAlphaHandler(); var token = new CancellationToken(); var nullSynchronizer = new NullSynchronizer(algorithm); algorithm.Initialize(); algorithm.PostInitialize(); results.Initialize(job, new QuantConnect.Messaging.Messaging(), new Api.Api(), new BacktestingSetupHandler(), transactions); results.SetAlgorithm(algorithm); transactions.Initialize(algorithm, new BacktestingBrokerage(algorithm), results); feed.Initialize(algorithm, job, results, null, null, null, dataManager, null); Log.Trace("Starting algorithm manager loop to process " + nullSynchronizer.Count + " time slices"); var sw = Stopwatch.StartNew(); algorithmManager.Run(job, algorithm, nullSynchronizer, transactions, results, realtime, leanManager, alphas, token); sw.Stop(); var thousands = nullSynchronizer.Count / 1000d; var seconds = sw.Elapsed.TotalSeconds; Log.Trace("COUNT: " + nullSynchronizer.Count + " KPS: " + thousands/seconds); } public class NullAlphaHandler : IAlphaHandler { public bool IsActive { get; } public AlphaRuntimeStatistics RuntimeStatistics { get; } public void Initialize(AlgorithmNodePacket job, IAlgorithm algorithm, IMessagingHandler messagingHandler, IApi api) { } public void OnAfterAlgorithmInitialized(IAlgorithm algorithm) { } public void ProcessSynchronousEvents() { } public void Run() { } public void Exit() { } } public class NullLeanManager : ILeanManager { public void Dispose() { } public void Initialize(LeanEngineSystemHandlers systemHandlers, LeanEngineAlgorithmHandlers algorithmHandlers, AlgorithmNodePacket job, AlgorithmManager algorithmManager) { } public void SetAlgorithm(IAlgorithm algorithm) { } public void Update() { } public void OnAlgorithmStart() { } public void OnAlgorithmEnd() { } } class NullResultHandler : IResultHandler { public ConcurrentQueue<Packet> Messages { get; set; } public ConcurrentDictionary<string, Chart> Charts { get; set; } public TimeSpan ResamplePeriod { get; } public TimeSpan NotificationPeriod { get; } public bool IsActive { get; } public void Initialize(AlgorithmNodePacket job, IMessagingHandler messagingHandler, IApi api, ISetupHandler setupHandler, ITransactionHandler transactionHandler) { } public void Run() { } public void DebugMessage(string message) { } public void SystemDebugMessage(string message) { } public void SecurityType(List<SecurityType> types) { } public void LogMessage(string message) { } public void ErrorMessage(string error, string stacktrace = "") { } public void RuntimeError(string message, string stacktrace = "") { } public void Sample(string chartName, string seriesName, int seriesIndex, SeriesType seriesType, DateTime time, decimal value, string unit = "$") { } public void SampleEquity(DateTime time, decimal value) { } public void SamplePerformance(DateTime time, decimal value) { } public void SampleBenchmark(DateTime time, decimal value) { } public void SampleAssetPrices(Symbol symbol, DateTime time, decimal value) { } public void SampleRange(List<Chart> samples) { } public void SetAlgorithm(IAlgorithm algorithm) { } public void SetAlphaRuntimeStatistics(AlphaRuntimeStatistics statistics) { } public void StoreResult(Packet packet, bool async = false) { } public void SendFinalResult(AlgorithmNodePacket job, Dictionary<int, Order> orders, Dictionary<DateTime, decimal> profitLoss, Dictionary<string, Holding> holdings, CashBook cashbook, StatisticsResults statisticsResults, Dictionary<string, string> banner) { } public void SendStatusUpdate(AlgorithmStatus status, string message = "") { } public void SetChartSubscription(string symbol) { } public void RuntimeStatistic(string key, string value) { } public void OrderEvent(OrderEvent newEvent) { } public void Exit() { } public void PurgeQueue() { } public void ProcessSynchronousEvents(bool forceProcess = false) { } public string SaveLogs(string id, IEnumerable<string> logs) { return id; } public void SaveResults(string name, Result result) { } public void SetDataManager(IDataFeedSubscriptionManager dataManager) { } } class NullRealTimeHandler : IRealTimeHandler { public void Add(ScheduledEvent scheduledEvent) { } public void Remove(ScheduledEvent scheduledEvent) { } public bool IsActive { get; } public void Setup(IAlgorithm algorithm, AlgorithmNodePacket job, IResultHandler resultHandler, IApi api) { } public void Run() { } public void SetTime(DateTime time) { } public void ScanPastEvents(DateTime time) { } public void Exit() { } } class NullTransactionHandler : ITransactionHandler { public int OrdersCount { get; } public Order GetOrderById(int orderId) { throw new NotImplementedException(); } public Order GetOrderByBrokerageId(string brokerageId) { throw new NotImplementedException(); } public IEnumerable<OrderTicket> GetOrderTickets(Func<OrderTicket, bool> filter = null) { throw new NotImplementedException(); } public IEnumerable<OrderTicket> GetOpenOrderTickets(Func<OrderTicket, bool> filter = null) { return OrderTickets.Values.Where(x => x.Status.IsOpen() && (filter == null || filter(x))); } public OrderTicket GetOrderTicket(int orderId) { throw new NotImplementedException(); } public IEnumerable<Order> GetOrders(Func<Order, bool> filter = null) { throw new NotImplementedException(); } public OrderTicket Process(OrderRequest request) { throw new NotImplementedException(); } public List<Order> GetOpenOrders(Func<Order, bool> filter = null) { return Orders.Values.Where(x => x.Status.IsOpen() && (filter == null || filter(x))).ToList(); } public bool IsActive { get; } public ConcurrentDictionary<int, Order> Orders { get; } public ConcurrentDictionary<int, OrderTicket> OrderTickets { get; } public void Initialize(IAlgorithm algorithm, IBrokerage brokerage, IResultHandler resultHandler) { } public void Run() { } public void Exit() { } public void ProcessSynchronousEvents() { } public void AddOpenOrder(Order order, OrderTicket orderTicket) { throw new NotImplementedException(); } public event EventHandler<OrderEvent> NewOrderEvent; } class NullSynchronizer : ISynchronizer { private DateTime _frontierUtc; private readonly DateTime _endTimeUtc; private readonly List<BaseData> _data = new List<BaseData>(); private readonly List<UpdateData<SubscriptionDataConfig>> _consolidatorUpdateData = new List<UpdateData<SubscriptionDataConfig>>(); private readonly List<TimeSlice> _timeSlices = new List<TimeSlice>(); private readonly TimeSpan _frontierStepSize = TimeSpan.FromSeconds(1); private readonly List<UpdateData<ISecurityPrice>> _securitiesUpdateData = new List<UpdateData<ISecurityPrice>>(); public int Count => _timeSlices.Count; public NullSynchronizer(IAlgorithm algorithm) { _frontierUtc = algorithm.StartDate.ConvertToUtc(algorithm.TimeZone); _endTimeUtc = algorithm.EndDate.ConvertToUtc(algorithm.TimeZone); foreach (var kvp in algorithm.Securities) { var security = kvp.Value; var tick = new Tick { Symbol = security.Symbol, EndTime = _frontierUtc.ConvertFromUtc(security.Exchange.TimeZone) }; _data.Add(tick); _securitiesUpdateData.Add(new UpdateData<ISecurityPrice>(security, typeof(Tick), new BaseData[] { tick })); _consolidatorUpdateData.Add(new UpdateData<SubscriptionDataConfig>(security.Subscriptions.First(), typeof(Tick), new BaseData[] { tick })); } _timeSlices.AddRange(GenerateTimeSlices().Take(int.MaxValue / 1000)); } public IEnumerable<TimeSlice> StreamData(CancellationToken cancellationToken) { return _timeSlices; } private IEnumerable<TimeSlice> GenerateTimeSlices() { var bars = new TradeBars(); var quotes = new QuoteBars(); var ticks = new Ticks(); var options = new OptionChains(); var futures = new FuturesChains(); var splits = new Splits(); var dividends = new Dividends(); var delistings = new Delistings(); var symbolChanges = new SymbolChangedEvents(); var dataFeedPackets = new List<DataFeedPacket>(); var customData = new List<UpdateData<ISecurityPrice>>(); var changes = SecurityChanges.None; do { var slice = new Slice(default(DateTime), _data, bars, quotes, ticks, options, futures, splits, dividends, delistings, symbolChanges); var timeSlice = new TimeSlice(_frontierUtc, _data.Count, slice, dataFeedPackets, _securitiesUpdateData, _consolidatorUpdateData, customData, changes, new Dictionary<Universe, BaseDataCollection>()); yield return timeSlice; _frontierUtc += _frontierStepSize; } while (_frontierUtc <= _endTimeUtc); } } } }
34.128378
218
0.574738
[ "Apache-2.0" ]
alexotsu/Lean
Tests/Engine/AlgorithmManagerTests.cs
15,155
C#
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package syscall -- go2cs converted at 2020 October 09 05:02:04 UTC // import "syscall" ==> using syscall = go.syscall_package // Original source: C:\Go\src\syscall\types_windows_arm.go using static go.builtin; namespace go { public static partial class syscall_package { public partial struct WSAData { public ushort Version; public ushort HighVersion; public array<byte> Description; public array<byte> SystemStatus; public ushort MaxSockets; public ushort MaxUdpDg; public ptr<byte> VendorInfo; } public partial struct Servent { public ptr<byte> Name; public ptr<ptr<byte>> Aliases; public ushort Port; public ptr<byte> Proto; } } }
28.371429
69
0.619335
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/syscall/types_windows_arm.cs
993
C#
using StreamCompanion.Contract; using StreamCompanion.Contract.Json; using System; using System.Collections.Generic; namespace StreamCompanion.JsonConverter { public class SerializedRoot : IConverterRoot { public SerializedRoot(Guid id, IEnumerable<ISerie> currentlyWatching, IEnumerable<ISerie> completed, IEnumerable<ISerie> onHold, IEnumerable<ISerie> dropped, IEnumerable<ISerie> planToWatch) { this.CurrentlyWatching = new List<ISerie>(currentlyWatching); this.Completed = new List<ISerie>(completed); this.OnHold = new List<ISerie>(onHold); this.Dropped = new List<ISerie>(dropped); this.PlanToWatch = new List<ISerie>(planToWatch); this.Id = id; } public Guid Id { get; private set; } public List<ISerie> CurrentlyWatching { get; private set; } public List<ISerie> Completed { get; private set; } public List<ISerie> OnHold { get; private set; } public List<ISerie> Dropped { get; private set; } public List<ISerie> PlanToWatch { get; private set; } } }
34.090909
198
0.666667
[ "MIT" ]
dreanor/StreamCompanion
src/jsonconverter/SerializedRoot.cs
1,127
C#
using System; namespace Simplic.Cloud.API.DataHub { /// <summary> /// Queue count result /// </summary> public class QueueCountResult { /// <summary> /// Gets or sets the id /// </summary> public Guid Id { get; set; } /// <summary> /// Gets or sets the queue count /// </summary> public int Count { get; set; } } }
19.333333
40
0.5
[ "MIT" ]
simplic/simplic-cloud-api
src/Simplic.Cloud.API.DataHub/Model/EventQueue/QueueCountResult.cs
408
C#
using System.Threading; using NUnit.Framework; using WPILib.Commands; namespace WPILib.IntegrationTests.Commands { [TestFixture] public class CommandTimeoutTest : AbstractCommandTest { [Test] public void TestTwoSecondTimeout() { ASubsystem subsystem = new ASubsystem(); MockCommand command = new TimedMockCommand(); command.AddRequires(subsystem); command.MockSetTimeout(2); command.Start(); AssertCommandState(command, 0, 0, 0, 0, 0); Scheduler.Instance.Run(); AssertCommandState(command, 0, 0, 0, 0, 0); Scheduler.Instance.Run(); AssertCommandState(command, 1, 1, 1, 0, 0); Scheduler.Instance.Run(); AssertCommandState(command, 1, 2, 2, 0, 0); Scheduler.Instance.Run(); AssertCommandState(command, 1, 3, 3, 0, 0); Thread.Sleep(2000); Scheduler.Instance.Run(); AssertCommandState(command, 1, 4, 4, 1, 0); Scheduler.Instance.Run(); AssertCommandState(command, 1, 4, 4, 1, 0); } } internal class TimedMockCommand : MockCommand { protected override bool IsFinished() { return base.IsFinished() || IsTimedOut(); } } }
29.23913
57
0.569517
[ "MIT" ]
Team-1922/OzWPILib.NET
WPILib.IntegrationTests/Commands/CommandTimeoutTest.cs
1,347
C#
using BuildIt.Auth; using System; using System.Diagnostics; using System.Net; using Xamarin.Forms; namespace Authentication { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } private OAuthManager AzureManager { get; } = new OAuthManager { Specification = new AzureActiveDirectoryOAuthSpecification { ClientId = "5db87179-0079-4264-a325-32be8cea7117", RedirectUri = "ext.auth://callback", PostLogoutRedirectUrl = "ext.auth://callback", Tenant = "nicksdemodir.onmicrosoft.com", IsMultiTenanted = false, State = "12345", Nounce = "7362CAEA-9CA5-4B43-9BA3-34D7C303EBA7", Resource = "https://graph.microsoft.com", } }; private OAuthManager GoogleManager { get; } = new OAuthManager { Specification = new GoogleOAuthSpecification { ClientId = "966274654419-2s5tgbb717ecev48ghn46ij0p8qp90nf.apps.googleusercontent.com", RedirectUri = "ext.auth:/callback", Scope = "email profile" } }; //private string MicrosoftAuthorizationLink => // "https://login.microsoftonline.com/nicksdemodir.onmicrosoft.com/oauth2/authorize?" + // "client_id=5db87179-0079-4264-a325-32be8cea7117&" + // "response_type=code&" + // "redirect_uri=extauth%3A%2F%2Fcallback&" + // "scope=offline_acesss&" + // "state=12345&" + // "nonce=7362CAEA-9CA5-4B43-9BA3-34D7C303EBA7&" + // "resource=https%3A%2F%2Fgraph.microsoft.com"; //private string MicrosoftTokenUrl => "https://login.microsoftonline.com/nicksdemodir.onmicrosoft.com/oauth2/token"; //private IDictionary<string,string> MicrosoftTokenPost(string code) //{ // return ("grant_type=authorization_code&" + // "client_id=5db87179-0079-4264-a325-32be8cea7117&" + // "redirect_uri=extauth://callback&" + // "resource=https://graph.microsoft.com&" + // $"code={code}").Split('&') // .Select(q => q.Split('=')) // .ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault()); //} //private string GoogleAuthorizationLink => // "https://accounts.google.com/o/oauth2/v2/auth?" + // "scope=email%20profile&" + // "redirect_uri=ext.auth:/callback&" + // "response_type=code&" + // "client_id=966274654419-2s5tgbb717ecev48ghn46ij0p8qp90nf.apps.googleusercontent.com"; //private string GoogleTokenUrl => "https://www.googleapis.com/oauth2/v4/token"; //private IDictionary<string, string> GoogleTokenPost(string code) //{ // return ( // $"code={code}&" + // "client_id=966274654419-2s5tgbb717ecev48ghn46ij0p8qp90nf.apps.googleusercontent.com&" + // "redirect_uri=ext.auth:/callback&" + // "grant_type=authorization_code" // ).Split('&') // .Select(q => q.Split('=')) // .ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault()); //} protected override void OnAppearing() { base.OnAppearing(); //UriLauncher.Register(UriCallback); } protected override void OnDisappearing() { base.OnDisappearing(); AzureManager.Unregister(); GoogleManager.Unregister(); //UriLauncher.Unregister(); } private void AzureAuthenticated(bool authenticated) { Debug.WriteLine($"Azure authenticated - {authenticated}"); } private void GoogleAuthenticated(bool authenticated) { Debug.WriteLine($"Google authenticated - {authenticated}"); } //private async void UriCallback(Uri uri) //{ // Debug.WriteLine(uri != null); // var isMicrosoft = false; // if (uri.AbsoluteUri.Contains("extauth")) // { // isMicrosoft = true; // } // var arguments = uri?.Query // .Substring(1) // Remove '?' // .Split('&') // .Select(q => q.Split('=')) // .ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault()); // var code = arguments?["code"]; // var url =isMicrosoft? MicrosoftTokenUrl:GoogleTokenUrl; // var post = isMicrosoft ? MicrosoftTokenPost(code) : GoogleTokenPost(code); // var content = new FormUrlEncodedContent(post); // using (var client = new HttpClient()) // { // var result = await client.PostAsync(new Uri(url), content); // var output = await result.Content.ReadAsStringAsync(); // Debug.WriteLine(result!=null); // var tokenInfo = JsonConvert.DeserializeObject<TokenData>(output); // Debug.WriteLine(result!=null); // } //} private void Button_Clicked(object sender, EventArgs e) { //Device.OpenUri(new Uri(MicrosoftAuthorizationLink)); AzureManager.Register(AzureAuthenticated); Device.OpenUri(new Uri(AzureManager.OAuthLogonUrl)); } private void ButtonGoogle_Clicked(object sender, EventArgs e) { //Device.OpenUri(new Uri(GoogleAuthorizationLink)); GoogleManager.Register(GoogleAuthenticated); Device.OpenUri(new Uri(GoogleManager.OAuthLogonUrl)); } private async void ButtonAzureRefresh_Clicked(object sender, EventArgs e) { await AzureManager.RefreshAccessToken(); } private async void ButtonGoogleRefresh_Clicked(object sender, EventArgs e) { await GoogleManager.RefreshAccessToken(); } private void ButtonAzureLogout_Clicked(object sender, EventArgs e) { Device.OpenUri(new Uri(AzureManager.OAuthLogOffUrl)); } private void ButtonGoogleLogout_Clicked(object sender, EventArgs e) { //Device.OpenUri(new Uri($"https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue={WebUtility.UrlEncode("ext.auth:/callback")}")); Device.OpenUri(new Uri($"{GoogleManager.OAuthLogOffUrl}?token={WebUtility.UrlEncode(GoogleManager.Token.AccessToken)}")); } } }
38.706522
184
0.540719
[ "MIT" ]
builttoroam/BuildIt
src/BuildIt.Auth/Samples/Authentication/MainPage.xaml.cs
7,124
C#
using System; namespace exemplo { class Program { static void Main(string[] args) { DateTime dt = new DateTime(2018, 11, 16, 8, 10, 45); Console.WriteLine(dt.ElapsedTime()); } } }
17.285714
64
0.520661
[ "MIT" ]
Maxel-Uds/Curso-C-Sharp
Extension_Methods/exemplo/Program.cs
244
C#
using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.VisualBasic.CompilerServices; using NSubstitute.Analyzers.Tests.Shared.CodeFixProviders; namespace NSubstitute.Analyzers.Tests.VisualBasic.CodeFixProvidersTests { public abstract class VisualBasicSuppressDiagnosticSettingsVerifier : SuppressDiagnosticSettingsVerifier { private static readonly MetadataReference[] AdditionalReferences = { MetadataReference.CreateFromFile(typeof(StandardModuleAttribute).Assembly.Location) }; protected override string Language { get; } = LanguageNames.VisualBasic; protected override string FileExtension { get; } = "vb"; protected override CompilationOptions GetCompilationOptions() { return new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionStrict: OptionStrict.On); } protected override IEnumerable<MetadataReference> GetAdditionalMetadataReferences() { return AdditionalReferences; } } }
38.166667
122
0.731878
[ "MIT" ]
Acidburn0zzz/NSubstitute.Analyzers
tests/NSubstitute.Analyzers.Tests.VisualBasic/CodeFixProvidersTests/VisualBasicSuppressDiagnosticSettingsVerifier.cs
1,118
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Yandex.Inputs { public sealed class StorageBucketServerSideEncryptionConfigurationRuleGetArgs : Pulumi.ResourceArgs { /// <summary> /// A single object for setting server-side encryption by default. (documented below) /// </summary> [Input("applyServerSideEncryptionByDefault", required: true)] public Input<Inputs.StorageBucketServerSideEncryptionConfigurationRuleApplyServerSideEncryptionByDefaultGetArgs> ApplyServerSideEncryptionByDefault { get; set; } = null!; public StorageBucketServerSideEncryptionConfigurationRuleGetArgs() { } } }
36.576923
178
0.739222
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-yandex
sdk/dotnet/Inputs/StorageBucketServerSideEncryptionConfigurationRuleGetArgs.cs
951
C#
using System; using System.Collections.Generic; using System.Numerics; using Veldrid.Sdl2; namespace Veldrid.NeoDemo { public static class InputTracker { private static HashSet<Key> _currentlyPressedKeys = new(); private static HashSet<Key> _newKeysThisFrame = new(); private static HashSet<MouseButton> _currentlyPressedMouseButtons = new(); private static HashSet<MouseButton> _newMouseButtonsThisFrame = new(); public static Vector2 MousePosition; public static Vector2 MouseDelta; public static InputSnapshot FrameSnapshot { get; private set; } public static bool GetKey(Key key) { return _currentlyPressedKeys.Contains(key); } public static bool GetKeyDown(Key key) { return _newKeysThisFrame.Contains(key); } public static bool GetMouseButton(MouseButton button) { return _currentlyPressedMouseButtons.Contains(button); } public static bool GetMouseButtonDown(MouseButton button) { return _newMouseButtonsThisFrame.Contains(button); } public static void UpdateFrameInput(InputSnapshot snapshot, Sdl2Window window) { FrameSnapshot = snapshot; _newKeysThisFrame.Clear(); _newMouseButtonsThisFrame.Clear(); MousePosition = snapshot.MousePosition; MouseDelta = window.MouseDelta; ReadOnlySpan<KeyEvent> keyEvents = snapshot.KeyEvents; for (int i = 0; i < keyEvents.Length; i++) { KeyEvent ke = keyEvents[i]; if (ke.Down) { KeyDown(ke.Physical); } else { KeyUp(ke.Physical); } } ReadOnlySpan<MouseButtonEvent> mouseEvents = snapshot.MouseEvents; for (int i = 0; i < mouseEvents.Length; i++) { MouseButtonEvent me = mouseEvents[i]; if (me.Down) { MouseDown(me.MouseButton); } else { MouseUp(me.MouseButton); } } } private static void MouseUp(MouseButton mouseButton) { _currentlyPressedMouseButtons.Remove(mouseButton); _newMouseButtonsThisFrame.Remove(mouseButton); } private static void MouseDown(MouseButton mouseButton) { if (_currentlyPressedMouseButtons.Add(mouseButton)) { _newMouseButtonsThisFrame.Add(mouseButton); } } private static void KeyUp(Key key) { _currentlyPressedKeys.Remove(key); _newKeysThisFrame.Remove(key); } private static void KeyDown(Key key) { if (_currentlyPressedKeys.Add(key)) { _newKeysThisFrame.Add(key); } } } }
29.028037
86
0.551513
[ "MIT" ]
JoeTwizzle/veldrid
src/NeoDemo/InputTracker.cs
3,108
C#
using System; using System.Linq; using Ploeh.AutoFixture.Kernel; using Ploeh.TestTypeFoundation; using Xunit; namespace Ploeh.AutoFixture.Xunit2.UnitTest { public class FavorEnumerablesAttributeTest { [Fact] public void SutIsAttribute() { // Fixture setup // Exercise system var sut = new FavorEnumerablesAttribute(); // Verify outcome Assert.IsAssignableFrom<CustomizeAttribute>(sut); // Teardown } [Fact] public void GetCustomizationFromNullParameterThrows() { // Fixture setup var sut = new FavorEnumerablesAttribute(); // Exercise system and verify outcome Assert.Throws<ArgumentNullException>(() => sut.GetCustomization(null)); // Teardown } [Fact] public void GetCustomizationReturnsCorrectResult() { // Fixture setup var sut = new FavorEnumerablesAttribute(); var parameter = typeof(TypeWithOverloadedMembers).GetMethod("DoSomething", new[] { typeof(object) }).GetParameters().Single(); // Exercise system var result = sut.GetCustomization(parameter); // Verify outcome var invoker = Assert.IsAssignableFrom<ConstructorCustomization>(result); Assert.Equal(parameter.ParameterType, invoker.TargetType); Assert.IsAssignableFrom<EnumerableFavoringConstructorQuery>(invoker.Query); // Teardown } } }
32.306122
138
0.606443
[ "MIT" ]
TeaDrivenDev/AutoFixture
Src/AutoFixture.xUnit.net2.UnitTest/FavorEnumerablesAttributeTest.cs
1,585
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Roslynator.CSharp.Syntax.SyntaxInfoHelpers; namespace Roslynator.CSharp.Syntax { /// <summary> /// Provides information about "as" expression. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public readonly struct AsExpressionInfo { private AsExpressionInfo( BinaryExpressionSyntax asExpression, ExpressionSyntax expression, TypeSyntax type) { AsExpression = asExpression; Expression = expression; Type = type; } /// <summary> /// The "as" expression. /// </summary> public BinaryExpressionSyntax AsExpression { get; } /// <summary> /// The expression that is being casted. /// </summary> public ExpressionSyntax Expression { get; } /// <summary> /// The type to which the expression is being cast. /// </summary> public TypeSyntax Type { get; } /// <summary> /// The "as" operator token. /// </summary> public SyntaxToken OperatorToken { get { return AsExpression?.OperatorToken ?? default(SyntaxToken); } } /// <summary> /// Determines whether this struct was initialized with an actual syntax. /// </summary> public bool Success { get { return Expression != null; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay { get { return ToDebugString(Success, this, AsExpression); } } internal static AsExpressionInfo Create( SyntaxNode node, bool walkDownParentheses = true, bool allowMissing = false) { return CreateImpl( Walk(node, walkDownParentheses) as BinaryExpressionSyntax, walkDownParentheses, allowMissing); } internal static AsExpressionInfo Create( BinaryExpressionSyntax binaryExpression, bool walkDownParentheses = true, bool allowMissing = false) { return CreateImpl(binaryExpression, walkDownParentheses, allowMissing); } private static AsExpressionInfo CreateImpl( BinaryExpressionSyntax binaryExpression, bool walkDownParentheses = true, bool allowMissing = false) { if (binaryExpression?.Kind() != SyntaxKind.AsExpression) return default; ExpressionSyntax expression = Walk(binaryExpression.Left, walkDownParentheses); if (!Check(expression, allowMissing)) return default; var type = binaryExpression.Right as TypeSyntax; if (!Check(type, allowMissing)) return default; return new AsExpressionInfo(binaryExpression, expression, type); } } }
31.557692
160
0.599025
[ "Apache-2.0" ]
ADIX7/Roslynator
src/CSharp/CSharp/Syntax/AsExpressionInfo.cs
3,284
C#
namespace ShoppingCart.WebApi { using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
23.944444
76
0.61949
[ "MIT" ]
djamseed/shopping-cart
src/ShoppingCart.WebApi/Program.cs
433
C#
#if ((UNITY_IOS || UNITY_TVOS || UNITY_STANDALONE_OSX) && !UNITY_EDITOR) #define APPLE_AUTH_MANAGER_NATIVE_IMPLEMENTATION_AVAILABLE #endif using AppleAuth.Enums; using AppleAuth.Interfaces; using System; namespace AppleAuth { public class AppleAuthManager : IAppleAuthManager { static AppleAuthManager() { const string versionMessage = "Using Sign in with Apple Unity Plugin - v1.3.0"; #if APPLE_AUTH_MANAGER_NATIVE_IMPLEMENTATION_AVAILABLE PInvoke.AppleAuth_LogMessage(versionMessage); #else UnityEngine.Debug.Log(versionMessage); #endif } #if APPLE_AUTH_MANAGER_NATIVE_IMPLEMENTATION_AVAILABLE private readonly IPayloadDeserializer _payloadDeserializer; private Action<string> _credentialsRevokedCallback; #endif public static bool IsCurrentPlatformSupported { get { #if APPLE_AUTH_MANAGER_NATIVE_IMPLEMENTATION_AVAILABLE return PInvoke.AppleAuth_IsCurrentPlatformSupported(); #else return false; #endif } } public AppleAuthManager(IPayloadDeserializer payloadDeserializer) { #if APPLE_AUTH_MANAGER_NATIVE_IMPLEMENTATION_AVAILABLE this._payloadDeserializer = payloadDeserializer; #endif } public void QuickLogin(Action<ICredential> successCallback, Action<IAppleError> errorCallback) { this.QuickLogin(new AppleAuthQuickLoginArgs(), successCallback, errorCallback); } public void QuickLogin( AppleAuthQuickLoginArgs quickLoginArgs, Action<ICredential> successCallback, Action<IAppleError> errorCallback) { #if APPLE_AUTH_MANAGER_NATIVE_IMPLEMENTATION_AVAILABLE var nonce = quickLoginArgs.Nonce; var state = quickLoginArgs.State; var requestId = CallbackHandler.AddMessageCallback( true, payload => { var response = this._payloadDeserializer.DeserializeLoginWithAppleIdResponse(payload); if (response.Error != null) errorCallback(response.Error); else if (response.PasswordCredential != null) successCallback(response.PasswordCredential); else successCallback(response.AppleIDCredential); }); PInvoke.AppleAuth_QuickLogin(requestId, nonce, state); #else throw new Exception("AppleAuthManager is not supported in this platform"); #endif } public void LoginWithAppleId(LoginOptions options, Action<ICredential> successCallback, Action<IAppleError> errorCallback) { this.LoginWithAppleId(new AppleAuthLoginArgs(options), successCallback, errorCallback); } public void LoginWithAppleId( AppleAuthLoginArgs loginArgs, Action<ICredential> successCallback, Action<IAppleError> errorCallback) { #if APPLE_AUTH_MANAGER_NATIVE_IMPLEMENTATION_AVAILABLE var loginOptions = loginArgs.Options; var nonce = loginArgs.Nonce; var state = loginArgs.State; var requestId = CallbackHandler.AddMessageCallback( true, payload => { var response = this._payloadDeserializer.DeserializeLoginWithAppleIdResponse(payload); if (response.Error != null) errorCallback(response.Error); else successCallback(response.AppleIDCredential); }); PInvoke.AppleAuth_LoginWithAppleId(requestId, (int)loginOptions, nonce, state); #else throw new Exception("AppleAuthManager is not supported in this platform"); #endif } public void GetCredentialState( string userId, Action<CredentialState> successCallback, Action<IAppleError> errorCallback) { #if APPLE_AUTH_MANAGER_NATIVE_IMPLEMENTATION_AVAILABLE var requestId = CallbackHandler.AddMessageCallback( true, payload => { var response = this._payloadDeserializer.DeserializeCredentialStateResponse(payload); if (response.Error != null) errorCallback(response.Error); else successCallback(response.CredentialState); }); PInvoke.AppleAuth_GetCredentialState(requestId, userId); #else throw new Exception("AppleAuthManager is not supported in this platform"); #endif } public void SetCredentialsRevokedCallback(Action<string> credentialsRevokedCallback) { #if APPLE_AUTH_MANAGER_NATIVE_IMPLEMENTATION_AVAILABLE if (this._credentialsRevokedCallback != null) { CallbackHandler.NativeCredentialsRevoked -= this._credentialsRevokedCallback; this._credentialsRevokedCallback = null; } if (credentialsRevokedCallback != null) { CallbackHandler.NativeCredentialsRevoked += credentialsRevokedCallback; this._credentialsRevokedCallback = credentialsRevokedCallback; } #endif } public void Update() { #if APPLE_AUTH_MANAGER_NATIVE_IMPLEMENTATION_AVAILABLE CallbackHandler.ExecutePendingCallbacks(); #endif } #if APPLE_AUTH_MANAGER_NATIVE_IMPLEMENTATION_AVAILABLE private static class CallbackHandler { private const uint InitialCallbackId = 1U; private const uint MaxCallbackId = uint.MaxValue; private static readonly object SyncLock = new object(); private static readonly System.Collections.Generic.Dictionary<uint, Entry> CallbackDictionary = new System.Collections.Generic.Dictionary<uint, Entry>(); private static readonly System.Collections.Generic.List<Action> ScheduledActions = new System.Collections.Generic.List<Action>(); private static uint _callbackId = InitialCallbackId; private static bool _initialized = false; private static uint _credentialsRevokedCallbackId = 0U; private static event Action<string> _nativeCredentialsRevoked = null; public static event Action<string> NativeCredentialsRevoked { add { lock (SyncLock) { if (_nativeCredentialsRevoked == null) { _credentialsRevokedCallbackId = AddMessageCallback(false, payload => _nativeCredentialsRevoked.Invoke(payload)); PInvoke.AppleAuth_RegisterCredentialsRevokedCallbackId(_credentialsRevokedCallbackId); } _nativeCredentialsRevoked += value; } } remove { lock (SyncLock) { _nativeCredentialsRevoked -= value; if (_nativeCredentialsRevoked == null) { RemoveMessageCallback(_credentialsRevokedCallbackId); _credentialsRevokedCallbackId = 0U; PInvoke.AppleAuth_RegisterCredentialsRevokedCallbackId(0U); } } } } public static void ScheduleCallback(uint requestId, string payload) { lock (SyncLock) { var callbackEntry = default(Entry); if (CallbackDictionary.TryGetValue(requestId, out callbackEntry)) { var callback = callbackEntry.MessageCallback; ScheduledActions.Add(() => callback.Invoke(payload)); if (callbackEntry.IsSingleUseCallback) { CallbackDictionary.Remove(requestId); } } } } public static void ExecutePendingCallbacks() { lock (SyncLock) { while (ScheduledActions.Count > 0) { var action = ScheduledActions[0]; ScheduledActions.RemoveAt(0); action.Invoke(); } } } public static uint AddMessageCallback(bool isSingleUse, Action<string> messageCallback) { if (!_initialized) { PInvoke.AppleAuth_SetupNativeMessageHandlerCallback(PInvoke.NativeMessageHandlerCallback); _initialized = true; } if (messageCallback == null) { throw new Exception("Can't add a null Message Callback."); } var usedCallbackId = default(uint); lock (SyncLock) { usedCallbackId = _callbackId; _callbackId += 1; if (_callbackId >= MaxCallbackId) _callbackId = InitialCallbackId; var callbackEntry = new Entry(isSingleUse, messageCallback); CallbackDictionary.Add(usedCallbackId, callbackEntry); } return usedCallbackId; } public static void RemoveMessageCallback(uint requestId) { lock (SyncLock) { if (!CallbackDictionary.ContainsKey(requestId)) { throw new Exception("Callback with id " + requestId + " does not exist and can't be removed"); } CallbackDictionary.Remove(requestId); } } private class Entry { public readonly bool IsSingleUseCallback; public readonly Action<string> MessageCallback; public Entry(bool isSingleUseCallback, Action<string> messageCallback) { this.IsSingleUseCallback = isSingleUseCallback; this.MessageCallback = messageCallback; } } } private static class PInvoke { #if UNITY_IOS || UNITY_TVOS private const string DllName = "__Internal"; #elif UNITY_STANDALONE_OSX private const string DllName = "MacOSAppleAuthManager"; #endif public delegate void NativeMessageHandlerCallbackDelegate(uint requestId, string payload); [AOT.MonoPInvokeCallback(typeof(NativeMessageHandlerCallbackDelegate))] public static void NativeMessageHandlerCallback(uint requestId, string payload) { try { CallbackHandler.ScheduleCallback(requestId, payload); } catch (Exception exception) { Console.WriteLine("Received exception while scheduling a callback for request ID " + requestId); Console.WriteLine("Detailed payload:\n" + payload); Console.WriteLine("Exception: " + exception); } } [System.Runtime.InteropServices.DllImport(DllName)] public static extern bool AppleAuth_IsCurrentPlatformSupported(); [System.Runtime.InteropServices.DllImport(DllName)] public static extern void AppleAuth_SetupNativeMessageHandlerCallback(NativeMessageHandlerCallbackDelegate callback); [System.Runtime.InteropServices.DllImport(DllName)] public static extern void AppleAuth_GetCredentialState(uint requestId, string userId); [System.Runtime.InteropServices.DllImport(DllName)] public static extern void AppleAuth_LoginWithAppleId(uint requestId, int loginOptions, string nonceCStr, string stateCStr); [System.Runtime.InteropServices.DllImport(DllName)] public static extern void AppleAuth_QuickLogin(uint requestId, string nonceCStr, string stateCStr); [System.Runtime.InteropServices.DllImport(DllName)] public static extern void AppleAuth_RegisterCredentialsRevokedCallbackId(uint callbackId); [System.Runtime.InteropServices.DllImport(DllName)] public static extern void AppleAuth_LogMessage(string messageCStr); } #endif } }
38.489676
165
0.579093
[ "MIT" ]
Kezzo/apple-signin-unity
AppleAuth/AppleAuthManager.cs
13,048
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Gerenciador_Financeiro.Migrations { public partial class CreateValor : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<decimal>( name: "Valor", table: "Receitas", nullable: false, defaultValue: 0m); migrationBuilder.AddColumn<decimal>( name: "Valor", table: "Despesas", nullable: false, defaultValue: 0m); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Valor", table: "Receitas"); migrationBuilder.DropColumn( name: "Valor", table: "Despesas"); } } }
27.235294
71
0.531317
[ "MIT" ]
alcyonjr/GerenciadorFinanceiro
Gerenciador_Financeiro/Migrations/20190221050630_CreateValor.cs
928
C#
namespace ControlTower.Printer.Messages { /// <summary> /// Message used to disconnect the protocol layer /// </summary> public class DisconnectProtocol { /// <summary> /// Initializes a new instance of <see cref="DisconnectProtocol" /> /// </summary> private DisconnectProtocol() { } /// <summary> /// Gets the static instance of the message /// </summary> public static DisconnectProtocol Instance { get; } = new DisconnectProtocol(); } }
27.85
86
0.567325
[ "Apache-2.0" ]
wmeints/controltower
src/ControlTower/Printer/Messages/DisconnectProtocol.cs
557
C#
using Nop.Web.Framework.Models; using Nop.Web.Framework.Mvc.ModelBinding; namespace Nop.Web.Areas.Admin.Models.Settings { /// <summary> /// Represents an admin area settings model /// </summary> public partial record AdminAreaSettingsModel : BaseNopModel, ISettingsModel { #region Properties public int ActiveStoreScopeConfiguration { get; set; } [NopResourceDisplayName("Admin.Configuration.Settings.GeneralCommon.AdminArea.UseRichEditorInMessageTemplates")] public bool UseRichEditorInMessageTemplates { get; set; } public bool UseRichEditorInMessageTemplates_OverrideForStore { get; set; } #endregion } }
32.571429
120
0.725146
[ "CC0-1.0" ]
peterthomet/BioPuur
nopCommerce 4.4/src/Presentation/Nop.Web/Areas/Admin/Models/Settings/AdminAreaSettingsModel.cs
686
C#
using System; using System.Collections.Generic; using System.Text; namespace Stopwatch.View { using System.Threading; using ViewModel; class StopwatchView { private StopwatchViewModel _viewModel = new StopwatchViewModel(); private bool _quit = false; /// <summary> /// Clears the console and displays the stopwatch /// </summary> public StopwatchView() { ClearScreenAndAddHelpMessage(); TimerCallback timerCallback = UpdateTimeCallback; var _timer = new Timer(timerCallback, null, 0, 10); while (!_quit) Thread.Sleep(100); Console.CursorVisible = true; } /// <summary> /// Clears the screen, adds the help message to fourth row, and makes the cursor invisible /// </summary> private static void ClearScreenAndAddHelpMessage() { Console.Clear(); Console.CursorTop = 3; // This moves the cursor to the fourth row (rows start at 0) Console.WriteLine("Space to start or stop, R to reset, L for lap time, any other key to quit"); Console.CursorVisible = false; } /// <summary> /// Callback to update the time dispay that the time calls each time it ticks /// </summary> private void UpdateTimeCallback(object? state) { if (Console.KeyAvailable) { switch (Console.ReadKey(true).KeyChar.ToString().ToUpper()) { case " ": _viewModel.StartStop(); break; case "R": _viewModel.Reset(); break; case "L": _viewModel.LapTime(); break; default: Console.CursorVisible = true; Console.CursorLeft = 0; Console.CursorTop = 5; _quit = true; break; } } WriteCurrentTime(); } /// <summary> /// Writes the current time to the second row and 24th column of the screen /// </summary> private void WriteCurrentTime() { Console.CursorTop = 1; // This moves the cursor to the second row (rows start at 0) Console.CursorLeft = 23; // This moves the cursor to the 24th column var time = $"{_viewModel.Hours}:{_viewModel.Minutes}:" + $"{_viewModel.Seconds}.{_viewModel.Tenths}"; var lapTime = $"{_viewModel.LapHours}:{_viewModel.LapMinutes}:" + $"{_viewModel.LapSeconds}.{_viewModel.LapTenths}"; Console.Write($"{time} - lap time {lapTime}"); } } }
35.470588
108
0.494196
[ "MIT" ]
JoyfulReaper/fourth-edition
Code/MVVM_WPF/Stopwatch/Stopwatch/View/StopwatchView.cs
3,017
C#
using System; using System.Collections.Generic; namespace VotingIrregularities.Domain.Models { public partial class Raspuns { public int IdObservator { get; set; } public int IdRaspunsDisponibil { get; set; } public int IdSectieDeVotare { get; set; } public DateTime DataUltimeiModificari { get; set; } public string Value { get; set; } public string CodJudet { get; set; } public int NumarSectie { get; set; } public virtual Observator IdObservatorNavigation { get; set; } public virtual RaspunsDisponibil IdRaspunsDisponibilNavigation { get; set; } public virtual SectieDeVotare IdSectieDeVotareNavigation { get; set; } } }
34.333333
84
0.678225
[ "MPL-2.0" ]
levinineiasi/monitorizare-vot
private-api/app/src/VotingIrregularities.Domain/Models/Raspuns.cs
723
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace chunked_upload_api { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
27.875
70
0.715994
[ "MIT" ]
sul-patompong/chunked-upload
api/chunked-upload-api/chunked-upload-api/Global.asax.cs
671
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vowel_or_Digit { class Program { static void Main(string[] args) { char symbol = char.Parse(Console.ReadLine()); if (symbol>'\u002f' && symbol<'\u003a') { Console.WriteLine("digit"); } else if (symbol=='a' || symbol == 'e' || symbol == 'o' || symbol == 'i' || symbol == 'u' || symbol == 'y') { Console.WriteLine("vowel"); } else { Console.WriteLine("other"); } } } }
24.103448
118
0.467811
[ "MIT" ]
SimeonShterev/2017.09.21-2017.11.05-ProgramingFundamentals
2017.09.29 - H4 DATA TYPES AND VARS/Vowel or Digit/Program.cs
701
C#
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; namespace Microsoft.Azure.Management.RemoteApp.Models { /// <summary> /// Current status of a long-running operation. /// </summary> public enum RemoteAppOperationStatus { /// <summary> /// The operation is pending. /// </summary> Pending = 0, /// <summary> /// The operation is in progress. /// </summary> InProgress = 1, /// <summary> /// The operation was successfully completed. /// </summary> Success = 2, /// <summary> /// The operation failed. /// </summary> Failed = 3, } }
27.981132
76
0.623736
[ "Apache-2.0" ]
dud5/azure-sdk-for-net
src/RemoteApp/Generated/Models/RemoteAppOperationStatus.cs
1,483
C#
using ADS.Algorithms.Graphs; using ADS.DataStructures; using System.Linq; using Xunit; namespace ADS.UnitTests.Algorithms.Graphs { public class TopologicalSortDfs_Order { [Fact] public void HappyPathUnweighted_OrderedCorrectly() { //Arrange (int, int)[] edges = new (int, int)[] { (0, 1), (0, 2), (0, 5), (1, 4), (3, 6), (3, 2), (3, 5), (3, 4), (5, 2), (6, 0), (6, 4) }; int[] expectedOrder = new int[] { 3, 6, 0, 5, 2, 1, 4 }; Digraph digraph = new Digraph(7); foreach (var edge in edges) digraph.AddEdge(edge.Item1, edge.Item2); //Act TopologicalSortDfs ts = new TopologicalSortDfs(digraph); int[] topologicalOrder = ts.Order().ToArray(); ; //Assert Assert.True(expectedOrder.SequenceEqual(topologicalOrder)); } [Fact] public void HappyPathWeighted_OrderedCorrectly() { //Arrange DirectedEdge[] edges = new DirectedEdge[] { new DirectedEdge(0, 1, 5), new DirectedEdge(0, 2, 2), new DirectedEdge(0, 5, -5), new DirectedEdge(1, 4, 30), new DirectedEdge(3, 6, 2.34), new DirectedEdge(3, 2, 17.5), new DirectedEdge(3, 5, 8), new DirectedEdge(3, 4, 0), new DirectedEdge(5, 2, -14), new DirectedEdge(6, 0, -158), new DirectedEdge(6, 4, 20) }; int[] expectedOrder = new int[] { 3, 6, 0, 5, 2, 1, 4 }; EdgeWeightedDigraph digraph = new EdgeWeightedDigraph(7); foreach (DirectedEdge edge in edges) digraph.AddEdge(edge); //Act TopologicalSortDfs ts = new TopologicalSortDfs(digraph); int[] topologicalOrder = ts.Order().ToArray(); ; //Assert Assert.True(expectedOrder.SequenceEqual(topologicalOrder)); } } }
34.644068
141
0.515166
[ "MIT" ]
MarkoPapic/ADS
Tests/ADS.UnitTests/Algorithms/Graphs/TopologicalSortDfs_Order.cs
2,046
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace DbConnector.Tests.Entities { [Table("Currency", Schema = "Sales")] public partial class Currency { public Currency() { CountryRegionCurrency = new HashSet<CountryRegionCurrency>(); CurrencyRateFromCurrencyCodeNavigation = new HashSet<CurrencyRate>(); CurrencyRateToCurrencyCodeNavigation = new HashSet<CurrencyRate>(); } [StringLength(3)] public string CurrencyCode { get; set; } [Required] [StringLength(50)] public string Name { get; set; } [Column(TypeName = "datetime")] public DateTime ModifiedDate { get; set; } [InverseProperty("CurrencyCodeNavigation")] public virtual ICollection<CountryRegionCurrency> CountryRegionCurrency { get; set; } [InverseProperty("FromCurrencyCodeNavigation")] public virtual ICollection<CurrencyRate> CurrencyRateFromCurrencyCodeNavigation { get; set; } [InverseProperty("ToCurrencyCodeNavigation")] public virtual ICollection<CurrencyRate> CurrencyRateToCurrencyCodeNavigation { get; set; } } }
37.382353
101
0.693155
[ "Apache-2.0" ]
SavantBuffer/DbConnector
DbConnector.Tests/Entities/Currency.cs
1,273
C#
using System.ComponentModel; namespace GBT35255.ProtoBase { /// <summary> /// 消息ID枚举。 /// </summary> [Description("消息ID")] public enum MessageId : ushort { #region 配置命令 /// <summary> /// 配置命令。 /// </summary> [Description("配置")] ConfigurationCommand = 0x1001, #endregion #region 操作维护 /// <summary> /// 操作维护。 /// </summary> [Description("维护")] OperationMaintenance = 0x1002, #endregion #region 控制命令 /// <summary> /// 设置默认开灯时间。 /// </summary> [Description("设置默认开灯时间")] SettingDefaultTurnOnTime = 0x1201, /// <summary> /// 设置默认关灯时间。 /// </summary> [Description("设置默认关灯时间")] SettingDefaultTurnOffTime = 0x1202, /// <summary> /// 设置默认调整亮度时间。 /// </summary> [Description("设置默认调整亮度时间")] SettingDefaultAdjustBrightnessTime = 0x1203, /// <summary> /// 设置计划开灯时间。 /// </summary> [Description("设置计划开灯时间")] SettingPlanTurnOnTime = 0x1204, /// <summary> /// 设置计划关灯时间。 /// </summary> [Description("设置计划关灯时间")] SettingPlanTurnOffTime = 0x1205, /// <summary> /// 设置灯具调光计划。 /// </summary> [Description("设置灯具调光计划")] SettingLuminaireDimmingPlan = 0x1206, /// <summary> /// 设置触发告警阈值。 /// </summary> [Description("设置触发告警阈值")] SettingTriggerAlarmThreshold = 0x1207, /// <summary> /// 实时开/关灯和调整亮度。 /// </summary> [Description("实时开/关灯和调整亮度")] RealTimeControlLuminaire = 0x1208, /// <summary> /// 实时查询灯具状态。 /// </summary> [Description("实时查询灯具状态")] RealTimeQueryLuminaireStatus = 0x1209, /// <summary> /// 设置灯具数据采集周期。 /// </summary> [Description("设置灯具数据采集周期")] SettingLuminaireDataCollectionPeriod = 0x120A, /// <summary> /// 设置灯具分组。 /// </summary> [Description("设置灯具分组")] SettingLuminaireGroup = 0x120B, /// <summary> /// 删除灯具分组。 /// </summary> [Description("删除灯具分组")] RemoveLuminaireGroup = 0x120C, /// <summary> /// 设置灯具场景。 /// </summary> [Description("设置灯具场景")] SettingLuminaireScene = 0x120D, /// <summary> /// 删除灯具场景。 /// </summary> [Description("删除灯具场景")] RemoveLuminaireScene = 0x120E, /// <summary> /// 设置灯具运行模式。 /// <para>自动或手动。</para> /// </summary> [Description("设置灯具运行模式")] SettingRunningMode = 0x120F, /// <summary> /// 要求上传灯具日志。 /// </summary> [Description("要求上传灯具日志")] RequireReportLuminaireLog = 0x1210, /// <summary> /// 灯具恢复出厂状态。 /// </summary> [Description("灯具恢复出厂状态")] LuminaireFactoryReset = 0x1211, /// <summary> /// 更新RSA密钥。 /// </summary> [Description("更新RSA密钥")] UpdateRSAKey = 0x1212, /// <summary> /// 更新DES密钥。 /// </summary> [Description("更新DES密钥")] UpdateDESKey = 0x1213, /// <summary> /// 同步时间。 /// </summary> [Description("同步时间")] SynchronizeTime = 0x1214, /// <summary> /// 设置通信故障下灯具默认亮度。 /// </summary> [Description("设置通信故障下灯具默认亮度")] SettingCommunicationFailureDefaultBrightness = 0x1215, /// <summary> /// 设置灯具默认上电亮度。 /// </summary> [Description("设置灯具默认上电亮度")] SettingPowerOnDefaultBrightness = 0x1216, /// <summary> /// 接入认证请求。 /// <para>由网关向服务器发起。</para> /// </summary> [Description("接入认证请求")] AccessAuthenticationRequest = 0x1300, #region 厂商自定义 /// <summary> /// 启用或禁用功能。 /// <para>防盗。</para> /// <para>移动传感器。</para> /// <para>亮度传感器。</para> /// <para>天气状况。</para> /// <para>交通量。</para> /// <para>经纬度。</para> /// <para>光衰补偿。</para> /// </summary> [Description("启用或禁用功能")] SettingEnableFunction = 0x1400, /// <summary> /// 灯具绑定到网关。 /// </summary> [Description("灯具绑定到网关")] BindingGateway = 0x1401, /// <summary> /// 灯具从网关解除绑定。 /// </summary> [Description("灯具从网关解除绑定")] UnbindingGateway = 0x1402, /// <summary> /// 设置ZigBee无线网络参数。 /// <para>无线频点,即ZigBee无线通信的信道,取值范围:[01,16]。</para> /// <para>其他参数待定。</para> /// </summary> [Description("设置ZigBee无线网络参数")] SettingZigBeeParameter = 0x1403, /// <summary> /// 设置光衰补偿参数。 /// </summary> [Description("设置光衰补偿参数")] SettingAttenuationCompensationParameter = 0x1404, /// <summary> /// 搜索设备。 /// </summary> [Description("搜索设备")] SearchDevice = 0x1405, /// <summary> /// 查询计划定时任务。 /// </summary> [Description("查询计划定时任务")] QueryPlanTimingTask = 0x1406, /// <summary> /// 删除计划定时任务。 /// </summary> [Description("删除计划定时任务")] RemovePlanTimingTask = 0x1407, /// <summary> /// 查询资源2状态参数。 /// </summary> [Description("查询资源2状态参数")] QueryResource2Status = 0x1408, /// <summary> /// 设置移动传感器参数。 /// </summary> [Description("设置移动传感器参数")] 设置移动传感器参数 = 0x1409, /// <summary> /// 设置亮度传感器参数。 /// </summary> [Description("设置亮度传感器参数")] 设置亮度传感器参数 = 0x140A, /// <summary> /// 设置经纬度参数。 /// </summary> [Description("设置经纬度参数")] 设置经纬度参数 = 0x140B, /// <summary> /// 校准电参数。 /// </summary> [Description("校准电参数")] 校准电参数 = 0x140C, /// <summary> /// 设置电参数阈值。 /// </summary> [Description("设置电参数阈值")] 设置电参数阈值 = 0x140D, /// <summary> /// 准备下发调光策略。 /// </summary> [Description("准备下发调光策略")] 准备下发调光策略 = 0x140E, /// <summary> /// 查询通信网络参数。 /// <para>如GPRS/3G/4G等网络参数。</para> /// </summary> [Description("查询通信网络参数")] 查询通信网络参数 = 0x1410, /// <summary> /// 发送短信息。 /// </summary> [Description("发送短信息")] 发送短信息 = 0x1411, /// <summary> /// 读取短信息。 /// </summary> [Description("读取短信息")] 读取短信息 = 0x1412, /// <summary> /// 查询灯具分组。 /// </summary> [Description("查询灯具分组")] 查询灯具分组 = 0x1420, #endregion #endregion #region 事件列表 #region 数据采集 /// <summary> /// 数据采集。 /// </summary> [Description("数据采集")] DataCollection = 0x2101, #region 厂商自定义 /// <summary> /// 上报搜索到的设备。 /// </summary> [Description("上报搜索到的设备")] DeviceDiscovered = 0x2110, /// <summary> /// 上报计划定时任务。 /// </summary> [Description("上报计划定时任务")] ReportPlanTimingTask = 0x2111, /// <summary> /// 上报移动传感器参数。 /// </summary> [Description("上报移动传感器参数")] 上报移动传感器参数 = 0x2112, /// <summary> /// 上报亮度传感器状态。 /// </summary> [Description("上报亮度传感器参数")] 上报亮度传感器参数 = 0x2113, /// <summary> /// 上报经纬度参数。 /// </summary> [Description("上报经纬度参数")] 上报经纬度参数 = 0x2114, /// <summary> /// 上报电参数。 /// </summary> [Description("上报电参数")] 上报电参数 = 0x2115, /// <summary> /// 上报电参数阈值。 /// </summary> [Description("上报电参数阈值")] 上报电参数阈值 = 0x2116, /// <summary> /// 上报灯具运行模式。 /// </summary> [Description("上报灯具运行模式")] ReportRunningMode = 0x2117, /// <summary> /// 上报灯具开关调光次数。 /// </summary> [Description("上报灯具开关调光次数")] 上报灯具开关调光次数 = 0x2118, /// <summary> /// 上报通信网络参数。 /// </summary> [Description("上报通信网络参数")] 上报通信网络参数 = 0x2119, /// <summary> /// 上报短信内容。 /// </summary> [Description("上报短信内容")] 上报短信内容 = 0x211A, /// <summary> /// 请求下发调光策略。 /// </summary> [Description("请求下发调光策略")] 请求下发调光策略 = 0x211B, /// <summary> /// 上报灯具分组。 /// </summary> [Description("上报灯具分组")] 上报灯具分组 = 0x2120, #endregion #endregion #region 故障告警事件 /// <summary> /// 灯具重新启动。 /// </summary> [Description("灯具重新启动")] LuminaireRestart = 0x2200, /// <summary> /// 灯具临界告警消除。 /// </summary> [Description("灯具临界告警消除")] LuminaireThresholdEliminateAlarm = 0x2202, /// <summary> /// 灯具临界告警。 /// </summary> [Description("灯具临界告警")] LuminaireThresholdAlarm = 0x2302, /// <summary> /// 网关与灯具通信故障告警。 /// </summary> [Description("网关与灯具通信故障告警")] CommunicationFailureAlarm = 0x2303, /// <summary> /// 网关与灯具通信故障告警消除。 /// </summary> [Description("网关与灯具通信故障告警消除")] CommunicationFailureEliminateAlarm = 0x2203, /// <summary> /// 灯具未按控制设定工作告警。 /// </summary> [Description("灯具未按控制设定工作告警")] LuminaireRunExceptionAlarm = 0x2304, /// <summary> /// 灯具未按控制设定工作告警消除。 /// </summary> [Description("灯具未按控制设定工作告警消除")] LuminaireRunExceptionEliminateAlarm = 0x2204, /// <summary> /// 灯具防盗告警。 /// </summary> [Description("灯具防盗告警")] LuminaireBurglarAlarm = 0x2305, #endregion #endregion #region 远程升级 /// <summary> /// 远程升级。 /// </summary> [Description("远程升级")] RemoteUpgrade = 0x1100, /// <summary> /// 请求第N段文件。 /// </summary> [Description("请求第N段文件")] RequestNthSegmentFile = 0x1101, #region 厂商自定义 /// <summary> /// 获取设备版本。 /// </summary> [Description("获取设备版本")] 获取设备版本 = 0x1110, /// <summary> /// 上报设备版本。 /// </summary> [Description("上报设备版本")] 上报设备版本 = 0x1111, #endregion #endregion } }
23.056156
62
0.465574
[ "Apache-2.0" ]
li2008kui/GBT35255
src/GBT35255.ProtoBase/MessageId.cs
13,471
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using STM.Implementation.Lockbased; namespace STM.Collections { public class SingleItemBuffer<T> { private readonly TMVar<T> _item; private readonly TMVar<bool> _full; public bool IsFull { get { return _full.GetValue(); } } public SingleItemBuffer(T initial) { _item = new TMVar<T>(initial); _full = new TMVar<bool>(true); } public SingleItemBuffer() { _item = new TMVar<T>(default(T)); _full = new TMVar<bool>(false); } public T GetValue() { return STMSystem.Atomic(() => { if (!_full.GetValue()) { STMSystem.Retry(); } _full.SetValue(false); return _item.GetValue(); }); } public void SetValue(T value) { STMSystem.Atomic(() => { if (_full.GetValue()) { STMSystem.Retry(); } _full.SetValue(true); _item.SetValue(value); }); } } }
22.568966
63
0.468296
[ "MIT" ]
Felorati/Thesis
code/STM/STM/STM/Collections/SingleItemBuffer.cs
1,311
C#
using System.IO; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Firestorm.Client.Content { internal class JsonContentSerializer : IContentSerializer { private readonly JsonSerializer _jsonSerializer; public JsonContentSerializer() { _jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings { // would be better to use the NamingConvention stuff in Endpoints.Formatting. Perhaps move that to Core.Web ? ContractResolver = new DefaultContractResolver() { NamingStrategy = new SnakeCaseNamingStrategy() }, Converters = { new RestItemDataConverter() } }); } public async Task<T> DeserializeAsync<T>(HttpResponseMessage response) { using (Stream stream = await response.Content.ReadAsStreamAsync()) { if (response.IsSuccessStatusCode) return DeserializeFromStream<T>(stream); var errorData = DeserializeFromStream<ExceptionResponse>(stream); throw new ClientRestApiException(response.StatusCode, errorData); } } private T DeserializeFromStream<T>(Stream stream) { using (var streamReader = new StreamReader(stream)) using (var jsonReader = new JsonTextReader(streamReader)) { return _jsonSerializer.Deserialize<T>(jsonReader); } } public StringContent SerializeItemToContent(object obj) { using (var stringWriter = new StringWriter()) { _jsonSerializer.Serialize(stringWriter, obj); return new StringContent(stringWriter.ToString(), Encoding.UTF8, "application/json"); } } } }
35.833333
125
0.617571
[ "MIT" ]
connellw/Firestorm
src/Firestorm.Client/Content/JsonContentSerializer.cs
1,937
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 11.12.2020. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Or.Complete.Int16.Int64{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1=System.Int16; using T_DATA2=System.Int64; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields public static class TestSet_001__fields { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_SMALLINT"; private const string c_NameOf__COL_DATA2 ="COL2_BIGINT"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_00a01() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1 c_value1=2+4; const T_DATA2 c_value2=1+2; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); Assert.AreEqual (7, c_value1|c_value2); #pragma warning disable CS0675 var recs=db.testTable.Where(r => (r.COL_DATA1|r.COL_DATA2)==7 && r.TEST_ID==testID); #pragma warning restore CS0675 int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r var sqlt =new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (BIN_OR(").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).T(") = 7) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"); db.CheckTextOfLastExecutedCommand (sqlt); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_00a01 //----------------------------------------------------------------------- [Test] public static void Test_00x01() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1 c_value1=2; const T_DATA2 c_value2=1; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); Assert.AreEqual (3, c_value1|c_value2|c_value2); #pragma warning disable CS0675 var recs=db.testTable.Where(r => (r.COL_DATA1|r.COL_DATA2|r.COL_DATA2)==3 && r.TEST_ID==testID); #pragma warning restore CS0675 int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r var sqlt =new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (BIN_OR(BIN_OR(").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).T("), ").N("t",c_NameOf__COL_DATA2).T(") = 3) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"); db.CheckTextOfLastExecutedCommand (sqlt); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_00x01 //----------------------------------------------------------------------- [Test] public static void Test_00x02() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1 c_value1=2; const T_DATA2 c_value2=1; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); Assert.AreEqual (2, c_value1|(c_value2+c_value2)); #pragma warning disable CS0675 var recs=db.testTable.Where(r => (r.COL_DATA1|(r.COL_DATA2+r.COL_DATA2))==2 && r.TEST_ID==testID); #pragma warning restore CS0675 int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r var sqlt =new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (BIN_OR(").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).T(" + ").N("t",c_NameOf__COL_DATA2).T(") = 2) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"); db.CheckTextOfLastExecutedCommand (sqlt); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_00x02 //----------------------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Or.Complete.Int16.Int64
26.170569
203
0.555399
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/Or/Complete/Int16/Int64/TestSet_001__fields.cs
7,827
C#
namespace CSharpAlgo.DataStructure.Graph { public class AdjacencyMatrix { public int[,] Value; public int N { get; set; } public bool IsDirected { get; set; } public AdjacencyMatrix(int[,] graph) { Value = graph; N = graph.GetLength(0); } public AdjacencyMatrix(int n, bool isDirected = false) { N = n; Value = new int[N, N]; IsDirected = isDirected; } public void AddEdge(int src, int des, bool isDirected = false) { Value[src, des] = 1; if (!IsDirected) { Value[des, src] = 1; } } public int this[int src, int des] { get { return Value[src, des]; } set { Value[src, des] = value; } } } }
21.704545
70
0.419895
[ "MIT" ]
yiweishen1988/CSharpAlgo
DataStructure/Graph/AdjacencyMatrix.cs
957
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101 { using Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.PowerShell; /// <summary>Operations discovery class.</summary> [System.ComponentModel.TypeConverter(typeof(OperationsDiscoveryTypeConverter))] public partial class OperationsDiscovery { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.OperationsDiscovery" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscovery" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscovery DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new OperationsDiscovery(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.OperationsDiscovery" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscovery" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscovery DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new OperationsDiscovery(content); } /// <summary> /// Creates a new instance of <see cref="OperationsDiscovery" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscovery FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.OperationsDiscovery" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal OperationsDiscovery(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.DisplayTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Name, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Origin, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.IAny) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.AnyTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayProvider, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayResource, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayOperation, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayDescription, global::System.Convert.ToString); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.OperationsDiscovery" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal OperationsDiscovery(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.DisplayTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Name, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Origin, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.IAny) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.AnyTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayProvider, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayResource, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayOperation, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api202101.IOperationsDiscoveryInternal)this).DisplayDescription, global::System.Convert.ToString); AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Operations discovery class. [System.ComponentModel.TypeConverter(typeof(OperationsDiscoveryTypeConverter))] public partial interface IOperationsDiscovery { } }
95.088435
453
0.748104
[ "MIT" ]
Amrinder-Singh29/azure-powershell
src/ResourceMover/generated/api/Models/Api202101/OperationsDiscovery.PowerShell.cs
13,832
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public partial class CMSModules_Integration_Pages_Administration_OutcomingTasks_List { /// <summary> /// lblConnector control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMS.Base.Web.UI.LocalizedLabel lblConnector; /// <summary> /// connectorSelector control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMSModules_Integration_FormControls_ConnectorSelector connectorSelector; /// <summary> /// listElem control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMSModules_Integration_Controls_UI_IntegrationTask_List listElem; }
33.219512
94
0.589574
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSModules/Integration/Pages/Administration/OutcomingTasks/List.aspx.designer.cs
1,364
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BookStore.Models; using BookStore.Models.Repositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace BookStore.Controllers { public class AuthorController : Controller { private readonly IBookRepository<Auther> authorRepository; public AuthorController(IBookRepository<Auther> authorRepository) { this.authorRepository = authorRepository; } // GET: Author public ActionResult Index() { var authors = authorRepository.List(); return View(authors); } // GET: Author/Details/5 public ActionResult Details(int id) { var author = authorRepository.Find(id); return View(author); } // GET: Author/Create public ActionResult Create() { return View(); } // POST: Author/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Auther author) { if (ModelState.IsValid) { try { // TODO: Add insert logic here authorRepository.Add(author); return RedirectToAction(nameof(Index)); } catch { return View(); } } ModelState.AddModelError("", "Fill all required fields"); return View(); } // GET: Author/Edit/5 public ActionResult Edit(int id) { var author = authorRepository.Find(id); return View(author); } // POST: Author/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(int id, Auther author) { try { // TODO: Add update logic here authorRepository.Update(id, author); return RedirectToAction(nameof(Index)); } catch { return View(); } } // GET: Author/Delete/5 public ActionResult Delete(int id) { var author = authorRepository.Find(id); return View(author); } // POST: Author/Delete/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int id, Auther author) { try { authorRepository.Delete(id); return RedirectToAction(nameof(Index)); } catch { return View(); } } } }
25.770642
73
0.502314
[ "MIT" ]
AhmedSaber999/BookStore
BookStore/Controllers/AuthorController.cs
2,811
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class DigitAsWord { static void Main() { string digit = Console.ReadLine(); string text = ""; switch (digit) { case "0": text = "zero"; break; case "1": text = "one"; break; case "2": text = "two"; break; case "3": text = "three"; break; case "4": text = "four"; break; case "5": text = "five"; break; case "6": text = "six"; break; case "7": text = "seven"; break; case "8": text = "eight"; break; case "9": text = "nine"; break; default: text = "not a digit"; break; } Console.WriteLine(text); } }
24.04878
42
0.402637
[ "MIT" ]
zachdimitrov/Homework
CSharp-Part-1/05.Conditional-Statements/08.Digit as Word/DigitAsWord.cs
988
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace Id4Server { public class ExternalProvider { public string DisplayName { get; set; } public string AuthenticationScheme { get; set; } } }
29.416667
107
0.699717
[ "Apache-2.0" ]
mgx0612/quickstart
src/Id4Server/Quickstart/Account/ExternalProvider.cs
355
C#
namespace Spring.Expressions.Parser.antlr { internal class SupportClass { public static int URShift(int number, int bits) { if (number >= 0) return number >> bits; else return (number >> bits) + (2 << ~bits); } public static int URShift(int number, long bits) { return URShift(number, (int)bits); } public static long URShift(long number, int bits) { if (number >= 0) return number >> bits; else return (number >> bits) + (2L << ~bits); } public static long URShift(long number, long bits) { return URShift(number, (int)bits); } } }
24.375
58
0.478205
[ "Apache-2.0" ]
18502079446/cusss
Sys.Expression/Expressions/Parser/antlr/SupportClass.cs
780
C#
using System; class ExtractBit3 { static void Main() { //Using bitwise operators, write an expression for finding the value of the bit #3 of a given unsigned integer. //The bits are counted from right to left, starting from bit #0. //The result of the expression should be either 1 or 0. Console.WriteLine("Enter a number: "); int userNumber = int.Parse(Console.ReadLine()); Console.WriteLine("Enter position of bit to see it: "); int userPosition = int.Parse(Console.ReadLine()); int mask = 1 << userPosition; int userNumberAndMask = userNumber & mask; int result = userNumberAndMask >> userPosition; Console.WriteLine("Number before operation: \n"); Console.WriteLine(Convert.ToString(userNumber, 2).PadLeft(32, '0') + "\n"); Console.WriteLine("With mask: "); Console.WriteLine(Convert.ToString(mask, 2).PadLeft(32, '0')); Console.WriteLine("Number after intervence: \n"); Console.WriteLine(Convert.ToString(result, 2).PadLeft(32, '0') + "\n"); Console.WriteLine(result + "\n"); } }
36.323529
123
0.587045
[ "MIT" ]
pkindalov/beginner_exercises
OperatorsAndExpressionsHomework/11.ExtractBit3/ExtractBit3.cs
1,237
C#
namespace P03_JediGalaxy { public class Player { private int row; private int col; private long starsCollected; public Player() { StarsCollected = 0; } public Player(int row, int col) : this() { Row = row; Col = col; } public int Col { get { return col; } set { col = value; } } public int Row { get { return row; } set { row = value; } } public long StarsCollected { get { return starsCollected; } set { starsCollected = value; } } public static void MovePlayer(Player player) { while (player.Row >= 0 && player.Col < StartUp.board.Matrix.GetLength(1)) { if (StartUp.board.IsInside(player.Row, player.Col)) { player.StarsCollected += StartUp.board.Matrix[player.Row, player.Col]; } player.Col++; player.Row--; } } public static void MoveEnemy(Player evil) { while (evil.Row >= 0 && evil.Col >= 0) { if (StartUp.board.IsInside(evil.Row, evil.Col)) { StartUp.board.Matrix[evil.Row, evil.Col] = 0; } evil.Row--; evil.Col--; } } } }
23.765625
90
0.420776
[ "MIT" ]
teodortenchev/C-Sharp-Advanced-Coursework
C# OOP Basics/Refactoring/P03_JediGalaxy/Player.cs
1,523
C#
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Roslynator.CSharp.Refactorings { internal static class DuplicateSwitchSectionRefactoring { public static void ComputeRefactoring(RefactoringContext context, SwitchSectionSyntax switchSection) { if (!context.Span.IsEmpty) return; SyntaxList<StatementSyntax> statements = switchSection.Statements; if (!statements.Any()) return; if (statements.SingleOrDefault(shouldThrow: false) is BlockSyntax block && block.CloseBraceToken.Span.Contains(context.Span)) { RegisterRefactoring(context, switchSection); } if (!IsOnEmptyLine(context.Span, switchSection.GetLeadingTrivia())) return; var switchStatement = (SwitchStatementSyntax)switchSection.Parent; SyntaxList<SwitchSectionSyntax> sections = switchStatement.Sections; int index = sections.IndexOf(switchSection); if (index > 0) { SwitchSectionSyntax previousSection = sections[index - 1]; RegisterRefactoring(context, previousSection, insertNewLine: true); } } public static void ComputeRefactoring(RefactoringContext context, SwitchStatementSyntax switchStatement) { if (!context.Span.IsEmpty) return; SyntaxList<SwitchSectionSyntax> sections = switchStatement.Sections; if (!sections.Any()) return; if (!IsOnEmptyLine(context.Span, switchStatement.CloseBraceToken.LeadingTrivia)) return; RegisterRefactoring(context, sections.Last(), insertNewLine: true); } private static bool IsOnEmptyLine(TextSpan span, SyntaxTriviaList leadingTrivia) { SyntaxTriviaList.Enumerator en = leadingTrivia.GetEnumerator(); while (en.MoveNext()) { if (en.Current.Span.Contains(span)) { if (en.Current.IsEndOfLineTrivia()) return true; return en.Current.IsWhitespaceTrivia() && en.MoveNext() && en.Current.IsEndOfLineTrivia(); } } return false; } private static void RegisterRefactoring(RefactoringContext context, SwitchSectionSyntax switchSection, bool insertNewLine = false) { context.RegisterRefactoring( "Duplicate section", ct => DuplicateSwitchSectionAsync(context.Document, switchSection, insertNewLine, ct), RefactoringIdentifiers.DuplicateSwitchSection); } private static Task<Document> DuplicateSwitchSectionAsync( Document document, SwitchSectionSyntax switchSection, bool insertNewLine, CancellationToken cancellationToken) { var switchStatement = (SwitchStatementSyntax)switchSection.Parent; SyntaxList<SwitchSectionSyntax> sections = switchStatement.Sections; int index = sections.IndexOf(switchSection); SwitchLabelSyntax label = switchSection.Labels[0]; SyntaxToken firstToken = label.GetFirstToken(); SyntaxToken newFirstToken = firstToken.WithNavigationAnnotation(); if (insertNewLine && !firstToken.LeadingTrivia.Contains(SyntaxKind.EndOfLineTrivia)) { newFirstToken = newFirstToken.PrependToLeadingTrivia(CSharpFactory.NewLine()); } SwitchSectionSyntax newSection = switchSection .WithLabels(switchSection.Labels.ReplaceAt(0, label.ReplaceToken(firstToken, newFirstToken))) .WithFormatterAnnotation(); if (index == sections.Count - 1) newSection = newSection.TrimTrailingTrivia(); SyntaxList<SwitchSectionSyntax> newSections = sections.Insert(index + 1, newSection); SwitchStatementSyntax newSwitchStatement = switchStatement.WithSections(newSections); return document.ReplaceNodeAsync(switchStatement, newSwitchStatement, cancellationToken); } } }
36.387597
156
0.631231
[ "Apache-2.0" ]
onexey/Roslynator
src/Refactorings/CSharp/Refactorings/DuplicateSwitchSectionRefactoring.cs
4,696
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; using System.Xml; using ExchangeRateProvider.Models; namespace ExchangeRateProvider.Providers.Czk { public class CzechNationalBankProvider : IExchangeProvider { private const string ApiUrl = "http://www.cnb.cz/cs/financni_trhy/devizovy_trh/kurzy_devizoveho_trhu/denni_kurz.xml?date="; public Task<ICurrencyList> FetchCurrencyListByDateAsync(DateTime date) { var url = this.CreateUrlByDate(date); var xmlDocument = new XmlDocument(); xmlDocument.Load(url); var rows = xmlDocument.GetElementsByTagName("radek"); var list = new List<CurrencyDescriptor>(); foreach (XmlNode row in rows) { var code = row.Attributes["kod"].Value; var name = row.Attributes["mena"].Value; var amount = Convert.ToUInt32(row.Attributes["mnozstvi"].Value); var price = Decimal.Parse(row.Attributes["kurz"].Value, NumberStyles.AllowDecimalPoint, CultureInfo.GetCultureInfo("cs-cz")); var country = row.Attributes["zeme"].Value; list.Add(new CurrencyDescriptor(code, name, price, amount, country)); } return Task.FromResult<ICurrencyList>(new CurrencyList(list)); } private string CreateUrlByDate(DateTime date) { var czechDate = date.Day + "." + date.Month + "." + date.Year; return ApiUrl + czechDate; } } }
30.466667
129
0.7345
[ "Apache-2.0" ]
anydot/StatementParser
StatementParser/ExchangeRateProvider/Providers/Czk/CzechNationalBankProvider.cs
1,373
C#
using System; using System.Collections.Generic; using System.Threading; using BitcoinUtilities.P2P; using NLog; namespace BitcoinUtilities.Threading { /// <summary> /// <p>Manages starting and stopping of services that consume events, and distributes events between them.</p> /// <p>Uses different threads for concurrent processing of events.</p> /// <p>Each service can assume that it is called from one thread only, and that events are passed to it in the same order in which they were raised.</p> /// </summary> public class EventServiceController : IEventDispatcher, IDisposable { private readonly object monitor = new object(); private readonly List<ServiceThread> services = new List<ServiceThread>(); // todo: do we need thread-safety for service registration? private volatile bool started = false; public void Dispose() { Stop(); // todo: avoid excessive locks lock (monitor) { foreach (var service in services) { service.Dispose(); } } } public void Start() { started = true; lock (monitor) { foreach (var service in services) { service.Start(); } } } public void Stop() { started = false; List<ServiceThread> stoppedThreads; lock (monitor) { stoppedThreads = new List<ServiceThread>(services); foreach (var service in stoppedThreads) { service.Stop(); } } foreach (var service in stoppedThreads) { service.Join(); } } public void AddService(IEventHandlingService service) { var serviceThread = new ServiceThread(service); lock (monitor) { services.Add(serviceThread); if (started) { // todo: add test serviceThread.Start(); } } } public void RemoveService(IEventHandlingService service) { ServiceThread serviceThread; lock (monitor) { // todo: use dictionary int index = services.FindIndex(s => s.Service == service); if (index < 0) { throw new InvalidOperationException($"{nameof(EventServiceController)} does not have this service."); } serviceThread = services[index]; services.RemoveAt(index); } // todo: use list of services as parameter to stop all of them before a call to serviceThread.Join serviceThread.Stop(); serviceThread.Join(); serviceThread.Dispose(); } public void Raise<T>(T evt) where T : IEvent { lock (monitor) { foreach (var service in services) { if (service.Expects(evt)) { service.Queue(evt); } } } } private class ServiceThread : IDisposable { private static readonly ILogger logger = LogManager.GetCurrentClassLogger(); private readonly object monitor = new object(); private readonly AutoResetEvent stateChangedEvent = new AutoResetEvent(false); private readonly Queue<object> events = new Queue<object>(); private Thread thread; private volatile bool stopped = false; public ServiceThread(IEventHandlingService service) { Service = service; } public void Dispose() { Stop(); stateChangedEvent.Dispose(); } internal IEventHandlingService Service { get; } public void Start() { thread = new Thread(ServiceLoop); thread.Name = $"ServiceThread<{Service.GetType().Name}>"; thread.IsBackground = true; thread.Start(); } public void Stop() { stopped = true; lock (monitor) { events.Clear(); } stateChangedEvent.Set(); } public void Join() { thread?.Join(); } public void Queue(object evt) { const int maxQueueSize = 16384; lock (monitor) { // todo: add per endpoint restriction insteads if (events.Count >= maxQueueSize) { throw new InvalidOperationException( $"Cannot queue event '{evt}' for service '{Service}', because queue already has {maxQueueSize} events." ); } events.Enqueue(evt); } stateChangedEvent.Set(); } public bool Expects(object @event) { return Service.GetHandler(@event) != null; } private void ServiceLoop() { try { try { Service.OnStart(); } catch (Exception ex) { LogServiceException(ex, null); // if service crashed, its state may be corrupted stopped = true; } while (!stopped) { object evt = DequeEvent(); if (evt != null) { try { HandleEvent(evt); } catch (Exception ex) { LogServiceException(ex, evt); // if service crashed, its state may be corrupted stopped = true; } } else { stateChangedEvent.WaitOne(); } } try { // todo: should OnTearDown be called for crashed services? such services can have corrupted state Service.OnTearDown(); } catch (Exception ex) { LogServiceException(ex, null); } } catch (Exception ex) { logger.Error(ex, $"Unhandled exception in {Service} thread."); } finally { logger.Debug($"{Service} thread has stopped."); // todo: remove service from controller or properly stop it to avoid queuing events to a queue without handler } } private void LogServiceException(Exception ex, object evt) { bool ignorableException = ex is BitcoinNetworkException; if (ignorableException && logger.IsTraceEnabled) { logger.Trace(ex, FormatServiceError(evt)); } if (!ignorableException && logger.IsErrorEnabled) { logger.Error(ex, FormatServiceError(evt)); } } private string FormatServiceError(object evt) { string serviceName = Service.GetType().Name; if (evt == null) { return $"Failure in {serviceName}."; } return $"{serviceName} failed to handle {evt.GetType().Name}."; } private object DequeEvent() { lock (monitor) { if (events.Count == 0) { return null; } return events.Dequeue(); } } private void HandleEvent(object evt) { if (stopped) { return; } var handler = Service.GetHandler(evt); if (handler == null) { throw new InvalidOperationException($"Handler not found for event '{evt}' in service '{Service}'."); } handler(evt); } } } }
31.583607
157
0.409841
[ "MIT" ]
yu-kopylov/bitcoin-utilities
BitcoinUtilities/Threading/EventServiceController.cs
9,331
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="OverlapRemovalGlobalConfiguration.cs" company="Microsoft"> // (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // MSAGL class for Overlap removal global configuration constants. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Microsoft.Msagl.Core.Geometry { /// <summary> /// Global configuration constants for the OverlapRemoval namespace. /// </summary> public static class OverlapRemovalGlobalConfiguration { /// <summary> /// Default weight for a freely movable cluster border; overridable per BorderInfo instance. /// Should be very small compared to default node weight (1) so that it has no visible effect on layout. /// Too large and it will cause clusters to be squashed by their bounding variables (since OverlapRemovalCluster /// swaps the positions of Left/Right, Top/Bottom nodes to ensure that cluster bounds tightly fit their contents after a solve). /// Too small and you will see cluster boundaries "sticking" to nodes outside the cluster (because such constraints will not be /// split when they can be because the lagrangian multipliers will be so small as to be ignored before solver termination). /// </summary> public const double ClusterDefaultFreeWeight = 1e-6; /// <summary> /// Default weight for an unfixed (freely movable) cluster border; overridable per BorderInfo instance. /// </summary> public const double ClusterDefaultFixedWeight = 1e8; /// <summary> /// Default width of cluster borders; overridable per BorderInfo instance via BorderInfo.InnerMargin. /// </summary> public const double ClusterDefaultBorderWidth = 1e-3; #region InternalConstants /// <summary> /// For comparing event positions, the rounding epsilon. /// </summary> internal const double EventComparisonEpsilon = 1e-6; #endregion // InternalConstants } // end struct GlobalConfiguration } // end namespace ProjectionSolver
50.086957
136
0.621528
[ "MIT" ]
0xbeecaffe/MSAGL
GraphLayout/MSAGL/Core/Geometry/OverlapRemoval/OverlapRemovalGlobalConfiguration.cs
2,304
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Rds.Model.V20140815; namespace Aliyun.Acs.Rds.Transform.V20140815 { public class AddTagsToResourceResponseUnmarshaller { public static AddTagsToResourceResponse Unmarshall(UnmarshallerContext context) { AddTagsToResourceResponse addTagsToResourceResponse = new AddTagsToResourceResponse(); addTagsToResourceResponse.HttpResponse = context.HttpResponse; addTagsToResourceResponse.RequestId = context.StringValue("AddTagsToResource.RequestId"); return addTagsToResourceResponse; } } }
36.375
92
0.761512
[ "Apache-2.0" ]
bbs168/aliyun-openapi-net-sdk
aliyun-net-sdk-rds/Rds/Transform/V20140815/AddTagsToResourceResponseUnmarshaller.cs
1,455
C#
namespace AutoRepair { #if DEBUG using AutoRepair.Catalogs; #endif using AutoRepair.Lists; using AutoRepair.Util; using ColossalFramework; using ColossalFramework.UI; using ICities; using System.Collections.Generic; using UnityEngine; /// <summary> /// Renders the settings UI. /// </summary> public class SettingsUI { /// <summary> /// Define components for settings UI. /// /// Full settings are rendered at main menu; only partial settings are rendered in-game. /// </summary> /// /// <param name="helper">UI helper from the game.</param> /// <param name="scene">The currently active scene from <c>SceneManager.GetActiveScene()</c>.</param> public static void Render(UIHelperBase helper, string scene) { UIHelperBase group; bool selected = false; string path, caption; group = helper.AddGroup("Announcements"); if (Announcements.Notes.Count > 0) { foreach (KeyValuePair<ulong, string> entry in Announcements.Notes) { selected = Announce(group, entry.Key, entry.Value) || selected; } } if (!selected) { Announce(group, 0u, "There are currently no announcements."); } group = helper.AddGroup("Log File Options"); if (Application.platform == RuntimePlatform.OSXPlayer) { caption = "Search for 'AutoRepair Descriptors' in this file:"; path = "~/Library/Logs/Unity/Player.log"; // only way I could get logging working on Macs (see also: Log.cs) } else { if (Application.platform == RuntimePlatform.WindowsPlayer) { caption = "Copy this path in to Windows File Explorer to view log file:"; } else { caption = "Copy this path for log file location:"; } path = Log.LogFile; } UITextField field = (UITextField)group.AddTextfield(caption, path, _ => { }); field.selectOnFocus = true; field.width = 650f; if (Application.platform == RuntimePlatform.WindowsPlayer) { group.AddButton("Open File Explorer", () => System.Diagnostics.Process.Start("explorer.exe", "/select," + path)); } //Utils.OpenInFileBrowser(Application.dataPath); -- works on mac/linux, but need further testing if (scene == "Game") { return; } selected = Options.Instance.LogIntroText; group.AddCheckbox("Add notes on mod management at top of log file", selected, sel => { Options.Instance.LogIntroText = sel; Options.Instance.Save(); Scanner.PerformScan(); }); selected = Options.Instance.LogLanguages; group.AddCheckbox("Include details of languages/translations (where applicable)", selected, sel => { Options.Instance.LogLanguages = sel; Options.Instance.Save(); Scanner.PerformScan(); }); selected = Options.Instance.LogWorkshopURLs; group.AddCheckbox("Include URLs to Steam Workshop pages (if known)", selected, sel => { Options.Instance.LogWorkshopURLs = sel; Options.Instance.Save(); Scanner.PerformScan(); }); selected = Options.Instance.LogSourceURLs; group.AddCheckbox("Include URLs to source files (if known)", selected, sel => { Options.Instance.LogSourceURLs = sel; Options.Instance.Save(); Scanner.PerformScan(); }); selected = Options.Instance.LogDescriptorHeaders; group.AddCheckbox("Include descriptor headers (not recommended)", selected, sel => { Options.Instance.LogDescriptorHeaders = sel; Options.Instance.Save(); Scanner.PerformScan(); }); #if DEBUG group.AddButton("Dump CSV", () => { Catalog.Instance.DumpToCSV(); }); #endif } private static bool Announce(UIHelperBase group, ulong workshopId, string msg) { if (workshopId == 0u || IsSubscribed(workshopId)) { UICheckBox box = (UICheckBox)group.AddCheckbox(msg, true, (bool _) => { }); box.readOnly = true; box.opacity = 1f; return true; } else { return false; } } private static bool IsSubscribed(ulong workshopId) { return true; // todo } } }
37.527132
129
0.549473
[ "MIT" ]
CitiesSkylinesMods/AutoRepair
AutoRepair/AutoRepair/SettingsUI.cs
4,841
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Prism.Events; namespace IronText2.Events { public class CutTextEvent:PubSubEvent { } }
14.933333
41
0.754464
[ "MIT" ]
JayConnerGhost/IronText2
IronText2/Events/CutTextEvent.cs
226
C#
#pragma checksum "C:\Users\cna\Desktop\SmashTheBlock\BeeHive\MainPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "66202B2DFDDA4CABB5E1FD80DFA8CA94" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18010 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using BeeHive; using System; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Resources; using System.Windows.Shapes; using System.Windows.Threading; namespace BeeHive { public partial class MainPage : System.Windows.Controls.UserControl { internal System.Windows.Controls.Grid LayoutRoot; internal System.Windows.VisualStateGroup GameStatus; internal System.Windows.VisualState WaitStart; internal System.Windows.VisualState StartGame; internal System.Windows.VisualState ShowGameOver; internal System.Windows.VisualStateGroup Levels; internal System.Windows.VisualState Level1; internal System.Windows.VisualState Level2; internal System.Windows.VisualState Level3; internal System.Windows.VisualState GameOverLevel; internal System.Windows.Controls.Canvas BeeHive; internal BeeHive.GameEnvironment gameEnvironment; internal System.Windows.Shapes.Path background; internal System.Windows.Controls.Image grid; internal BeeHive.LevelHostControl levelHostControl; internal System.Windows.Controls.Image score; internal System.Windows.Controls.Image lives; internal System.Windows.Controls.Image LEFT_WALL; internal System.Windows.Controls.Image TOP_WALL; internal System.Windows.Controls.Image RIGHT_WALL; internal System.Windows.Controls.Image BOTTOM_WALL; internal System.Windows.Controls.Image BALL; internal System.Windows.Controls.Image PADDLE; internal System.Windows.Controls.TextBlock ScoreText; internal System.Windows.Controls.TextBlock LivesText; internal System.Windows.Controls.Image ClicktoStart; internal System.Windows.Controls.Image GameOver; internal System.Windows.Controls.TextBlock LastScoreText; internal System.Windows.Controls.TextBlock HiScoreText; internal System.Windows.Controls.Grid frame; internal System.Windows.Controls.Grid masterHead; internal System.Windows.Shapes.Rectangle masterHead_bg; internal System.Windows.Shapes.Rectangle footer; private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/BeeHive;component/MainPage.xaml", System.UriKind.Relative)); this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); this.GameStatus = ((System.Windows.VisualStateGroup)(this.FindName("GameStatus"))); this.WaitStart = ((System.Windows.VisualState)(this.FindName("WaitStart"))); this.StartGame = ((System.Windows.VisualState)(this.FindName("StartGame"))); this.ShowGameOver = ((System.Windows.VisualState)(this.FindName("ShowGameOver"))); this.Levels = ((System.Windows.VisualStateGroup)(this.FindName("Levels"))); this.Level1 = ((System.Windows.VisualState)(this.FindName("Level1"))); this.Level2 = ((System.Windows.VisualState)(this.FindName("Level2"))); this.Level3 = ((System.Windows.VisualState)(this.FindName("Level3"))); this.GameOverLevel = ((System.Windows.VisualState)(this.FindName("GameOverLevel"))); this.BeeHive = ((System.Windows.Controls.Canvas)(this.FindName("BeeHive"))); this.gameEnvironment = ((BeeHive.GameEnvironment)(this.FindName("gameEnvironment"))); this.background = ((System.Windows.Shapes.Path)(this.FindName("background"))); this.grid = ((System.Windows.Controls.Image)(this.FindName("grid"))); this.levelHostControl = ((BeeHive.LevelHostControl)(this.FindName("levelHostControl"))); this.score = ((System.Windows.Controls.Image)(this.FindName("score"))); this.lives = ((System.Windows.Controls.Image)(this.FindName("lives"))); this.LEFT_WALL = ((System.Windows.Controls.Image)(this.FindName("LEFT_WALL"))); this.TOP_WALL = ((System.Windows.Controls.Image)(this.FindName("TOP_WALL"))); this.RIGHT_WALL = ((System.Windows.Controls.Image)(this.FindName("RIGHT_WALL"))); this.BOTTOM_WALL = ((System.Windows.Controls.Image)(this.FindName("BOTTOM_WALL"))); this.BALL = ((System.Windows.Controls.Image)(this.FindName("BALL"))); this.PADDLE = ((System.Windows.Controls.Image)(this.FindName("PADDLE"))); this.ScoreText = ((System.Windows.Controls.TextBlock)(this.FindName("ScoreText"))); this.LivesText = ((System.Windows.Controls.TextBlock)(this.FindName("LivesText"))); this.ClicktoStart = ((System.Windows.Controls.Image)(this.FindName("ClicktoStart"))); this.GameOver = ((System.Windows.Controls.Image)(this.FindName("GameOver"))); this.LastScoreText = ((System.Windows.Controls.TextBlock)(this.FindName("LastScoreText"))); this.HiScoreText = ((System.Windows.Controls.TextBlock)(this.FindName("HiScoreText"))); this.frame = ((System.Windows.Controls.Grid)(this.FindName("frame"))); this.masterHead = ((System.Windows.Controls.Grid)(this.FindName("masterHead"))); this.masterHead_bg = ((System.Windows.Shapes.Rectangle)(this.FindName("masterHead_bg"))); this.footer = ((System.Windows.Shapes.Rectangle)(this.FindName("footer"))); } } }
45.253247
152
0.648874
[ "Apache-2.0" ]
liteboho123/Smash_Block_Game
SmashTheBlock/BeeHive/obj/Debug/MainPage.g.cs
6,971
C#
using System; using NpcService.Ai.NpcType; namespace NpcService.Ai.NpcCitizen { public class InnadrileDfTeleporter1 : Citizen { } }
14.5
49
0.731034
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
dr3dd/L2Interlude
NpcService/Ai/NpcCitizen/InnadrileDfTeleporter1.cs
145
C#
namespace OneTwoOne.Infrastructure.Models { public abstract class EntityBaseWithTypedId<TId> : ValidatableObject, IEntityWithTypedId<TId> { public virtual TId Id { get; protected set; } } }
26.375
97
0.720379
[ "Apache-2.0" ]
microcapital/one2one
src/OneTwoOne.Infrastructure/Models/EntityBaseWithTypedId.cs
213
C#
 namespace Consumption.EFCore { using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; /// <summary> /// Extension methods for setting up unit of work related services in an <see cref="IServiceCollection"/>. /// </summary> public static class UnitOfWorkServiceCollectionExtensions { /// <summary> /// Registers the unit of work given context as a service in the <see cref="IServiceCollection"/>. /// </summary> /// <typeparam name="TContext">The type of the db context.</typeparam> /// <param name="services">The <see cref="IServiceCollection"/> to add services to.</param> /// <returns>The same service collection so that multiple calls can be chained.</returns> /// <remarks> /// This method only support one db context, if been called more than once, will throw exception. /// </remarks> public static IServiceCollection AddUnitOfWork<TContext>(this IServiceCollection services) where TContext : DbContext { services.AddScoped<IRepositoryFactory, UnitOfWork<TContext>>(); // Following has a issue: IUnitOfWork cannot support multiple dbcontext/database, // that means cannot call AddUnitOfWork<TContext> multiple times. // Solution: check IUnitOfWork whether or null services.AddScoped<IUnitOfWork, UnitOfWork<TContext>>(); services.AddScoped<IUnitOfWork<TContext>, UnitOfWork<TContext>>(); return services; } /// <summary> /// Registers the unit of work given context as a service in the <see cref="IServiceCollection"/>. /// </summary> /// <typeparam name="TContext1">The type of the db context.</typeparam> /// <typeparam name="TContext2">The type of the db context.</typeparam> /// <param name="services">The <see cref="IServiceCollection"/> to add services to.</param> /// <returns>The same service collection so that multiple calls can be chained.</returns> /// <remarks> /// This method only support one db context, if been called more than once, will throw exception. /// </remarks> public static IServiceCollection AddUnitOfWork<TContext1, TContext2>(this IServiceCollection services) where TContext1 : DbContext where TContext2 : DbContext { services.AddScoped<IUnitOfWork<TContext1>, UnitOfWork<TContext1>>(); services.AddScoped<IUnitOfWork<TContext2>, UnitOfWork<TContext2>>(); return services; } /// <summary> /// Registers the unit of work given context as a service in the <see cref="IServiceCollection"/>. /// </summary> /// <typeparam name="TContext1">The type of the db context.</typeparam> /// <typeparam name="TContext2">The type of the db context.</typeparam> /// <typeparam name="TContext3">The type of the db context.</typeparam> /// <param name="services">The <see cref="IServiceCollection"/> to add services to.</param> /// <returns>The same service collection so that multiple calls can be chained.</returns> /// <remarks> /// This method only support one db context, if been called more than once, will throw exception. /// </remarks> public static IServiceCollection AddUnitOfWork<TContext1, TContext2, TContext3>(this IServiceCollection services) where TContext1 : DbContext where TContext2 : DbContext where TContext3 : DbContext { services.AddScoped<IUnitOfWork<TContext1>, UnitOfWork<TContext1>>(); services.AddScoped<IUnitOfWork<TContext2>, UnitOfWork<TContext2>>(); services.AddScoped<IUnitOfWork<TContext3>, UnitOfWork<TContext3>>(); return services; } /// <summary> /// Registers the unit of work given context as a service in the <see cref="IServiceCollection"/>. /// </summary> /// <typeparam name="TContext1">The type of the db context.</typeparam> /// <typeparam name="TContext2">The type of the db context.</typeparam> /// <typeparam name="TContext3">The type of the db context.</typeparam> /// <typeparam name="TContext4">The type of the db context.</typeparam> /// <param name="services">The <see cref="IServiceCollection"/> to add services to.</param> /// <returns>The same service collection so that multiple calls can be chained.</returns> /// <remarks> /// This method only support one db context, if been called more than once, will throw exception. /// </remarks> public static IServiceCollection AddUnitOfWork<TContext1, TContext2, TContext3, TContext4>(this IServiceCollection services) where TContext1 : DbContext where TContext2 : DbContext where TContext3 : DbContext where TContext4 : DbContext { services.AddScoped<IUnitOfWork<TContext1>, UnitOfWork<TContext1>>(); services.AddScoped<IUnitOfWork<TContext2>, UnitOfWork<TContext2>>(); services.AddScoped<IUnitOfWork<TContext3>, UnitOfWork<TContext3>>(); services.AddScoped<IUnitOfWork<TContext4>, UnitOfWork<TContext4>>(); return services; } /// <summary> /// Registers the custom repository as a service in the <see cref="IServiceCollection"/>. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <typeparam name="TRepository">The type of the custom repositry.</typeparam> /// <param name="services">The <see cref="IServiceCollection"/> to add services to.</param> /// <returns>The same service collection so that multiple calls can be chained.</returns> public static IServiceCollection AddCustomRepository<TEntity, TRepository>(this IServiceCollection services) where TEntity : class where TRepository : class, IRepository<TEntity> { services.AddScoped<IRepository<TEntity>, TRepository>(); return services; } } }
52.336134
132
0.647238
[ "MIT" ]
AngelBye/WPF-Examples
src/Consumption/Consumption.EFCore/UnitOfWorkServiceCollectionExtensions.cs
6,230
C#
using System.Linq; using NBitcoin; using Xels.Bitcoin.Features.RPC; using Xels.Bitcoin.Features.Wallet; using Xels.Bitcoin.IntegrationTests.Common; using Xels.Bitcoin.IntegrationTests.Common.EnvironmentMockUpHelpers; using Xels.Bitcoin.IntegrationTests.Common.ReadyData; using Xels.Bitcoin.Networks; using Xels.Bitcoin.Tests.Common; using Xunit; namespace Xels.Bitcoin.IntegrationTests.RPC { public class RawTransactionTests { private readonly Network network; public RawTransactionTests() { this.network = new XlcRegTest(); } private Money GetTotalInputValue(CoreNode node, Transaction fundedTransaction) { Money totalInputs = 0; foreach (TxIn input in fundedTransaction.Inputs) { Transaction inputSource = node.CreateRPCClient().GetRawTransaction(input.PrevOut.Hash); TxOut prevOut = inputSource.Outputs[input.PrevOut.N]; totalInputs += prevOut.Value; } return totalInputs; } /// <summary> /// Common checks that need to be performed on all funded raw transactions. /// As we cannot broadcast them to fully validate them these primarily relate to the choice of inputs. /// </summary> /// <returns>The computed fee amount.</returns> private Money CheckFunding(CoreNode node, Transaction fundedTransaction) { Assert.NotNull(fundedTransaction); Assert.NotEmpty(fundedTransaction.Inputs); // Need to check that the found inputs adequately fund the outputs. Money totalOutputs = fundedTransaction.TotalOut; Money totalInputs = this.GetTotalInputValue(node, fundedTransaction); Assert.True(totalInputs >= totalOutputs); // Return the computed fee as a convenience to the caller. return totalInputs - totalOutputs; } [Fact] public void CanFundRawTransactionWithoutOptions() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode node = builder.CreateXelsPosNode(this.network).WithReadyBlockchainData(ReadyBlockchain.XlcRegTest150Miner).Start(); var tx = this.network.CreateTransaction(); var dest = new Key().ScriptPubKey; tx.Outputs.Add(new TxOut(Money.Coins(1.0m), dest)); FundRawTransactionResponse funded = node.CreateRPCClient().FundRawTransaction(tx); Money fee = CheckFunding(node, funded.Transaction); Assert.Equal(new Money(this.network.MinRelayTxFee), fee); Assert.True(funded.ChangePos > -1); } } [Fact] public void CanFundRawTransactionWithChangeAddressSpecified() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode node = builder.CreateXelsPosNode(this.network).WithReadyBlockchainData(ReadyBlockchain.XlcRegTest150Miner).Start(); var tx = this.network.CreateTransaction(); var dest = new Key().ScriptPubKey; tx.Outputs.Add(new TxOut(Money.Coins(1.0m), dest)); // We specifically don't want to use the first available account as that is where the node has been mining to, and that is where the // fundrawtransaction RPC will by default get a change address from. // TODO: Investigate why WithReadyBlockchainData is not setting the node.WalletName and node.WalletPassword fields var account = node.FullNode.WalletManager().GetUnusedAccount("mywallet", "password"); var walletAccountReference = new WalletAccountReference("mywallet", account.Name); var changeAddress = node.FullNode.WalletManager().GetUnusedChangeAddress(walletAccountReference); var options = new FundRawTransactionOptions() { ChangeAddress = BitcoinAddress.Create(changeAddress.Address, this.network).ToString() }; FundRawTransactionResponse funded = node.CreateRPCClient().FundRawTransaction(tx, options); Money fee = CheckFunding(node, funded.Transaction); Assert.Equal(new Money(this.network.MinRelayTxFee), fee); Assert.True(funded.ChangePos > -1); } } [Fact] public void CanFundRawTransactionWithChangePositionSpecified() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode node = builder.CreateXelsPosNode(this.network).WithReadyBlockchainData(ReadyBlockchain.XlcRegTest150Miner).Start(); var tx = this.network.CreateTransaction(); tx.Outputs.Add(new TxOut(Money.Coins(1.1m), new Key().ScriptPubKey)); tx.Outputs.Add(new TxOut(Money.Coins(1.2m), new Key().ScriptPubKey)); tx.Outputs.Add(new TxOut(Money.Coins(1.3m), new Key().ScriptPubKey)); tx.Outputs.Add(new TxOut(Money.Coins(1.4m), new Key().ScriptPubKey)); Money totalSent = tx.TotalOut; // We specifically don't want to use the first available account as that is where the node has been mining to, and that is where the // fundrawtransaction RPC will by default get a change address from. var account = node.FullNode.WalletManager().GetUnusedAccount("mywallet", "password"); var walletAccountReference = new WalletAccountReference("mywallet", account.Name); var changeAddress = node.FullNode.WalletManager().GetUnusedChangeAddress(walletAccountReference); var options = new FundRawTransactionOptions() { ChangeAddress = BitcoinAddress.Create(changeAddress.Address, this.network).ToString(), ChangePosition = 2 }; FundRawTransactionResponse funded = node.CreateRPCClient().FundRawTransaction(tx, options); Money fee = this.CheckFunding(node, funded.Transaction); Money totalInputs = this.GetTotalInputValue(node, funded.Transaction); Assert.Equal(new Money(this.network.MinRelayTxFee), fee); Assert.Equal(2, funded.ChangePos); Assert.Equal(changeAddress.ScriptPubKey, funded.Transaction.Outputs[funded.ChangePos].ScriptPubKey); // Check that the value of the change in the specified position is the expected value. Assert.Equal(totalInputs - totalSent - fee, funded.Transaction.Outputs[funded.ChangePos].Value); } } [Fact] public void CanSignRawTransaction() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode node = builder.CreateXelsPosNode(this.network).WithReadyBlockchainData(ReadyBlockchain.XlcRegTest150Miner).Start(); var tx = this.network.CreateTransaction(); tx.Outputs.Add(new TxOut(Money.Coins(1.0m), new Key())); FundRawTransactionResponse funded = node.CreateRPCClient().FundRawTransaction(tx); node.CreateRPCClient().WalletPassphrase("password", 600); Transaction signed = node.CreateRPCClient().SignRawTransaction(funded.Transaction); Assert.NotNull(signed); Assert.NotEmpty(signed.Inputs); foreach (var input in signed.Inputs) { Assert.NotNull(input.ScriptSig); // Basic sanity check that the transaction has actually been signed. // A segwit transaction would fail this check but we aren't checking that here. // In any case, the mempool count test shows definitively if the transaction passes validation. Assert.NotEqual(input.ScriptSig, Script.Empty); } node.CreateRPCClient().SendRawTransaction(signed); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length == 1); TestHelper.MineBlocks(node, 1); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length == 0); } } [Fact] public void CannotSignRawTransactionWithUnownedUtxo() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode node = builder.CreateXelsPosNode(this.network).WithReadyBlockchainData(ReadyBlockchain.XlcRegTest150Miner).Start(); CoreNode node2 = builder.CreateXelsPosNode(this.network).WithWallet().Start(); TestHelper.ConnectAndSync(node, node2); TestBase.WaitLoop(() => node2.CreateRPCClient().GetBlockCount() >= 150); (HdAddress addressUsed, _) = TestHelper.MineBlocks(node2, 1); TransactionData otherFunds = addressUsed.Transactions.First(); var tx = this.network.CreateTransaction(); tx.Outputs.Add(new TxOut(Money.Coins(1.0m), new Key())); FundRawTransactionResponse funded = node.CreateRPCClient().FundRawTransaction(tx); // Add an additional (and unnecessary, but that doesn't matter) input belonging to the second node's wallet that the first node will not be able to sign for. funded.Transaction.Inputs.Add(new TxIn(new OutPoint(otherFunds.Id, otherFunds.Index))); node.CreateRPCClient().WalletPassphrase("password", 600); Assert.Throws<RPCException>(() => node.CreateRPCClient().SignRawTransaction(funded.Transaction)); } } } }
45.486239
173
0.62616
[ "MIT" ]
xels-io/SideChain-SmartContract
src/Xels.Bitcoin.IntegrationTests/RPC/RawTransactionTests.cs
9,918
C#
/*---------------------------------------------------------------- Copyright (C) 2001 R&R Soft - All rights reserved. author: Roberto Oliveira Jucá ----------------------------------------------------------------*/ //----- Include using System.ComponentModel.Composition; using rr.Library.Infrastructure; using Shared.Message; using Layout.Drawer.Shell.Presentation; using Layout.Drawer.Shell.Pattern.Models; //---------------------------// namespace Layout.Drawer.Shell.Pattern.ViewModels { [Export ("ShellFactoryViewModel", typeof (IShellFactoryViewModel))] public class TShellFactoryViewModel : TViewModelAware<TShellFactoryModel>, IHandleNavigateResponse, IShellFactoryViewModel { #region Constructor [ImportingConstructor] public TShellFactoryViewModel (IShellPresentation presentation) : base (new TShellFactoryModel ()) { presentation.RequestPresentationCommand (this); presentation.EventSubscribe (this); } #endregion #region IHandle public void Handle (TNavigateResponseMessage message) { if (message.IsActionNavigateTo) { if (message.IsSender (TNavigateMessage.TSender.Shell)) { if (message.IsWhere (TNavigateMessage.TWhere.Factory)) { ShowViewAnimation (); } else { HideViewAnimation (); } } } } #endregion #region Property IDelegateCommand DelegateCommand { get { return (PresentationCommand as IDelegateCommand); } } #endregion }; //---------------------------// } // namespace
26.540984
124
0.594812
[ "MIT" ]
robjuca/Suite
Layout/Drawer/Suite.Layout.Drawer/Shell/Pattern/ViewModels/ShellFactoryViewModel.cs
1,622
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class DynamicTypeSymbol : TypeSymbol, IDynamicTypeSymbol { internal static readonly DynamicTypeSymbol Instance = new DynamicTypeSymbol(); private DynamicTypeSymbol() { } public override string Name { get { return "dynamic"; } } public override bool IsAbstract { get { return false; } } public override bool IsReferenceType { get { return true; } } public override bool IsSealed { get { return false; } } public override SymbolKind Kind { get { return SymbolKind.DynamicType; } } public override TypeKind TypeKind { get { return TypeKind.Dynamic; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => null; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) { return ImmutableArray<NamedTypeSymbol>.Empty; } public override bool IsStatic { get { return false; } } public override bool IsValueType { get { return false; } } internal sealed override bool IsManagedType { get { return true; } } public sealed override bool IsRefLikeType { get { return false; } } internal sealed override bool IsReadOnly { get { return false; } } internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } public override ImmutableArray<Symbol> GetMembers() { return ImmutableArray<Symbol>.Empty; } public override ImmutableArray<Symbol> GetMembers(string name) { return ImmutableArray<Symbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitDynamicType(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitDynamicType(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitDynamicType(this); } public override Symbol ContainingSymbol { get { return null; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { return false; } public override int GetHashCode() { // return the distinguished value for 'object' because the hash code ignores the distinction // between dynamic and object. It also ignores custom modifiers. return (int)Microsoft.CodeAnalysis.SpecialType.System_Object; } internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if ((object)t2 == null) { return false; } if (ReferenceEquals(this, t2) || t2.TypeKind == TypeKind.Dynamic) { return true; } if ((comparison & TypeCompareKind.IgnoreDynamic) != 0) { var other = t2 as NamedTypeSymbol; return (object)other != null && other.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object; } return false; } internal override void AddNullableTransforms(ArrayBuilder<byte> transforms) { } internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result) { result = this; return true; } internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeSymbolWithAnnotations, TypeSymbolWithAnnotations> transform) { return this; } internal override TypeSymbol MergeNullability(TypeSymbol other, VarianceKind variance) { Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); return this; } #region ISymbol Members public override void Accept(SymbolVisitor visitor) { visitor.VisitDynamicType(this); } public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitDynamicType(this); } #endregion } }
26.078125
161
0.553925
[ "Apache-2.0" ]
Therzok/roslyn
src/Compilers/CSharp/Portable/Symbols/DynamicTypeSymbol.cs
6,678
C#
using UnityEngine; namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Edge Detection/Edge Detection")] public class EdgeDetection : PostEffectsBase { public enum EdgeDetectMode { TriangleDepthNormals = 0, RobertsCrossDepthNormals = 1, SobelDepth = 2, SobelDepthThin = 3, TriangleLuminance = 4, } public EdgeDetectMode mode = EdgeDetectMode.SobelDepthThin; public float sensitivityDepth = 1.0f; public float sensitivityNormals = 1.0f; public float lumThreshold = 0.2f; public float edgeExp = 1.0f; public float sampleDist = 1.0f; public float edgesOnly = 0.0f; public Color edgesOnlyBgColor = Color.white; public Shader edgeDetectShader; private Material edgeDetectMaterial = null; private EdgeDetectMode oldMode = EdgeDetectMode.SobelDepthThin; public override bool CheckResources() { CheckSupport(true); edgeDetectMaterial = CheckShaderAndCreateMaterial(edgeDetectShader, edgeDetectMaterial); if (mode != oldMode) SetCameraFlag(); oldMode = mode; if (!isSupported) ReportAutoDisable(); return isSupported; } new void Start() { oldMode = mode; } void SetCameraFlag() { if (mode == EdgeDetectMode.SobelDepth || mode == EdgeDetectMode.SobelDepthThin) GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth; else if (mode == EdgeDetectMode.TriangleDepthNormals || mode == EdgeDetectMode.RobertsCrossDepthNormals) GetComponent<Camera>().depthTextureMode |= DepthTextureMode.DepthNormals; } void OnEnable() { SetCameraFlag(); } [ImageEffectOpaque] void OnRenderImage(RenderTexture source, RenderTexture destination) { if (CheckResources() == false) { Graphics.Blit(source, destination); return; } Vector2 sensitivity = new Vector2(sensitivityDepth, sensitivityNormals); edgeDetectMaterial.SetVector("_Sensitivity", new Vector4(sensitivity.x, sensitivity.y, 1.0f, sensitivity.y)); edgeDetectMaterial.SetFloat("_BgFade", edgesOnly); edgeDetectMaterial.SetFloat("_SampleDistance", sampleDist); edgeDetectMaterial.SetVector("_BgColor", edgesOnlyBgColor); edgeDetectMaterial.SetFloat("_Exponent", edgeExp); edgeDetectMaterial.SetFloat("_Threshold", lumThreshold); Graphics.Blit(source, destination, edgeDetectMaterial, (int)mode); } } }
32.674157
121
0.614512
[ "MIT" ]
CDAGaming/RetroTVFX
Assets/Standard Assets/Effects/ImageEffects/Scripts/EdgeDetection.cs
2,908
C#
namespace MAVN.Service.WalletManagement.Settings { public class Constants { public string TokenSymbol { get; set; } public string TokenFormatCultureInfo { get; set; } public int TokenNumberDecimalPlaces { get; set; } public string TokenIntegerPartFormat { get; set; } } }
22.785714
58
0.664577
[ "MIT" ]
HannaAndreevna/MAVN.Service.WalletManagement
src/MAVN.Service.WalletManagement/Settings/Constants.cs
319
C#