commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
d7f8ba0b908563b7034f82363125ef79ad83e0ab
Remove deprecated
StanJav/language-ext,StefanBertels/language-ext,louthy/language-ext
LanguageExt.Process/Strategy/IProcessStrategy.cs
LanguageExt.Process/Strategy/IProcessStrategy.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LanguageExt { public interface IProcessStrategy { /// <summary> /// Handler function for a Process thrown exception /// </summary> /// <param name="pid">Failed process ID </param> /// <param name="state">Failed process strategy state</param> /// <param name="ex">Exception</param> /// <returns>Directive to invoke to handle the failure and the possibly modified state</returns> Tuple<IProcessStrategyState, Directive> HandleFailure(ProcessId pid, IProcessStrategyState state, Exception ex); /// <summary> /// Generate a new strategy state-object for a Process /// </summary> /// <param name="pid">Process ID</param> /// <returns>IProcessStrategyState</returns> IProcessStrategyState NewState(ProcessId pid); /// <summary> /// Returns the processes that are to be affected by the failure of /// the 'failedProcess' process. /// </summary> /// <remarks> /// 'failedProcess' itself will always be included regardless of what Affects returns /// </remarks> /// <param name="supervisor">Supervisor of the failed process</param> /// <param name="failedProcess">The process that has failed</param> /// <returns>Enumerable of processes to apply the directive to upon failure</returns> IEnumerable<ProcessId> Affects(ProcessId supervisor, ProcessId failedProcess, IEnumerable<ProcessId> supervisorChildren); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LanguageExt { public interface IProcessStrategy { /// <summary> /// Handler function for a Process thrown exception /// </summary> /// <param name="pid">Failed process ID </param> /// <param name="state">Failed process strategy state</param> /// <param name="ex">Exception</param> /// <returns>Directive to invoke to handle the failure and the possibly modified state</returns> Tuple<IProcessStrategyState, Directive> HandleFailure(ProcessId pid, IProcessStrategyState state, Exception ex); /// <summary> /// Generate a new strategy state-object for a Process /// </summary> /// <param name="pid">Process ID</param> /// <returns>IProcessStrategyState</returns> IProcessStrategyState NewState(ProcessId pid); /// <summary> /// Returns the processes that are to be affected by the failure of /// the 'failedProcess' process. /// </summary> /// <remarks> /// 'failedProcess' itself will always be included regardless of what Affects returns /// </remarks> /// <param name="supervisor">Supervisor of the failed process</param> /// <param name="failedProcess">The process that has failed</param> /// <returns>Enumerable of processes to apply the directive to upon failure</returns> IEnumerable<ProcessId> Affects(ProcessId supervisor, ProcessId failedProcess, IEnumerable<ProcessId> supervisorChildren); } public interface IProcessStrategy<TState> : IProcessStrategy where TState : IProcessStrategyState { } }
mit
C#
22ac0888b7755a60388651780e952e308f5f71a6
Update BinanceConvertTransferRecord.cs
JKorf/Binance.Net
Binance.Net/Objects/Models/Spot/ConvertTransfer/BinanceConvertTransferRecord.cs
Binance.Net/Objects/Models/Spot/ConvertTransfer/BinanceConvertTransferRecord.cs
using CryptoExchange.Net.Converters; using Newtonsoft.Json; using System; namespace Binance.Net.Objects.Models.Spot.ConvertTransfer { /// <summary> /// Result of a convert transfer operation /// </summary> public class BinanceConvertTransferRecord { /// <summary> /// Transfer id /// </summary> [JsonProperty("tranId")] public long TransferId { get; set; } /// <summary> /// Status of the transfer (definitions currently unknown) /// </summary> public string Status { get; set; } = string.Empty; /// <summary> /// Timestamp /// </summary> [JsonConverter(typeof(DateTimeConverter))] public DateTime Time { get; set; } /// <summary> /// Type /// </summary> public int Type { get; set; } /// <summary> /// Deducted asset /// </summary> public string DeductedAsset { get; set; } = string.Empty; /// <summary> /// Deducted quantity /// </summary> [JsonProperty("deductedAmount")] public decimal DeductedQuantity { get; set; } /// <summary> /// Target asset /// </summary> public string TargetAsset { get; set; } = string.Empty; /// <summary> /// Target quantity /// </summary> [JsonProperty("targetAmount")] public decimal TargetQuantity { get; set; } /// <summary> /// Account type /// </summary> public string AccountType { get; set; } = string.Empty; } }
using CryptoExchange.Net.Converters; using Newtonsoft.Json; using System; namespace Binance.Net.Objects.Models.Spot.ConvertTransfer { /// <summary> /// Result of a convert transfer operation /// </summary> public class BinanceConvertTransferRecord { /// <summary> /// Transfer id /// </summary> [JsonProperty("tranId")] public long TransferId { get; set; } /// <summary> /// Status of the transfer (definitions currently unknown) /// </summary> public string Status { get; set; } = string.Empty; /// <summary> /// Timestamp /// </summary> [JsonConverter(typeof(DateTimeConverter))] public DateTime Time { get; set; } /// <summary> /// Type /// </summary> public int Type { get; set; } /// <summary> /// Deducted asset /// </summary> public string DeductedAsset { get; set; } = string.Empty; /// <summary> /// Deducted quantity /// </summary> public decimal DeductedQuantity { get; set; } /// <summary> /// Target asset /// </summary> public string TargetAsset { get; set; } = string.Empty; /// <summary> /// Target quantity /// </summary> [JsonProperty("targetAmount")] public decimal TargetQuantity { get; set; } /// <summary> /// Account type /// </summary> public string AccountType { get; set; } = string.Empty; } }
mit
C#
ee7bb8555cfc35bc07630c9f6f2b070c4af26970
Update AssemblyInfo.cs
Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal
Master/Appleseed/Projects/PortableAreas/MemberInvite/Properties/AssemblyInfo.cs
Master/Appleseed/Projects/PortableAreas/MemberInvite/Properties/AssemblyInfo.cs
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("MemberInvite")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ANANT Corporation")] [assembly: AssemblyProduct("MemberInvite")] [assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")] [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("a253f79d-1922-4ba1-b48e-339c41da5feb")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.4.98.383")] [assembly: AssemblyFileVersion("1.4.98.383")]
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("MemberInvite")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ANANT Corporation")] [assembly: AssemblyProduct("MemberInvite")] [assembly: AssemblyCopyright("Copyright © ANANT Corporation 2017")] [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("a253f79d-1922-4ba1-b48e-339c41da5feb")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.3.69.342")] [assembly: AssemblyFileVersion("1.3.68.342")]
apache-2.0
C#
3b0b85e2232506f94ecd8ac752e32ef58832efec
Add NUL to invalid characters
villermen/runescape-cache-tools,villermen/runescape-cache-tools
RuneScapeCacheTools/Extensions/PathExtensions.cs
RuneScapeCacheTools/Extensions/PathExtensions.cs
using System; namespace Villermen.RuneScapeCacheTools.Extensions { public static class PathExtensions { public static char[] InvalidCharacters = { '/', ':', '"', '*', '?', '>', '<', '|', '\0' }; /// <summary> /// Parses the given directory and unifies its format, to be applied to unpredictable user input. /// Converts backslashes to forward slashes, and appends a directory separator. /// </summary> /// <param name="path"></param> /// <returns></returns> public static string FixDirectory(string path) { // Expand environment variables var result = Environment.ExpandEnvironmentVariables(path); // Replace backslashes with forward slashes result = result.Replace('\\', '/'); // Add trailing slash if not present if (!result.EndsWith("/")) { result += "/"; } return result; } } }
using System; namespace Villermen.RuneScapeCacheTools.Extensions { public static class PathExtensions { public static char[] InvalidCharacters = { '/', ':', '"', '*', '?', '>', '<', '|' }; /// <summary> /// Parses the given directory and unifies its format, to be applied to unpredictable user input. /// Converts backslashes to forward slashes, and appends a directory separator. /// </summary> /// <param name="path"></param> /// <returns></returns> public static string FixDirectory(string path) { // Expand environment variables var result = Environment.ExpandEnvironmentVariables(path); // Replace backslashes with forward slashes result = result.Replace('\\', '/'); // Add trailing slash if not present if (!result.EndsWith("/")) { result += "/"; } return result; } } }
mit
C#
d32a35a4988dd716f7b8060d3152cf9a7f128740
Fix mod selection binding
asarium/FSOLauncher
UI/WPF/Modules/UI.WPF.Modules.Installation/ViewModels/Mods/ModGroupViewModel.cs
UI/WPF/Modules/UI.WPF.Modules.Installation/ViewModels/Mods/ModGroupViewModel.cs
#region Usings using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using ModInstallation.Interfaces.Mods; using ReactiveUI; using Semver; using UI.WPF.Launcher.Common.Classes; #endregion namespace UI.WPF.Modules.Installation.ViewModels.Mods { public class ModGroupViewModel : ReactiveObjectBase { private readonly IModGroup _group; private ModViewModel _currentMod; private bool? _isSelected; private SemVersion _selectedVersion; public IEnumerable<SemVersion> Versions { get; private set; } public bool HasMultipleVersions { get; private set; } public ModGroupViewModel(IModGroup group, InstallationTabViewModel installationTabViewModel) { InstallationTabViewModel = installationTabViewModel; _group = @group; this.WhenAnyValue(x => x.SelectedVersion) .Where(x => x != null && _group.Versions.ContainsKey(x)) .Select(x => new ModViewModel(_group.Versions[x], installationTabViewModel)) .BindTo(this, x => x.CurrentMod); // When selected changes, propagate to the mod view model this.WhenAnyValue(x => x.CurrentMod.ModSelected).BindTo(this, x => x.IsSelected); this.WhenAnyValue(x => x.IsSelected).BindTo(this, x => x.CurrentMod.ModSelected); SelectedVersion = _group.Versions.Keys.Max(); Versions = group.Versions.Keys.OrderByDescending(x => x).ToList(); HasMultipleVersions = Versions.Count() > 1; } public InstallationTabViewModel InstallationTabViewModel { get; set; } public bool? IsSelected { get { return _isSelected; } set { RaiseAndSetIfPropertyChanged(ref _isSelected, value); } } public SemVersion SelectedVersion { get { return _selectedVersion; } set { RaiseAndSetIfPropertyChanged(ref _selectedVersion, value); } } public ModViewModel CurrentMod { get { return _currentMod; } private set { RaiseAndSetIfPropertyChanged(ref _currentMod, value); } } public IModGroup Group { get { return _group; } } } }
#region Usings using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using ModInstallation.Interfaces.Mods; using ReactiveUI; using Semver; using UI.WPF.Launcher.Common.Classes; #endregion namespace UI.WPF.Modules.Installation.ViewModels.Mods { public class ModGroupViewModel : ReactiveObjectBase { private readonly IModGroup _group; private ModViewModel _currentMod; private bool? _isSelected; private SemVersion _selectedVersion; public IEnumerable<SemVersion> Versions { get; private set; } public bool HasMultipleVersions { get; private set; } public ModGroupViewModel(IModGroup group, InstallationTabViewModel installationTabViewModel) { InstallationTabViewModel = installationTabViewModel; _group = @group; this.WhenAnyValue(x => x.SelectedVersion) .Where(x => x != null && _group.Versions.ContainsKey(x)) .Select(x => new ModViewModel(_group.Versions[x], installationTabViewModel)) .BindTo(this, x => x.CurrentMod); // When the current mod changes, use the old value from the group to initialize the selection status this.WhenAnyValue(x => x.CurrentMod).Where(x => x != null).Subscribe(newMod => newMod.ModSelected = IsSelected); // When selected changes, propagate to the mod view model this.WhenAnyValue(x => x.IsSelected).BindTo(this, x => x.CurrentMod.ModSelected); this.WhenAnyValue(x => x.CurrentMod.ModSelected).BindTo(this, x => x.IsSelected); SelectedVersion = _group.Versions.Keys.Max(); Versions = group.Versions.Keys.OrderByDescending(x => x).ToList(); HasMultipleVersions = Versions.Count() > 1; } public InstallationTabViewModel InstallationTabViewModel { get; set; } public bool? IsSelected { get { return _isSelected; } set { RaiseAndSetIfPropertyChanged(ref _isSelected, value); } } public SemVersion SelectedVersion { get { return _selectedVersion; } set { RaiseAndSetIfPropertyChanged(ref _selectedVersion, value); } } public ModViewModel CurrentMod { get { return _currentMod; } private set { RaiseAndSetIfPropertyChanged(ref _currentMod, value); } } public IModGroup Group { get { return _group; } } } }
mit
C#
64dc63f54ee96972d522c6b9bae173da87584fc3
Add License
chraft/c-raft
Chraft/World/NBT/TagNodeListNamed.cs
Chraft/World/NBT/TagNodeListNamed.cs
/* Minecraft NBT reader * * Copyright 2010-2011 Michael Ong, all rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using System.Collections.Generic; namespace Chraft.World.NBT { /// <summary> /// Represents a sequential named custom TAG_TYPE list. /// </summary> public class TagNodeListNamed : Dictionary<string, INBTTag>, INBTTag { private string _name; /// <summary> /// Gets the name of the list. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } /// <summary> /// Gets the value (payload) of the list. /// </summary> public dynamic Payload { get { return this; } set { throw new NotImplementedException(); } } /// <summary> /// Simply returns a TAG_COMPOUND when called. /// </summary> public TagNodeType Type { get { return TagNodeType.TAG_COMPOUND; } set { throw new NotImplementedException(); } } /// <summary> /// Creates a new TagNodeListNamed. /// </summary> /// <param name="name">The name of the list.</param> public TagNodeListNamed(string name) : base() { this._name = name; } } }
using System; using System.Collections.Generic; namespace Chraft.World.NBT { /// <summary> /// Represents a sequential named custom TAG_TYPE list. /// </summary> public class TagNodeListNamed : Dictionary<string, INBTTag>, INBTTag { private string _name; /// <summary> /// Gets the name of the list. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } /// <summary> /// Gets the value (payload) of the list. /// </summary> public dynamic Payload { get { return this; } set { throw new NotImplementedException(); } } /// <summary> /// Simply returns a TAG_COMPOUND when called. /// </summary> public TagNodeType Type { get { return TagNodeType.TAG_COMPOUND; } set { throw new NotImplementedException(); } } /// <summary> /// Creates a new TagNodeListNamed. /// </summary> /// <param name="name">The name of the list.</param> public TagNodeListNamed(string name) : base() { this._name = name; } } }
agpl-3.0
C#
36a00f700a3bb83e090da89c2d787d45988d96d7
Delete unnecessary line breaks.
t-miyake/OutlookOkan
OutlookAddIn/ThisAddIn.cs
OutlookAddIn/ThisAddIn.cs
using Outlook = Microsoft.Office.Interop.Outlook; using System.Windows.Forms; namespace OutlookAddIn { public partial class ThisAddIn { private void ThisAddIn_Startup(object sender, System.EventArgs e) { Application.ItemSend += Application_ItemSend; } public void Application_ItemSend(object item, ref bool cancel) { var mail = item as Outlook.MailItem; var confirmWindow = new ConfirmWindow(mail); var dialogResult = confirmWindow.ShowDialog(); confirmWindow.Dispose(); if(dialogResult == DialogResult.OK) { //メールを送信。 }else if (dialogResult == DialogResult.Cancel) { cancel = true; } } private void ThisAddIn_Shutdown(object sender, System.EventArgs e) { //注: Outlook はこのイベントを発行しなくなりました。Outlook が // シャットダウンする際に実行が必要なコードがある場合は、http://go.microsoft.com/fwlink/?LinkId=506785 を参照してください。 } #region VSTO で生成されたコード /// <summary> /// デザイナーのサポートに必要なメソッドです。 /// このメソッドの内容をコード エディターで変更しないでください。 /// </summary> private void InternalStartup() { this.Startup += new System.EventHandler(ThisAddIn_Startup); this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); } #endregion } }
using Outlook = Microsoft.Office.Interop.Outlook; using System.Windows.Forms; namespace OutlookAddIn { public partial class ThisAddIn { private void ThisAddIn_Startup(object sender, System.EventArgs e) { Application.ItemSend += Application_ItemSend; } public void Application_ItemSend(object item, ref bool cancel) { var mail = item as Outlook.MailItem; var confirmWindow = new ConfirmWindow(mail); var dialogResult = confirmWindow.ShowDialog(); confirmWindow.Dispose(); if(dialogResult == DialogResult.OK) { //メールを送信。 }else if (dialogResult == DialogResult.Cancel) { cancel = true; } } private void ThisAddIn_Shutdown(object sender, System.EventArgs e) { //注: Outlook はこのイベントを発行しなくなりました。Outlook が // シャットダウンする際に実行が必要なコードがある場合は、http://go.microsoft.com/fwlink/?LinkId=506785 を参照してください。 } #region VSTO で生成されたコード /// <summary> /// デザイナーのサポートに必要なメソッドです。 /// このメソッドの内容をコード エディターで変更しないでください。 /// </summary> private void InternalStartup() { this.Startup += new System.EventHandler(ThisAddIn_Startup); this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); } #endregion } }
apache-2.0
C#
2eb0ad31b066b7358748c87d1ab0290800c77ad9
Use cts pages for routes for now
RikkiGibson/Corvallis-Bus-Server,RikkiGibson/Corvallis-Bus-Server
CorvallisBus.Core/Models/BusRoute.cs
CorvallisBus.Core/Models/BusRoute.cs
using CorvallisBus.Core.Models.Connexionz; using CorvallisBus.Core.Models.GoogleTransit; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace CorvallisBus.Core.Models { /// <summary> /// Represents a CTS Route. /// </summary> public class BusRoute { [JsonConstructor] public BusRoute( string routeNo, List<int> path, string color, string url, string polyline) { RouteNo = routeNo; Path = path; Color = color; Url = url; Polyline = polyline; } public static BusRoute Create(ConnexionzRoute connectionzRoute, Dictionary<string, GoogleRoute> googleRoutes) { var routeNo = connectionzRoute.RouteNo; var googleRoute = googleRoutes[routeNo]; var path = connectionzRoute.Path .Select(platform => platform.PlatformId) .ToList(); var url = "https://www.corvallisoregon.gov/cts/page/cts-route-" + routeNo; return new BusRoute(routeNo, path, googleRoute.Color, url, connectionzRoute.Polyline); } /// <summary> /// Route Number (e.g. 1, 2, NON, CVA, etc). /// </summary> [JsonProperty("routeNo")] public string RouteNo { get; } /// <summary> /// List of stop ids on this route, in the order the bus reaches them. /// </summary> [JsonProperty("path")] public List<int> Path { get; } /// <summary> /// CTS-defined color for this route. /// </summary> [JsonProperty("color")] public string Color { get; } /// <summary> /// URL to the CTS web page for this route. /// </summary> [JsonProperty("url")] public string Url { get; } /// <summary> /// Google maps polyline for this route. /// </summary> [JsonProperty("polyline")] public string Polyline { get; } } }
using CorvallisBus.Core.Models.Connexionz; using CorvallisBus.Core.Models.GoogleTransit; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace CorvallisBus.Core.Models { /// <summary> /// Represents a CTS Route. /// </summary> public class BusRoute { [JsonConstructor] public BusRoute( string routeNo, List<int> path, string color, string url, string polyline) { RouteNo = routeNo; Path = path; Color = color; Url = url; Polyline = polyline; } public static BusRoute Create(ConnexionzRoute connectionzRoute, Dictionary<string, GoogleRoute> googleRoutes) { var routeNo = connectionzRoute.RouteNo; var googleRoute = googleRoutes[routeNo]; var path = connectionzRoute.Path .Select(platform => platform.PlatformId) .ToList(); return new BusRoute(routeNo, path, googleRoute.Color, googleRoute.Url, connectionzRoute.Polyline); } /// <summary> /// Route Number (e.g. 1, 2, NON, CVA, etc). /// </summary> [JsonProperty("routeNo")] public string RouteNo { get; } /// <summary> /// List of stop ids on this route, in the order the bus reaches them. /// </summary> [JsonProperty("path")] public List<int> Path { get; } /// <summary> /// CTS-defined color for this route. /// </summary> [JsonProperty("color")] public string Color { get; } /// <summary> /// URL to the CTS web page for this route. /// </summary> [JsonProperty("url")] public string Url { get; } /// <summary> /// Google maps polyline for this route. /// </summary> [JsonProperty("polyline")] public string Polyline { get; } } }
mit
C#
0a8bfe9ecae4d85b2b741814d1edbaf80af11e93
add Pause and Resume method
endlessz/Flappy-Cube
Assets/Scripts/GameManager.cs
Assets/Scripts/GameManager.cs
using UnityEngine; using System.Collections; using UnityEngine.UI; public enum GameStates{ PREGAME, //State before play INGAME, //State when play and player alive GAMEOVER , //State when player dead } public class GameManager : MonoBehaviour { [Header("Text")] public Text scoreText; public Text newBestScoreText; public Text gameoverScoreText; public Text gameoverBestScoreText; public Text gamesPlayedText; [Header("Canvas UI")] public Canvas pregameCanvas; public Canvas gameoverCanvas; public Canvas ingameCanvas; public Canvas pauseCanvas; [HideInInspector] public static GameManager instance; public GameStates currentState; private int score; void Awake () { instance = this; currentState = GameStates.PREGAME; //Begin with PREGAME state } public void addScore(){ score++; scoreText.text = score.ToString(); } public void startGame(){ currentState = GameStates.INGAME; //Change state to INGAME pregameCanvas.gameObject.SetActive (false); //Hide pregameCanvas ingameCanvas.gameObject.SetActive (true); //Show ingameCanvas PlayerPrefs.SetInt("gamesPlayed", PlayerPrefs.GetInt ("gamesPlayed", 0) + 1 ); } public void gameOver(){ currentState = GameStates.GAMEOVER; checkHighScore (); gamesPlayedText.text += PlayerPrefs.GetInt ("gamesPlayed", 0); gameoverScoreText.text = score.ToString(); gameoverBestScoreText.text += PlayerPrefs.GetInt ("bestscore", 0); StartCoroutine (ShowGameoverCanvas ()); } public void restartGame(){ Application.LoadLevel(Application.loadedLevel); } IEnumerator ShowGameoverCanvas(){ yield return new WaitForSeconds (1.5f); gameoverCanvas.gameObject.SetActive (true); ingameCanvas.gameObject.SetActive (false); } private void checkHighScore(){ if( score > PlayerPrefs.GetInt("bestscore", 0) ) { PlayerPrefs.SetInt("bestscore", score); newBestScoreText.gameObject.SetActive(true); } } public void Pause(){ Time.timeScale = 0; //Change timeScale to 0 pauseCanvas.gameObject.SetActive (true); //Show pauseCanvas } public void Resume(){ Time.timeScale = 1; //Change timeScale to 1 pauseCanvas.gameObject.SetActive (false); //Hide pauseCanvas } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public enum GameStates{ PREGAME, //State before play INGAME, //State when play and player alive GAMEOVER , //State when player dead } public class GameManager : MonoBehaviour { [Header("Text")] public Text scoreText; public Text newBestScoreText; public Text gameoverScoreText; public Text gameoverBestScoreText; public Text gamesPlayedText; [Header("Canvas UI")] public Canvas pregameCanvas; public Canvas gameoverCanvas; public Canvas ingameCanvas; public Canvas pauseCanvas; [HideInInspector] public static GameManager instance; public GameStates currentState; private int score; void Awake () { instance = this; currentState = GameStates.PREGAME; //Begin with PREGAME state } public void addScore(){ score++; scoreText.text = score.ToString(); } public void startGame(){ currentState = GameStates.INGAME; //Change state to INGAME pregameCanvas.gameObject.SetActive (false); //Hide pregameCanvas ingameCanvas.gameObject.SetActive (true); //Show ingameCanvas PlayerPrefs.SetInt("gamesPlayed", PlayerPrefs.GetInt ("gamesPlayed", 0) + 1 ); } public void gameOver(){ currentState = GameStates.GAMEOVER; checkHighScore (); gamesPlayedText.text += PlayerPrefs.GetInt ("gamesPlayed", 0); gameoverScoreText.text = score.ToString(); gameoverBestScoreText.text += PlayerPrefs.GetInt ("bestscore", 0); StartCoroutine (ShowGameoverCanvas ()); } public void restartGame(){ Application.LoadLevel(Application.loadedLevel); } IEnumerator ShowGameoverCanvas(){ yield return new WaitForSeconds (1.5f); gameoverCanvas.gameObject.SetActive (true); ingameCanvas.gameObject.SetActive (false); } private void checkHighScore(){ if( score > PlayerPrefs.GetInt("bestscore", 0) ) { PlayerPrefs.SetInt("bestscore", score); newBestScoreText.gameObject.SetActive(true); } } }
mit
C#
0bebdb70ab13ad560f23e231b8e1e343762124a1
Update Remote.cs
wolfspelz/ConfigSharp
ConfigSharpTester/Configuration/Remote.cs
ConfigSharpTester/Configuration/Remote.cs
//reference "System.Uri, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" using System; namespace ConfigSharpTester.Configuration { class Remote { public static void Run(ConfigSharpTester.MyConfig config) { config.PropertyFromHttpInclude = "Remote value from " + new Uri(config.CurrentFile).PathAndQuery; } } }
#pragma reference "C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll" using System; namespace ConfigSharpTester.Configuration { class Remote { public static void Run(ConfigSharpTester.MyConfig config) { config.PropertyFromHttpInclude = "Remote value from " + new Uri(config.CurrentFile).PathAndQuery; } } }
apache-2.0
C#
e47f6d8935330b547a8ae36e315ab8dde3d57809
Update Form1.cs
Miro382/CSharp_Weather
Examples/WeatherApplication/Form1.cs
Examples/WeatherApplication/Form1.cs
using CSharp_Weather; using System; using System.Diagnostics; using System.Windows.Forms; namespace WeatherApplication { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { /* Weather weather = new Weather("1234567891011121314151617", Weather.Fahrenheit); weather.SetLanguage("en",true); if(weather.GetWeather(weather.GetCountry())) { if(weather.GetWeatherIsSuccessful()) { label2.Text = weather.weatherinfo.Temperature +weather.UnitSymbol(); label4.Text = weather.weatherinfo.Humidity + " " + weather.weatherinfo.HumidityUnit; label6.Text = weather.weatherinfo.WindSpeed; label8.Text = weather.weatherinfo.Pressure + " " + weather.weatherinfo.PressureUnit; label10.Text = weather.weatherinfo.CityName + " ( " + weather.weatherinfo.CountryCode+" )"; } } */ CityLocator cityloc = new CityLocator(); cityloc.GetGeoCoordByCityName("Michalovce"); WeatherMET weather = new WeatherMET(); if(weather.GetWeatherData(cityloc.Latitude,cityloc.Longtitude)) { pictureBox1.Image = weather.GetIcon(0); label2.Text = weather.weatherinfo.Temperature + "°C"; label4.Text = weather.weatherinfo.Humidity + " " + weather.weatherinfo.HumidityUnit; label6.Text = weather.weatherinfo.WindSpeed; label8.Text = weather.weatherinfo.Pressure + " " + weather.weatherinfo.PressureUnit; label10.Text = cityloc.PlaceDisplayName; } } } }
using CSharp_Weather; using System; using System.Diagnostics; using System.Windows.Forms; namespace WeatherApplication { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { /* Weather weather = new Weather("79f4bd16a8425b5ba8153d93e67a7c21", Weather.Fahrenheit); weather.SetLanguage("en",true); if(weather.GetWeather(weather.GetCountry())) { if(weather.GetWeatherIsSuccessful()) { label2.Text = weather.weatherinfo.Temperature +weather.UnitSymbol(); label4.Text = weather.weatherinfo.Humidity + " " + weather.weatherinfo.HumidityUnit; label6.Text = weather.weatherinfo.WindSpeed; label8.Text = weather.weatherinfo.Pressure + " " + weather.weatherinfo.PressureUnit; label10.Text = weather.weatherinfo.CityName + " ( " + weather.weatherinfo.CountryCode+" )"; } } */ CityLocator cityloc = new CityLocator(); cityloc.GetGeoCoordByCityName("Michalovce"); WeatherMET weather = new WeatherMET(); if(weather.GetWeatherData(cityloc.Latitude,cityloc.Longtitude)) { pictureBox1.Image = weather.GetIcon(0); label2.Text = weather.weatherinfo.Temperature + "°C"; label4.Text = weather.weatherinfo.Humidity + " " + weather.weatherinfo.HumidityUnit; label6.Text = weather.weatherinfo.WindSpeed; label8.Text = weather.weatherinfo.Pressure + " " + weather.weatherinfo.PressureUnit; label10.Text = cityloc.PlaceDisplayName; } } } }
mit
C#
a06115d32a94a1997af3335b5c2f59ca8765ee82
update version
IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework
Src/iFramework/Properties/AssemblyInfo.cs
Src/iFramework/Properties/AssemblyInfo.cs
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("IFramework")] [assembly: AssemblyDescription("IFramework")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ivan")] [assembly: AssemblyProduct("IFramework")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("ec283c09-6f77-4d72-9a18-08aba1ffa74d")] // 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.18")] [assembly: AssemblyFileVersion("1.0.0.18")] // nuget pack -build -properties configuration=release // nuget push IFramework.1.0.0.nupkg -source https://www.nuget.org/api/v2/package
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("IFramework")] [assembly: AssemblyDescription("IFramework")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ivan")] [assembly: AssemblyProduct("IFramework")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("ec283c09-6f77-4d72-9a18-08aba1ffa74d")] // 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.17")] [assembly: AssemblyFileVersion("1.0.0.17")] // nuget pack -build -properties configuration=release // nuget push IFramework.1.0.0.nupkg -source https://www.nuget.org/api/v2/package
mit
C#
37b6923e35634ecb00b5ec1aa79d398134b25d74
fix test
lschaffer2/MetaMorpheus,zrolfs/MetaMorpheus,XRSHEERAN/MetaMorpheus,smith-chem-wisc/MetaMorpheus,hoffmann4/MetaMorpheus,rmillikin/MetaMorpheus,lonelu/MetaMorpheus
Test/CalibrationEngineTest.cs
Test/CalibrationEngineTest.cs
using InternalLogicCalibration; using InternalLogicEngineLayer; using MassSpectrometry; using NUnit.Framework; using OldInternalLogic; using Proteomics; using Spectra; using System.Collections.Generic; namespace Test { [TestFixture] public class CalibrationEngineTests { #region Public Methods [Test] public static void TestCalibrationEngine() { Dictionary<int, List<MorpheusModification>> oneBasedPossibleLocalizedModifications = new Dictionary<int, List<MorpheusModification>>(); Protein ParentProtein = new Protein("MQQQQQQQ", null, oneBasedPossibleLocalizedModifications, null, null, null, null, null, 0, false, false); PeptideWithPossibleModifications modPep = new PeptideWithPossibleModifications(1, 8, ParentProtein, 0, "kk"); Dictionary<int, MorpheusModification> twoBasedVariableAndLocalizeableModificationss = new Dictionary<int, MorpheusModification>(); PeptideWithSetModifications pepWithSetMods = new PeptideWithSetModifications(modPep, twoBasedVariableAndLocalizeableModificationss); IMsDataFile<IMzSpectrum<MzPeak>> myMsDataFile = new TestDataFile(pepWithSetMods); Tolerance fragmentTolerance = new Tolerance(ToleranceUnit.Absolute, 0.01); double toleranceInMZforMS2Search = fragmentTolerance.Value; List<NewPsmWithFdr> identifications = new List<NewPsmWithFdr>(); ParentSpectrumMatch newPsm = new TestParentSpectrumMatch(2, 2); PSMwithProteinHashSet thisPSM = new PSMwithProteinHashSet(newPsm, new HashSet<PeptideWithSetModifications>() { pepWithSetMods }, fragmentTolerance, myMsDataFile); NewPsmWithFdr thePsmwithfdr = new NewPsmWithFdr(thisPSM, 1, 0, 0); identifications.Add(thePsmwithfdr); int randomSeed = 0; int minMS1isotopicPeaksNeededForConfirmedIdentification = 3; int minMS2isotopicPeaksNeededForConfirmedIdentification = 2; int numFragmentsNeededForEveryIdentification = 10; double toleranceInMZforMS1Search = 0.01; var calibrationEngine = new CalibrationEngine(myMsDataFile, randomSeed, toleranceInMZforMS2Search, identifications, minMS1isotopicPeaksNeededForConfirmedIdentification, minMS2isotopicPeaksNeededForConfirmedIdentification, numFragmentsNeededForEveryIdentification, toleranceInMZforMS1Search, FragmentTypes.b, FragmentTypes.y); var res = calibrationEngine.Run(); Assert.IsTrue(res is CalibrationResults); } #endregion Public Methods } }
using InternalLogicCalibration; using InternalLogicEngineLayer; using MassSpectrometry; using NUnit.Framework; using OldInternalLogic; using Spectra; using System.Collections.Generic; namespace Test { [TestFixture] public class CalibrationEngineTests { #region Public Methods [Test] public static void TestCalibrationEngine() { Dictionary<int, List<MorpheusModification>> oneBasedPossibleLocalizedModifications = new Dictionary<int, List<MorpheusModification>>(); Protein ParentProtein = new Protein("MQQQQQQQ", null, oneBasedPossibleLocalizedModifications, null, null, null, null, null, 0, false, false); PeptideWithPossibleModifications modPep = new PeptideWithPossibleModifications(1, 8, ParentProtein, 0, "kk"); Dictionary<int, MorpheusModification> twoBasedVariableAndLocalizeableModificationss = new Dictionary<int, MorpheusModification>(); PeptideWithSetModifications pepWithSetMods = new PeptideWithSetModifications(modPep, twoBasedVariableAndLocalizeableModificationss); IMsDataFile<IMzSpectrum<MzPeak>> myMsDataFile = new TestDataFile(pepWithSetMods); Tolerance fragmentTolerance = new Tolerance(ToleranceUnit.Absolute, 0.01); double toleranceInMZforMS2Search = fragmentTolerance.Value; List<NewPsmWithFdr> identifications = new List<NewPsmWithFdr>(); ParentSpectrumMatch newPsm = new TestParentSpectrumMatch(2, 2); PSMwithProteinHashSet thisPSM = new PSMwithProteinHashSet(newPsm, new HashSet<PeptideWithSetModifications>() { pepWithSetMods }, fragmentTolerance, myMsDataFile); NewPsmWithFdr thePsmwithfdr = new NewPsmWithFdr(thisPSM, 1, 0, 0); identifications.Add(thePsmwithfdr); int randomSeed = 0; int minMS1isotopicPeaksNeededForConfirmedIdentification = 3; int minMS2isotopicPeaksNeededForConfirmedIdentification = 2; int numFragmentsNeededForEveryIdentification = 10; double toleranceInMZforMS1Search = 0.01; var calibrationEngine = new CalibrationEngine(myMsDataFile, randomSeed, toleranceInMZforMS2Search, identifications, minMS1isotopicPeaksNeededForConfirmedIdentification, minMS2isotopicPeaksNeededForConfirmedIdentification, numFragmentsNeededForEveryIdentification, toleranceInMZforMS1Search); var res = calibrationEngine.Run(); Assert.IsTrue(res is CalibrationResults); } #endregion Public Methods } }
mit
C#
f5d246e7c83385f425344e4af63b8777a8e3003a
Correct teardown for Qyoto tests
TobiasKappe/Selene,TobiasKappe/Selene
Selene.Testing/Harness.cs
Selene.Testing/Harness.cs
// Copyright (c) 2009 Tobias Kappé // // 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. // // Except as contained in this notice, the name(s) of the above // copyright holders shall not be used in advertising or otherwise // to promote the sale, use or other dealings in this Software // without prior written authorization. // // 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 NUnit.Framework; using Gtk; using Qyoto; namespace Selene.Testing { [TestFixture] public partial class Harness { [TestFixtureSetUp] public void Setup() { #if GTK string[] Dummy = new string[] { }; Init.Check(ref Dummy); #endif #if QYOTO new QApplication(new string[] { } ); #endif } [TestFixtureTearDown] public void Teardown() { #if QYOTO QApplication.Quit(); #endif #if WINDOWS System.Windows.Forms.Application.Exit(); #endif } } }
// Copyright (c) 2009 Tobias Kappé // // 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. // // Except as contained in this notice, the name(s) of the above // copyright holders shall not be used in advertising or otherwise // to promote the sale, use or other dealings in this Software // without prior written authorization. // // 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 NUnit.Framework; using Gtk; using Qyoto; namespace Selene.Testing { [TestFixture] public partial class Harness { [TestFixtureSetUp] public void Setup() { #if GTK string[] Dummy = new string[] { }; Init.Check(ref Dummy); #endif #if QYOTO new QApplication(new string[] { } ); #endif } [TestFixtureTearDown] public void Teardown() { #if QYOTO QApplication.Exec(); #endif #if WINDOWS System.Windows.Forms.Application.Exit(); #endif } } }
mit
C#
cee8c9e3c9b870a6373aaf1e664e508a4dc1a13b
add license
NDark/ndinfrastructure,NDark/ndinfrastructure
Unity/UnityTools/UnityFind.cs
Unity/UnityTools/UnityFind.cs
/** MIT License Copyright (c) 2017 NDark 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. */ /** @file UnityFind.cs @author NDark @date 20170812 . file started. */ using UnityEngine; public static class UnityFind { public static GameObject GameObjectFind( GameObject _Obj , string _Name ) { if( null != _Obj ) { var trans = _Obj.transform.Find( _Name ); if( null != trans ) { return trans.gameObject ; } } return null ; } public static T ComponentFind<T>( Transform _Root , string _Name ) { var trans = _Root.Find( _Name ); if( null == trans ) { Debug.LogError( _Name ); return default(T) ; } var c = trans.gameObject.GetComponent<T>(); if( null == c ) { Debug.LogError( "null == c" ); return default(T) ; } return c; } }
using UnityEngine; public static class UnityFind { public static GameObject GameObjectFind( GameObject _Obj , string _Name ) { if( null != _Obj ) { var trans = _Obj.transform.Find( _Name ); if( null != trans ) { return trans.gameObject ; } } return null ; } public static T ComponentFind<T>( Transform _Root , string _Name ) { var trans = _Root.Find( _Name ); if( null == trans ) { Debug.LogError( _Name ); return default(T) ; } var c = trans.gameObject.GetComponent<T>(); if( null == c ) { Debug.LogError( "null == c" ); return default(T) ; } return c; } }
mit
C#
c46364f1b40d417e9b1039fca06b46ea8f0d8d3f
Add docs and IndentIndex to State
exodrifter/unity-rumor
Parser/State.cs
Parser/State.cs
namespace Exodrifter.Rumor.Parser { /// <summary> /// Contains the state of a parsing operation. /// </summary> public class State { /// <summary> /// The contents of the source file that is being parsed. /// </summary> public string Source { get; } /// <summary> /// The current index in the source file the parser is pointing at. /// </summary> public int Index { get; } /// <summary> /// The index in the source file to check the current indentation level /// against, if needed. /// </summary> public int IndentIndex { get; } /// <summary> /// Creates a new parser state. /// </summary> /// <param name="source"> /// The contents of the source to parse. /// </param> /// <param name="index"> /// The index where the parser should start. /// </param> public State(string source, int index = 0) { Source = source; Index = index; IndentIndex = 0; } /// <summary> /// Returns a new state with the index changed by the specified delta. /// </summary> /// <param name="indexDelta"> /// The amount to change the index. /// </param> /// <returns> /// A new state with a modified index. /// </returns> public State AddIndex(int indexDelta) { return new State(Source, Index + indexDelta, IndentIndex); } /// <summary> /// Sets the index of the location used for checking indentation levels /// to the current index. /// </summary> /// <returns> /// A new state with a modified index for checking indentation levels. /// </returns> public State SetIndent() { return new State(Source, Index, Index); } #region Internal private State(string source, int index, int indentIndex) { Source = source; Index = index; IndentIndex = indentIndex; } #endregion } }
namespace Exodrifter.Rumor.Parser { public class State { public string Source { get; } public int Index { get; } public State(string source, int index = 0) { Source = source; Index = index; } /// <summary> /// Makes a copy of another state except for the index. /// </summary> /// <param name="state">The state to copy.</param> /// <param name="index">The new index.</param> public State(State state, int index = 0) { Source = state.Source; Index = index; } public State AddIndex(int indexDelta) { return new State(this, Index + indexDelta); } } }
mit
C#
dbd70ed7af3e197073534b0a2c18c54011979c7c
Update default project to start an engine and tick a few times.
Simie/OpenAOE
Source/OpenAOE/Program.cs
Source/OpenAOE/Program.cs
using System; using System.Collections.Generic; using Ninject; using Ninject.Extensions.Logging; using Ninject.Extensions.Logging.NLog4; using OpenAOE.Engine; using OpenAOE.Engine.Entity; namespace OpenAOE { class Program { static void Main(string[] args) { var context = new StandardKernel( new NinjectSettings() { LoadExtensions = false }, new Engine.EngineModule(), new Games.AGE2.Module(), new NLogModule()); var log = context.Get<ILoggerFactory>().GetCurrentClassLogger(); log.Info("Starting"); var engineFactory = context.Get<IEngineFactory>(); log.Info("Creating Engine"); var engine = engineFactory.Create(new List<EntityData>(), new List<EntityTemplate>()); for (var i = 0; i < 10; ++i) { var tick = engine.Tick(new EngineTickInput()); tick.Start(); tick.Wait(); engine.Synchronize(); } /*context.Bind<IDataService>().ToConstant(VersionedDataService.FromRoot(new Root())); var instance = context.Get<ISimulationInstance>(); context.Unbind(typeof(IDataService));*/ log.Info("Done"); Console.ReadKey(true); log.Info("Exiting"); } } }
using System; using Ninject; using Ninject.Extensions.Logging; using Ninject.Extensions.Logging.NLog4; using OpenAOE.Engine; namespace OpenAOE { class Program { static void Main(string[] args) { var context = new StandardKernel( new NinjectSettings() { LoadExtensions = false }, new EngineModule(), new Games.AGE2.Module(), new NLogModule()); var log = context.Get<ILoggerFactory>().GetCurrentClassLogger(); log.Info("Starting"); /*context.Bind<IDataService>().ToConstant(VersionedDataService.FromRoot(new Root())); var instance = context.Get<ISimulationInstance>(); context.Unbind(typeof(IDataService));*/ log.Info("Done"); Console.ReadKey(true); log.Info("Exiting"); } } }
apache-2.0
C#
12accc841f4c4228b6af85895688884f7e987737
Debug CORS
WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework
Framework/Server/StartupFramework.cs
Framework/Server/StartupFramework.cs
namespace Framework.Server { using Framework.Application; using Framework.Config; using Framework.Dal.Memory; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using System; /// <summary> /// ASP.NET Core configuration. /// </summary> public static class StartupFramework { public static void ConfigureServices(IServiceCollection services) { // Dependency Injection DI. See also https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1 services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // Needed for IIS. Otherwise new HttpContextAccessor(); results in null reference exception. services.AddScoped<UtilServer.InstanceService, UtilServer.InstanceService>(); // Singleton per request. services.AddSingleton<MemoryInternal>(); services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.Name = "FrameworkSession"; options.IdleTimeout = TimeSpan.FromSeconds(60); }); services.AddCors(); } public static void Configure(IApplicationBuilder applicationBuilder, AppSelector appSelector) { UtilServer.ApplicationBuilder = applicationBuilder; if (UtilServer.IsIssServer == false) { if (ConfigFramework.Load().IsServerSideRendering) { UtilServer.StartUniversalServer(); } } if (ConfigFramework.Load().IsUseDeveloperExceptionPage) { applicationBuilder.UseDeveloperExceptionPage(); } applicationBuilder.UseDefaultFiles(); // Used for index.html applicationBuilder.UseStaticFiles(); // Enable access to files in folder wwwwroot. applicationBuilder.UseSession(); applicationBuilder.UseCors(config => config.WithOrigins("http://demo.workplacex.org").AllowCredentials()); // Access-Control-Allow-Origin. Client POST uses withCredentials to pass cookies! applicationBuilder.Run(new Request(applicationBuilder, appSelector).RunAsync); } } }
namespace Framework.Server { using Framework.Application; using Framework.Config; using Framework.Dal.Memory; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using System; /// <summary> /// ASP.NET Core configuration. /// </summary> public static class StartupFramework { public static void ConfigureServices(IServiceCollection services) { // Dependency Injection DI. See also https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1 services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // Needed for IIS. Otherwise new HttpContextAccessor(); results in null reference exception. services.AddScoped<UtilServer.InstanceService, UtilServer.InstanceService>(); // Singleton per request. services.AddSingleton<MemoryInternal>(); services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.Name = "FrameworkSession"; options.IdleTimeout = TimeSpan.FromSeconds(60); }); services.AddCors(); } public static void Configure(IApplicationBuilder applicationBuilder, AppSelector appSelector) { UtilServer.ApplicationBuilder = applicationBuilder; if (UtilServer.IsIssServer == false) { if (ConfigFramework.Load().IsServerSideRendering) { UtilServer.StartUniversalServer(); } } if (ConfigFramework.Load().IsUseDeveloperExceptionPage) { applicationBuilder.UseDeveloperExceptionPage(); } applicationBuilder.UseDefaultFiles(); // Used for index.html applicationBuilder.UseStaticFiles(); // Enable access to files in folder wwwwroot. applicationBuilder.UseSession(); applicationBuilder.UseCors(config => config.AllowAnyOrigin().AllowCredentials()); // Access-Control-Allow-Origin. Client POST uses withCredentials to pass cookies! applicationBuilder.Run(new Request(applicationBuilder, appSelector).RunAsync); } } }
mit
C#
3d5309209db20a0a9e61e5336f87af5d66f3a057
fix brace layout
NickStrupat/CacheLineSize.NET
Linux.cs
Linux.cs
using System; using System.Runtime.InteropServices; namespace NickStrupat { internal static class Linux { public static Int32 GetSize() => (Int32) sysconf(_SC_LEVEL1_DCACHE_LINESIZE); [DllImport("libc")] private static extern long sysconf(int name); private const Int32 _SC_LEVEL1_DCACHE_LINESIZE = 190; } }
using System; using System.Runtime.InteropServices; namespace NickStrupat { internal static class Linux { public static Int32 GetSize() => (Int32) sysconf(_SC_LEVEL1_DCACHE_LINESIZE); [DllImport("libc")] private static extern long sysconf(int name); private const Int32 _SC_LEVEL1_DCACHE_LINESIZE = 190; } }
mit
C#
43817f1bcb92bfc7bead0491ce864040817e8434
correct js for bundle
ucdavis/Commencement,ucdavis/Commencement,ucdavis/Commencement
Commencement.Mvc/App_Start/BundleConfig.cs
Commencement.Mvc/App_Start/BundleConfig.cs
using System.Web; using System.Web.Optimization; namespace Commencement.Mvc { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-1.10.2.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); bundles.Add(new StyleBundle("~/Content/csscal").Include( "~/Content/bootstrap.css", "~/Content/maincal.css")); } } }
using System.Web; using System.Web.Optimization; namespace Commencement.Mvc { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); bundles.Add(new StyleBundle("~/Content/csscal").Include( "~/Content/bootstrap.css", "~/Content/maincal.css")); } } }
mit
C#
ce70a58d5c598fca407ff7de9dc17e7b3fd861b8
Update SDK version to 4.2.0
NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity
ncmb_unity/Assets/NCMB/Script/CommonConstant.cs
ncmb_unity/Assets/NCMB/Script/CommonConstant.cs
/******* Copyright 2017-2020 FUJITSU CLOUD TECHNOLOGIES LIMITED 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. **********/ using System.Collections; namespace NCMB.Internal { //通信種別 internal enum ConnectType { //GET通信 GET, //POST通信 POST, //PUT通信 PUT, //DELETE通信 DELETE } /// <summary> /// 定数を定義する共通用のクラスです /// </summary> internal static class CommonConstant { //service public static readonly string DOMAIN = "mbaas.api.nifcloud.com";//ドメイン public static readonly string DOMAIN_URL = "https://mbaas.api.nifcloud.com";//ドメインのURL public static readonly string API_VERSION = "2013-09-01";//APIバージョン public static readonly string SDK_VERSION = "4.2.0"; //SDKバージョン //DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください } }
/******* Copyright 2017-2020 FUJITSU CLOUD TECHNOLOGIES LIMITED 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. **********/ using System.Collections; namespace NCMB.Internal { //通信種別 internal enum ConnectType { //GET通信 GET, //POST通信 POST, //PUT通信 PUT, //DELETE通信 DELETE } /// <summary> /// 定数を定義する共通用のクラスです /// </summary> internal static class CommonConstant { //service public static readonly string DOMAIN = "mbaas.api.nifcloud.com";//ドメイン public static readonly string DOMAIN_URL = "https://mbaas.api.nifcloud.com";//ドメインのURL public static readonly string API_VERSION = "2013-09-01";//APIバージョン public static readonly string SDK_VERSION = "4.1.0"; //SDKバージョン //DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください } }
apache-2.0
C#
7991e48dac14cfc4d508d86495cff687f6fd5113
Add Team information to AccountInfo
DropNet/DropNet
DropNet/Models/AccountInfo.cs
DropNet/Models/AccountInfo.cs
namespace DropNet.Models { public class AccountInfo { public string referral_link { get; set; } public string country { get; set; } public string email { get; set; } public string display_name { get; set; } public QuotaInfo quota_info { get; set; } public long uid { get; set; } public Team team { get; set; } } public class QuotaInfo { public long shared { get; set; } public long quota { get; set; } public long normal { get; set; } } public class Team { public string name { get; set; } } }
namespace DropNet.Models { public class AccountInfo { public string referral_link { get; set; } public string country { get; set; } public string email { get; set; } public string display_name { get; set; } public QuotaInfo quota_info { get; set; } public long uid { get; set; } } public class QuotaInfo { public long shared { get; set; } public long quota { get; set; } public long normal { get; set; } } }
apache-2.0
C#
ee38a0e62b57781100d984ab4944935c58000b9a
Improve replay test UI
SnpM/Lockstep-Framework,yanyiyun/LockstepFramework
Example/ExampleGameManager.cs
Example/ExampleGameManager.cs
using UnityEngine; using UnityEngine.SceneManagement; using System.Collections; using Lockstep.Data; using TypeReferences; using System; namespace Lockstep.Example { public class ExampleGameManager : GameManager { static Replay LastSave = new Replay(); void OnGUI() { GUI.matrix = Matrix4x4.TRS(new Vector3(0, 0, 0), Quaternion.identity, new Vector3(2.5f, 2.5f, 1)); if (GUILayout.Button("Restart")) { ReplayManager.Stop(); LSUtility.LoadLevel(SceneManager.GetActiveScene().name); } if (GUILayout.Button("Playback")) { LastSave = ReplayManager.SerializeCurrent(); LSUtility.LoadLevel(SceneManager.GetActiveScene().name); ReplayManager.Play(LastSave); } } } }
using UnityEngine; using UnityEngine.SceneManagement; using System.Collections; using Lockstep.Data; using TypeReferences; using System; namespace Lockstep.Example { public class ExampleGameManager : GameManager { Replay LastSave = new Replay(); void OnGUI () { GUI.matrix = Matrix4x4.TRS (new Vector3(0, 0, 0), Quaternion.identity, new Vector3 (2.5f, 2.5f, 1)); if (ReplayManager.IsPlayingBack) { if (ReplayManager.CurrentReplay != null) { if (GUILayout.Button("Stop")) { ReplayManager.CurrentReplay = null; ReplayManager.Stop(); LSUtility.LoadLevel(SceneManager.GetActiveScene().name); } if (GUILayout.Button("Rewind")) { ReplayManager.Play(LastSave); LSUtility.LoadLevel(SceneManager.GetActiveScene().name); } } } else { if (GUILayout.Button ("Restart")) { LSUtility.LoadLevel (SceneManager.GetActiveScene().name); } if (GUILayout.Button ("Save")) { LastSave = ReplayManager.SerializeCurrent(); LSUtility.LoadLevel (SceneManager.GetActiveScene().name); ReplayManager.Play (LastSave); } } } } }
mit
C#
7215f3f66b6c7891f7d9b8de14ff6ba7fe155ed8
Fix `CalculateAverageHitError` throwing if there are zero `HitEvent`s
peppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu
osu.Game/Rulesets/Scoring/HitEventExtensions.cs
osu.Game/Rulesets/Scoring/HitEventExtensions.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; namespace osu.Game.Rulesets.Scoring { public static class HitEventExtensions { /// <summary> /// Calculates the "unstable rate" for a sequence of <see cref="HitEvent"/>s. /// </summary> /// <returns> /// A non-null <see langword="double"/> value if unstable rate could be calculated, /// and <see langword="null"/> if unstable rate cannot be calculated due to <paramref name="hitEvents"/> being empty. /// </returns> public static double? CalculateUnstableRate(this IEnumerable<HitEvent> hitEvents) { double[] timeOffsets = hitEvents.Where(affectsUnstableRate).Select(ev => ev.TimeOffset).ToArray(); return 10 * standardDeviation(timeOffsets); } /// <summary> /// Calculates the average hit offset/error for a sequence of <see cref="HitEvent"/>s, where negative numbers mean the user hit too early on average. /// </summary> /// <returns> /// A non-null <see langword="double"/> value if unstable rate could be calculated, /// and <see langword="null"/> if unstable rate cannot be calculated due to <paramref name="hitEvents"/> being empty. /// </returns> public static double? CalculateAverageHitError(this IEnumerable<HitEvent> hitEvents) { double[] timeOffsets = hitEvents.Where(affectsUnstableRate).Select(ev => ev.TimeOffset).ToArray(); if (timeOffsets.Length == 0) return null; return timeOffsets.Average(); } private static bool affectsUnstableRate(HitEvent e) => !(e.HitObject.HitWindows is HitWindows.EmptyHitWindows) && e.Result.IsHit(); private static double? standardDeviation(double[] timeOffsets) { if (timeOffsets.Length == 0) return null; double mean = timeOffsets.Average(); double squares = timeOffsets.Select(offset => Math.Pow(offset - mean, 2)).Sum(); return Math.Sqrt(squares / timeOffsets.Length); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; namespace osu.Game.Rulesets.Scoring { public static class HitEventExtensions { /// <summary> /// Calculates the "unstable rate" for a sequence of <see cref="HitEvent"/>s. /// </summary> /// <returns> /// A non-null <see langword="double"/> value if unstable rate could be calculated, /// and <see langword="null"/> if unstable rate cannot be calculated due to <paramref name="hitEvents"/> being empty. /// </returns> public static double? CalculateUnstableRate(this IEnumerable<HitEvent> hitEvents) { double[] timeOffsets = hitEvents.Where(affectsUnstableRate).Select(ev => ev.TimeOffset).ToArray(); return 10 * standardDeviation(timeOffsets); } /// <summary> /// Calculates the average hit offset/error for a sequence of <see cref="HitEvent"/>s, where negative numbers mean the user hit too early on average. /// </summary> /// <returns> /// A non-null <see langword="double"/> value if unstable rate could be calculated, /// and <see langword="null"/> if unstable rate cannot be calculated due to <paramref name="hitEvents"/> being empty. /// </returns> public static double? CalculateAverageHitError(this IEnumerable<HitEvent> hitEvents) => hitEvents.Where(affectsUnstableRate).Select(ev => ev.TimeOffset).Average(); private static bool affectsUnstableRate(HitEvent e) => !(e.HitObject.HitWindows is HitWindows.EmptyHitWindows) && e.Result.IsHit(); private static double? standardDeviation(double[] timeOffsets) { if (timeOffsets.Length == 0) return null; double mean = timeOffsets.Average(); double squares = timeOffsets.Select(offset => Math.Pow(offset - mean, 2)).Sum(); return Math.Sqrt(squares / timeOffsets.Length); } } }
mit
C#
70dc51fe650e420a8d5aa3143bccc535126090f1
Update DbContextExtensions.cs
refactorthis/GraphDiff
GraphDiff/GraphDiff/DbContextExtensions.cs
GraphDiff/GraphDiff/DbContextExtensions.cs
/* * This code is provided as is with no warranty. If you find a bug please report it on github. * If you would like to use the code please leave this comment at the top of the page * License MIT (c) Brent McKendrick 2012 */ using System; using System.Data.Entity; using System.Linq.Expressions; using RefactorThis.GraphDiff.Internal; using RefactorThis.GraphDiff.Internal.Graph; namespace RefactorThis.GraphDiff { public static class DbContextExtensions { /// <summary> /// Merges a graph of entities with the data store. /// </summary> /// <typeparam name="T">The type of the root entity</typeparam> /// <param name="context">The database context to attach / detach.</param> /// <param name="entity">The root entity.</param> /// <param name="mapping">The mapping configuration to define the bounds of the graph</param> /// <param name="allowDelete">NEED TEXTE!!!!</param> /// <returns>The attached entity graph</returns> public static T UpdateGraph<T>(this DbContext context, T entity, Expression<Func<IUpdateConfiguration<T>, object>> mapping = null, bool allowDelete = true) where T : class, new() { var root = mapping == null ? new GraphNode() : new ConfigurationVisitor<T>().GetNodes(mapping); root.AllowDelete = allowDelete; var graphDiffer = new GraphDiffer<T>(root); return graphDiffer.Merge(context, entity); } // TODO add IEnumerable<T> entities } }
/* * This code is provided as is with no warranty. If you find a bug please report it on github. * If you would like to use the code please leave this comment at the top of the page * License MIT (c) Brent McKendrick 2012 */ using System; using System.Data.Entity; using System.Linq.Expressions; using RefactorThis.GraphDiff.Internal; using RefactorThis.GraphDiff.Internal.Graph; namespace RefactorThis.GraphDiff { public static class DbContextExtensions { /// <summary> /// Merges a graph of entities with the data store. /// </summary> /// <typeparam name="T">The type of the root entity</typeparam> /// <param name="context">The database context to attach / detach.</param> /// <param name="entity">The root entity.</param> /// <param name="mapping">The mapping configuration to define the bounds of the graph</param> /// <returns>The attached entity graph</returns> public static T UpdateGraph<T>(this DbContext context, T entity, Expression<Func<IUpdateConfiguration<T>, object>> mapping = null) where T : class, new() { var root = mapping == null ? new GraphNode() : new ConfigurationVisitor<T>().GetNodes(mapping); var graphDiffer = new GraphDiffer<T>(root); return graphDiffer.Merge(context, entity); } // TODO add IEnumerable<T> entities } }
mit
C#
e4b92dd6d9136b25ff4a9bf7aa2d82cf1f3ea337
Refactor to allow injection of custom version parsers
hinteadan/H.Versioning
H.Versioning/H.Versioning/VersionNumber.cs
H.Versioning/H.Versioning/VersionNumber.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; using H.Versioning.VersionNumberParsers; namespace H.Versioning { public sealed class VersionNumber { private static readonly ConcurrentStack<ICanParseVersionNumber> parsers = new ConcurrentStack<ICanParseVersionNumber>(new ICanParseVersionNumber[] { new SemanticVersionParser() }); public static readonly VersionNumber Unknown = new VersionNumber(0, 0, 0, 0, "unknown"); public readonly int Major; public readonly int Minor; public readonly int? Patch; public readonly int? Build; public readonly string Suffix; public VersionNumber(int major, int minor, int? patch, int? build, string suffix) { this.Major = major; this.Minor = minor; this.Patch = patch; this.Build = build; this.Suffix = suffix; } public VersionNumber(int major, int minor) : this(major, minor, null, null, null) { } public VersionNumber(int major, int minor, int patch) : this(major, minor, patch, null, null) { } public VersionNumber(int major, int minor, int patch, int build) : this(major, minor, patch, build, null) { } public static VersionNumber Parse(string version) { List<Exception> exceptions = new List<Exception>(); foreach (var parser in parsers) { try { return parser.Parse(version); } catch (Exception ex) { exceptions.Add(ex); } } throw new AggregateException($"Unable to parse version string \"{version}\" with any of the registered parsers. See inner exceptions for details.", exceptions); } public override string ToString() { var versionString = new StringBuilder($"{this.Major}.{this.Minor}"); if (this.Patch != null) { versionString.Append($".{this.Patch}"); if (this.Build != null) { versionString.Append($".{this.Build}"); } } if (!string.IsNullOrWhiteSpace(this.Suffix)) { versionString.Append($"-{this.Suffix}"); } return versionString.ToString(); } public static void Use(params ICanParseVersionNumber[] parsers) { VersionNumber.parsers.PushRange(parsers); } } }
using System; using System.Text; using H.Versioning.VersionNumberParsers; namespace H.Versioning { public sealed class VersionNumber { public static readonly VersionNumber Unknown = new VersionNumber(0, 0, 0, 0, "unknown"); public readonly int Major; public readonly int Minor; public readonly int? Patch; public readonly int? Build; public readonly string Suffix; public VersionNumber(int major, int minor, int? patch, int? build, string suffix) { this.Major = major; this.Minor = minor; this.Patch = patch; this.Build = build; this.Suffix = suffix; } public VersionNumber(int major, int minor) : this(major, minor, null, null, null) { } public VersionNumber(int major, int minor, int patch) : this(major, minor, patch, null, null) { } public VersionNumber(int major, int minor, int patch, int build) : this(major, minor, patch, build, null) { } public static VersionNumber Parse(string semanticVersion) { return new SemanticVersionParser().Parse(semanticVersion); } public override string ToString() { var versionString = new StringBuilder($"{this.Major}.{this.Minor}"); if (this.Patch != null) { versionString.Append($".{this.Patch}"); if (this.Build != null) { versionString.Append($".{this.Build}"); } } if (!string.IsNullOrWhiteSpace(this.Suffix)) { versionString.Append($"-{this.Suffix}"); } return versionString.ToString(); } } }
mit
C#
6e5df1db9b750cc7f86a0579f353fe80199d50e9
Bump v2.5.0
Gizeta/KanColleCacher
KanColleCacher/Properties/AssemblyInfo.cs
KanColleCacher/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using d_f_32.KanColleCacher; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle(AssemblyInfo.Title)] [assembly: AssemblyDescription(AssemblyInfo.Description)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct(AssemblyInfo.Name)] [assembly: AssemblyCopyright(AssemblyInfo.Copyright)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID //[assembly: Guid("7909a3f7-15a8-4ee5-afc5-11a7cfa40576")] [assembly: Guid("DA0FF655-A2CA-40DC-A78B-6DC85C2D448B")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion(AssemblyInfo.Version)] [assembly: AssemblyFileVersion(AssemblyInfo.Version)] namespace d_f_32.KanColleCacher { public static class AssemblyInfo { public const string Name = "KanColleCacher"; public const string Version = "2.5.0.53"; public const string Author = "d.f.32"; public const string Copyright = "©2014 - d.f.32"; #if DEBUG public const string Title = "提督很忙!缓存工具 (DEBUG)"; #else public const string Title = "提督很忙!缓存工具"; #endif public const string Description = "通过创建本地缓存以加快游戏加载速度(并支持魔改)"; } }
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using d_f_32.KanColleCacher; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle(AssemblyInfo.Title)] [assembly: AssemblyDescription(AssemblyInfo.Description)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct(AssemblyInfo.Name)] [assembly: AssemblyCopyright(AssemblyInfo.Copyright)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID //[assembly: Guid("7909a3f7-15a8-4ee5-afc5-11a7cfa40576")] [assembly: Guid("DA0FF655-A2CA-40DC-A78B-6DC85C2D448B")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion(AssemblyInfo.Version)] [assembly: AssemblyFileVersion(AssemblyInfo.Version)] namespace d_f_32.KanColleCacher { public static class AssemblyInfo { public const string Name = "KanColleCacher"; public const string Version = "2.4.0.50"; public const string Author = "d.f.32"; public const string Copyright = "©2014 - d.f.32"; #if DEBUG public const string Title = "提督很忙!缓存工具 (DEBUG)"; #else public const string Title = "提督很忙!缓存工具"; #endif public const string Description = "通过创建本地缓存以加快游戏加载速度(并支持魔改)"; } }
mit
C#
8a8e01759a89cf52a4fac009fc9236db9f797977
Fix GlobalSetupAttributeMethodsMustHaveNoParameters
adamsitnik/BenchmarkDotNet,Ky7m/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Ky7m/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet
tests/BenchmarkDotNet.IntegrationTests/GlobalSetupAttributeInvalidMethodTest.cs
tests/BenchmarkDotNet.IntegrationTests/GlobalSetupAttributeInvalidMethodTest.cs
using System; using System.Threading; using BenchmarkDotNet.Attributes; using Xunit; using Xunit.Abstractions; namespace BenchmarkDotNet.IntegrationTests { public class GlobalSetupAttributeInvalidMethodTest : BenchmarkTestExecutor { public GlobalSetupAttributeInvalidMethodTest(ITestOutputHelper output) : base(output) { } [Fact] public void GlobalSetupAttributeMethodsMustHaveNoParameters() { var summary = CanExecute<GlobalSetupAttributeInvalidMethod>(fullValidation: false); Assert.Equal("GlobalSetup method GlobalSetup has incorrect signature.\nMethod shouldn't have any arguments.", summary.Title); } public class GlobalSetupAttributeInvalidMethod { [GlobalSetup] public void GlobalSetup(int someParameters) // [GlobalSetup] methods must have no parameters { Console.WriteLine("// ### GlobalSetup called ###"); } [Benchmark] public void Benchmark() { Thread.Sleep(5); } } } }
using System; using System.Threading; using BenchmarkDotNet.Attributes; using Xunit; using Xunit.Abstractions; namespace BenchmarkDotNet.IntegrationTests { public class GlobalSetupAttributeInvalidMethodTest : BenchmarkTestExecutor { public GlobalSetupAttributeInvalidMethodTest(ITestOutputHelper output) : base(output) { } [Fact] public void GlobalSetupAttributeMethodsMustHaveNoParameters() { Assert.Throws<InvalidOperationException>(() => CanExecute<GlobalSetupAttributeInvalidMethod>()); } public class GlobalSetupAttributeInvalidMethod { [GlobalSetup] public void GlobalSetup(int someParameters) // [GlobalSetup] methods must have no parameters { Console.WriteLine("// ### GlobalSetup called ###"); } [Benchmark] public void Benchmark() { Thread.Sleep(5); } } } }
mit
C#
4ea7a6643a5911d36ea7b279302607d252a917d2
Update src/Avalonia.Controls/Notifications/Notification.cs
AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,akrisiun/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex
src/Avalonia.Controls/Notifications/Notification.cs
src/Avalonia.Controls/Notifications/Notification.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; namespace Avalonia.Controls.Notifications { /// <summary> /// A notification that can be shown in a window or by the host operating system. /// Can be displayed by both <see cref="INotificationManager"/> and <see cref="IManagedNotificationManager"/> /// </summary> /// <remarks> /// This class represents a notification that can be displayed either in a window using /// <see cref="WindowNotificationManager"/> or by the host operating system (to be implemented). /// </remarks> public class Notification : INotification { /// <summary> /// Initializes a new instance of the <see cref="Notification"/> class. /// </summary> /// <param name="title">The title of the notification.</param> /// <param name="message">The message to be displayed in the notification.</param> /// <param name="type">The <see cref="NotificationType"/> of the notification.</param> /// <param name="expiration">The expiry time at which the notification will close. /// Use <see cref="TimeSpan.Zero"/> for notifications that will remain open.</param> /// <param name="onClick">An Action to call when the notification is clicked.</param> /// <param name="onClose">The Action to call when the notification is closed.</param> public Notification(string title, string message, NotificationType type = NotificationType.Information, TimeSpan? expiration = null, Action onClick = null, Action onClose = null) { Title = title; Message = message; Type = type; Expiration = expiration.HasValue ? expiration.Value : TimeSpan.FromSeconds(5); OnClick = onClick; OnClose = onClose; } /// <inheritdoc/> public string Title { get; private set; } /// <inheritdoc/> public string Message { get; private set; } /// <inheritdoc/> public NotificationType Type { get; private set; } /// <inheritdoc/> public TimeSpan Expiration { get; private set; } /// <inheritdoc/> public Action OnClick { get; private set; } /// <inheritdoc/> public Action OnClose { get; private set; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; namespace Avalonia.Controls.Notifications { /// <summary> /// A notification that can be shown in a window or by the host operating system. /// Can be displayed by both <see cref="INotificationManager"/> and <see cref="IManagedNotificationManager"/> /// </summary> /// <remarks> /// This class represents a notification that can be displayed either in a window using /// <see cref="WindowNotificationManager"/> or by the host operating system (to be implemented). /// </remarks> public class Notification : INotification { /// <summary> /// Initializes a new instance of the <see cref="Notification"/> class. /// </summary> /// <param name="title">The title of the notification.</param> /// <param name="message">The message to be displayed in the notification.</param> /// <param name="type">The <see cref="NotificationType"/> of the notification.</param> /// <param name="expiration">The expiry time at which the notification will close. /// Use <see cref="TimeSpan.Zero"/> for notifications that will remain open.</param> /// <param name="onClick">The Action to call when the notification is clicked.</param> /// <param name="onClose">The Action to call when the notification is closed.</param> public Notification(string title, string message, NotificationType type = NotificationType.Information, TimeSpan? expiration = null, Action onClick = null, Action onClose = null) { Title = title; Message = message; Type = type; Expiration = expiration.HasValue ? expiration.Value : TimeSpan.FromSeconds(5); OnClick = onClick; OnClose = onClose; } /// <inheritdoc/> public string Title { get; private set; } /// <inheritdoc/> public string Message { get; private set; } /// <inheritdoc/> public NotificationType Type { get; private set; } /// <inheritdoc/> public TimeSpan Expiration { get; private set; } /// <inheritdoc/> public Action OnClick { get; private set; } /// <inheritdoc/> public Action OnClose { get; private set; } } }
mit
C#
3e2dcfbc469856a54faea8782a21474c06f9d720
Update XmlnsDefinitionsModel.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
src/Core2D/Serializer/Xaml/XmlnsDefinitionsModel.cs
src/Core2D/Serializer/Xaml/XmlnsDefinitionsModel.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Core2D.Serializer.Xaml; using Portable.Xaml.Markup; [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Containers", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Data", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Renderer", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Renderer.Presenters", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.History", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Interfaces", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Path", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Shapes", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Style", AssemblyName = "Core2D.Model")] [assembly: XmlnsPrefix(XamlConstants.ModelNamespace, "m")]
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Portable.Xaml.Markup; using Core2D.Serializer.Xaml; [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Containers", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Data", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Renderer", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Renderer.Presenters", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.History", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Interfaces", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Path", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Shapes", AssemblyName = "Core2D.Model")] [assembly: XmlnsDefinition(XamlConstants.ModelNamespace, "Core2D.Style", AssemblyName = "Core2D.Model")] [assembly: XmlnsPrefix(XamlConstants.ModelNamespace, "m")]
mit
C#
66c65e75918b45c3f529a8e7ceaf080fe35daf1b
Fix typo in summary.
PenguinF/sandra-three
Sandra.UI.WF/Storage/FileNameType.cs
Sandra.UI.WF/Storage/FileNameType.cs
/********************************************************************************* * FileNameType.cs * * Copyright (c) 2004-2018 Henk Nicolai * * 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.IO; namespace Sandra.UI.WF.Storage { /// <summary> /// Specialized PType that only accepts strings that are legal file names. /// </summary> public sealed class FileNameType : PType.Filter<string> { public static FileNameType Instance = new FileNameType(); private FileNameType() : base(PType.CLR.String) { } public override bool IsValid(string fileName) => !string.IsNullOrEmpty(fileName) && !fileName.StartsWith(".") && fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0; } }
/********************************************************************************* * FileNameType.cs * * Copyright (c) 2004-2018 Henk Nicolai * * 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.IO; namespace Sandra.UI.WF.Storage { /// <summary> /// Specialized PType that only accepts a strings that are legal file names. /// </summary> public sealed class FileNameType : PType.Filter<string> { public static FileNameType Instance = new FileNameType(); private FileNameType() : base(PType.CLR.String) { } public override bool IsValid(string fileName) => !string.IsNullOrEmpty(fileName) && !fileName.StartsWith(".") && fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0; } }
apache-2.0
C#
93a47eddda98f9c4551f382d3ac5937107c94a67
Check if column exist in table
cezarypiatek/MaintainableSelenium,cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium
Src/MvcPages/WebPages/WebTableRow.cs
Src/MvcPages/WebPages/WebTableRow.cs
using System; using System.Collections.Generic; using OpenQA.Selenium; using OpenQA.Selenium.Remote; namespace Tellurium.MvcPages.WebPages { public class WebTableRow : WebElementCollection<PageFragment> { private readonly IWebElement webElement; private Dictionary<string, int> columnsMap; public WebTableRow(RemoteWebDriver driver, IWebElement webElement, Dictionary<string, int> columnsMap) : base(driver, webElement) { this.webElement = webElement; this.columnsMap = columnsMap; } protected override IWebElement GetItemsContainer() { return webElement; } protected override PageFragment MapToItem(IWebElement webElementItem) { return new PageFragment(Driver, webElementItem); } public IPageFragment this[string columnName] { get { if (string.IsNullOrWhiteSpace(columnName)) { throw new ArgumentException("Column name cannot be empty", nameof(columnName)); } if (columnsMap.ContainsKey(columnName) == false) { throw new ArgumentException($"There is no column with header {columnName}", nameof(columnName)); } var index = columnsMap[columnName]; return this[index]; } } } }
using System; using System.Collections.Generic; using OpenQA.Selenium; using OpenQA.Selenium.Remote; namespace Tellurium.MvcPages.WebPages { public class WebTableRow : WebElementCollection<PageFragment> { private readonly IWebElement webElement; private Dictionary<string, int> columnsMap; public WebTableRow(RemoteWebDriver driver, IWebElement webElement, Dictionary<string, int> columnsMap) : base(driver, webElement) { this.webElement = webElement; this.columnsMap = columnsMap; } protected override IWebElement GetItemsContainer() { return webElement; } protected override PageFragment MapToItem(IWebElement webElementItem) { return new PageFragment(Driver, webElementItem); } public IPageFragment this[string columnName] { get { if (string.IsNullOrWhiteSpace(columnName)) { throw new ArgumentException("Column name cannot be empty", nameof(columnName)); } var index = columnsMap[columnName]; return this[index]; } } } }
mit
C#
34d0fac09a943d5a5abc87e8db6ee4478beec6c2
Update version
shana/octokit.net,SmithAndr/octokit.net,ivandrofly/octokit.net,eriawan/octokit.net,chunkychode/octokit.net,SmithAndr/octokit.net,gabrielweyer/octokit.net,michaKFromParis/octokit.net,octokit-net-test/octokit.net,SamTheDev/octokit.net,SamTheDev/octokit.net,eriawan/octokit.net,Sarmad93/octokit.net,Sarmad93/octokit.net,gdziadkiewicz/octokit.net,M-Zuber/octokit.net,shana/octokit.net,darrelmiller/octokit.net,rlugojr/octokit.net,octokit/octokit.net,geek0r/octokit.net,takumikub/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,shiftkey-tester/octokit.net,chunkychode/octokit.net,mminns/octokit.net,cH40z-Lord/octokit.net,alfhenrik/octokit.net,editor-tools/octokit.net,dampir/octokit.net,ivandrofly/octokit.net,thedillonb/octokit.net,octokit/octokit.net,bslliw/octokit.net,devkhan/octokit.net,hitesh97/octokit.net,khellang/octokit.net,yonglehou/octokit.net,gdziadkiewicz/octokit.net,ChrisMissal/octokit.net,nsrnnnnn/octokit.net,rlugojr/octokit.net,nsnnnnrn/octokit.net,fake-organization/octokit.net,M-Zuber/octokit.net,dlsteuer/octokit.net,adamralph/octokit.net,forki/octokit.net,SLdragon1989/octokit.net,octokit-net-test-org/octokit.net,hahmed/octokit.net,fffej/octokit.net,gabrielweyer/octokit.net,shiftkey/octokit.net,editor-tools/octokit.net,shiftkey-tester/octokit.net,magoswiat/octokit.net,naveensrinivasan/octokit.net,kdolan/octokit.net,daukantas/octokit.net,hahmed/octokit.net,alfhenrik/octokit.net,Red-Folder/octokit.net,TattsGroup/octokit.net,devkhan/octokit.net,TattsGroup/octokit.net,kolbasov/octokit.net,yonglehou/octokit.net,dampir/octokit.net,shiftkey/octokit.net,mminns/octokit.net,octokit-net-test-org/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,khellang/octokit.net,brramos/octokit.net,thedillonb/octokit.net
SolutionInfo.cs
SolutionInfo.cs
// <auto-generated/> using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyProductAttribute("Octokit")] [assembly: AssemblyVersionAttribute("0.1.3")] [assembly: AssemblyFileVersionAttribute("0.1.3")] [assembly: ComVisibleAttribute(false)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.1.3"; } }
// <auto-generated/> using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyProductAttribute("Octokit")] [assembly: AssemblyVersionAttribute("0.1.2")] [assembly: AssemblyFileVersionAttribute("0.1.2")] [assembly: ComVisibleAttribute(false)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.1.2"; } }
mit
C#
87ec8ca7faf7c670ad1c84f905ba8b9b31cc3ae2
Document class and Matches method
oliverzick/Delizious-Filtering
src/Library/Match.T.cs
src/Library/Match.T.cs
#region Copyright and license // // <copyright file="Match.T.cs" company="Oliver Zick"> // // Copyright (c) 2016 Oliver Zick. All rights reserved. // // </copyright> // // <author>Oliver Zick</author> // // <license> // // 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. // // </license> #endregion namespace Delizious.Filtering { using System.Linq; /// <summary> /// Represents a strongly typed match that provides a method to determine whether a value matches with. /// </summary> /// <typeparam name="T"> /// The type of the value to match. /// </typeparam> public sealed class Match<T> : IMatch<T> { private readonly IMatch<T> match; private Match(IMatch<T> match) { this.match = match; } internal static Match<T> Create(IMatch<T> match) { return new Match<T>(match); } internal static Match<T> All(params Match<T>[] matches) { return Create(new All<T>(matches.Select(match => match.match).ToArray())); } internal static Match<T> Any(params Match<T>[] matches) { return Create(new Any<T>(matches.Select(match => match.match).ToArray())); } internal static Match<T> None(params Match<T>[] matches) { return Create(new None<T>(matches.Select(match => match.match).ToArray())); } /// <summary> /// Determines whether the specified <paramref name="value"/> successfully matches with this match instance. /// </summary> /// <param name="value"> /// The value to match. /// </param> /// <returns> /// <c>true</c> if <paramref name="value"/> successfully matches with this match instance; otherwise, <c>false</c>. /// </returns> public bool Matches(T value) { return this.match.Matches(value); } } }
#region Copyright and license // // <copyright file="Match.T.cs" company="Oliver Zick"> // // Copyright (c) 2016 Oliver Zick. All rights reserved. // // </copyright> // // <author>Oliver Zick</author> // // <license> // // 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. // // </license> #endregion namespace Delizious.Filtering { using System.Linq; public sealed class Match<T> : IMatch<T> { private readonly IMatch<T> match; private Match(IMatch<T> match) { this.match = match; } internal static Match<T> Create(IMatch<T> match) { return new Match<T>(match); } internal static Match<T> All(params Match<T>[] matches) { return Create(new All<T>(matches.Select(match => match.match).ToArray())); } internal static Match<T> Any(params Match<T>[] matches) { return Create(new Any<T>(matches.Select(match => match.match).ToArray())); } internal static Match<T> None(params Match<T>[] matches) { return Create(new None<T>(matches.Select(match => match.match).ToArray())); } public bool Matches(T value) { return this.match.Matches(value); } } }
apache-2.0
C#
14d37286ad880594f3b461bdbca50deec160c5e0
Fix tests with new enum values of Month
erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner
Zk.Tests/Controllers/CropControllerTest.cs
Zk.Tests/Controllers/CropControllerTest.cs
using System; using System.Linq; using System.Web.Mvc; using NUnit.Framework; using Zk.Controllers; using Zk.Models; using Zk.Repositories; using Zk.Tests.Fakes; namespace Zk.Tests.Controllers { [TestFixture] public class CropControllerTest { private CropController _controller; [TestFixtureSetUp] public void Setup() { // Initialize a fake database with one crop. var db = new FakeZkContext { Crops = { new Crop { Id = 1, Name = "Broccoli", SowingMonths = Month.Mei ^ Month.Juni ^ Month.Oktober ^ Month.November } } }; _controller = new CropController(db); } [Test] public void Controllers_Crop_From_Id_Success() { // Arrange var id = 1; var expectedResult = "Broccoli"; // Act var viewResult = _controller.Crop(id); var actualResult = ((Crop)viewResult.ViewData.Model).Name; // Assert Assert.AreEqual(expectedResult, actualResult, "Since there is a broccoli with ID 1 in the database the crop method should return it."); } [Test] public void Controllers_Crop_From_Name_Success() { // Arrange var name = "Broccoli"; // Act var viewResult = _controller.Crop(name); var result = ((Crop)viewResult.ViewData.Model).SowingMonths; // Assert Assert.AreEqual(Month.Mei ^ Month.Juni ^ Month.Oktober ^ Month.November, result, "Since there is a crop with the name broccoli in the database the crop method should return it" + "and the sowing months should be may, june, october and november."); } } }
using System; using System.Linq; using System.Web.Mvc; using NUnit.Framework; using Zk.Controllers; using Zk.Models; using Zk.Repositories; using Zk.Tests.Fakes; namespace Zk.Tests.Controllers { [TestFixture] public class CropControllerTest { private CropController _controller; [TestFixtureSetUp] public void Setup() { // Initialize a fake database with one crop. var db = new FakeZkContext { Crops = { new Crop { Id = 1, Name = "Broccoli", SowingMonths = Month.May ^ Month.June ^ Month.October ^ Month.November } } }; _controller = new CropController(db); } [Test] public void Controllers_Crop_From_Id_Success() { // Arrange var id = 1; var expectedResult = "Broccoli"; // Act var viewResult = _controller.Crop(id); var actualResult = ((Crop)viewResult.ViewData.Model).Name; // Assert Assert.AreEqual(expectedResult, actualResult, "Since there is a broccoli with ID 1 in the database the crop method should return it."); } [Test] public void Controllers_Crop_From_Name_Success() { // Arrange var name = "Broccoli"; // Act var viewResult = _controller.Crop(name); var result = ((Crop)viewResult.ViewData.Model).SowingMonths; // Assert Assert.AreEqual(Month.May ^ Month.June ^ Month.October ^ Month.November, result, "Since there is a crop with the name broccoli in the database the crop method should return it" + "and the sowing months should be may, june, october and november."); } } }
mit
C#
aee510b9f50243c1d1b923696d380be7345db629
Fix version
antoshkab/unity.wcf,ViceIce/unity.wcf
Unity.Wcf/Properties/AssemblyInfo.cs
Unity.Wcf/Properties/AssemblyInfo.cs
using System.Reflection; 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("Unity.Wcf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DevTrends")] [assembly: AssemblyProduct("Unity.Wcf")] [assembly: AssemblyCopyright("Copyright © DevTrends 2012")] [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("23d35d8e-4fcf-4883-a014-63e622391798")] // 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("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0")] [assembly: AssemblyInformationalVersion("2.0.0")]
using System.Reflection; 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("Unity.Wcf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DevTrends")] [assembly: AssemblyProduct("Unity.Wcf")] [assembly: AssemblyCopyright("Copyright © DevTrends 2012")] [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("23d35d8e-4fcf-4883-a014-63e622391798")] // 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("2.2.0")] [assembly: AssemblyInformationalVersion("2.2.0")]
mit
C#
5cb812d621b71dab552bfa24191acb8917352e31
Add Windows auth to service, and authorize to the SpiderCrab Operators group
GingerTommy/SpiderCrab
src/SpiderCrab.Agent/App_Start/Startup.cs
src/SpiderCrab.Agent/App_Start/Startup.cs
namespace SpiderCrab.Agent { using Newtonsoft.Json.Serialization; using Ninject; using Ninject.Web.Common.OwinHost; using Ninject.Web.WebApi.OwinHost; using Owin; using Properties; using System; using System.Net; using System.Reflection; using System.Web.Http; public class Startup { public void Configuration(IAppBuilder app) { var listenerKey = typeof(HttpListener).FullName; if (app.Properties==null || !app.Properties.ContainsKey(listenerKey)) { throw new ArgumentOutOfRangeException( nameof(app), "Cannnot access HTTP listener property"); } // Authn; Authz var listener = (HttpListener)app.Properties[listenerKey]; listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication; var config = new HttpConfiguration(); config.Filters.Add( new AuthorizeAttribute { Roles = $"{Environment.MachineName}\\SpiderCrab Operators" }); // Routes config.Routes.MapHttpRoute( name: "default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); // Serialization config.Formatters.XmlFormatter.UseXmlSerializer = true; config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Dependency injection app.UseNinjectMiddleware(CreateKernel) .UseNinjectWebApi(config); } private IKernel CreateKernel() { var kernel = new StandardKernel(new ServiceModule(Settings.Default)); kernel.Load(Assembly.GetExecutingAssembly()); return kernel; } } }
namespace SpiderCrab.Agent { using Ninject; using Ninject.Web.Common.OwinHost; using Ninject.Web.WebApi.OwinHost; using Owin; using Properties; using System.Reflection; using System.Web.Http; public class Startup { public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); app.UseNinjectMiddleware(CreateKernel) .UseNinjectWebApi(config); } private IKernel CreateKernel() { var kernel = new StandardKernel(new ServiceModule(Settings.Default)); kernel.Load(Assembly.GetExecutingAssembly()); return kernel; } } }
mit
C#
c63a205867fe3223463cdb5d1e655a6422305905
Handle download exceptions when attempting to fetch update
webprofusion/Certify,ndouthit/Certify
src/Certify.UI/Utils/UpdateCheckUtils.cs
src/Certify.UI/Utils/UpdateCheckUtils.cs
using Certify.Locales; using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace Certify.UI.Utils { public class UpdateCheckUtils { public async Task<Models.UpdateCheck> UpdateWithDownload() { Mouse.OverrideCursor = Cursors.Wait; Models.UpdateCheck updateCheck; try { updateCheck = await new Management.Util().DownloadUpdate(); } catch (Exception exp) { //could not complete or verify download MessageBox.Show("Sorry, the update could not be downloaded. Please try again later."); System.Diagnostics.Debug.WriteLine(exp.ToString()); return null; } if (!string.IsNullOrEmpty(updateCheck.UpdateFilePath)) { if (MessageBox.Show(SR.Update_ReadyToApply, ConfigResources.AppName, MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes) { // file has been downloaded and verified System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.FileName = updateCheck.UpdateFilePath; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.Arguments = "/SILENT"; p.Start(); //stop certify.service /*ServiceController service = new ServiceController("ServiceName"); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped);*/ Application.Current.Shutdown(); } } Mouse.OverrideCursor = Cursors.Arrow; return updateCheck; } } }
using Certify.Locales; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace Certify.UI.Utils { public class UpdateCheckUtils { public async Task<Models.UpdateCheck> UpdateWithDownload() { Mouse.OverrideCursor = Cursors.Wait; var updateCheck = await new Management.Util().DownloadUpdate(); if (!string.IsNullOrEmpty(updateCheck.UpdateFilePath)) { if (MessageBox.Show(SR.Update_ReadyToApply, ConfigResources.AppName, MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes) { // file has been downloaded and verified System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.FileName = updateCheck.UpdateFilePath; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.Arguments = "/SILENT"; p.Start(); //stop certify.service /*ServiceController service = new ServiceController("ServiceName"); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped);*/ Application.Current.Shutdown(); } } Mouse.OverrideCursor = Cursors.Arrow; return updateCheck; } } }
mit
C#
81bad76b04763e0fb73cb850db1cbd46d635b21f
Bump to v0.5
nickbabcock/Pdoxcl2Sharp
SharedAssemblyVersion.cs
SharedAssemblyVersion.cs
using System.Reflection; [assembly: AssemblyTitle("Pdoxcl2Sharp")] [assembly: AssemblyDescription("A Paradox Interactive general file parser.")] [assembly: AssemblyCompany("NBSoftSolutions")] [assembly: AssemblyProduct("Pdoxcl2Sharp")] [assembly: AssemblyCopyright("Copyright (C) Nick Babcock")] [assembly: AssemblyVersion("0.5.0.0")]
using System.Reflection; [assembly: AssemblyTitle("Pdoxcl2Sharp")] [assembly: AssemblyDescription("A Paradox Interactive general file parser.")] [assembly: AssemblyCompany("NBSoftSolutions")] [assembly: AssemblyProduct("Pdoxcl2Sharp")] [assembly: AssemblyCopyright("Copyright (C) Nick Babcock")] [assembly: AssemblyVersion("0.4.0.0")]
mit
C#
92c2b0e7717061da29fbe572891f3c2998bad32c
Fix SampleGame.iOS not using GameUIApplication
peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework
SampleGame.iOS/Application.cs
SampleGame.iOS/Application.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using UIKit; namespace SampleGame.iOS { public class Application { // This is the main entry point of the application. public static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, "GameUIApplication", "AppDelegate"); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using UIKit; namespace SampleGame.iOS { public class Application { // This is the main entry point of the application. public static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
mit
C#
42c166cdcd73683a17b69bd2a40441e9c35a0999
Send index.html for any unknown paths
Nemo157/DocNuget,Nemo157/DocNuget,Nemo157/DocNuget,Nemo157/DocNuget,Nemo157/DocNuget
src/DocNuget/Startup.cs
src/DocNuget/Startup.cs
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.AspNet.StaticFiles; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.Logging; using Newtonsoft.Json; namespace DocNuget { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.ConfigureMvcJson(options => { options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All; options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize; }); } public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.MinimumLevel = LogLevel.Debug; loggerFactory.AddConsole(LogLevel.Debug); app .UseErrorPage() .UseDefaultFiles() .UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true, }) .UseMvc() .UseSendFileFallback() .Use(async (context, next) => { await context.Response.SendFileAsync("wwwroot/index.html"); }); } } }
using System; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc; using Microsoft.AspNet.StaticFiles; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.Logging; using Newtonsoft.Json; namespace DocNuget { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.ConfigureMvcJson(options => { options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All; options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize; }); } public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { loggerFactory.MinimumLevel = LogLevel.Debug; loggerFactory.AddConsole(LogLevel.Debug); app.UseErrorPage(); app.UseDefaultFiles(); app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true, }); app.UseMvc(); } } }
mit
C#
6e6f232d3731f52d9493f10c2dd20cace0d1d244
Support RFC DateTime in Azure generator too
Azure/autorest,balajikris/autorest,brjohnstmsft/autorest,matt-gibbs/AutoRest,csmengwan/autorest,garimakhulbe/autorest,sharadagarwal/autorest,anudeepsharma/autorest,Azure/azure-sdk-for-java,matthchr/autorest,fhoring/autorest,yaqiyang/autorest,sergey-shandar/autorest,veronicagg/autorest,xingwu1/autorest,navalev/azure-sdk-for-java,yaqiyang/autorest,tbombach/autorest,dsgouda/autorest,annatisch/autorest,vulcansteel/autorest,Azure/azure-sdk-for-java,brodyberg/autorest,stankovski/AutoRest,yugangw-msft/autorest,begoldsm/autorest,BurtBiel/autorest,matt-gibbs/AutoRest,jianghaolu/AutoRest,BurtBiel/autorest,selvasingh/azure-sdk-for-java,vishrutshah/autorest,amarzavery/AutoRest,Azure/azure-sdk-for-java,sergey-shandar/autorest,AzCiS/autorest,haocs/autorest,lmazuel/autorest,stankovski/AutoRest,garimakhulbe/autorest,fhoring/autorest,devigned/autorest,garimakhulbe/autorest,brodyberg/autorest,John-Hart/autorest,jianghaolu/AutoRest,Azure/autorest,lmazuel/autorest,begoldsm/autorest,balajikris/autorest,vishrutshah/autorest,yaqiyang/autorest,matt-gibbs/AutoRest,vulcansteel/autorest,AzCiS/autorest,garimakhulbe/autorest,Azure/autorest,amarzavery/AutoRest,annatisch/autorest,csmengwan/autorest,vulcansteel/autorest,vishrutshah/autorest,haocs/autorest,matt-gibbs/AutoRest,garimakhulbe/autorest,veronicagg/autorest,haocs/autorest,devigned/autorest,vishrutshah/autorest,matthchr/autorest,BurtBiel/autorest,matt-gibbs/AutoRest,lmazuel/autorest,jkonecki/autorest,vishrutshah/autorest,haocs/autorest,ljhljh235/AutoRest,devigned/autorest,haocs/autorest,brodyberg/autorest,vishrutshah/autorest,sergey-shandar/autorest,vulcansteel/autorest,ljhljh235/AutoRest,vishrutshah/autorest,matt-gibbs/AutoRest,selvasingh/azure-sdk-for-java,dsgouda/autorest,tbombach/autorest,fhoring/autorest,sergey-shandar/autorest,annatisch/autorest,balajikris/autorest,devigned/autorest,stankovski/AutoRest,matthchr/autorest,csmengwan/autorest,haocs/autorest,sharadagarwal/autorest,amarzavery/AutoRest,jkonecki/autorest,amarzavery/AutoRest,xingwu1/autorest,devigned/autorest,AzCiS/autorest,olydis/autorest,yugangw-msft/autorest,jhendrixMSFT/autorest,stankovski/AutoRest,anudeepsharma/autorest,ljhljh235/AutoRest,anudeepsharma/autorest,sergey-shandar/autorest,csmengwan/autorest,fhoring/autorest,brodyberg/autorest,amarzavery/AutoRest,veronicagg/autorest,amarzavery/AutoRest,yugangw-msft/autorest,annatisch/autorest,hovsepm/AutoRest,xingwu1/autorest,yugangw-msft/autorest,devigned/autorest,xingwu1/autorest,csmengwan/autorest,anudeepsharma/autorest,brjohnstmsft/autorest,vulcansteel/autorest,veronicagg/autorest,AzCiS/autorest,AzCiS/autorest,Azure/autorest,jhancock93/autorest,brodyberg/autorest,yaqiyang/autorest,hovsepm/AutoRest,veronicagg/autorest,stankovski/AutoRest,Azure/azure-sdk-for-java,yaqiyang/autorest,tbombach/autorest,yugangw-msft/autorest,John-Hart/autorest,ljhljh235/AutoRest,sergey-shandar/autorest,vulcansteel/autorest,annatisch/autorest,balajikris/autorest,John-Hart/autorest,AzCiS/autorest,dsgouda/autorest,csmengwan/autorest,jhancock93/autorest,amarzavery/AutoRest,BurtBiel/autorest,ljhljh235/AutoRest,fearthecowboy/autorest,jkonecki/autorest,jhancock93/autorest,navalev/azure-sdk-for-java,vulcansteel/autorest,jianghaolu/AutoRest,navalev/azure-sdk-for-java,balajikris/autorest,tbombach/autorest,haocs/autorest,begoldsm/autorest,sharadagarwal/autorest,xingwu1/autorest,selvasingh/azure-sdk-for-java,BurtBiel/autorest,jhendrixMSFT/autorest,navalev/azure-sdk-for-java,anudeepsharma/autorest,matthchr/autorest,annatisch/autorest,tbombach/autorest,lmazuel/autorest,fhoring/autorest,annatisch/autorest,anudeepsharma/autorest,hovsepm/AutoRest,begoldsm/autorest,navalev/azure-sdk-for-java,sharadagarwal/autorest,jhancock93/autorest,jianghaolu/AutoRest,annatisch/autorest,jhendrixMSFT/autorest,garimakhulbe/autorest,John-Hart/autorest,lmazuel/autorest,sergey-shandar/autorest,AzCiS/autorest,stankovski/AutoRest,vishrutshah/autorest,ljhljh235/AutoRest,fhoring/autorest,ljhljh235/AutoRest,amarzavery/AutoRest,hovsepm/AutoRest,jhancock93/autorest,Azure/azure-sdk-for-java,haocs/autorest,begoldsm/autorest,vishrutshah/autorest,jianghaolu/AutoRest,hovsepm/AutoRest,yugangw-msft/autorest,hovsepm/AutoRest,xingwu1/autorest,dsgouda/autorest,jianghaolu/AutoRest,veronicagg/autorest,brodyberg/autorest,stankovski/AutoRest,anudeepsharma/autorest,veronicagg/autorest,dsgouda/autorest,tbombach/autorest,hovsepm/AutoRest,jianghaolu/AutoRest,jhancock93/autorest,jianghaolu/AutoRest,tbombach/autorest,fhoring/autorest,yugangw-msft/autorest,devigned/autorest,sergey-shandar/autorest,yaqiyang/autorest,amarzavery/AutoRest,veronicagg/autorest,yaqiyang/autorest,brodyberg/autorest,dsgouda/autorest,lmazuel/autorest,garimakhulbe/autorest,matthchr/autorest,balajikris/autorest,annatisch/autorest,BurtBiel/autorest,jianghaolu/AutoRest,jkonecki/autorest,jkonecki/autorest,brodyberg/autorest,balajikris/autorest,jhancock93/autorest,dsgouda/autorest,matthchr/autorest,veronicagg/autorest,jhancock93/autorest,xingwu1/autorest,begoldsm/autorest,balajikris/autorest,tbombach/autorest,begoldsm/autorest,devigned/autorest,BurtBiel/autorest,fhoring/autorest,sharadagarwal/autorest,John-Hart/autorest,csmengwan/autorest,dsgouda/autorest,lmazuel/autorest,matthchr/autorest,haocs/autorest,begoldsm/autorest,sergey-shandar/autorest,matthchr/autorest,csmengwan/autorest,devigned/autorest,lmazuel/autorest,jhancock93/autorest,sharadagarwal/autorest,fearthecowboy/autorest,balajikris/autorest,AzCiS/autorest,yugangw-msft/autorest,jhendrixMSFT/autorest,anudeepsharma/autorest,dsgouda/autorest,garimakhulbe/autorest,yaqiyang/autorest,fhoring/autorest,begoldsm/autorest,hovsepm/AutoRest,BurtBiel/autorest,sharadagarwal/autorest,tbombach/autorest,matthchr/autorest,ljhljh235/AutoRest,yugangw-msft/autorest,lmazuel/autorest,olydis/autorest,anudeepsharma/autorest,John-Hart/autorest,John-Hart/autorest,xingwu1/autorest,sharadagarwal/autorest,John-Hart/autorest,stankovski/AutoRest,garimakhulbe/autorest,hovsepm/AutoRest
AutoRest/Generators/CSharp/Azure.CSharp/Templates/AzureMethodGroupTemplate.cshtml
AutoRest/Generators/CSharp/Azure.CSharp/Templates/AzureMethodGroupTemplate.cshtml
@using Microsoft.Rest.Generator.CSharp @using Microsoft.Rest.Generator.CSharp.Templates @using Microsoft.Rest.Generator.CSharp.Azure @using Microsoft.Rest.Generator.CSharp.Azure.Templates @inherits Microsoft.Rest.Generator.Template<Microsoft.Rest.Generator.CSharp.Azure.AzureMethodGroupTemplateModel> @Header("// ") @EmptyLine namespace @Settings.Namespace { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; @foreach (var usingString in Model.Usings) { @: using @usingString; } @EmptyLine /// <summary> /// @(Model.MethodGroupType) operations. /// </summary> internal partial class @(Model.MethodGroupType) : IServiceOperations<@(Model.Name)>, I@(Model.MethodGroupType) { /// <summary> /// Initializes a new instance of the @(Model.MethodGroupType) class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal @(Model.MethodGroupType)(@(Model.Name) client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } @EmptyLine /// <summary> /// Gets a reference to the @(Model.Name) /// </summary> public @(Model.Name) Client { get; private set; } @EmptyLine @foreach (var method in Model.MethodTemplateModels) { @:@(Include(new AzureMethodTemplate(), (AzureMethodTemplateModel)method)) @EmptyLine } } }
@using Microsoft.Rest.Generator.CSharp @using Microsoft.Rest.Generator.CSharp.Templates @using Microsoft.Rest.Generator.CSharp.Azure @using Microsoft.Rest.Generator.CSharp.Azure.Templates @inherits Microsoft.Rest.Generator.Template<Microsoft.Rest.Generator.CSharp.Azure.AzureMethodGroupTemplateModel> @Header("// ") @EmptyLine namespace @Settings.Namespace { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Newtonsoft.Json; @foreach (var usingString in Model.Usings) { @: using @usingString; } @EmptyLine /// <summary> /// @(Model.MethodGroupType) operations. /// </summary> internal partial class @(Model.MethodGroupType) : IServiceOperations<@(Model.Name)>, I@(Model.MethodGroupType) { /// <summary> /// Initializes a new instance of the @(Model.MethodGroupType) class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal @(Model.MethodGroupType)(@(Model.Name) client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } @EmptyLine /// <summary> /// Gets a reference to the @(Model.Name) /// </summary> public @(Model.Name) Client { get; private set; } @EmptyLine @foreach (var method in Model.MethodTemplateModels) { @:@(Include(new AzureMethodTemplate(), (AzureMethodTemplateModel)method)) @EmptyLine } } }
mit
C#
42c94c6f528626470c9cba00b69f85d42e072670
Speed up file writing
avao/Qart,mcraveiro/Qart,tudway/Qart
Src/Qart.Core/Io/FileUtils.cs
Src/Qart.Core/Io/FileUtils.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Qart.Core.Io { public static class FileUtils { public static void EnsureCanBeWritten(string path) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } public static FileStream OpenFileStreamForReading(string path) { return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); } public static FileStream OpenFileStreamForWritingNoTruncate(string path) { return OpenFileStreamForWriting(path, FileMode.OpenOrCreate, FileAccess.Write); } public static FileStream OpenFileStreamForWriting(string path) { return OpenFileStreamForWriting(path, FileMode.Create, FileAccess.Write); } private static FileStream OpenFileStreamForWriting(string path, FileMode fileMode, FileAccess fileAccess) { //if IO is slow (shared network folder) it is faster to try executing an action and then if directory does not exist catch exception and create one. try { return new FileStream(path, fileMode, fileAccess); } catch (IOException ex) { //TODO more specific exception } FileUtils.EnsureCanBeWritten(path); return new FileStream(path, fileMode, fileAccess); } public static int ReadFromFile(string path, int length, byte[] buf) { using (var stream = OpenFileStreamForReading(path)) { return stream.Read(buf, 0, length); } } public static void WriteAllText(string path, string content) { FileUtils.EnsureCanBeWritten(path); File.WriteAllText(path, content); } public static string GetAssemblyDirectory() { string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Qart.Core.Io { public static class FileUtils { public static void EnsureCanBeWritten(string path) { string dirName = Path.GetDirectoryName(path); if (!System.IO.Directory.Exists(dirName)) {//Create it Directory.CreateDirectory(dirName); } } public static FileStream OpenFileStreamForReading(string path) { return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); } public static FileStream OpenFileStreamForWritingNoTruncate(string path) { FileUtils.EnsureCanBeWritten(path); return new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); } public static FileStream OpenFileStreamForWriting(string path) { FileUtils.EnsureCanBeWritten(path); return new FileStream(path, FileMode.Create, FileAccess.Write); } public static int ReadFromFile(string path, int length, byte[] buf) { using (var stream = OpenFileStreamForReading(path)) { return stream.Read(buf, 0, length); } } public static void WriteAllText(string path, string content) { FileUtils.EnsureCanBeWritten(path); File.WriteAllText(path, content); } public static string GetAssemblyDirectory() { string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path); } } }
apache-2.0
C#
b3ef1336cf1986aab6992126906891894730f7a1
Use IBasicProperties#SetPersistent
SaiNadh001/rabbitmq-tutorials,bwong199/rabbitmq-tutorials,bwong199/rabbitmq-tutorials,thoven78/rabbitmq-tutorials,fams/rabbitmq-tutorials,fengjx/rabbitmq-tutorials,yepesasecas/rabbitmq-tutorials,borna2exl/rabbitmq-tutorials,tkssharma/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,yepesasecas/rabbitmq-tutorials,mixmar91/rabbitmq,hangshiisi/rabbitmq-tutorials,fams/rabbitmq-tutorials,anhzhi/rabbitmq-tutorials,bwong199/rabbitmq-tutorials,yhiguchi/rabbitmq-tutorials,youyesun/rabbitmq-tutorials,hangshiisi/rabbitmq-tutorials,Dim0N22/rabbitmq-tutorials,fengjx/rabbitmq-tutorials,tkssharma/rabbitmq-tutorials,fengjx/rabbitmq-tutorials,AlexandrT/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,AlexandrT/rabbitmq-tutorials,SaiNadh001/rabbitmq-tutorials,thoven78/rabbitmq-tutorials,SaiNadh001/rabbitmq-tutorials,fams/rabbitmq-tutorials,SaiNadh001/rabbitmq-tutorials,bwong199/rabbitmq-tutorials,mixmar91/rabbitmq,girirajsharma/rabbitmq-tutorials,girirajsharma/rabbitmq-tutorials,Dim0N22/rabbitmq-tutorials,tkssharma/rabbitmq-tutorials,thoven78/rabbitmq-tutorials,youyesun/rabbitmq-tutorials,hangshiisi/rabbitmq-tutorials,thoven78/rabbitmq-tutorials,jonahglover/rabbitmq-tutorials,anhzhi/rabbitmq-tutorials,Dim0N22/rabbitmq-tutorials,anhzhi/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,girirajsharma/rabbitmq-tutorials,mixmar91/rabbitmq,yepesasecas/rabbitmq-tutorials,youyesun/rabbitmq-tutorials,youyesun/rabbitmq-tutorials,fengjx/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,borna2exl/rabbitmq-tutorials,hangshiisi/rabbitmq-tutorials,Dim0N22/rabbitmq-tutorials,mixmar91/rabbitmq,rabbitmq/rabbitmq-tutorials,youyesun/rabbitmq-tutorials,yhiguchi/rabbitmq-tutorials,yhiguchi/rabbitmq-tutorials,borna2exl/rabbitmq-tutorials,AlexandrT/rabbitmq-tutorials,fams/rabbitmq-tutorials,jonahglover/rabbitmq-tutorials,SaiNadh001/rabbitmq-tutorials,Dim0N22/rabbitmq-tutorials,yepesasecas/rabbitmq-tutorials,tkssharma/rabbitmq-tutorials,jonahglover/rabbitmq-tutorials,AlexandrT/rabbitmq-tutorials,yhiguchi/rabbitmq-tutorials,thoven78/rabbitmq-tutorials,youyesun/rabbitmq-tutorials,jonahglover/rabbitmq-tutorials,tkssharma/rabbitmq-tutorials,jonahglover/rabbitmq-tutorials,borna2exl/rabbitmq-tutorials,borna2exl/rabbitmq-tutorials,fengjx/rabbitmq-tutorials,jonahglover/rabbitmq-tutorials,anhzhi/rabbitmq-tutorials,fams/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,hangshiisi/rabbitmq-tutorials,AlexandrT/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,bwong199/rabbitmq-tutorials,girirajsharma/rabbitmq-tutorials,youyesun/rabbitmq-tutorials,borna2exl/rabbitmq-tutorials,mixmar91/rabbitmq,Dim0N22/rabbitmq-tutorials,yepesasecas/rabbitmq-tutorials,SaiNadh001/rabbitmq-tutorials,thoven78/rabbitmq-tutorials,Dim0N22/rabbitmq-tutorials,yepesasecas/rabbitmq-tutorials,girirajsharma/rabbitmq-tutorials,thoven78/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,anhzhi/rabbitmq-tutorials,anhzhi/rabbitmq-tutorials,thoven78/rabbitmq-tutorials,girirajsharma/rabbitmq-tutorials,AlexandrT/rabbitmq-tutorials,anhzhi/rabbitmq-tutorials,jonahglover/rabbitmq-tutorials,girirajsharma/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,mixmar91/rabbitmq,anhzhi/rabbitmq-tutorials,SaiNadh001/rabbitmq-tutorials,fengjx/rabbitmq-tutorials,yhiguchi/rabbitmq-tutorials,girirajsharma/rabbitmq-tutorials,Dim0N22/rabbitmq-tutorials,bwong199/rabbitmq-tutorials,yhiguchi/rabbitmq-tutorials,SaiNadh001/rabbitmq-tutorials,fams/rabbitmq-tutorials,tkssharma/rabbitmq-tutorials,tkssharma/rabbitmq-tutorials,fams/rabbitmq-tutorials,mixmar91/rabbitmq,bwong199/rabbitmq-tutorials,jonahglover/rabbitmq-tutorials,fengjx/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,mixmar91/rabbitmq,yepesasecas/rabbitmq-tutorials,hangshiisi/rabbitmq-tutorials,borna2exl/rabbitmq-tutorials,tkssharma/rabbitmq-tutorials,fams/rabbitmq-tutorials,hangshiisi/rabbitmq-tutorials,AlexandrT/rabbitmq-tutorials,tkssharma/rabbitmq-tutorials,yepesasecas/rabbitmq-tutorials,mixmar91/rabbitmq,AlexandrT/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,yhiguchi/rabbitmq-tutorials,Dim0N22/rabbitmq-tutorials,bwong199/rabbitmq-tutorials,yhiguchi/rabbitmq-tutorials,SaiNadh001/rabbitmq-tutorials,anhzhi/rabbitmq-tutorials,borna2exl/rabbitmq-tutorials,yepesasecas/rabbitmq-tutorials,girirajsharma/rabbitmq-tutorials,borna2exl/rabbitmq-tutorials,youyesun/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,bwong199/rabbitmq-tutorials,fams/rabbitmq-tutorials,fengjx/rabbitmq-tutorials,AlexandrT/rabbitmq-tutorials,hangshiisi/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,jonahglover/rabbitmq-tutorials
dotnet/NewTask.cs
dotnet/NewTask.cs
using System; using RabbitMQ.Client; using System.Text; class NewTask { public static void Main(string[] args) { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare("task_queue", true, false, false, null); var message = (args.Length > 0) ? string.Join(" ", args) : "Hello World!"; var body = Encoding.UTF8.GetBytes(message); var properties = channel.CreateBasicProperties(); properties.SetPersistent(true); channel.BasicPublish("", "task_queue", properties, body); Console.WriteLine(" [x] Sent {0}", message); } } } }
using System; using RabbitMQ.Client; using System.Text; class NewTask { public static void Main(string[] args) { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare("task_queue", true, false, false, null); var message = (args.Length > 0) ? string.Join(" ", args) : "Hello World!"; var body = Encoding.UTF8.GetBytes(message); var properties = channel.CreateBasicProperties(); properties.DeliveryMode = 2; channel.BasicPublish("", "task_queue", properties, body); Console.WriteLine(" [x] Sent {0}", message); } } } }
apache-2.0
C#
c594b30c76f7f87132a6a4495ee246d78e95e63a
Use 3x3x3.vox as default example
Arlorean/Voxels
Voxels.CommandLine/Program.cs
Voxels.CommandLine/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Voxels.SkiaSharp; namespace Voxels.CommandLine { class Program { static void Main(string[] args) { var filename = args.Length == 1 ? args[0] : "3x3x3.vox"; using (var stream = File.OpenRead(filename)) { var voxelData = MagicaVoxel.Read(stream); var guid = Guid.NewGuid(); File.WriteAllBytes($"output{guid}.png", Renderer.RenderPng(512, voxelData)); File.WriteAllBytes($"output{guid}.svg", Renderer.RenderSvg(512, voxelData)); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Voxels.SkiaSharp; namespace Voxels.CommandLine { class Program { static void Main(string[] args) { var filename = args.Length == 1 ? args[0] : "monu9.vox"; // "3x3x3.vox"; using (var stream = File.OpenRead(filename)) { var voxelData = MagicaVoxel.Read(stream); var guid = Guid.NewGuid(); File.WriteAllBytes($"output{guid}.png", Renderer.RenderPng(512, voxelData)); File.WriteAllBytes($"output{guid}.svg", Renderer.RenderSvg(512, voxelData)); } } } }
mit
C#
47bf769c6fb25fb85923b0b32d88d593456975c7
refactor DeleteTriggerFromJob to DeleteTrigger
Paymentsense/Dapper.SimpleSave
PS.Mothership.Core/PS.Mothership.Core.Common/Contracts/IQuartzManagementService.cs
PS.Mothership.Core/PS.Mothership.Core.Common/Contracts/IQuartzManagementService.cs
using PS.Mothership.Core.Common.Constructs; using PS.Mothership.Core.Common.Dto.DynamicRequest; using PS.Mothership.Core.Common.Dto.QuartzManagement; using PS.Mothership.Core.Common.Enums.QuartzManagement; using Quartz; using System; using System.Collections.Generic; using System.ServiceModel; namespace PS.Mothership.Core.Common.Contracts { [ServiceContract(Name = "QuartzManagementService")] public interface IQuartzManagementService { [OperationContract] QuartzServerInfoDto GetQuartzServerInfo(); [OperationContract] void ScheduleNewJob(string triggerName, string jobName, AvailableJobGroupsEnum jobGroupName, string jobClass, IntervalUnit occurance, string interval, DateTimeOffset startTime, IEnumerable<DayOfWeek> dayOfWeek = null); [OperationContract] void PauseAllTriggers(); [OperationContract] void ResumeAllTriggers(); [OperationContract] void PauseJob(string jobName); [OperationContract] void ResumeJob(string jobName); [OperationContract] void PauseTrigger(string triggerName); [OperationContract] void ResumeTrigger(string triggerName); [OperationContract] PagedList<JobProfileDto> GetJobs(DataRequestDto dataRequestDto); [OperationContract] void ExecuteJobNow(string jobName); [OperationContract] void AddTriggerToJob(string triggerName, string jobName, IntervalUnit occurance, string interval, DateTimeOffset startTime, IEnumerable<DayOfWeek> dayOfWeek = null); [OperationContract] void DeleteTrigger(string triggerName); [OperationContract] void RescheduleTrigger(string triggerName, IntervalUnit occurance, string interval, DateTimeOffset startTime, IEnumerable<DayOfWeek> dayOfWeek = null); } }
using PS.Mothership.Core.Common.Constructs; using PS.Mothership.Core.Common.Dto.DynamicRequest; using PS.Mothership.Core.Common.Dto.QuartzManagement; using PS.Mothership.Core.Common.Enums.QuartzManagement; using Quartz; using System; using System.Collections.Generic; using System.ServiceModel; namespace PS.Mothership.Core.Common.Contracts { [ServiceContract(Name = "QuartzManagementService")] public interface IQuartzManagementService { [OperationContract] QuartzServerInfoDto GetQuartzServerInfo(); [OperationContract] void ScheduleNewJob(string triggerName, string jobName, AvailableJobGroupsEnum jobGroupName, string jobClass, IntervalUnit occurance, string interval, DateTimeOffset startTime, IEnumerable<DayOfWeek> dayOfWeek = null); [OperationContract] void PauseAllTriggers(); [OperationContract] void ResumeAllTriggers(); [OperationContract] void PauseJob(string jobName); [OperationContract] void ResumeJob(string jobName); [OperationContract] void PauseTrigger(string triggerName); [OperationContract] void ResumeTrigger(string triggerName); [OperationContract] PagedList<JobProfileDto> GetJobs(DataRequestDto dataRequestDto); [OperationContract] void ExecuteJobNow(string jobName); [OperationContract] void AddTriggerToJob(string triggerName, string jobName, IntervalUnit occurance, string interval, DateTimeOffset startTime, IEnumerable<DayOfWeek> dayOfWeek = null); [OperationContract] void DeleteTriggerFromJob(string triggerName); [OperationContract] void RescheduleTrigger(string triggerName, IntervalUnit occurance, string interval, DateTimeOffset startTime, IEnumerable<DayOfWeek> dayOfWeek = null); } }
mit
C#
4395ef4e937ad445f7bd334e42cc0f9141b1a67f
Add HSTS header too.
qinxgit/azure-ssl-configure,qinxgit/azure-ssl-configure,qinxgit/azure-ssl-configure
AzureCloudServiceSample/WebRoleSample/Global.asax.cs
AzureCloudServiceSample/WebRoleSample/Global.asax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace WebRoleSample { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } protected void Application_EndRequest(Object sender, EventArgs e) { HttpContext context = HttpContext.Current; context.Response.AddHeader("Strict-Transport-Security", "max-age=15724800;includeSubDomains"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace WebRoleSample { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
mit
C#
e073dd26d3f5fa49d0a5470bfd42f01c1f05fb32
Fix for editing measurements
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Views/ABCP/Measurements.cshtml
Battery-Commander.Web/Views/ABCP/Measurements.cshtml
@model ABCP @{ if(!Model.Measurements.Any()) { Model.Measurements = new[] { new ABCP.Measurement{ }, new ABCP.Measurement{ }, new ABCP.Measurement{ } }; } } <panel class="panel"> <div class="panel-heading"> <h1>ABCP for @Html.DisplayFor(model => model.Soldier) on @Html.DisplayFor(model => model.Date)</h1> </div> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.Id) <table> <thead> <tr> <th>@Html.DisplayNameFor(model => model.Measurements.FirstOrDefault().Waist)</th> <th>@Html.DisplayNameFor(model => model.Measurements.FirstOrDefault().Neck)</th> @if (Model.Soldier.Gender == Gender.Female) { <th>@Html.DisplayNameFor(model => model.Measurements.FirstOrDefault().Hips)</th> } </tr> </thead> @for (int i = 0; i < Model.Measurements.Count(); i++) { <tr> <td><input name="measurements[@i].Waist" value="@Model.Measurements.ElementAt(i).Waist" /></td> <td><input name="measurements[@i].Neck" value="@Model.Measurements.ElementAt(i).Neck" /></td> @if (Model.Soldier.Gender == Gender.Female) { <td><input name="measurements[@i].Hips" value="@Model.Measurements.ElementAt(i).Hips" /></td> } </tr> } </table> <button type="submit">Save</button> } </panel>
@model ABCP <panel class="panel"> <div class="panel-heading"> <h1>ABCP for @Html.DisplayFor(model => model.Soldier) on @Html.DisplayFor(model => model.Date)</h1> </div> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.Id) <table> <thead> <tr> <th>@Html.DisplayNameFor(model => model.Measurements.FirstOrDefault().Waist)</th> <th>@Html.DisplayNameFor(model => model.Measurements.FirstOrDefault().Neck)</th> @if (Model.Soldier.Gender == Gender.Female) { <th>@Html.DisplayNameFor(model => model.Measurements.FirstOrDefault().Hips)</th> } </tr> </thead> @for (int i = 0; i < 3; i++) { <tr> <td><input name="measurements[@i].Waist" /></td> <td><input name="measurements[@i].Neck" /></td> @if (Model.Soldier.Gender == Gender.Female) { <td><input name="measurements[@i].Hips" /></td> } </tr> } </table> <button type="submit">Save</button> } </panel>
mit
C#
e42e8bd5620254d2ce39937b1d50c099ae2ba7c0
Fix the expected / actual order to correct the message
Tragetaschen/DbusCore
src/Dbus/ReceivedMessage.cs
src/Dbus/ReceivedMessage.cs
using System; using System.IO; using System.Runtime.InteropServices; namespace Dbus { public class ReceivedMessage : IDisposable { private readonly MessageHeader messageHeader; public ReceivedMessage( MessageHeader messageHeader, Decoder decoder ) { this.messageHeader = messageHeader; Decoder = decoder; } public SafeHandle[]? UnixFds => messageHeader.UnixFds; public Stream GetStream(int index) => messageHeader.GetStream(index); public Decoder Decoder { get; } public void AssertSignature(Signature expectedSignature) => messageHeader.BodySignature!.AssertEqual(expectedSignature); public void Dispose() => Decoder.Dispose(); } }
using System; using System.IO; using System.Runtime.InteropServices; namespace Dbus { public class ReceivedMessage : IDisposable { private readonly MessageHeader messageHeader; public ReceivedMessage( MessageHeader messageHeader, Decoder decoder ) { this.messageHeader = messageHeader; Decoder = decoder; } public SafeHandle[]? UnixFds => messageHeader.UnixFds; public Stream GetStream(int index) => messageHeader.GetStream(index); public Decoder Decoder { get; } public void AssertSignature(Signature signature) => signature.AssertEqual(messageHeader.BodySignature!); public void Dispose() => Decoder.Dispose(); } }
mit
C#
ca1ccaf17873916936c76221f24f96cc0afca2df
fix open log folder not working for private channels
AerysBat/slimCat,WreckedAvent/slimCat
slimCat/Commands/Channel/OpenLogCommand.cs
slimCat/Commands/Channel/OpenLogCommand.cs
#region Copyright // -------------------------------------------------------------------------------------------------------------------- // <copyright file="OpenLogCommand.cs"> // Copyright (c) 2013, Justin Kadrovach, All rights reserved. // // This source is subject to the Simplified BSD License. // Please see the License.txt file for more information. // All other rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace slimCat.Services { #region Usings using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms.VisualStyles; using Models; using Utilities; #endregion public partial class UserCommandService { private void OnOpenLogRequested(IDictionary<string, object> command) { logger.OpenLog(false, model.CurrentChannel.Title, model.CurrentChannel.Id); } private void OnOpenLogFolderRequested(IDictionary<string, object> command) { if (command.ContainsKey(Constants.Arguments.Channel)) { var toOpen = command.Get(Constants.Arguments.Channel); if (string.IsNullOrWhiteSpace(toOpen)) return; var match = model.AllChannels.FirstByIdOrNull(toOpen) ?? (ChannelModel) model.CurrentPms.FirstByIdOrNull(toOpen); if (match != null) logger.OpenLog(true, match.Title, match.Id); else logger.OpenLog(true, toOpen, toOpen); } else logger.OpenLog(true, model.CurrentChannel.Title, model.CurrentChannel.Id); } } }
#region Copyright // -------------------------------------------------------------------------------------------------------------------- // <copyright file="OpenLogCommand.cs"> // Copyright (c) 2013, Justin Kadrovach, All rights reserved. // // This source is subject to the Simplified BSD License. // Please see the License.txt file for more information. // All other rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace slimCat.Services { #region Usings using System.Collections.Generic; using Utilities; #endregion public partial class UserCommandService { private void OnOpenLogRequested(IDictionary<string, object> command) { logger.OpenLog(false, model.CurrentChannel.Title, model.CurrentChannel.Id); } private void OnOpenLogFolderRequested(IDictionary<string, object> command) { if (command.ContainsKey(Constants.Arguments.Channel)) { var toOpen = command.Get(Constants.Arguments.Channel); if (!string.IsNullOrWhiteSpace(toOpen)) logger.OpenLog(true, toOpen, toOpen); } else logger.OpenLog(true, model.CurrentChannel.Title, model.CurrentChannel.Id); } } }
bsd-2-clause
C#
bebba2a11394e8d7e3015e18836a1064af64704f
Make UnrootedConnectionsGetRemovedFromHeartbeat test less flaky (#1727)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/Microsoft.AspNetCore.Server.Kestrel.Core.Tests/FrameConnectionManagerTests.cs
test/Microsoft.AspNetCore.Server.Kestrel.Core.Tests/FrameConnectionManagerTests.cs
// Copyright (c) .NET Foundation. 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.Runtime.CompilerServices; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Testing; using Moq; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class FrameConnectionManagerTests { [Fact] public void UnrootedConnectionsGetRemovedFromHeartbeat() { var connectionId = "0"; var trace = new Mock<IKestrelTrace>(); var frameConnectionManager = new FrameConnectionManager(trace.Object); // Create FrameConnection in inner scope so it doesn't get rooted by the current frame. UnrootedConnectionsGetRemovedFromHeartbeatInnerScope(connectionId, frameConnectionManager, trace); GC.Collect(); GC.WaitForPendingFinalizers(); var connectionCount = 0; frameConnectionManager.Walk(_ => connectionCount++); Assert.Equal(0, connectionCount); trace.Verify(t => t.ApplicationNeverCompleted(connectionId), Times.Once()); } [MethodImpl(MethodImplOptions.NoInlining)] private void UnrootedConnectionsGetRemovedFromHeartbeatInnerScope( string connectionId, FrameConnectionManager frameConnectionManager, Mock<IKestrelTrace> trace) { var serviceContext = new TestServiceContext { ConnectionManager = frameConnectionManager }; // The FrameConnection constructor adds itself to the connection manager. var frameConnection = new FrameConnection(new FrameConnectionContext { ServiceContext = serviceContext, ConnectionId = connectionId }); var connectionCount = 0; frameConnectionManager.Walk(_ => connectionCount++); Assert.Equal(1, connectionCount); trace.Verify(t => t.ApplicationNeverCompleted(connectionId), Times.Never()); // Ensure frameConnection doesn't get GC'd before this point. GC.KeepAlive(frameConnection); } } }
// Copyright (c) .NET Foundation. 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.Runtime.CompilerServices; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Testing; using Moq; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class FrameConnectionManagerTests { [Fact(Skip = "Flaky test")] public void UnrootedConnectionsGetRemovedFromHeartbeat() { var connectionId = "0"; var trace = new Mock<IKestrelTrace>(); var frameConnectionManager = new FrameConnectionManager(trace.Object); // Create FrameConnection in inner scope so it doesn't get rooted by the current frame. UnrootedConnectionsGetRemovedFromHeartbeatInnerScope(connectionId, frameConnectionManager, trace); GC.Collect(); GC.WaitForPendingFinalizers(); var connectionCount = 0; frameConnectionManager.Walk(_ => connectionCount++); Assert.Equal(0, connectionCount); trace.Verify(t => t.ApplicationNeverCompleted(connectionId), Times.Once()); } [MethodImpl(MethodImplOptions.NoInlining)] private void UnrootedConnectionsGetRemovedFromHeartbeatInnerScope( string connectionId, FrameConnectionManager frameConnectionManager, Mock<IKestrelTrace> trace) { var serviceContext = new TestServiceContext { ConnectionManager = frameConnectionManager }; // The FrameConnection constructor adds itself to the connection manager. var ignore = new FrameConnection(new FrameConnectionContext { ServiceContext = serviceContext, ConnectionId = connectionId }); var connectionCount = 0; frameConnectionManager.Walk(_ => connectionCount++); Assert.Equal(1, connectionCount); trace.Verify(t => t.ApplicationNeverCompleted(connectionId), Times.Never()); } } }
apache-2.0
C#
5171f7610c2246ffc3a8c64e036e824adfda8daf
Update AssemblyInfo.cs
wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter
SimpleWavSplitter.Console/Properties/AssemblyInfo.cs
SimpleWavSplitter.Console/Properties/AssemblyInfo.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. 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("SimpleWavSplitter.Console")] [assembly: AssemblyDescription("SimpleWavSplitter.Console by Wiesław Šoltés")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Wiesław Šoltés")] [assembly: AssemblyProduct("SimpleWavSplitter.Console")] [assembly: AssemblyCopyright("Copyright © Wiesław Šoltés 2010-2012. All Rights Reserved")] [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("303d23dd-c234-4e0c-8cbc-4ab06c51702b")] // 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("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
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("SimpleWavSplitter.Console")] [assembly: AssemblyDescription("SimpleWavSplitter.Console by Wiesław Šoltés")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Wiesław Šoltés")] [assembly: AssemblyProduct("SimpleWavSplitter.Console")] [assembly: AssemblyCopyright("Copyright © Wiesław Šoltés 2010-2012. All Rights Reserved")] [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("303d23dd-c234-4e0c-8cbc-4ab06c51702b")] // 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("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
mit
C#
071c52f55c1332e58a3bea4fc8d1893dc96f711e
Test the publish/connect methods on IConnectableObservable.
georgebearden/ReactiveTests
Source/ReactiveTests/Tests/HotColdObservableTests.cs
Source/ReactiveTests/Tests/HotColdObservableTests.cs
using NUnit.Framework; using System; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; namespace ReactiveTests.Tests { public class HotColdObservableTests { /// <summary> /// A cold observable will create a new instance of the observable sequence /// from the specified subscribe method implementation each time it is called. /// </summary> [Test] public void CreateColdObservable() { int creationCount = 0; var coldObservable = Observable.Create<Unit>(_ => { creationCount++; return Disposable.Empty; }); coldObservable.Subscribe(_ => { }).Dispose(); Assert.AreEqual(1, creationCount); coldObservable.Subscribe(_ => { }).Dispose(); Assert.AreEqual(2, creationCount); } /// <summary> /// A hot observable will return the same instance of the observable sequence /// from the specified subscribe method implementation /// </summary> [Test] public void CreateHotObservable() { int creationCount = 0; var coldObservable = Observable.Create<Unit>(_ => { creationCount++; return Disposable.Empty; }); var hotObservable = coldObservable.Publish(); var hotDisposable = hotObservable.Connect(); hotObservable.Subscribe(_ => { }).Dispose(); Assert.AreEqual(1, creationCount); hotObservable.Subscribe(_ => { }).Dispose(); Assert.AreEqual(1, creationCount); } [Test] public void ObservableCreateIsLazy() { var isCreated = false; var coldObservable = Observable.Create<Unit>(_ => { isCreated = true; return Disposable.Empty; }); Assert.False(isCreated); } [Test] public void CallingConnectOnConnectableObservableCreatesTheObservableSequence() { var isCreated = false; var coldObservable = Observable.Create<Unit>(_ => { isCreated = true; return Disposable.Empty; }); // Observable.Create should be lazy Assert.False(isCreated); var hotObservable = coldObservable.Publish(); // Publish makes the observable sequence share the subscription but still does not instantiate it Assert.False(isCreated); var hotDisposable = hotObservable.Connect(); // Connect actually instantiates the subscription. Assert.True(isCreated); } } }
using NUnit.Framework; using System; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; namespace ReactiveTests.Tests { public class HotColdObservableTests { /// <summary> /// A cold observable will create a new instance of the observable sequence /// from the specified subscribe method implementation each time it is called. /// </summary> [Test] public void CreateColdObservable() { int creationCount = 0; var coldObservable = Observable.Create<Unit>(_ => { creationCount++; return Disposable.Empty; }); coldObservable.Subscribe(_ => { }).Dispose(); Assert.AreEqual(1, creationCount); coldObservable.Subscribe(_ => { }).Dispose(); Assert.AreEqual(2, creationCount); } /// <summary> /// A hot observable will return the same instance of the observable sequence /// from the specified subscribe method implementation /// </summary> [Test] public void CreateHotObservable() { int creationCount = 0; var coldObservable = Observable.Create<Unit>(_ => { creationCount++; return Disposable.Empty; }); var hotObservable = coldObservable.Publish(); var hotDisposable = hotObservable.Connect(); hotObservable.Subscribe(_ => { }).Dispose(); Assert.AreEqual(1, creationCount); hotObservable.Subscribe(_ => { }).Dispose(); Assert.AreEqual(1, creationCount); } } }
mit
C#
6ffabed421ff3351176acc7208cdc2c875285edf
add tracing for opening couchbase connection
Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek
Tweek.ApiService/Services/BucketConnectionIsAlive.cs
Tweek.ApiService/Services/BucketConnectionIsAlive.cs
using System; using System.Diagnostics; using Couchbase; using Couchbase.Core; using Tweek.ApiService.Interfaces; namespace Tweek.ApiService.Services { public class BucketConnectionIsAlive : IDisposable, IDiagnosticsProvider { public string Name { get; } = "CouchbaseConnectionIsAlive"; private readonly Cluster _cluster; private readonly string _bucketName; private IBucket _bucket; public BucketConnectionIsAlive(Cluster cluster, string bucketNameToCheck) { _cluster = cluster; _bucketName = bucketNameToCheck; } public object GetDetails() { return new { IsConnectionAlive = IsAlive() }; } public bool IsAlive() { if (!_cluster.IsOpen(_bucketName)) { Trace.TraceInformation("Opening couchbase connection"); _bucket = _cluster.OpenBucket(_bucketName); } return _cluster.IsOpen(_bucketName); } public void Dispose() { if (_bucket != null) _cluster.CloseBucket(_bucket); } } }
using System; using Couchbase; using Couchbase.Core; using Tweek.ApiService.Interfaces; namespace Tweek.ApiService.Services { public class BucketConnectionIsAlive : IDisposable, IDiagnosticsProvider { public string Name { get; } = "CouchbaseConnectionIsAlive"; private readonly Cluster _cluster; private readonly string _bucketName; private IBucket _bucket; public BucketConnectionIsAlive(Cluster cluster, string bucketNameToCheck) { _cluster = cluster; _bucketName = bucketNameToCheck; } public object GetDetails() { return new { IsConnectionAlive = IsAlive() }; } public bool IsAlive() { if (!_cluster.IsOpen(_bucketName)) { _bucket = _cluster.OpenBucket(_bucketName); } return _cluster.IsOpen(_bucketName); } public void Dispose() { if (_bucket != null) _cluster.CloseBucket(_bucket); } } }
mit
C#
5df3e9756957683a06d18adc771375802f858377
Update ObservableExtensions.cs
keith-hall/Extensions,keith-hall/Extensions
src/ObservableExtensions.cs
src/ObservableExtensions.cs
using System; using System.Reactive.Linq; namespace HallLibrary.Extensions { /// <summary> /// Contains extension methods for working with observables. /// </summary> public static class ObservableExtensions { /// <summary> /// Returns the current value of an observable with the previous value. /// </summary> /// <typeparam name="TSource">The source type.</typeparam> /// <typeparam name="TOutput">The output type after the <paramref name="projection" /> has been applied.</typeparam> /// <param name="source">The observable.</param> /// <param name="projection">The projection to apply.</param> /// <returns>The current observable value with the previous value.</returns> public static IObservable<TOutput> WithPrevious<TSource, TOutput>(this IObservable<TSource> source, Func<TSource, TSource, TOutput> projection) { // http://www.zerobugbuild.com/?p=213 return source.Scan(Tuple.Create(default(TSource), default(TSource)), (previous, current) => Tuple.Create(previous.Item2, current)) .Select(t => projection(t.Item1, t.Item2)); } } }
using System; using System.Reactive.Linq; namespace HallLibrary.Extensions { /// <summary> /// Contains extension methods for working with observables. /// </summary> public static class ObservableExtensions { /// <summary> /// Returns the current value of an observable with the previous value. /// </summary> /// <typeparam name="TSource">The source type.</typeparam> /// <typeparam name="TOutput">The output type after the <paramref name="projection" /> has been applied.</typeparam> /// <param name="source">The observable.</param> /// <param name="projection">The projection to apply.</param> /// <returns>The current observable value with the previous value.</returns> public static IObservable<TOutput> WithPrevious<TSource, TOutput>(this IObservable<TSource> source, Func<TSource, TSource, TOutput> projection) { return source.Scan(Tuple.Create(default(TSource), default(TSource)), (previous, current) => Tuple.Create(previous.Item2, current)) .Select(t => projection(t.Item1, t.Item2)); } } }
apache-2.0
C#
5403960e863327ce33c9d05f66aeff95b26706c6
update version number
OpenRA/tao,mono/tao,OpenRA/tao,mono/tao
src/Tao.Sdl/AssemblyInfo.cs
src/Tao.Sdl/AssemblyInfo.cs
#region License /* MIT License Copyright 2003-2005 Tao Framework Team http://www.taoframework.com All rights reserved. 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. */ #endregion License using System; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; [assembly: AllowPartiallyTrustedCallers] [assembly: AssemblyCompany("Tao Framework -- http://www.taoframework.com")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Retail")] #endif [assembly: AssemblyCopyright("Copyright 2003-2005 Tao Framework Team. All rights reserved.")] [assembly: AssemblyCulture("")] [assembly: AssemblyDefaultAlias("Tao.Sdl")] [assembly: AssemblyDelaySign(false)] #if WIN32 [assembly: AssemblyDescription("Tao Framework SDL Binding For .NET (Windows)")] #elif LINUX [assembly: AssemblyDescription("Tao Framework SDL Binding For .NET (Linux)")] #endif [assembly: AssemblyFileVersion("1.2.9.0")] [assembly: AssemblyInformationalVersion("1.2.9.0")] #if STRONG [assembly: AssemblyKeyFile(@"Tao.Sdl.snk")] #else [assembly: AssemblyKeyFile("")] #endif [assembly: AssemblyKeyName("")] #if DEBUG [assembly: AssemblyProduct("Tao.Sdl.dll *** Debug Build ***")] #else [assembly: AssemblyProduct("Tao.Sdl.dll")] #endif #if WIN32 [assembly: AssemblyTitle("Tao Framework SDL Binding For .NET (Windows)")] #elif LINUX [assembly: AssemblyTitle("Tao Framework SDL Binding For .NET (Linux)")] #endif [assembly: AssemblyTrademark("Tao Framework -- http://www.taoframework.com")] [assembly: AssemblyVersion("1.2.9.1")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.Execution)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.SkipVerification)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.UnmanagedCode)]
#region License /* MIT License Copyright 2003-2005 Tao Framework Team http://www.taoframework.com All rights reserved. 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. */ #endregion License using System; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; [assembly: AllowPartiallyTrustedCallers] [assembly: AssemblyCompany("Tao Framework -- http://www.taoframework.com")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Retail")] #endif [assembly: AssemblyCopyright("Copyright 2003-2005 Tao Framework Team. All rights reserved.")] [assembly: AssemblyCulture("")] [assembly: AssemblyDefaultAlias("Tao.Sdl")] [assembly: AssemblyDelaySign(false)] #if WIN32 [assembly: AssemblyDescription("Tao Framework SDL Binding For .NET (Windows)")] #elif LINUX [assembly: AssemblyDescription("Tao Framework SDL Binding For .NET (Linux)")] #endif [assembly: AssemblyFileVersion("1.2.9.0")] [assembly: AssemblyInformationalVersion("1.2.9.0")] #if STRONG [assembly: AssemblyKeyFile(@"Tao.Sdl.snk")] #else [assembly: AssemblyKeyFile("")] #endif [assembly: AssemblyKeyName("")] #if DEBUG [assembly: AssemblyProduct("Tao.Sdl.dll *** Debug Build ***")] #else [assembly: AssemblyProduct("Tao.Sdl.dll")] #endif #if WIN32 [assembly: AssemblyTitle("Tao Framework SDL Binding For .NET (Windows)")] #elif LINUX [assembly: AssemblyTitle("Tao Framework SDL Binding For .NET (Linux)")] #endif [assembly: AssemblyTrademark("Tao Framework -- http://www.taoframework.com")] [assembly: AssemblyVersion("1.2.8.1")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.Execution)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.SkipVerification)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.UnmanagedCode)]
mit
C#
1fbf35c3aa87a4f65e983b412e2cb805256c20d4
add stop watch to Program
jmrnilsson/efpad,jmrnilsson/efpad,jmrnilsson/efpad,jmrnilsson/efpad
c_scaffold/Program.cs
c_scaffold/Program.cs
using System; using System.Linq; using System.Diagnostics; using System.Collections.Generic; using Microsoft.Data.Entity; namespace c_scaffold { public class Program { public static void Main() { using (var db = new blogContext()) { var stopWatch = new Stopwatch(); stopWatch.Start(); var expression = from b in db.Blog join p in db.Post on b.BlogId equals p.BlogId select new {b.Url, p.Title, p.Content}; long interpret = stopWatch.ElapsedMilliseconds; var items = expression.ToList(); long read = stopWatch.ElapsedMilliseconds - interpret; var filtered = items.Where(i => i.Url == "768aea71-c405-4808-b1e6-150692142875").ToList(); long scan = stopWatch.ElapsedMilliseconds - read; foreach(var item in filtered) { Console.WriteLine("{0} - {1} - {2}", item.Url, item.Title, item.Content); } Console.WriteLine(); Console.WriteLine("{0} records read in {1} ms", items.Count(), read); Console.WriteLine("Average {0} ms per record", Math.Round((double) read / items.Count(), 2)); Console.WriteLine("Expression interpretation in {0} ms", interpret); Console.WriteLine("In-memory scan in {0} ms", scan); } } } }
using System; using System.Linq; using System.Collections.Generic; using Microsoft.Data.Entity; namespace c_scaffold { public class Program { public static void Main() { using (var db = new blogContext()) { var start = DateTime.UtcNow; var items = ( from p in db.Post select new {p.Blog.Url, p.Title, p.Content} ).ToList(); var duration = DateTime.UtcNow - start; foreach(var item in items) { Console.WriteLine("{0} - {1} - {2}", item.Url, item.Title, item.Content); } Console.WriteLine(); Console.WriteLine("{0} records read in {1} ms ", items.Count(), duration.TotalMilliseconds); Console.WriteLine("Total of {0} ms per record", duration.TotalMilliseconds / items.Count()); } } } }
mit
C#
060c1b780366fec06bf938806d16f46ca2363c4b
Add additional properties to Company
sevenshadow/sevenshadow-tagnifi
Company.cs
Company.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Web; using System.Runtime.Serialization; namespace SevenShadow.TagniFi { [DataContract(Name = "company")] public class Company { [DataMember(Name = "id")] public string ID { get; set; } [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "sic_code")] public int Sic_Code { get; set; } [DataMember(Name = "web_site")] public string Web_Site { get; set; } [DataMember(Name = "ticker")] public string Ticker { get; set; } [DataMember(Name = "industry_template")] public string Industry_Template { get; set; } [DataMember(Name = "fundamentals_history_link")] public string Fundamentals_History_Link { get; set; } [DataMember(Name = "description")] public string Description { get; set; } [DataMember(Name = "naics")] public string Naics { get; set; } [DataMember(Name = "industry")] public string Industry { get; set; } [DataMember(Name = "exchange")] public string Exchange { get; set; } [DataMember(Name = "employees")] public int Employees { get; set; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Web; using System.Runtime.Serialization; namespace SevenShadow.TagniFi { [DataContract(Name = "company")] public class Company { [DataMember(Name = "id")] public string ID { get; set; } [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "sic_code")] public int Sic_Code { get; set; } [DataMember(Name = "web_site")] public string Web_Site { get; set; } [DataMember(Name = "ticker")] public string Ticker { get; set; } [DataMember(Name = "industry_template")] public string Industry_Template { get; set; } [DataMember(Name = "fundamentals_history_link")] public string Fundamentals_History_Link { get; set; } } }
mit
C#
9eb0773bd0935d500118c833f97f26fc9b1d697c
Update HtmlTextNode.cs
zzzprojects/html-agility-pack,zzzprojects/html-agility-pack
src/HtmlAgilityPack.Shared/HtmlTextNode.cs
src/HtmlAgilityPack.Shared/HtmlTextNode.cs
// Description: Html Agility Pack - HTML Parsers, selectors, traversors, manupulators. // Website & Documentation: http://html-agility-pack.net // Forum & Issues: https://github.com/zzzprojects/html-agility-pack // License: https://github.com/zzzprojects/html-agility-pack/blob/master/LICENSE // More projects: http://www.zzzprojects.com/ // Copyright © ZZZ Projects Inc. 2014 - 2017. All rights reserved. namespace HtmlAgilityPack { /// <summary> /// Represents an HTML text node. /// </summary> public class HtmlTextNode : HtmlNode { #region Fields private string _text; #endregion Fields #region Constructors internal HtmlTextNode(HtmlDocument ownerdocument, int index) : base(HtmlNodeType.Text, ownerdocument, index) { } #endregion Constructors #region Properties /// <summary> /// Gets or Sets the HTML between the start and end tags of the object. In the case of a text node, it is equals to OuterHtml. /// </summary> public override string InnerHtml { get { return OuterHtml; } set { _text = value; } } /// <summary> /// Gets or Sets the object and its content in HTML. /// </summary> public override string OuterHtml { get { if (_text == null) { return base.OuterHtml; } return _text; } } /// <summary> /// Gets or Sets the text of the node. /// </summary> public string Text { get { if (_text == null) { return base.OuterHtml; } return _text; } set { _text = value; SetChanged(); } } #endregion Properties } }
// Description: Html Agility Pack - HTML Parsers, selectors, traversors, manupulators. // Website & Documentation: http://html-agility-pack.net // Forum & Issues: https://github.com/zzzprojects/html-agility-pack // License: https://github.com/zzzprojects/html-agility-pack/blob/master/LICENSE // More projects: http://www.zzzprojects.com/ // Copyright ZZZ Projects Inc. 2014 - 2017. All rights reserved. namespace HtmlAgilityPack { /// <summary> /// Represents an HTML text node. /// </summary> public class HtmlTextNode : HtmlNode { #region Fields private string _text; #endregion #region Constructors internal HtmlTextNode(HtmlDocument ownerdocument, int index) : base(HtmlNodeType.Text, ownerdocument, index) { } #endregion #region Properties /// <summary> /// Gets or Sets the HTML between the start and end tags of the object. In the case of a text node, it is equals to OuterHtml. /// </summary> public override string InnerHtml { get { return OuterHtml; } set { _text = value; } } /// <summary> /// Gets or Sets the object and its content in HTML. /// </summary> public override string OuterHtml { get { if (_text == null) { return base.OuterHtml; } return _text; } } /// <summary> /// Gets or Sets the text of the node. /// </summary> public string Text { get { if (_text == null) { return base.OuterHtml; } return _text; } set { _text = value; } } #endregion } }
mit
C#
c06c1aecb82613c2ce193d574502f7fc57536993
make member variables readonly
icarus-consulting/Yaapii.Atoms
src/Yaapii.Atoms/IO/LoggingOutputStream.cs
src/Yaapii.Atoms/IO/LoggingOutputStream.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using Yaapii.Atoms.Scalar; namespace Yaapii.Atoms.IO { public sealed class LoggingOutputStream : Stream { private readonly Stream origin; private readonly string destination; private readonly IScalar<IList<long>> bytes; private readonly IScalar<IList<long>> time; public LoggingOutputStream(Stream output, string destination) { this.origin = output; this.destination = destination; this.bytes = new ScalarOf<IList<long>>( new List<long>(1) { 0 }); this.time = new ScalarOf<IList<long>>( new List<long>(1) { 0 }); } public override bool CanRead => this.origin.CanRead; public override bool CanSeek => this.origin.CanSeek; public override bool CanWrite => this.origin.CanWrite; public override long Length => this.origin.Length; public override long Position { get => this.origin.Position; set => this.origin.Position = value; } public override void Flush() { this.origin.Flush(); Debug.WriteLine($"Written {this.bytes.Value()[0]} byte(s) to {this.destination} in {this.time.Value()[0]}ms."); } public override int Read(byte[] buffer, int offset, int count) { return this.origin.Read(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return this.origin.Seek(offset, origin); } public override void SetLength(long value) { this.origin.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { DateTime start = DateTime.UtcNow; this.origin.Write(buffer, offset, count); DateTime end = DateTime.UtcNow; long millis = (long)end.Subtract(start).TotalMilliseconds; this.bytes.Value()[0] += count; this.time.Value()[0] += millis; Debug.WriteLine($"Written {this.bytes.Value()[0]} byte(s) to {this.destination} in {this.time.Value()[0]}."); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; namespace Yaapii.Atoms.IO { public sealed class LoggingOutputStream : Stream { private readonly Stream origin; private readonly string destination; private long bytes; private long time; public LoggingOutputStream(Stream output, string destination) { this.origin = output; this.destination = destination; } public override bool CanRead => this.origin.CanRead; public override bool CanSeek => this.origin.CanSeek; public override bool CanWrite => this.origin.CanWrite; public override long Length => this.origin.Length; public override long Position { get => this.origin.Position; set => this.origin.Position = value; } public override void Flush() { this.origin.Flush(); Debug.WriteLine($"Flushed output stream from {this.destination}."); } public override int Read(byte[] buffer, int offset, int count) { return this.origin.Read(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return this.origin.Seek(offset, origin); } public override void SetLength(long value) { this.origin.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { DateTime start = DateTime.UtcNow; this.origin.Write(buffer, offset, count); DateTime end = DateTime.UtcNow; long millis = (long)end.Subtract(start).TotalMilliseconds; this.bytes += count; this.time += millis; Debug.WriteLine($"Written {this.bytes} byte(s) to {this.destination} in {this.time}."); } } }
mit
C#
36191dd71879fb4aced27f4e55ee747c733c6a22
Check ResolutionScope for ModuleRef/Def before resolving an assembly
ilkerhalil/dnlib,picrap/dnlib,ZixiangBoy/dnlib,yck1509/dnlib,jorik041/dnlib,Arthur2e5/dnlib,modulexcite/dnlib,kiootic/dnlib,0xd4d/dnlib
src/DotNet/Resolver.cs
src/DotNet/Resolver.cs
using dot10.DotNet.MD; namespace dot10.DotNet { /// <summary> /// Resolves types, methods, fields /// </summary> public class Resolver : IResolver { IAssemblyResolver assemblyResolver; /// <summary> /// Constructor /// </summary> /// <param name="assemblyResolver">The assembly resolver</param> public Resolver(IAssemblyResolver assemblyResolver) { this.assemblyResolver = assemblyResolver; } /// <inheritdoc/> public TypeDef Resolve(TypeRef typeRef) { if (typeRef == null) return null; var nonNestedTypeRef = TypeRef.GetNonNestedTypeRef(typeRef); if (nonNestedTypeRef != null) { var moduleDef = nonNestedTypeRef.ResolutionScope as ModuleDef; if (moduleDef != null) return moduleDef.Find(typeRef); var moduleRef = nonNestedTypeRef.ResolutionScope as ModuleRef; if (moduleRef != null && nonNestedTypeRef.OwnerModule != null) { if (new SigComparer().Equals(moduleRef, nonNestedTypeRef.OwnerModule)) return nonNestedTypeRef.OwnerModule.Find(typeRef); if (nonNestedTypeRef.OwnerModule.Assembly != null) return nonNestedTypeRef.OwnerModule.Assembly.Find(typeRef); } } var asm = assemblyResolver.Resolve(typeRef.DefinitionAssembly, typeRef.OwnerModule); return asm == null ? null : asm.Find(typeRef); } /// <inheritdoc/> public IMemberForwarded Resolve(MemberRef memberRef) { var declaringType = GetDeclaringType(memberRef); return declaringType == null ? null : declaringType.Resolve(memberRef); } TypeDef GetDeclaringType(MemberRef memberRef) { if (memberRef == null) return null; var parent = memberRef.Class; if (parent == null) return null; var declaringTypeDef = parent as TypeDef; if (declaringTypeDef != null) return declaringTypeDef; var declaringTypeRef = parent as TypeRef; if (declaringTypeRef != null) return Resolve(declaringTypeRef); // A module ref is used to reference the global type of a module in the same // assembly as the current module. var moduleRef = parent as ModuleRef; if (moduleRef != null) { var ownerModule = memberRef.OwnerModule; if (ownerModule == null) return null; TypeDef globalType = null; if (new SigComparer(0).Equals(ownerModule, moduleRef)) globalType = ownerModule.GlobalType; if (globalType == null && ownerModule.Assembly != null) { var moduleDef = ownerModule.Assembly.FindModule(moduleRef.Name); if (moduleDef != null) globalType = moduleDef.GlobalType; } return globalType; } // parent is Method or TypeSpec return null; } } }
using dot10.DotNet.MD; namespace dot10.DotNet { /// <summary> /// Resolves types, methods, fields /// </summary> public class Resolver : IResolver { IAssemblyResolver assemblyResolver; /// <summary> /// Constructor /// </summary> /// <param name="assemblyResolver">The assembly resolver</param> public Resolver(IAssemblyResolver assemblyResolver) { this.assemblyResolver = assemblyResolver; } /// <inheritdoc/> public TypeDef Resolve(TypeRef typeRef) { if (typeRef == null) return null; var asm = assemblyResolver.Resolve(typeRef.DefinitionAssembly, typeRef.OwnerModule); return asm == null ? null : asm.Find(typeRef); } /// <inheritdoc/> public IMemberForwarded Resolve(MemberRef memberRef) { var declaringType = GetDeclaringType(memberRef); return declaringType == null ? null : declaringType.Resolve(memberRef); } TypeDef GetDeclaringType(MemberRef memberRef) { if (memberRef == null) return null; var parent = memberRef.Class; if (parent == null) return null; var declaringTypeDef = parent as TypeDef; if (declaringTypeDef != null) return declaringTypeDef; var declaringTypeRef = parent as TypeRef; if (declaringTypeRef != null) return Resolve(declaringTypeRef); // A module ref is used to reference the global type of a module in the same // assembly as the current module. var moduleRef = parent as ModuleRef; if (moduleRef != null) { var ownerModule = memberRef.OwnerModule; if (ownerModule == null) return null; TypeDef globalType = null; if (new SigComparer(0).Equals(ownerModule, moduleRef)) globalType = ownerModule.GlobalType; if (globalType == null && ownerModule.Assembly != null) { var moduleDef = ownerModule.Assembly.FindModule(moduleRef.Name); if (moduleDef != null) globalType = moduleDef.GlobalType; } return globalType; } // parent is Method or TypeSpec return null; } } }
mit
C#
fa6bab479ae27e6704fae5d132790832e0be7f7f
Fix "Pack" step to be dependent on the "Test" step
HangfireIO/Cronos
build.cake
build.cake
#tool "nuget:?package=xunit.runner.console" #addin "Cake.FileHelpers" // Don't edit manually! Use `.\build.ps1 -ScriptArgs '--newVersion="*.*.*"'` command instead! var version = "0.2.0"; var configuration = Argument("configuration", "Release"); var newVersion = Argument("newVersion", version); var target = Argument("target", "Pack"); Task("Restore") .Does(()=> { DotNetCoreRestore(); }); Task("Clean") .Does(()=> { CleanDirectory("./build"); StartProcess("dotnet", "clean -c:" + configuration); }); Task("Version") .Does(() => { if(newVersion == version) return; var versionRegex = @"[0-9]+(\.([0-9]+|\*)){1,3}"; var cakeRegex = "var version = \"" + versionRegex + "\""; ReplaceRegexInFiles("build.cake", cakeRegex, "var version = \"" + newVersion + "\""); ReplaceRegexInFiles("appveyor.yml", "version: " + versionRegex, "version: " + newVersion + ""); }); Task("Build") .IsDependentOn("Version") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(()=> { DotNetCoreBuild("src/Cronos/Cronos.csproj", new DotNetCoreBuildSettings { Configuration = configuration, ArgumentCustomization = args => args.Append("/p:Version=" + version) }); }); Task("Test") .IsDependentOn("Build") .Does(() => { DotNetCoreTest("./tests/Cronos.Tests/Cronos.Tests.csproj", new DotNetCoreTestSettings { Configuration = "Release", ArgumentCustomization = args => args.Append("/p:BuildProjectReferences=false") }); }); Task("AppVeyor") .IsDependentOn("Test") .Does(()=> { if (AppVeyor.Environment.Repository.Tag.IsTag) { var tagName = AppVeyor.Environment.Repository.Tag.Name; if(tagName.StartsWith("v")) { version = tagName.Substring(1); } AppVeyor.UpdateBuildVersion(version); } }); Task("Local") .Does(()=> { RunTarget("Test"); }); Task("Pack") .IsDependentOn("Test") .Does(()=> { var target = AppVeyor.IsRunningOnAppVeyor ? "AppVeyor" : "Local"; RunTarget(target); CreateDirectory("build"); Zip("./src/Cronos/bin/" + configuration, "build/Cronos-" + version +".zip"); }); RunTarget(target);
#tool "nuget:?package=xunit.runner.console" #addin "Cake.FileHelpers" // Don't edit manually! Use `.\build.ps1 -ScriptArgs '--newVersion="*.*.*"'` command instead! var version = "0.2.0"; var configuration = Argument("configuration", "Release"); var newVersion = Argument("newVersion", version); var target = Argument("target", "Pack"); Task("Restore") .Does(()=> { DotNetCoreRestore(); }); Task("Clean") .Does(()=> { CleanDirectory("./build"); StartProcess("dotnet", "clean -c:" + configuration); }); Task("Version") .Does(() => { if(newVersion == version) return; var versionRegex = @"[0-9]+(\.([0-9]+|\*)){1,3}"; var cakeRegex = "var version = \"" + versionRegex + "\""; ReplaceRegexInFiles("build.cake", cakeRegex, "var version = \"" + newVersion + "\""); ReplaceRegexInFiles("appveyor.yml", "version: " + versionRegex, "version: " + newVersion + ""); }); Task("Build") .IsDependentOn("Version") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(()=> { DotNetCoreBuild("src/Cronos/Cronos.csproj", new DotNetCoreBuildSettings { Configuration = configuration, ArgumentCustomization = args => args.Append("/p:Version=" + version) }); }); Task("Test") .IsDependentOn("Build") .Does(() => { DotNetCoreTest("./tests/Cronos.Tests/Cronos.Tests.csproj", new DotNetCoreTestSettings { Configuration = "Release", ArgumentCustomization = args => args.Append("/p:BuildProjectReferences=false") }); }); Task("AppVeyor") .IsDependentOn("Test") .Does(()=> { if (AppVeyor.Environment.Repository.Tag.IsTag) { var tagName = AppVeyor.Environment.Repository.Tag.Name; if(tagName.StartsWith("v")) { version = tagName.Substring(1); } AppVeyor.UpdateBuildVersion(version); } }); Task("Local") .Does(()=> { RunTarget("Test"); }); Task("Pack") .Does(()=> { var target = AppVeyor.IsRunningOnAppVeyor ? "AppVeyor" : "Local"; RunTarget(target); CreateDirectory("build"); Zip("./src/Cronos/bin/" + configuration, "build/Cronos-" + version +".zip"); }); RunTarget(target);
mit
C#
2b8d41afc14675fc9fd4b96852cb9a19645f0e6b
Fix branch <-> repo switch
agc93/Cake.VisualStudio,agc93/Cake.VisualStudio
build.cake
build.cake
/////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var solutionPath = File("./Cake.VisualStudio.sln"); var solution = ParseSolution(solutionPath); var projects = solution.Projects; var projectPaths = projects.Select(p => p.Path.GetDirectory()); var artifacts = "./dist/"; /////////////////////////////////////////////////////////////////////////////// // BUILD VARIABLES /////////////////////////////////////////////////////////////////////////////// var buildSystem = BuildSystem; var IsMainCakeVsRepo = StringComparer.OrdinalIgnoreCase.Equals("cake-build/cake-vs", buildSystem.AppVeyor.Environment.Repository.Name); var IsMainCakeVsBranch = StringComparer.OrdinalIgnoreCase.Equals("master", buildSystem.AppVeyor.Environment.Repository.Branch); var IsBuildTagged = buildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(buildSystem.AppVeyor.Environment.Repository.Tag.Name); /////////////////////////////////////////////////////////////////////////////// // SETUP / TEARDOWN /////////////////////////////////////////////////////////////////////////////// Setup(ctx => { // Executed BEFORE the first task. Information("Running tasks..."); }); Teardown(ctx => { // Executed AFTER the last task. Information("Finished running tasks."); }); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { // Clean solution directories. foreach(var path in projectPaths) { Information("Cleaning {0}", path); CleanDirectories(path + "/**/bin/" + configuration); CleanDirectories(path + "/**/obj/" + configuration); } Information("Cleaning common files..."); CleanDirectory(artifacts); }); Task("Restore") .Does(() => { // Restore all NuGet packages. Information("Restoring solution..."); NuGetRestore(solutionPath); }); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { Information("Building solution..."); MSBuild(solutionPath, settings => settings.SetPlatformTarget(PlatformTarget.MSIL) .SetMSBuildPlatform(MSBuildPlatform.x86) .WithProperty("TreatWarningsAsErrors","true") .SetVerbosity(Verbosity.Quiet) .WithTarget("Build") .SetConfiguration(configuration)); }); Task("Post-Build") .IsDependentOn("Build") .Does(() => { CopyFileToDirectory("./src/bin/" + configuration + "/Cake.VisualStudio.vsix", artifacts); }); Task("Publish-Extension") .IsDependentOn("Post-Build") .WithCriteria(() => AppVeyor.IsRunningOnAppVeyor) .WithCriteria(() => IsMainCakeVsRepo) .Does(() => { AppVeyor.UploadArtifact(artifacts + "Cake.VisualStudio.vsix"); }); Task("Default") .IsDependentOn("Post-Build"); Task("AppVeyor") .IsDependentOn("Publish-Extension"); RunTarget(target);
/////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var solutionPath = File("./Cake.VisualStudio.sln"); var solution = ParseSolution(solutionPath); var projects = solution.Projects; var projectPaths = projects.Select(p => p.Path.GetDirectory()); var artifacts = "./dist/"; /////////////////////////////////////////////////////////////////////////////// // BUILD VARIABLES /////////////////////////////////////////////////////////////////////////////// var buildSystem = BuildSystem; var IsMainCakeVsRepo = StringComparer.OrdinalIgnoreCase.Equals("master", buildSystem.AppVeyor.Environment.Repository.Branch); var IsMainCakeVsBranch = StringComparer.OrdinalIgnoreCase.Equals("cake-build/cake-vs", buildSystem.AppVeyor.Environment.Repository.Name); var IsBuildTagged = buildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(buildSystem.AppVeyor.Environment.Repository.Tag.Name); /////////////////////////////////////////////////////////////////////////////// // SETUP / TEARDOWN /////////////////////////////////////////////////////////////////////////////// Setup(ctx => { // Executed BEFORE the first task. Information("Running tasks..."); }); Teardown(ctx => { // Executed AFTER the last task. Information("Finished running tasks."); }); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { // Clean solution directories. foreach(var path in projectPaths) { Information("Cleaning {0}", path); CleanDirectories(path + "/**/bin/" + configuration); CleanDirectories(path + "/**/obj/" + configuration); } Information("Cleaning common files..."); CleanDirectory(artifacts); }); Task("Restore") .Does(() => { // Restore all NuGet packages. Information("Restoring solution..."); NuGetRestore(solutionPath); }); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { Information("Building solution..."); MSBuild(solutionPath, settings => settings.SetPlatformTarget(PlatformTarget.MSIL) .SetMSBuildPlatform(MSBuildPlatform.x86) .WithProperty("TreatWarningsAsErrors","true") .SetVerbosity(Verbosity.Quiet) .WithTarget("Build") .SetConfiguration(configuration)); }); Task("Post-Build") .IsDependentOn("Build") .Does(() => { CopyFileToDirectory("./src/bin/" + configuration + "/Cake.VisualStudio.vsix", artifacts); }); Task("Publish-Extension") .IsDependentOn("Post-Build") .WithCriteria(() => AppVeyor.IsRunningOnAppVeyor) .WithCriteria(() => IsMainCakeVsRepo) .Does(() => { AppVeyor.UploadArtifact(artifacts + "Cake.VisualStudio.vsix"); }); Task("Default") .IsDependentOn("Post-Build"); Task("AppVeyor") .IsDependentOn("Publish-Extension"); RunTarget(target);
mit
C#
42b95019dc440711fc32b1e6f0e1eb0823ee5745
fix for running test target.
masteryee/protoactor-dotnet,masteryee/protoactor-dotnet,Bee-Htcpcp/protoactor-dotnet,tomliversidge/protoactor-dotnet,raskolnikoov/protoactor-dotnet,Bee-Htcpcp/protoactor-dotnet,AsynkronIT/protoactor-dotnet,raskolnikoov/protoactor-dotnet,tomliversidge/protoactor-dotnet
build.cake
build.cake
#addin Cake.Git var packageVersion = "0.1.8"; var target = Argument("target", "Default"); var mygetApiKey = Argument<string>("mygetApiKey", null); var currentBranch = Argument<string>("currentBranch", GitBranchCurrent("./").FriendlyName); var buildNumber = Argument<string>("buildNumber", null); var configuration = "Release"; var versionSuffix = ""; if (currentBranch != "master") { versionSuffix += "-" + currentBranch; if (buildNumber != null) { versionSuffix += "-build" + buildNumber.PadLeft(5, '0'); } packageVersion += versionSuffix; } Information("Version: " + packageVersion); Task("PatchVersion") .Does(() => { foreach(var proj in GetFiles("src/**/*.csproj")) { Information("Patching " + proj); XmlPoke(proj, "/Project/PropertyGroup/Version", packageVersion); } }); Task("Restore") .IsDependentOn("PatchVersion") .Does(() => { DotNetCoreRestore(); }); Task("Build") .IsDependentOn("Restore") .Does(() => { DotNetCoreBuild("ProtoActor.sln", new DotNetCoreBuildSettings { Configuration = configuration, }); }); Task("UnitTest") .Does(() => { foreach(var proj in GetFiles("tests/**/*.Tests.csproj")) { DotNetCoreTest(proj.ToString(), new DotNetCoreTestSettings { NoBuild = true, Configuration = configuration }); } }); Task("Pack") .Does(() => { foreach(var proj in GetFiles("src/**/*.csproj")) { DotNetCorePack(proj.ToString(), new DotNetCorePackSettings { OutputDirectory = "out", Configuration = configuration, NoBuild = true, }); } }); Task("Push") .Does(() => { var pkgs = GetFiles("out/*.nupkg"); foreach(var pkg in pkgs) { NuGetPush(pkg, new NuGetPushSettings { Source = "https://www.myget.org/F/protoactor/api/v2/package", ApiKey = mygetApiKey }); } }); Task("Default") .IsDependentOn("Restore") .IsDependentOn("PatchVersion") .IsDependentOn("Build") .IsDependentOn("UnitTest") .IsDependentOn("Pack") ; RunTarget(target);
#addin Cake.Git var packageVersion = "0.1.8"; var target = Argument("target", "Default"); var mygetApiKey = Argument<string>("mygetApiKey", null); var currentBranch = Argument<string>("currentBranch", GitBranchCurrent("./").FriendlyName); var buildNumber = Argument<string>("buildNumber", null); var versionSuffix = ""; if (currentBranch != "master") { versionSuffix += "-" + currentBranch; if (buildNumber != null) { versionSuffix += "-build" + buildNumber.PadLeft(5, '0'); } packageVersion += versionSuffix; } Information("Version: " + packageVersion); Task("PatchVersion") .Does(() => { foreach(var proj in GetFiles("src/**/*.csproj")) { Information("Patching " + proj); XmlPoke(proj, "/Project/PropertyGroup/Version", packageVersion); } }); Task("Restore") .IsDependentOn("PatchVersion") .Does(() => { DotNetCoreRestore(); }); Task("Build") .IsDependentOn("Restore") .Does(() => { DotNetCoreBuild("ProtoActor.sln", new DotNetCoreBuildSettings { Configuration = "Release", }); }); Task("UnitTest") .Does(() => { foreach(var proj in GetFiles("tests/**/*.Tests.csproj")) { DotNetCoreTest(proj.ToString(), new DotNetCoreTestSettings { NoBuild = true, }); } }); Task("Pack") .Does(() => { foreach(var proj in GetFiles("src/**/*.csproj")) { DotNetCorePack(proj.ToString(), new DotNetCorePackSettings { OutputDirectory = "out", Configuration = "Release", NoBuild = true, }); } }); Task("Push") .Does(() => { var pkgs = GetFiles("out/*.nupkg"); foreach(var pkg in pkgs) { NuGetPush(pkg, new NuGetPushSettings { Source = "https://www.myget.org/F/protoactor/api/v2/package", ApiKey = mygetApiKey }); } }); Task("Default") .IsDependentOn("Restore") .IsDependentOn("PatchVersion") .IsDependentOn("Build") .IsDependentOn("UnitTest") .IsDependentOn("Pack") ; RunTarget(target);
apache-2.0
C#
4f7d37306a4f4b4a47db14de39148caaf363beca
prepare for release to 3.7
bjartebore/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,yamamoWorks/azure-activedirectory-library-for-dotnet,AzureAD/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet
src/ADAL.Common/CommonAssemblyInfo.cs
src/ADAL.Common/CommonAssemblyInfo.cs
//---------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // 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.Reflection; [assembly: AssemblyProduct("Active Directory Authentication Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCulture("")] [assembly: AssemblyCompany("Microsoft Open Technologies")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Open Technologies. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("3.7.0.0")] // Keep major and minor versions in AssemblyFileVersion in sync with AssemblyVersion. // Build and revision numbers are replaced on build machine for official builds. [assembly: AssemblyFileVersion("3.7.00000.0000")] // On official build, attribute AssemblyInformationalVersionAttribute is added as well // with its value equal to the hash of the last commit to the git branch. // e.g.: [assembly: AssemblyInformationalVersionAttribute("4392c9835a38c27516fc0cd7bad7bccdcaeab161")] [assembly: CLSCompliant(false)]
//---------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // 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.Reflection; [assembly: AssemblyProduct("Active Directory Authentication Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCulture("")] [assembly: AssemblyCompany("Microsoft Open Technologies")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Open Technologies. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("3.6.0.0")] // Keep major and minor versions in AssemblyFileVersion in sync with AssemblyVersion. // Build and revision numbers are replaced on build machine for official builds. [assembly: AssemblyFileVersion("3.6.00000.0000")] // On official build, attribute AssemblyInformationalVersionAttribute is added as well // with its value equal to the hash of the last commit to the git branch. // e.g.: [assembly: AssemblyInformationalVersionAttribute("4392c9835a38c27516fc0cd7bad7bccdcaeab161")] [assembly: CLSCompliant(false)]
mit
C#
da35920df25f36d1ea7a8b1f7f2bad5195a10c1e
Update DavidHall.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/DavidHall.cs
src/Firehose.Web/Authors/DavidHall.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class DavidHall : IAmACommunityMember { public string FirstName => "David"; public string LastName => "Hall"; public string ShortBioOrTagLine => "Microsoft PowerShell Enthusiast. Founder of SignalWarrant.com"; public string StateOrRegion => "Georgia, USA"; public string EmailAddress => ""; public string TwitterHandle => "signalwarrant"; public string GitHubHandle => "signalwarrant"; public string GravatarHash => "afd7acd25c1511435fd85cdeda29aa43"; public GeoPosition Position => new GeoPosition(33.281, -82.0743); public Uri WebSite => new Uri("https://signalwarrant.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.cyberautomate.io/index.xml"); } } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class DavidHall : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "David"; public string LastName => "Hall"; public string ShortBioOrTagLine => "Microsoft PowerShell Enthusiast. Founder of SignalWarrant.com"; public string StateOrRegion => "Georgia, USA"; public string EmailAddress => ""; public string TwitterHandle => "signalwarrant"; public string GitHubHandle => "signalwarrant"; public string GravatarHash => "afd7acd25c1511435fd85cdeda29aa43"; public GeoPosition Position => new GeoPosition(33.281, -82.0743); public Uri WebSite => new Uri("https://signalwarrant.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://signalwarrant.com/feed/"); } } public bool Filter(SyndicationItem item) { return item.Categories?.Any(c => c.Name.ToLowerInvariant().Contains("powershell")) ?? false; } public string FeedLanguageCode => "en"; } }
mit
C#
b73a1c8957443fdc8d898f620a20e02fa83dbb19
Update @peterfoot with new URLs (#662)
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/PeterFoot.cs
src/Firehose.Web/Authors/PeterFoot.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class PeterFoot : IAmAMicrosoftMVP { public string FirstName => "Peter"; public string LastName => "Foot"; public string StateOrRegion => "United Kingdom"; public string EmailAddress => "peter@peterfoot.net"; public string TwitterHandle => "peterfoot"; public Uri WebSite => new Uri("https://inthehand.com/blog/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://inthehand.com/category/xamarin/feed/"); } } public string GravatarHash => "fa15aeeccc4b23e8a4677aeacb65b7bb"; public string ShortBioOrTagLine => "develops Xamarin and Windows applications at In The Hand Ltd"; public string GitHubHandle => "peterfoot"; public GeoPosition Position => new GeoPosition(52.76872, -2.37825); public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class PeterFoot : IAmAMicrosoftMVP { public string FirstName => "Peter"; public string LastName => "Foot"; public string StateOrRegion => "United Kingdom"; public string EmailAddress => "peter@peterfoot.net"; public string TwitterHandle => "peterfoot"; public Uri WebSite => new Uri("https://peterfoot.net"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://peterfoot.net/feed/"); } } public string GravatarHash => "fa15aeeccc4b23e8a4677aeacb65b7bb"; public string ShortBioOrTagLine => "develops Xamarin and Windows applications at In The Hand Ltd"; public string GitHubHandle => "peterfoot"; public GeoPosition Position => new GeoPosition(52.76872, -2.37825); public string FeedLanguageCode => "en"; } }
mit
C#
3378ec6a843e62faa8f109a548893c0926e17bf4
Add new property to LastTag
realworld666/lastfm,Brijen/lastfm
src/IF.Lastfm.Core/Objects/LastTag.cs
src/IF.Lastfm.Core/Objects/LastTag.cs
using System; using Newtonsoft.Json.Linq; namespace IF.Lastfm.Core.Objects { public class LastTag : ILastfmObject { #region Properties public string Name { get; set; } public Uri Url { get; set; } public int? Count { get; set; } public string RelatedTo { get; set; } public bool? Streamable { get; set; } /// <summary> /// The number of users that have used this tag /// </summary> public int? Reach { get; set; } #endregion public LastTag() { } public LastTag(string name, string uri, int? count = null) { Name = name; Url = new Uri(uri, UriKind.RelativeOrAbsolute); Count = count; } internal static LastTag ParseJToken(JToken token, string relatedTag = null) { var name = token.Value<string>("name"); var url = token.Value<string>("url"); int? count = null; var countToken = token.SelectToken("count"); if (countToken != null) { count = countToken.ToObject<int?>(); } bool? streamable = null; var streamableToken = token.SelectToken("streamable"); if (streamableToken != null) { streamable = Convert.ToBoolean(streamableToken.Value<int>()); } int? reach = null; var reachToken = token.SelectToken("reach"); if (reachToken != null) { reach = reachToken.ToObject<int?>(); } return new LastTag(name, url, count) { Streamable = streamable, RelatedTo = relatedTag, Reach = reach }; } } }
using System; using Newtonsoft.Json.Linq; namespace IF.Lastfm.Core.Objects { public class LastTag : ILastfmObject { #region Properties public string Name { get; set; } public Uri Url { get; set; } public int? Count { get; set; } public string RelatedTo { get; set; } public bool? Streamable { get; set; } #endregion public LastTag() { } public LastTag(string name, string uri, int? count = null) { Name = name; Url = new Uri(uri, UriKind.RelativeOrAbsolute); Count = count; } internal static LastTag ParseJToken(JToken token, string relatedTag = null) { var name = token.Value<string>("name"); var url = token.Value<string>("url"); int? count = null; var countToken = token.SelectToken("count"); if (countToken != null) { count = countToken.ToObject<int?>(); } bool? streamable = null; var streamableToken = token.SelectToken("streamable"); if (streamableToken != null) { streamable = Convert.ToBoolean(streamableToken.Value<int>()); } return new LastTag(name, url, count) { Streamable = streamable, RelatedTo = relatedTag }; } } }
mit
C#
79e1cd1cfad93e463886df9bac6907a016c85576
Fix support for Npgsql6 provider (#3064)
fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core
src/NHibernate/Driver/NpgsqlDriver.cs
src/NHibernate/Driver/NpgsqlDriver.cs
using System.Data; using System.Data.Common; using NHibernate.AdoNet; namespace NHibernate.Driver { /// <summary> /// The PostgreSQL data provider provides a database driver for PostgreSQL. /// <p> /// Author: <a href="mailto:oliver@weichhold.com">Oliver Weichhold</a> /// </p> /// </summary> /// <remarks> /// <p> /// In order to use this Driver you must have the Npgsql.dll Assembly available for /// NHibernate to load it. /// </p> /// <p> /// Please check the products website /// <a href="http://www.postgresql.org/">http://www.postgresql.org/</a> /// for any updates and or documentation. /// </p> /// <p> /// The homepage for the .NET DataProvider is: /// <a href="http://pgfoundry.org/projects/npgsql">http://pgfoundry.org/projects/npgsql</a>. /// </p> /// </remarks> public class NpgsqlDriver : ReflectionBasedDriver, IEmbeddedBatcherFactoryProvider { /// <summary> /// Initializes a new instance of the <see cref="NpgsqlDriver"/> class. /// </summary> /// <exception cref="HibernateException"> /// Thrown when the <c>Npgsql</c> assembly can not be loaded. /// </exception> public NpgsqlDriver() : base( "Npgsql", "Npgsql", "Npgsql.NpgsqlConnection", "Npgsql.NpgsqlCommand") { } public override bool UseNamedPrefixInSql => true; public override bool UseNamedPrefixInParameter => true; public override string NamedPrefix => ":"; public override bool SupportsMultipleOpenReaders => false; /// <remarks> /// NH-2267 Patrick Earl /// </remarks> protected override bool SupportsPreparingCommands => true; public override bool SupportsNullEnlistment => false; public override IResultSetsCommand GetResultSetsCommand(Engine.ISessionImplementor session) { return new BasicResultSetsCommand(session); } public override bool SupportsMultipleQueries => true; protected override void InitializeParameter(DbParameter dbParam, string name, SqlTypes.SqlType sqlType) { if (sqlType == null) throw new QueryException($"No type assigned to parameter '{name}'"); dbParam.ParameterName = FormatNameForParameter(name); if (sqlType.DbType == DbType.Currency) { // Since the .NET currency type has 4 decimal places, we use a decimal type in PostgreSQL instead of its native 2 decimal currency type. dbParam.DbType = DbType.Decimal; } else if (DriverVersionMajor < 6 || sqlType.DbType != DbType.DateTime) { dbParam.DbType = sqlType.DbType; } else { // Let Npgsql 6 driver to decide parameter type } } // Prior to v3, Npgsql was expecting DateTime for time. // https://github.com/npgsql/npgsql/issues/347 public override bool RequiresTimeSpanForTime => DriverVersionMajor >= 3; public override bool HasDelayedDistributedTransactionCompletion => true; System.Type IEmbeddedBatcherFactoryProvider.BatcherFactoryClass => typeof(GenericBatchingBatcherFactory); private int DriverVersionMajor => DriverVersion?.Major ?? 3; } }
using System.Data; using System.Data.Common; using NHibernate.AdoNet; namespace NHibernate.Driver { /// <summary> /// The PostgreSQL data provider provides a database driver for PostgreSQL. /// <p> /// Author: <a href="mailto:oliver@weichhold.com">Oliver Weichhold</a> /// </p> /// </summary> /// <remarks> /// <p> /// In order to use this Driver you must have the Npgsql.dll Assembly available for /// NHibernate to load it. /// </p> /// <p> /// Please check the products website /// <a href="http://www.postgresql.org/">http://www.postgresql.org/</a> /// for any updates and or documentation. /// </p> /// <p> /// The homepage for the .NET DataProvider is: /// <a href="http://pgfoundry.org/projects/npgsql">http://pgfoundry.org/projects/npgsql</a>. /// </p> /// </remarks> public class NpgsqlDriver : ReflectionBasedDriver, IEmbeddedBatcherFactoryProvider { /// <summary> /// Initializes a new instance of the <see cref="NpgsqlDriver"/> class. /// </summary> /// <exception cref="HibernateException"> /// Thrown when the <c>Npgsql</c> assembly can not be loaded. /// </exception> public NpgsqlDriver() : base( "Npgsql", "Npgsql", "Npgsql.NpgsqlConnection", "Npgsql.NpgsqlCommand") { } public override bool UseNamedPrefixInSql => true; public override bool UseNamedPrefixInParameter => true; public override string NamedPrefix => ":"; public override bool SupportsMultipleOpenReaders => false; /// <remarks> /// NH-2267 Patrick Earl /// </remarks> protected override bool SupportsPreparingCommands => true; public override bool SupportsNullEnlistment => false; public override IResultSetsCommand GetResultSetsCommand(Engine.ISessionImplementor session) { return new BasicResultSetsCommand(session); } public override bool SupportsMultipleQueries => true; protected override void InitializeParameter(DbParameter dbParam, string name, SqlTypes.SqlType sqlType) { base.InitializeParameter(dbParam, name, sqlType); // Since the .NET currency type has 4 decimal places, we use a decimal type in PostgreSQL instead of its native 2 decimal currency type. if (sqlType.DbType == DbType.Currency) dbParam.DbType = DbType.Decimal; } // Prior to v3, Npgsql was expecting DateTime for time. // https://github.com/npgsql/npgsql/issues/347 public override bool RequiresTimeSpanForTime => (DriverVersion?.Major ?? 3) >= 3; public override bool HasDelayedDistributedTransactionCompletion => true; System.Type IEmbeddedBatcherFactoryProvider.BatcherFactoryClass => typeof(GenericBatchingBatcherFactory); } }
lgpl-2.1
C#
f582266df162efb71416e327c63b9b4278054ce2
cover more equals possibilities
fealty/Frost
Frost/Testing.cs
Frost/Testing.cs
// Copyright (c) 2012, Joshua Burke // All rights reserved. // // See LICENSE for more information. using System; using System.Diagnostics.Contracts; using System.Reflection; #if(UNIT_TESTING) namespace Frost { internal class FactAttribute : Xunit.FactAttribute { } internal class Assert : Xunit.Assert { public static void TestObject<T>(T item1, T item2) { Contract.Requires(!item1.Equals(item2)); object object1 = item1; object object2 = item2; // test IEquatable<T> if any on the type Equal(item1, item1); NotEqual(item1, item2); NotEqual(item2, item1); Equal(item2, item2); // test null on IEquatable IEquatable<T> equate = item1 as IEquatable<T>; if(equate != null) { // ReSharper disable ReturnValueOfPureMethodIsNotUsed equate.Equals(default(T)); // ReSharper restore ReturnValueOfPureMethodIsNotUsed } // test the object.Equals() on the type True(item1.Equals(object1)); False(item1.Equals(null)); False(item1.Equals(object2)); False(item2.Equals(object1)); True(item2.Equals(object2)); False(item2.Equals(null)); // test ToString() on the objects NotNull(object1.ToString()); NotNull(object2.ToString()); // test GetHashCode() on the objects Equal(object1.GetHashCode(), object1.GetHashCode()); Equal(object2.GetHashCode(), object2.GetHashCode()); // test the == operator if any is defined on the type MethodInfo opEquality1 = object1.GetType().GetMethod("op_Equality"); MethodInfo opEquality2 = object2.GetType().GetMethod("op_Equality"); if(opEquality1 != null && opEquality2 != null) { False((bool)opEquality1.Invoke(null, new[] {object1, object2})); False((bool)opEquality2.Invoke(null, new[] {object2, object1})); True((bool)opEquality1.Invoke(null, new[] {object1, object1})); True((bool)opEquality2.Invoke(null, new[] {object2, object2})); } // test the != operator if any is defined on the type MethodInfo opInequality1 = object1.GetType().GetMethod("op_Inequality"); MethodInfo opInequality2 = object2.GetType().GetMethod("op_Inequality"); if(opInequality1 != null && opInequality2 != null) { True((bool)opInequality1.Invoke(null, new[] {object1, object2})); True((bool)opInequality2.Invoke(null, new[] {object2, object1})); False((bool)opInequality1.Invoke(null, new[] {object1, object1})); False((bool)opInequality2.Invoke(null, new[] {object2, object2})); } } } } #endif
// Copyright (c) 2012, Joshua Burke // All rights reserved. // // See LICENSE for more information. using System.Diagnostics.Contracts; using System.Reflection; #if(UNIT_TESTING) namespace Frost { internal class FactAttribute : Xunit.FactAttribute { } internal class Assert : Xunit.Assert { public static void TestObject<T>(T item1, T item2) { Contract.Requires(!item1.Equals(item2)); object object1 = item1; object object2 = item2; // test IEquatable<T> if any on the type Equal(item1, item1); NotEqual(item1, item2); NotEqual(item2, item1); Equal(item2, item2); // test the object.Equals() on the type True(item1.Equals(object1)); False(item1.Equals(null)); False(item1.Equals(object2)); False(item2.Equals(object1)); True(item2.Equals(object2)); False(item2.Equals(null)); // test ToString() on the objects NotNull(object1.ToString()); NotNull(object2.ToString()); // test GetHashCode() on the objects Equal(object1.GetHashCode(), object1.GetHashCode()); Equal(object2.GetHashCode(), object2.GetHashCode()); // test the == operator if any is defined on the type MethodInfo opEquality1 = object1.GetType().GetMethod("op_Equality"); MethodInfo opEquality2 = object2.GetType().GetMethod("op_Equality"); if(opEquality1 != null && opEquality2 != null) { False((bool)opEquality1.Invoke(null, new[] {object1, object2})); False((bool)opEquality2.Invoke(null, new[] {object2, object1})); True((bool)opEquality1.Invoke(null, new[] {object1, object1})); True((bool)opEquality2.Invoke(null, new[] {object2, object2})); } // test the != operator if any is defined on the type MethodInfo opInequality1 = object1.GetType().GetMethod("op_Inequality"); MethodInfo opInequality2 = object2.GetType().GetMethod("op_Inequality"); if(opInequality1 != null && opInequality2 != null) { True((bool)opInequality1.Invoke(null, new[] {object1, object2})); True((bool)opInequality2.Invoke(null, new[] {object2, object1})); False((bool)opInequality1.Invoke(null, new[] {object1, object1})); False((bool)opInequality2.Invoke(null, new[] {object2, object2})); } } } } #endif
bsd-2-clause
C#
17af7989003c66c6c931ee177a08116b7037f86f
Remove UnityEngine.UI dependency.
unity3d-jp/AlembicImporter,unity3d-jp/AlembicImporter,unity3d-jp/AlembicImporter
proto.com.unity.formats.alembic/Runtime/Scripts/Importer/AlembicStreamDescriptor.cs
proto.com.unity.formats.alembic/Runtime/Scripts/Importer/AlembicStreamDescriptor.cs
using UnityEngine; namespace UnityEngine.Formats.Alembic.Importer { internal class AlembicStreamDescriptor : ScriptableObject { [SerializeField] private string pathToAbc; public string PathToAbc { get { return pathToAbc; } set { pathToAbc = value; } } [SerializeField] private AlembicStreamSettings settings = new AlembicStreamSettings(); public AlembicStreamSettings Settings { get { return settings; } set { settings = value; } } [SerializeField] private bool hasVaryingTopology = false; public bool HasVaryingTopology { get { return hasVaryingTopology; } set { hasVaryingTopology = value; } } [SerializeField] private bool hasAcyclicFramerate = false; public bool HasAcyclicFramerate { get { return hasAcyclicFramerate; } set { hasAcyclicFramerate = value; } } [SerializeField] public double abcStartTime = double.MinValue; [SerializeField] public double abcEndTime = double.MaxValue; public double duration { get { return abcEndTime - abcStartTime; } } } }
using UnityEngine; using UnityEngine.UI; namespace UnityEngine.Formats.Alembic.Importer { internal class AlembicStreamDescriptor : ScriptableObject { [SerializeField] private string pathToAbc; public string PathToAbc { get { return pathToAbc; } set { pathToAbc = value; } } [SerializeField] private AlembicStreamSettings settings = new AlembicStreamSettings(); public AlembicStreamSettings Settings { get { return settings; } set { settings = value; } } [SerializeField] private bool hasVaryingTopology = false; public bool HasVaryingTopology { get { return hasVaryingTopology; } set { hasVaryingTopology = value; } } [SerializeField] private bool hasAcyclicFramerate = false; public bool HasAcyclicFramerate { get { return hasAcyclicFramerate; } set { hasAcyclicFramerate = value; } } [SerializeField] public double abcStartTime = double.MinValue; [SerializeField] public double abcEndTime = double.MaxValue; public double duration { get { return abcEndTime - abcStartTime; } } } }
mit
C#
3e4da419ca8788d28d908b3356c6a632cfd87bde
update assembly version
agileharbor/shipStationAccess
src/Global/GlobalAssemblyInfo.cs
src/Global/GlobalAssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [ assembly : ComVisible( false ) ] [ assembly : AssemblyProduct( "ShipStationAccess" ) ] [ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ] [ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ] [ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ] [ assembly : AssemblyTrademark( "" ) ] [ assembly : AssemblyCulture( "" ) ] [ assembly : CLSCompliant( false ) ] // 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.*")] // Keep in track with CA API version [ assembly : AssemblyVersion( "1.3.75.0" ) ]
using System; using System.Reflection; using System.Runtime.InteropServices; [ assembly : ComVisible( false ) ] [ assembly : AssemblyProduct( "ShipStationAccess" ) ] [ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ] [ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ] [ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ] [ assembly : AssemblyTrademark( "" ) ] [ assembly : AssemblyCulture( "" ) ] [ assembly : CLSCompliant( false ) ] // 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.*")] // Keep in track with CA API version [ assembly : AssemblyVersion( "1.3.74.0" ) ]
bsd-3-clause
C#
65fbb600e4dac9bb331cbfc367b9a5dd56bebea9
Add TODO comment to remind to revert
AmadeusW/roslyn,eriawan/roslyn,KevinRansom/roslyn,stephentoub/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,brettfo/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,genlu/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,AlekseyTs/roslyn,aelij/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,brettfo/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,mavasani/roslyn,wvdd007/roslyn,mavasani/roslyn,gafter/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,heejaechang/roslyn,dotnet/roslyn,tannergooding/roslyn,bartdesmet/roslyn,weltkante/roslyn,mavasani/roslyn,jmarolf/roslyn,diryboy/roslyn,stephentoub/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,sharwell/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,heejaechang/roslyn,tmat/roslyn,sharwell/roslyn,jmarolf/roslyn,heejaechang/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,gafter/roslyn,davkean/roslyn,aelij/roslyn,AlekseyTs/roslyn,physhi/roslyn,genlu/roslyn,gafter/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,wvdd007/roslyn,davkean/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,AmadeusW/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,mgoertz-msft/roslyn,davkean/roslyn,aelij/roslyn,tmat/roslyn,ErikSchierboom/roslyn,tannergooding/roslyn,wvdd007/roslyn,panopticoncentral/roslyn,physhi/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,dotnet/roslyn,bartdesmet/roslyn,jmarolf/roslyn,genlu/roslyn
src/Features/LanguageServer/Protocol/Handler/References/FindAllReferencesHandler.cs
src/Features/LanguageServer/Protocol/Handler/References/FindAllReferencesHandler.cs
// 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. #nullable enable using System; using System.Composition; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.CustomProtocol; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServer.Protocol; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportLspMethod(LSP.Methods.TextDocumentReferencesName), Shared] internal class FindAllReferencesHandler : IRequestHandler<LSP.ReferenceParams, LSP.VSReferenceItem[]> { private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FindAllReferencesHandler(IMetadataAsSourceFileService metadataAsSourceFileService) { _metadataAsSourceFileService = metadataAsSourceFileService; } public async Task<LSP.VSReferenceItem[]> HandleRequestAsync( Solution solution, ReferenceParams referenceParams, ClientCapabilities clientCapabilities, string? clientName, CancellationToken cancellationToken) { Debug.Assert(clientCapabilities.HasVisualStudioLspCapability()); var document = solution.GetDocumentFromURI(referenceParams.TextDocument.Uri, clientName); if (document == null) { return Array.Empty<LSP.VSReferenceItem>(); } var findUsagesService = document.GetRequiredLanguageService<IFindUsagesLSPService>(); var position = await document.GetPositionFromLinePositionAsync( ProtocolConversions.PositionToLinePosition(referenceParams.Position), cancellationToken).ConfigureAwait(false); var context = new FindUsagesLSPContext(document, position, _metadataAsSourceFileService, cancellationToken); // Finds the references for the symbol at the specific position in the document, reporting them via streaming to the LSP client. // TODO: Change back FAR to use streaming once the following LSP bug is fixed: // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1094786/ await findUsagesService.FindReferencesAsync(document, position, context).ConfigureAwait(false); return context.GetReferences().ToArray(); } } }
// 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. #nullable enable using System; using System.Composition; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.CustomProtocol; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServer.Protocol; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportLspMethod(LSP.Methods.TextDocumentReferencesName), Shared] internal class FindAllReferencesHandler : IRequestHandler<LSP.ReferenceParams, LSP.VSReferenceItem[]> { private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FindAllReferencesHandler(IMetadataAsSourceFileService metadataAsSourceFileService) { _metadataAsSourceFileService = metadataAsSourceFileService; } public async Task<LSP.VSReferenceItem[]> HandleRequestAsync( Solution solution, ReferenceParams referenceParams, ClientCapabilities clientCapabilities, string? clientName, CancellationToken cancellationToken) { Debug.Assert(clientCapabilities.HasVisualStudioLspCapability()); var document = solution.GetDocumentFromURI(referenceParams.TextDocument.Uri, clientName); if (document == null) { return Array.Empty<LSP.VSReferenceItem>(); } var findUsagesService = document.GetRequiredLanguageService<IFindUsagesLSPService>(); var position = await document.GetPositionFromLinePositionAsync( ProtocolConversions.PositionToLinePosition(referenceParams.Position), cancellationToken).ConfigureAwait(false); var context = new FindUsagesLSPContext(document, position, _metadataAsSourceFileService, cancellationToken); // Finds the references for the symbol at the specific position in the document, reporting them via streaming to the LSP client. await findUsagesService.FindReferencesAsync(document, position, context).ConfigureAwait(false); return context.GetReferences().ToArray(); } } }
mit
C#
80902778807faacb0fb1a87e458afceefdd3b6f9
Fix - Corretto generatore di codici richiesta
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
src/backend/SO115App.Persistence.MongoDB/GestioneInterventi/Utility/GetMaxCodice.cs
src/backend/SO115App.Persistence.MongoDB/GestioneInterventi/Utility/GetMaxCodice.cs
using MongoDB.Driver; using Persistence.MongoDB; using SO115App.API.Models.Classi.Soccorso; using System; using System.Linq; namespace SO115App.Persistence.MongoDB.GestioneInterventi.Utility { public class GetMaxCodice { private readonly DbContext _dbContext; public GetMaxCodice(DbContext dbContext) { _dbContext = dbContext; } public int GetMax(string codiceSede) { int MaxIdSintesi; var codiceProvincia = codiceSede.Split('.')[0]; var ListaRichieste = _dbContext.RichiestaAssistenzaCollection.Find(Builders<RichiestaAssistenza>.Filter.Empty).ToList().Where(x => x.Codice.IndexOf(codiceProvincia) != -1); if (ListaRichieste.Any()) { var codiceRichiesta = ListaRichieste.OrderByDescending(x => x.CodRichiesta).FirstOrDefault().CodRichiesta; if (codiceRichiesta != null) MaxIdSintesi = Convert.ToInt16(codiceRichiesta.Substring(codiceRichiesta.Length - 5)) + 1; else MaxIdSintesi = 0; } else MaxIdSintesi = 0; return MaxIdSintesi; } public int GetMaxCodiceChiamata(string codiceSede) { int MaxIdSintesi; var codiceProvincia = codiceSede.Split('.')[0]; var ListaRichieste = _dbContext.RichiestaAssistenzaCollection.Find(Builders<RichiestaAssistenza>.Filter.Empty).ToList().Where(x => x.Codice.IndexOf(codiceProvincia) != -1); if (ListaRichieste.Any()) { string codice = ListaRichieste.OrderByDescending(x => x.IstanteRicezioneRichiesta).FirstOrDefault().Codice; MaxIdSintesi = Convert.ToInt16(codice.Substring(codice.Length - 5)) + 1; } else { MaxIdSintesi = 0; } return MaxIdSintesi; } } }
using MongoDB.Driver; using Persistence.MongoDB; using SO115App.API.Models.Classi.Soccorso; using System; using System.Linq; namespace SO115App.Persistence.MongoDB.GestioneInterventi.Utility { public class GetMaxCodice { private readonly DbContext _dbContext; public GetMaxCodice(DbContext dbContext) { _dbContext = dbContext; } public int GetMax(string codiceSede) { int MaxIdSintesi; var codiceProvincia = codiceSede.Split('.')[0]; var ListaRichieste = _dbContext.RichiestaAssistenzaCollection.Find(Builders<RichiestaAssistenza>.Filter.Empty).ToList().Where(x => x.Codice.IndexOf(codiceProvincia) != -1); if (ListaRichieste.Any()) { var idPRov = ListaRichieste.OrderByDescending(x => x.CodRichiesta).FirstOrDefault().CodRichiesta; MaxIdSintesi = Convert.ToInt16(idPRov.Substring(idPRov.Length - 5)) + 1; } else MaxIdSintesi = 0; return MaxIdSintesi; } public int GetMaxCodiceChiamata(string codiceSede) { int MaxIdSintesi; var codiceProvincia = codiceSede.Split('.')[0]; var ListaRichieste = _dbContext.RichiestaAssistenzaCollection.Find(Builders<RichiestaAssistenza>.Filter.Empty).ToList().Where(x => x.Codice.IndexOf(codiceProvincia) != -1); if (ListaRichieste.Any()) { string codice = ListaRichieste.OrderByDescending(x => x.IstanteRicezioneRichiesta).FirstOrDefault().Codice; MaxIdSintesi = Convert.ToInt16(codice.Substring(codice.Length - 5)) + 1; } else { MaxIdSintesi = 0; } return MaxIdSintesi; } } }
agpl-3.0
C#
915b3e4ba839904c008d846c8f26086fae69fd6b
Format HexColor.cs and remove setters from properties.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
src/NadekoBot/Common/HexColor.cs
src/NadekoBot/Common/HexColor.cs
using System.Globalization; using System.Text.RegularExpressions; using Discord; namespace Mitternacht.Common { public class HexColor { public byte Red { get; } public byte Green { get; } public byte Blue { get; } public HexColor(byte red, byte green, byte blue) { Red = red; Green = green; Blue = blue; } public static bool TryParse(string s, out HexColor hcolor) { s = s.Trim().ToLowerInvariant(); hcolor = null; if(string.IsNullOrWhiteSpace(s)) return false; var regex = new Regex("#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})"); if(!regex.IsMatch(s)) return false; var match = regex.Match(s); if(!byte.TryParse(match.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var red) || !byte.TryParse(match.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var green) || !byte.TryParse(match.Groups[3].Value, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var blue)) return false; hcolor = new HexColor(red, green, blue); return true; } public Color ToColor() => new Color(Red, Green, Blue); public static implicit operator Color(HexColor hc) => hc.ToColor(); public static implicit operator Optional<Color>(HexColor hc) => new Optional<Color>(hc); public override string ToString() => $"#{Red:X2}{Green:X2}{Blue:X2}"; } }
using System; using System.Globalization; using System.Text.RegularExpressions; using Discord; namespace Mitternacht.Common { public class HexColor { public byte Red { get; set; } public byte Green { get; set; } public byte Blue { get; set; } public HexColor(byte red, byte green, byte blue) { Red = red; Green = green; Blue = blue; } public static bool TryParse(string s, out HexColor hcolor) { s = s.Trim().ToLowerInvariant(); hcolor = null; if (string.IsNullOrWhiteSpace(s)) return false; var regex = new Regex("#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})"); if (!regex.IsMatch(s)) return false; var match = regex.Match(s); if (!byte.TryParse(match.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var red) || !byte.TryParse(match.Groups[2].Value, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var green) || !byte.TryParse(match.Groups[3].Value, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var blue)) return false; hcolor = new HexColor(red, green, blue); return true; } public Color ToColor() => new Color(Red, Green, Blue); public static implicit operator Color(HexColor hc) => hc.ToColor(); public static implicit operator Optional<Color>(HexColor hc) => new Optional<Color>(hc); public override string ToString() => $"#{Red:X2}{Green:X2}{Blue:X2}"; } }
mit
C#
f1dab946fff325ae420f87364a2636af4293316f
Remove need to trim query string
johnneijzen/osu,johnneijzen/osu,UselessToucan/osu,peppy/osu,peppy/osu-new,EVAST9919/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu,ppy/osu,ppy/osu,ZLima12/osu,NeoAdonis/osu,ZLima12/osu,NeoAdonis/osu,smoogipoo/osu,2yangk23/osu,EVAST9919/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,2yangk23/osu
osu.Game/Online/API/Requests/GetScoresRequest.cs
osu.Game/Online/API/Requests/GetScoresRequest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Screens.Select.Leaderboards; using osu.Game.Online.API.Requests.Responses; using osu.Game.Rulesets.Mods; using System.Text; using System.Collections.Generic; namespace osu.Game.Online.API.Requests { public class GetScoresRequest : APIRequest<APILegacyScores> { private readonly BeatmapInfo beatmap; private readonly BeatmapLeaderboardScope scope; private readonly RulesetInfo ruleset; private readonly IEnumerable<Mod> mods; public GetScoresRequest(BeatmapInfo beatmap, RulesetInfo ruleset, BeatmapLeaderboardScope scope = BeatmapLeaderboardScope.Global, IEnumerable<Mod> mods = null) { if (!beatmap.OnlineBeatmapID.HasValue) throw new InvalidOperationException($"Cannot lookup a beatmap's scores without having a populated {nameof(BeatmapInfo.OnlineBeatmapID)}."); if (scope == BeatmapLeaderboardScope.Local) throw new InvalidOperationException("Should not attempt to request online scores for a local scoped leaderboard"); this.beatmap = beatmap; this.scope = scope; this.ruleset = ruleset ?? throw new ArgumentNullException(nameof(ruleset)); this.mods = mods ?? Array.Empty<Mod>(); Success += onSuccess; } private void onSuccess(APILegacyScores r) { foreach (APILegacyScoreInfo score in r.Scores) { score.Beatmap = beatmap; score.Ruleset = ruleset; } } protected override string Target => $@"beatmaps/{beatmap.OnlineBeatmapID}/scores{createQueryParameters()}"; private string createQueryParameters() { StringBuilder query = new StringBuilder(@"?"); query.Append($@"type={scope.ToString().ToLowerInvariant()}"); query.Append($@"&mode={ruleset.ShortName}"); foreach (var mod in mods) query.Append($@"&mods[]={mod.Acronym}"); return query.ToString(); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Screens.Select.Leaderboards; using osu.Game.Online.API.Requests.Responses; using osu.Game.Rulesets.Mods; using System.Text; using System.Collections.Generic; namespace osu.Game.Online.API.Requests { public class GetScoresRequest : APIRequest<APILegacyScores> { private readonly BeatmapInfo beatmap; private readonly BeatmapLeaderboardScope scope; private readonly RulesetInfo ruleset; private readonly IEnumerable<Mod> mods; public GetScoresRequest(BeatmapInfo beatmap, RulesetInfo ruleset, BeatmapLeaderboardScope scope = BeatmapLeaderboardScope.Global, IEnumerable<Mod> mods = null) { if (!beatmap.OnlineBeatmapID.HasValue) throw new InvalidOperationException($"Cannot lookup a beatmap's scores without having a populated {nameof(BeatmapInfo.OnlineBeatmapID)}."); if (scope == BeatmapLeaderboardScope.Local) throw new InvalidOperationException("Should not attempt to request online scores for a local scoped leaderboard"); this.beatmap = beatmap; this.scope = scope; this.ruleset = ruleset ?? throw new ArgumentNullException(nameof(ruleset)); this.mods = mods ?? Array.Empty<Mod>(); Success += onSuccess; } private void onSuccess(APILegacyScores r) { foreach (APILegacyScoreInfo score in r.Scores) { score.Beatmap = beatmap; score.Ruleset = ruleset; } } protected override string Target => $@"beatmaps/{beatmap.OnlineBeatmapID}/scores{createQueryParameters()}"; private string createQueryParameters() { StringBuilder query = new StringBuilder(@"?"); query.Append($@"type={scope.ToString().ToLowerInvariant()}&"); query.Append($@"mode={ruleset.ShortName}&"); foreach (var mod in mods) query.Append($@"mods[]={mod.Acronym}&"); return query.ToString().TrimEnd('&'); } } }
mit
C#
ec334f91cb6b0863f50e62dc0bce13de54cb611d
Revise RayGun registration
unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,jlewin/MatterControl,mmoening/MatterControl,jlewin/MatterControl
Program.cs
Program.cs
using System; using System.Globalization; using System.IO; using System.Threading; using MatterHackers.Agg.Platform; using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.SettingsManagement; using Mindscape.Raygun4Net; namespace MatterHackers.MatterControl { static class Program { private const int RaygunMaxNotifications = 15; private static int raygunNotificationCount = 0; private static RaygunClient _raygunClient; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] public static void Main() { // this sets the global culture for the app and all new threads CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; // and make sure the app is set correctly Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; if (AggContext.OperatingSystem == OSType.Mac) { _raygunClient = new RaygunClient("qmMBpKy3OSTJj83+tkO7BQ=="); // this is the Mac key } else { _raygunClient = new RaygunClient("hQIlyUUZRGPyXVXbI6l1dA=="); // this is the PC key } AggContext.Init(embeddedResourceName: "config.json"); // Make sure we have the right working directory as we assume everything relative to the executable. Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)); Datastore.Instance.Initialize(); #if !DEBUG // Conditionally spin up error reporting if not on the Stable channel string channel = UserSettings.Instance.get(UserSettingsKey.UpdateFeedType); if (string.IsNullOrEmpty(channel) || channel != "release" || OemSettings.Instance.WindowTitleExtra == "Experimental") #endif { System.Windows.Forms.Application.ThreadException += (s, e) => { if(raygunNotificationCount++ < RaygunMaxNotifications) { _raygunClient.Send(e.Exception); } }; AppDomain.CurrentDomain.UnhandledException += (s, e) => { if (raygunNotificationCount++ < RaygunMaxNotifications) { _raygunClient.Send(e.ExceptionObject as Exception); } }; } // Get startup bounds from MatterControl and construct system window //var systemWindow = new DesktopMainWindow(400, 200) var (width, height) = RootSystemWindow.GetStartupBounds(); var systemWindow = Application.LoadRootWindow(width, height); systemWindow.ShowAsSystemWindow(); } // ** Standard Winforms Main ** // //[STAThread] //static void Main() //{ // Application.EnableVisualStyles(); // Application.SetCompatibleTextRenderingDefault(false); // Application.Run(new Form1()); //} } }
using System; using System.Globalization; using System.IO; using System.Threading; using MatterHackers.Agg.Platform; using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.SettingsManagement; using Mindscape.Raygun4Net; namespace MatterHackers.MatterControl { static class Program { private const int RaygunMaxNotifications = 15; private static int raygunNotificationCount = 0; private static RaygunClient _raygunClient = GetCorrectClient(); /// <summary> /// The main entry point for the application. /// </summary> [STAThread] public static void Main() { // this sets the global culture for the app and all new threads CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; // and make sure the app is set correctly Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; AggContext.Init(embeddedResourceName: "config.json"); // Make sure we have the right working directory as we assume everything relative to the executable. Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)); Datastore.Instance.Initialize(); #if !DEBUG // Conditionally spin up error reporting if not on the Stable channel string channel = UserSettings.Instance.get(UserSettingsKey.UpdateFeedType); if (string.IsNullOrEmpty(channel) || channel != "release" || OemSettings.Instance.WindowTitleExtra == "Experimental") #endif { System.Windows.Forms.Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); } // Get startup bounds from MatterControl and construct system window //var systemWindow = new DesktopMainWindow(400, 200) var (width, height) = RootSystemWindow.GetStartupBounds(); var systemWindow = Application.LoadRootWindow(width, height); systemWindow.ShowAsSystemWindow(); } private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { #if !DEBUG if(raygunNotificationCount++ < RaygunMaxNotifications) { _raygunClient.Send(e.Exception); } #endif } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { #if !DEBUG if(raygunNotificationCount++ < RaygunMaxNotifications) { _raygunClient.Send(e.ExceptionObject as Exception); } #endif } private static RaygunClient GetCorrectClient() { if (AggContext.OperatingSystem == OSType.Mac) { return new RaygunClient("qmMBpKy3OSTJj83+tkO7BQ=="); // this is the Mac key } else { return new RaygunClient("hQIlyUUZRGPyXVXbI6l1dA=="); // this is the PC key } } // ** Standard Winforms Main ** // //[STAThread] //static void Main() //{ // Application.EnableVisualStyles(); // Application.SetCompatibleTextRenderingDefault(false); // Application.Run(new Form1()); //} } }
bsd-2-clause
C#
9c44d202d5eb1e8c35ecd5105af532b6d1c8a8f9
Change the deployment structure a bit
jacksonh/MCloud,jacksonh/MCloud
src/MCloud.Deploy/ScriptDeployment.cs
src/MCloud.Deploy/ScriptDeployment.cs
using System; using Tamir.SharpSsh; namespace MCloud { public class ScriptDeployment : PutFileDeployment { public ScriptDeployment (string local) : base (local) { } public ScriptDeployment (string local, string remote_dir) : base (local, remote_dir) { } protected override void RunImpl (Node node, NodeAuth auth) { string host = node.PublicIPs [0].ToString (); string remote = String.Concat (RemoteDirectory, FileName); PutFile (host, auth, FileName, remote); RunCommand (remote, host, auth); } } }
using System; using Tamir.SharpSsh; namespace MCloud { public class ScriptDeployment : SSHDeployment { public ScriptDeployment (string local_path) : this (local_path, String.Concat ("/root/", local_path)) { } public ScriptDeployment (string local_path, string remote_path) { LocalScriptPath = local_path; RemoteScriptPath = remote_path; } public string LocalScriptPath { get; private set; } public string RemoteScriptPath { get; private set; } protected override void RunImpl (Node node, NodeAuth auth) { if (node == null) throw new ArgumentNullException ("node"); if (auth == null) throw new ArgumentNullException ("auth"); if (node.PublicIPs.Count < 1) throw new ArgumentException ("node", "No public IPs available on node."); string host = node.PublicIPs [0].ToString (); CopyScript (host, auth); RunCommand (RemoteScriptPath, host, auth); } private void CopyScript (string host, NodeAuth auth) { Scp scp = new Scp (host, auth.UserName); SetupSSH (scp, auth); scp.Put (LocalScriptPath, RemoteScriptPath); scp.Close (); } } }
mit
C#
b22c4e794e645def78c15fc9af327f242c11503c
Add facebook href.
bigfont/sweet-water-revolver
mvcWebApp/Views/Home/_ExternalLinks.cshtml
mvcWebApp/Views/Home/_ExternalLinks.cshtml
<section class="container"> <div id="our-external-links"> @*href="https://myspace.com/sweetwaterrevolver" href="https://www.facebook.com/pages/Sweet-Water-Revolver/390852040983091" href="http://www.reverbnation.com/sweetwaterrevolver"*@ <a href="https://www.facebook.com/pages/Sweet-Water-Revolver/390852040983091"><i class="fa fa-facebook fa-5x"></i></a> <a href=""><i class="fa fa-flickr fa-5x"></i></a> <a href=""><i class="fa fa-google-plus fa-5x"></i></a> <a href=""><i class="fa fa-pinterest fa-5x"></i></a> <a href=""><i class="fa fa-tumblr fa-5x"></i></a> <a href=""><i class="fa fa-twitter fa-5x"></i></a> <a href=""><i class="fa fa-vimeo fa-5x"></i></a> <a href=""><i class="fa fa-youtube fa-5x"></i></a> </div> </section>
<section class="container"> <div id="our-external-links"> @*href="https://myspace.com/sweetwaterrevolver" href="https://www.facebook.com/pages/Sweet-Water-Revolver/390852040983091" href="http://www.reverbnation.com/sweetwaterrevolver"*@ <a href=""><i class="fa fa-facebook fa-5x"></i></a> <a href=""><i class="fa fa-flickr fa-5x"></i></a> <a href=""><i class="fa fa-google-plus fa-5x"></i></a> <a href=""><i class="fa fa-pinterest fa-5x"></i></a> <a href=""><i class="fa fa-tumblr fa-5x"></i></a> <a href=""><i class="fa fa-twitter fa-5x"></i></a> <a href=""><i class="fa fa-vimeo fa-5x"></i></a> <a href=""><i class="fa fa-youtube fa-5x"></i></a> </div> </section>
mit
C#
52d25bf07ebfc19270f51c0465029fb06ba9eb38
Refactor puzzle 2
martincostello/project-euler
src/ProjectEuler/Puzzles/Puzzle002.cs
src/ProjectEuler/Puzzles/Puzzle002.cs
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Collections.Generic; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=2</c>. This class cannot be inherited. /// </summary> public sealed class Puzzle002 : Puzzle { /// <inheritdoc /> public override string Question => "By considering the terms in the Fibonacci sequence starting with 1 and 2 whose values do not exceed the specified value, what is the sum of the even-valued terms?"; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { if (!TryParseInt32(args[0], out int max) || max < 1) { Console.WriteLine("The specified maximum value is invalid."); return -1; } var fibonacciValues = new List<int>() { 1, 2 }; while (true) { int count = fibonacciValues.Count; int next = fibonacciValues[count - 1] + fibonacciValues[count - 2]; if (next > max) { break; } fibonacciValues.Add(next); } int answer = 0; for (int i = 0; i < fibonacciValues.Count; i++) { int number = fibonacciValues[i]; if (number % 2 == 0) { answer += number; } } Answer = answer; return 0; } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Collections.Generic; using System.Linq; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=2</c>. This class cannot be inherited. /// </summary> public sealed class Puzzle002 : Puzzle { /// <inheritdoc /> public override string Question => "By considering the terms in the Fibonacci sequence starting with 1 and 2 whose values do not exceed the specified value, what is the sum of the even-valued terms?"; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { if (!TryParseInt32(args[0], out int max) || max < 1) { Console.WriteLine("The specified maximum value is invalid."); return -1; } IList<int> fibonacciValues = new List<int>() { 1, 2 }; while (true) { int next = fibonacciValues[fibonacciValues.Count - 1] + fibonacciValues[fibonacciValues.Count - 2]; if (next > max) { break; } fibonacciValues.Add(next); } Answer = fibonacciValues .Where((p) => p % 2 == 0) .Sum(); return 0; } } }
apache-2.0
C#
30e7846e200d7b3fdc02767c86b79f3c0a0c9fb8
modify create view to match edit view
OlegKleyman/AlphaDev,OlegKleyman/AlphaDev,OlegKleyman/AlphaDev
web/AlphaDev.Web/Views/Posts/Create.cshtml
web/AlphaDev.Web/Views/Posts/Create.cshtml
@model AlphaDev.Web.Models.CreatePostViewModel @{ ViewBag.Title = "Create Post"; } @section styles { <link href="~/lib/bootstrap-markdown/css/bootstrap-markdown.min.css" rel="stylesheet"/> } <form id="createForm" method="post"> <div class="text-center"> <span asp-validation-for="Title" class="text-danger"></span> <label asp-for="Title"></label> - <input asp-for="Title" value="@Model?.Title" class="form-control titleInput" /> </div> <div class="col-lg-12"> <div> <span asp-validation-for="Content" class="text-danger"></span> <textarea asp-for="Content" class="blogEditor"></textarea> </div> </div> </form> @section scripts { <script src="~/lib/marked/lib/marked.js"></script> <script src="~/lib/bootstrap-markdown/js/bootstrap-markdown.js"></script> <script type="text/javascript"> $('#Content').markdown({ savable: true, onChange: function() { Prism.highlightAll(); }, onSave: function() { $('#createForm').submit(); } }) </script> }
@model AlphaDev.Web.Models.CreatePostViewModel @{ ViewBag.Title = "Create Post"; } @section styles { <link href="~/lib/bootstrap-markdown/css/bootstrap-markdown.min.css" rel="stylesheet"/> } <h1 class="text-center">Create Post</h1> <form id="createForm" method="post"> <div class="col-lg-12"> <div> <div> <label asp-for="Title"></label> </div> <div> <span asp-validation-for="Title" class="text-danger"></span> <input asp-for="Title" class="form-control"/> </div> </div> <div> <span asp-validation-for="Content" class="text-danger"></span> <textarea asp-for="Content" class="blogEditor"></textarea> </div> </div> </form> @section scripts { <script src="~/lib/marked/lib/marked.js"></script> <script src="~/lib/bootstrap-markdown/js/bootstrap-markdown.js"></script> <script type="text/javascript"> $('#Content').markdown({ savable: true, onChange: function() { Prism.highlightAll(); }, onSave: function() { $('#createForm').submit(); } }) </script> }
unlicense
C#
9f5649fb85babc1c24d1cf13d17e1f17e52c7970
Update PrateekSingh.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/PrateekSingh.cs
src/Firehose.Web/Authors/PrateekSingh.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class PrateekSingh : IFilterMyBlogPosts, IAmACommunityMember { public string FirstName => "Prateek"; public string LastName => "Singh"; public string ShortBioOrTagLine => "Infrastructure Developer, Automation engineer and PowerShell Blogger"; public string StateOrRegion => "New Delhi, India"; public string EmailAddress => "prateeksingh1590@gmail.com"; public string TwitterHandle => "SinghPrateik"; public string GravatarHash => "2b2f100e9097063a5777a26820a58fc7"; public Uri WebSite => new Uri("https://ridicurious.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://ridicurious.com/feed/"); } } public string GitHubHandle => "prateekkumarsingh"; public bool Filter(SyndicationItem item) { return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } public GeoPosition Position => new GeoPosition(28.4594970, 77.0266380); } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class PrateekSingh : IFilterMyBlogPosts, IAmACommunityMember { public string FirstName => "Prateek"; public string LastName => "Singh"; public string ShortBioOrTagLine => "Infrastructure Developer, Automation engineer and PowerShell Blogger"; public string StateOrRegion => "New Delhi, India"; public string EmailAddress => "prateeksingh1590@gmail.com"; public string TwitterHandle => "SinghPrateik"; public string GravatarHash => "2b2f100e9097063a5777a26820a58fc7"; public Uri WebSite => new Uri("https://geekeefy.wordpress.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://geekeefy.wordpress.com/feed/"); } } public string GitHubHandle => "prateekkumarsingh"; public bool Filter(SyndicationItem item) { return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } public GeoPosition Position => new GeoPosition(28.4594970, 77.0266380); } }
mit
C#
ca81547cd72fd513d0a7352824ec43b4413ab91c
Make MDToken public
kiootic/dnlib,picrap/dnlib,ilkerhalil/dnlib,ZixiangBoy/dnlib,Arthur2e5/dnlib,0xd4d/dnlib,yck1509/dnlib,modulexcite/dnlib,jorik041/dnlib
dot10/dotNET/MDToken.cs
dot10/dotNET/MDToken.cs
using System; namespace dot10.dotNET { /// <summary> /// MetaData token /// </summary> public struct MDToken : IEquatable<MDToken>, IComparable<MDToken> { uint token; /// <summary> /// Returns the table type /// </summary> public Table Table { get { return (Table)(token >> 24); } } /// <summary> /// Returns the row id /// </summary> public uint Rid { get { return token & 0x00FFFFFF; } } /// <summary> /// Returns the raw token /// </summary> public uint Raw { get { return token; } } /// <summary> /// Returns true if it's a null token /// </summary> public bool IsNull { get { return Rid == 0; } } /// <summary> /// Constructor /// </summary> /// <param name="token">Raw token</param> public MDToken(uint token) { this.token = token; } /// <summary> /// Constructor /// </summary> /// <param name="token">Raw token</param> public MDToken(int token) : this((uint)token) { } /// <summary>Overloaded operator</summary> public static bool operator ==(MDToken left, MDToken right) { return left.CompareTo(right) == 0; } /// <summary>Overloaded operator</summary> public static bool operator !=(MDToken left, MDToken right) { return left.CompareTo(right) != 0; } /// <summary>Overloaded operator</summary> public static bool operator <(MDToken left, MDToken right) { return left.CompareTo(right) < 0; } /// <summary>Overloaded operator</summary> public static bool operator >(MDToken left, MDToken right) { return left.CompareTo(right) > 0; } /// <summary>Overloaded operator</summary> public static bool operator <=(MDToken left, MDToken right) { return left.CompareTo(right) <= 0; } /// <summary>Overloaded operator</summary> public static bool operator >=(MDToken left, MDToken right) { return left.CompareTo(right) >= 0; } /// <inheritdoc/> public int CompareTo(MDToken other) { return token.CompareTo(other.token); } /// <inheritdoc/> public bool Equals(MDToken other) { return CompareTo(other) == 0; } /// <inheritdoc/> public override bool Equals(object obj) { if (!(obj is MDToken)) return false; return Equals((MDToken)obj); } /// <inheritdoc/> public override int GetHashCode() { return (int)token; } /// <inheritdoc/> public override string ToString() { return string.Format("{0} {1:X6}", Table.ToString(), Rid); } } }
using System; namespace dot10.dotNET { /// <summary> /// MetaData token /// </summary> struct MDToken : IEquatable<MDToken>, IComparable<MDToken> { uint token; /// <summary> /// Returns the table type /// </summary> public Table Table { get { return (Table)(token >> 24); } } /// <summary> /// Returns the row id /// </summary> public uint Rid { get { return token & 0x00FFFFFF; } } /// <summary> /// Returns the raw token /// </summary> public uint Raw { get { return token; } } /// <summary> /// Returns true if it's a null token /// </summary> public bool IsNull { get { return Rid == 0; } } /// <summary> /// Constructor /// </summary> /// <param name="token">Raw token</param> public MDToken(uint token) { this.token = token; } /// <summary> /// Constructor /// </summary> /// <param name="token">Raw token</param> public MDToken(int token) : this((uint)token) { } /// <summary>Overloaded operator</summary> public static bool operator ==(MDToken left, MDToken right) { return left.CompareTo(right) == 0; } /// <summary>Overloaded operator</summary> public static bool operator !=(MDToken left, MDToken right) { return left.CompareTo(right) != 0; } /// <summary>Overloaded operator</summary> public static bool operator <(MDToken left, MDToken right) { return left.CompareTo(right) < 0; } /// <summary>Overloaded operator</summary> public static bool operator >(MDToken left, MDToken right) { return left.CompareTo(right) > 0; } /// <summary>Overloaded operator</summary> public static bool operator <=(MDToken left, MDToken right) { return left.CompareTo(right) <= 0; } /// <summary>Overloaded operator</summary> public static bool operator >=(MDToken left, MDToken right) { return left.CompareTo(right) >= 0; } /// <inheritdoc/> public int CompareTo(MDToken other) { return token.CompareTo(other.token); } /// <inheritdoc/> public bool Equals(MDToken other) { return CompareTo(other) == 0; } /// <inheritdoc/> public override bool Equals(object obj) { if (!(obj is MDToken)) return false; return Equals((MDToken)obj); } /// <inheritdoc/> public override int GetHashCode() { return (int)token; } /// <inheritdoc/> public override string ToString() { return string.Format("{0} {1:X6}", Table.ToString(), Rid); } } }
mit
C#
63913bc353675d8b420b83b26ab837c81be66a17
Add new test
jamesmontemagno/app-coffeecups
UITests/Tests.cs
UITests/Tests.cs
using System; using System.IO; using System.Linq; using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITest.Queries; namespace CoffeeCups.UITests { [TestFixture(Platform.Android)] [TestFixture(Platform.iOS)] public class Tests { IApp app; Platform platform; public Tests(Platform platform) { this.platform = platform; } [SetUp] public void BeforeEachTest() { app = AppInitializer.StartApp(platform); } [Test] public void AppLaunches() { app.Screenshot("First screen."); } [Test] public void AppLaunches2() { app.Screenshot("Second screen."); } } }
using System; using System.IO; using System.Linq; using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITest.Queries; namespace CoffeeCups.UITests { [TestFixture(Platform.Android)] [TestFixture(Platform.iOS)] public class Tests { IApp app; Platform platform; public Tests(Platform platform) { this.platform = platform; } [SetUp] public void BeforeEachTest() { app = AppInitializer.StartApp(platform); } [Test] public void AppLaunches() { app.Screenshot("First screen."); } } }
mit
C#
fa7a433e59093e4a3cfee4a73f486ed1ac94bf7e
Remove NavMeshAgent handling from decision script (not its role)
allmonty/BrokenShield,allmonty/BrokenShield
Assets/Scripts/Enemy/Decision_OnTargetReached.cs
Assets/Scripts/Enemy/Decision_OnTargetReached.cs
using UnityEngine; [CreateAssetMenu (menuName = "AI/Decisions/TargetReached")] public class Decision_OnTargetReached : Decision { public bool overrideDistanceToReach; public float distanceToReach; public override bool Decide(StateController controller) { return isTargetReached(controller); } private bool isTargetReached(StateController controller) { var enemyControl = controller as Enemy_StateController; enemyControl.navMeshAgent.destination = enemyControl.chaseTarget.position; if(!overrideDistanceToReach) distanceToReach = enemyControl.navMeshAgent.stoppingDistance; if(enemyControl.navMeshAgent.remainingDistance <= distanceToReach && !enemyControl.navMeshAgent.pathPending) { return true; } else { return false; } } }
using UnityEngine; [CreateAssetMenu (menuName = "AI/Decisions/TargetReached")] public class Decision_OnTargetReached : Decision { public bool overrideDistanceToReach; public float distanceToReach; public override bool Decide(StateController controller) { return isTargetReached(controller); } private bool isTargetReached(StateController controller) { var enemyControl = controller as Enemy_StateController; enemyControl.navMeshAgent.destination = enemyControl.chaseTarget.position; if(!overrideDistanceToReach) distanceToReach = enemyControl.navMeshAgent.stoppingDistance; if(enemyControl.navMeshAgent.remainingDistance <= distanceToReach && !enemyControl.navMeshAgent.pathPending) { enemyControl.navMeshAgent.isStopped = true; return true; } else { enemyControl.navMeshAgent.isStopped = false; return false; } } }
apache-2.0
C#
b2a707053b99c518435b7aa46b40abac1106f135
Add expires_at parameter to Collaboration request params (#445)
box/box-windows-sdk-v2
Box.V2/Models/Request/BoxCollaborationRequest.cs
Box.V2/Models/Request/BoxCollaborationRequest.cs
using Newtonsoft.Json; using System; namespace Box.V2.Models { /// <summary> /// A request class for collaboration requests /// </summary> public class BoxCollaborationRequest : BoxRequestEntity { /// <summary> /// The item to add the collaboration on /// The ID and Type are required. The Type can be folder or file. /// </summary> [JsonProperty(PropertyName = "item")] public BoxRequestEntity Item { get; set; } /// <summary> /// The user who this collaboration applies to /// </summary> [JsonProperty(PropertyName = "accessible_by")] public BoxCollaborationUserRequest AccessibleBy { get; set; } /// <summary> /// The access level of this collaboration. Can be editor, viewer, previewer, uploader, previewer uploader, viewer uploader, co-owner, or owner /// </summary> [JsonProperty(PropertyName = "role")] public string Role { get; set; } /// <summary> /// Whether this collaboration has been accepted /// This can be set to ‘accepted’ or ‘rejected’ by the ‘accessible_by’ user if the status is ‘pending’ /// </summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } /// <summary> /// Whether view path collaboration feature is enabled or not. View path collaborations allow the invitee to see the entire ancestral path to the associated folder. /// The user will not gain privileges in any ancestral folder (e.g. see content the user is not collaborated on). /// </summary> [JsonProperty(PropertyName = "can_view_path")] public bool? CanViewPath { get; set; } /// <summary> /// When the collaboration should expire and be automatically removed. This value can only be updated if /// the collaboration is already set to expire and the user has permission to update the expiration time. /// </summary> [JsonProperty(PropertyName = "expires_at")] public DateTime? ExpiresAt { get; set; } } public static class BoxCollaborationRoles { public const string Editor = "editor"; public const string Viewer = "viewer"; public const string Previewer = "previewer"; public const string Uploader = "uploader"; public const string PreviewerUploader = "previewer uploader"; public const string ViewerUploader = "viewer uploader"; public const string CoOwner = "co-owner"; public const string Owner = "owner"; } }
using Newtonsoft.Json; namespace Box.V2.Models { /// <summary> /// A request class for collaboration requests /// </summary> public class BoxCollaborationRequest : BoxRequestEntity { /// <summary> /// The item to add the collaboration on /// The ID and Type are required. The Type can be folder or file. /// </summary> [JsonProperty(PropertyName = "item")] public BoxRequestEntity Item { get; set; } /// <summary> /// The user who this collaboration applies to /// </summary> [JsonProperty(PropertyName = "accessible_by")] public BoxCollaborationUserRequest AccessibleBy { get; set; } /// <summary> /// The access level of this collaboration. Can be editor, viewer, previewer, uploader, previewer uploader, viewer uploader, co-owner, or owner /// </summary> [JsonProperty(PropertyName = "role")] public string Role { get; set; } /// <summary> /// Whether this collaboration has been accepted /// This can be set to ‘accepted’ or ‘rejected’ by the ‘accessible_by’ user if the status is ‘pending’ /// </summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } /// <summary> /// Whether view path collaboration feature is enabled or not. View path collaborations allow the invitee to see the entire ancestral path to the associated folder. /// The user will not gain privileges in any ancestral folder (e.g. see content the user is not collaborated on). /// </summary> [JsonProperty(PropertyName = "can_view_path")] public bool? CanViewPath { get; set; } } public static class BoxCollaborationRoles { public const string Editor = "editor"; public const string Viewer = "viewer"; public const string Previewer = "previewer"; public const string Uploader = "uploader"; public const string PreviewerUploader = "previewer uploader"; public const string ViewerUploader = "viewer uploader"; public const string CoOwner = "co-owner"; public const string Owner = "owner"; } }
apache-2.0
C#
f5d6061c8653038e6c0d8d6ccab6c09df1d10fb6
fix test
wikibus/Argolis
src/Lernaean.Hydra.Tests/ApiDocumentation/DefaultPropertyRangeRetrievalPolicyTests.cs
src/Lernaean.Hydra.Tests/ApiDocumentation/DefaultPropertyRangeRetrievalPolicyTests.cs
using System; using System.Collections.Generic; using System.Reflection; using FakeItEasy; using FluentAssertions; using Hydra.Discovery.SupportedProperties; using JsonLD.Entities; using TestHydraApi; using Vocab; using Xunit; namespace Lernaean.Hydra.Tests.ApiDocumentation { public class DefaultPropertyRangeRetrievalPolicyTests { private readonly DefaultPropertyRangeRetrievalPolicy _rangePolicy; private readonly IPropertyRangeMappingPolicy _propertyType; public DefaultPropertyRangeRetrievalPolicyTests() { _propertyType = A.Fake<IPropertyRangeMappingPolicy>(); var mappings = new[] { _propertyType }; _rangePolicy = new DefaultPropertyRangeRetrievalPolicy(mappings); } [Fact] public void Should_use_RangAttribute_if_present() { // when var iriRef = _rangePolicy.GetRange(typeof (Issue).GetProperty("ProjectId"), new Dictionary<Type, Uri>()); // then iriRef.Should().Be((IriRef)"http://example.api/o#project"); } [Fact] public void Should_map_property_range_to_RDF_type() { // given var mappedPredicate = new Uri(Xsd.@string); var classIds = new Dictionary<Type, Uri> { { typeof(Issue), new Uri("http://example.com/issue") } }; A.CallTo(() => _propertyType.MapType(A<PropertyInfo>._, A<IReadOnlyDictionary<Type, Uri>>._)).Returns(mappedPredicate); // when var range = _rangePolicy.GetRange(typeof(Issue).GetProperty("Content"), classIds); // then range.Should().Be((IriRef)mappedPredicate); } } }
using System; using System.Collections.Generic; using System.Reflection; using FakeItEasy; using FluentAssertions; using Hydra.Discovery.SupportedProperties; using JsonLD.Entities; using TestHydraApi; using Vocab; using Xunit; namespace Lernaean.Hydra.Tests.ApiDocumentation { public class DefaultPropertyRangeRetrievalPolicyTests { private readonly DefaultPropertyRangeRetrievalPolicy _rangePolicy; private readonly IPropertyRangeMappingPolicy _propertyType; public DefaultPropertyRangeRetrievalPolicyTests() { _propertyType = A.Fake<IPropertyRangeMappingPolicy>(); var mappings = new[] { _propertyType }; _rangePolicy = new DefaultPropertyRangeRetrievalPolicy(mappings); } [Fact] public void Should_use_RangAttribute_if_present() { // when var iriRef = _rangePolicy.GetRange(typeof (Issue).GetProperty("ProjectId"), new Dictionary<Type, Uri>()); // then iriRef.Should().Be((IriRef)"http://example.api/o#project"); } [Fact] public void Should_map_property_range_to_RDF_type() { // given var mappedPredicate = new Uri(Xsd.@string); var classIds = new Dictionary<Type, Uri> { { typeof(Issue), new Uri("http://example.com/issue") } }; A.CallTo(() => _propertyType.MapType(A<PropertyInfo>._, A<IReadOnlyDictionary<Type, Uri>>._)).Returns(mappedPredicate); // when var range = _rangePolicy.GetRange(typeof(Issue).GetProperty("Id"), classIds); // then range.Should().Be((IriRef)mappedPredicate); } } }
mit
C#
0dd39d7f1e3746878fc28589962910c3cf41aff0
Change for issue #142
louthy/language-ext,StefanBertels/language-ext,StanJav/language-ext
LanguageExt.Process/ActorSys/Deserialise.cs
LanguageExt.Process/ActorSys/Deserialise.cs
using Newtonsoft.Json; using System; using System.Reflection; using LanguageExt.Trans; using static LanguageExt.Prelude; namespace LanguageExt { /// <summary> /// Helper function for invoking the generic JsonConvert.DeserializeObject function /// instead of the variant that takes a Type argument. This forces the type to be /// cast away from JObject and gives the caller the best chance of getting a useful /// value. /// </summary> internal static class Deserialise { static Map<string, MethodInfo> funcs = Map.empty<string, MethodInfo>(); static MethodInfo DeserialiseFunc(Type type) { var name = type.FullName; var result = funcs.Find(name); if (result.IsSome) return result.LiftUnsafe(); var func = typeof(JsonConvert).GetTypeInfo() .GetDeclaredMethods("DeserializeObject") .Filter(m => m.IsGenericMethod) .Filter(m => m.GetParameters().Length == 2) .Filter(m => m.GetParameters().ElementAt(1).ParameterType.Equals(typeof(JsonSerializerSettings))) .Head() .MakeGenericMethod(type); // No locks because we don't really care if it's done // more than once, but we do care about locking unnecessarily. funcs = funcs.AddOrUpdate(name, func); return func; } public static object Object(string value, Type type) => DeserialiseFunc(type).Invoke(null, new object[] { value, ActorSystemConfig.Default.JsonSerializerSettings }); } }
using Newtonsoft.Json; using System; using System.Reflection; using LanguageExt.Trans; using static LanguageExt.Prelude; namespace LanguageExt { /// <summary> /// Helper function for invoking the generic JsonConvert.DeserializeObject function /// instead of the variant that takes a Type argument. This forces the type to be /// cast away from JObject and gives the caller the best chance of getting a useful /// value. /// </summary> internal static class Deserialise { static Map<string, MethodInfo> funcs = Map.empty<string, MethodInfo>(); static MethodInfo DeserialiseFunc(Type type) { var name = type.FullName; var result = funcs.Find(name); if (result.IsSome) return result.LiftUnsafe(); var func = typeof(JsonConvert).GetTypeInfo() .GetDeclaredMethods("DeserializeObject") .Filter(m => m.IsGenericMethod) .Filter(m => m.GetParameters().Length == 1) .Head() .MakeGenericMethod(type); // No locks because we don't really care if it's done // more than once, but we do care about locking unnecessarily. funcs = funcs.AddOrUpdate(name, func); return func; } public static object Object(string value, Type type) => DeserialiseFunc(type).Invoke(null, new[] { value }); } }
mit
C#
dc7ada245a424152352afe2163e997d8698096ff
Bump version.
kyourek/Pagination,kyourek/Pagination,kyourek/Pagination
sln/Pagination/Properties/AssemblyInfo.cs
sln/Pagination/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Pagination")] [assembly: AssemblyDescription("Pagination")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ken Yourek")] [assembly: AssemblyProduct("Pagination")] [assembly: AssemblyCopyright("Copyright © Ken Yourek 2013-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("ce155db1-e4da-4e59-a151-7f47d3ac1f8c")] [assembly: AssemblyVersion("1.0.0")] [assembly: AssemblyFileVersion("1.0.3.25")] [assembly: AssemblyInformationalVersion("1.0.3")] [assembly: InternalsVisibleTo("Pagination.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Pagination")] [assembly: AssemblyDescription("Pagination")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ken Yourek")] [assembly: AssemblyProduct("Pagination")] [assembly: AssemblyCopyright("Copyright © Ken Yourek 2013-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("ce155db1-e4da-4e59-a151-7f47d3ac1f8c")] [assembly: AssemblyVersion("1.0.0")] [assembly: AssemblyFileVersion("1.0.3.24")] [assembly: AssemblyInformationalVersion("1.0.3")] [assembly: InternalsVisibleTo("Pagination.Tests")]
mit
C#
b123395ac71ed898ea7a7dfd5bd0698cdb6dbe56
Fix correct count 6 -> 7
darkestspirit/IdentityServer3.Contrib.Localization,johnkors/IdentityServer3.Contrib.Localization,Utdanningsdirektoratet/IdentityServer3.Contrib.Localization,totpero/IdentityServer3.Contrib.Localization,IdentityServer/IdentityServer3.Contrib.Localization
source/Unittests/AvailableTranslations.cs
source/Unittests/AvailableTranslations.cs
using System.Linq; using Thinktecture.IdentityServer.Core.Services.Contrib; using Xunit; namespace Unittests { public class AvailableTranslations { [Theory] [InlineData("Default")] [InlineData("pirate")] [InlineData("nb-NO")] [InlineData("tr-TR")] [InlineData("de-DE")] [InlineData("sv-SE")] [InlineData("es-AR")] public void ContainsLocales(string locale) { Assert.Contains(GlobalizedLocalizationService.GetAvailableLocales(), s => s.Equals(locale)); } [Fact] public void HasCorrectCount() { Assert.Equal(7, GlobalizedLocalizationService.GetAvailableLocales().Count()); } } }
using System.Linq; using Thinktecture.IdentityServer.Core.Services.Contrib; using Xunit; namespace Unittests { public class AvailableTranslations { [Theory] [InlineData("Default")] [InlineData("pirate")] [InlineData("nb-NO")] [InlineData("tr-TR")] [InlineData("de-DE")] [InlineData("sv-SE")] [InlineData("es-AR")] public void ContainsLocales(string locale) { Assert.Contains(GlobalizedLocalizationService.GetAvailableLocales(), s => s.Equals(locale)); } [Fact] public void HasCorrectCount() { Assert.Equal(6, GlobalizedLocalizationService.GetAvailableLocales().Count()); } } }
mit
C#
af12e3de8d7c884e89e6e8d462746024092fbc4f
Use room name as "identifier"
DragonEyes7/ConcoursUBI17,DragonEyes7/ConcoursUBI17
Proto/Assets/Scripts/Time/TimeController.cs
Proto/Assets/Scripts/Time/TimeController.cs
using UnityEngine; public class TimeController : MonoBehaviour { public MultipleDelegate Tick = new MultipleDelegate(); public MultipleDelegate End = new MultipleDelegate(); [SerializeField] private string _filePath; [SerializeField] private int _penalizePlayerOnWrongTarget = 20; int _Time, _maxTime = 30, _totalTime; float _Timer; bool _IsPlaying = false; public int time { get { return _Time; } set { _Time = value; } } public int maxTime { get { return _maxTime; } } public bool isPlaying { get { return _IsPlaying; } set { _IsPlaying = value; } } void FixedUpdate() { _Timer += Time.deltaTime; if (_Timer >= 1f && _IsPlaying) DoTick(); } public void DoTick() { _Timer = 0; _Time++; _totalTime++; Tick.Execute(_Time); if (_Time == _maxTime) { //Game has ended stop countdown and show the players they f*cked up FindObjectOfType<GameManager>().Defeat(); End.Execute(_Time); End.Empty(); } } public void SaveTime() { if (PhotonNetwork.isMasterClient) { new FileManager(_filePath).Write(PhotonNetwork.room.Name + " : " + _totalTime + "\n"); } } public void WrongTargetIntercepted() { _totalTime += _penalizePlayerOnWrongTarget; } public void SetMaxTime(int maxTime) { _maxTime = maxTime; } }
using UnityEngine; public class TimeController : MonoBehaviour { public MultipleDelegate Tick = new MultipleDelegate(); public MultipleDelegate End = new MultipleDelegate(); [SerializeField] private string _filePath; [SerializeField] private int _penalizePlayerOnWrongTarget = 20; int _Time, _maxTime = 30, _totalTime; float _Timer; bool _IsPlaying = false; public int time { get { return _Time; } set { _Time = value; } } public int maxTime { get { return _maxTime; } } public bool isPlaying { get { return _IsPlaying; } set { _IsPlaying = value; } } void FixedUpdate() { _Timer += Time.deltaTime; if (_Timer >= 1f && _IsPlaying) DoTick(); } public void DoTick() { _Timer = 0; _Time++; _totalTime++; Tick.Execute(_Time); if (_Time == _maxTime) { //Game has ended stop countdown and show the players they f*cked up FindObjectOfType<GameManager>().Defeat(); End.Execute(_Time); End.Empty(); } } public void SaveTime() { if (PhotonNetwork.isMasterClient) { new FileManager(_filePath).Write("Game time : " + _totalTime + "\n"); } } public void WrongTargetIntercepted() { _totalTime += _penalizePlayerOnWrongTarget; } public void SetMaxTime(int maxTime) { _maxTime = maxTime; } }
mit
C#
a1230f6e576535c0f60c665c4c6a647f13807290
Fix failing test
diaconesq/RecurringDates
RecurringDates.UnitTests/DayOfWeekRuleUT.cs
RecurringDates.UnitTests/DayOfWeekRuleUT.cs
using System; using FluentAssertions; using NUnit.Framework; namespace RecurringDates.UnitTests { public class DayOfWeekRuleUT<T> : ProjectedRuleTestFixture<T> where T : IRuleProcessor, new() { [Test] public void Day_ShouldMatch_Monday() { var rule = new DayOfWeekRule(DayOfWeek.Monday); var date = new DateTime(2015, 3, 9); Process(rule).IsMatch(date).Should().BeTrue(); } [Test] public void Day_WithFluentSyntax_ShouldMatch_Monday() { var rule = DayOfWeek.Monday.EveryWeek(); var date = new DateTime(2015, 3, 9); Process(rule).IsMatch(date).Should().BeTrue(); } } }
using System; using FluentAssertions; using NUnit.Framework; namespace RecurringDates.UnitTests { public class DayOfWeekRuleUT<T> : ProjectedRuleTestFixture<T> where T : IRuleProcessor, new() { [Test] public void Day_ShouldMatch_Monday() { var rule = new DayOfWeekRule(DayOfWeek.Monday); var date = new DateTime(2015, 3, 9); Process(rule).IsMatch(date).Should().BeTrue(); } [Test] public void Day_WithFluentSyntax_ShouldMatch_Monday() { var rule = DayOfWeek.Monday.EveryWeek(); var date = new DateTime(2015, 3, 9+1); Process(rule).IsMatch(date).Should().BeTrue(); } } }
bsd-2-clause
C#
cc4d23f18cb67c2672f2d659ea445c10582c79bd
Rename lastElement to previousElement.
mdavid/nuget,mdavid/nuget
NuPack.Dialog/Extensions/EnumerableExtensions.cs
NuPack.Dialog/Extensions/EnumerableExtensions.cs
using System.Collections.Generic; namespace NuGet.Dialog.Extensions { internal static class EnumerableExtensions { /// <summary> /// Returns a distinct set of elements using the comparer specified. This implementation will pick the last occurence /// of each element instead of picking the first. This method assumes that similar items occur in order. /// </summary> internal static IEnumerable<TElement> DistinctLast<TElement>(this IEnumerable<TElement> source, IEqualityComparer<TElement> comparer) { bool first = true; var previousElement = default(TElement); foreach (TElement element in source) { if (!first && !comparer.Equals(element, previousElement)) { yield return previousElement; } previousElement = element; first = false; } if (!first) { yield return previousElement; } } } }
using System.Collections.Generic; namespace NuGet.Dialog.Extensions { internal static class EnumerableExtensions { /// <summary> /// Returns a distinct set of elements using the comparer specified. This implementation will pick the last occurence /// of each element instead of picking the first. This method assumes that similar items occur in order. /// </summary> internal static IEnumerable<TElement> DistinctLast<TElement>(this IEnumerable<TElement> source, IEqualityComparer<TElement> comparer) { bool first = true; var lastElement = default(TElement); foreach (TElement element in source) { if (!first && !comparer.Equals(element, lastElement)) { yield return lastElement; } lastElement = element; first = false; } if (!first) { yield return lastElement; } } } }
apache-2.0
C#
617f93ee23137706196626a714defbbc05e2fa99
Use richer return type when possible.
ExRam/ExRam.Gremlinq
ExRam.Gremlinq.Core/ExecutionPipelines/Builder/GremlinQueryExecutionPipelineBuilder.cs
ExRam.Gremlinq.Core/ExecutionPipelines/Builder/GremlinQueryExecutionPipelineBuilder.cs
using ExRam.Gremlinq.Core.Serialization; using ExRam.Gremlinq.Providers; using LanguageExt; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ExRam.Gremlinq.Core { public static class GremlinQueryExecutionPipelineBuilder { public static IGremlinQueryExecutionPipelineBuilderWithSerializer<GroovySerializedGremlinQuery> UseGroovySerialization(this IGremlinQueryExecutionPipelineBuilder builder) { return builder.UseSerializer(GremlinQuerySerializer<GroovySerializedGremlinQuery>.FromVisitor<GroovyGremlinQueryElementVisitor>()); } public static IGremlinQueryExecutionPipeline<TSerializedQuery, JToken> UseGraphsonDeserialization<TSerializedQuery>(this IGremlinQueryExecutionPipelineBuilderWithExecutor<TSerializedQuery, JToken> builder, params JsonConverter[] additionalConverters) { return builder.UseDeserializerFactory(new GraphsonDeserializerFactory(additionalConverters)); } public static readonly IGremlinQueryExecutionPipelineBuilder Default = new GremlinQueryExecutionPipeline<Unit, Unit>( GremlinQuerySerializer<Unit>.Invalid, GremlinQueryExecutor<Unit, Unit>.Invalid, GremlinQueryExecutionResultDeserializerFactory<Unit>.Invalid); } }
using ExRam.Gremlinq.Core.Serialization; using ExRam.Gremlinq.Providers; using LanguageExt; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ExRam.Gremlinq.Core { public static class GremlinQueryExecutionPipelineBuilder { public static IGremlinQueryExecutionPipelineBuilderWithSerializer<GroovySerializedGremlinQuery> UseGroovySerialization(this IGremlinQueryExecutionPipelineBuilder builder) { return builder.UseSerializer(GremlinQuerySerializer<GroovySerializedGremlinQuery>.FromVisitor<GroovyGremlinQueryElementVisitor>()); } public static IGremlinQueryExecutionPipeline UseGraphsonDeserialization<TSerializedQuery>(this IGremlinQueryExecutionPipelineBuilderWithExecutor<TSerializedQuery, JToken> builder, params JsonConverter[] additionalConverters) { return builder.UseDeserializerFactory(new GraphsonDeserializerFactory(additionalConverters)); } public static readonly IGremlinQueryExecutionPipelineBuilder Default = new GremlinQueryExecutionPipeline<Unit, Unit>( GremlinQuerySerializer<Unit>.Invalid, GremlinQueryExecutor<Unit, Unit>.Invalid, GremlinQueryExecutionResultDeserializerFactory<Unit>.Invalid); } }
mit
C#
48bc5be6ce0e1b04adb44a8f6f515537a43e2491
Disable unimplemented CLI option "Verbose"
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
src/Arkivverket.Arkade.Cli/CommandLineOptions.cs
src/Arkivverket.Arkade.Cli/CommandLineOptions.cs
using System; using CommandLine; using CommandLine.Text; namespace Arkivverket.Arkade.Cli { /// <summary> /// Using CommandLine library for parsing options. See https://github.com/gsscoder/commandline/wiki/ /// </summary> internal class CommandLineOptions { [Option('a', "archive", HelpText = "Archive directory or file (.tar) to process.")] public string Archive { get; set; } [Option('t', "type", HelpText = "Archive type, valid values: noark3, noark4, noark5 or fagsystem")] public string ArchiveType { get; set; } [Option('m', "metadata-file", HelpText = "File with metadata to add to package.")] public string MetadataFile { get; set; } [Option('g', "generate-metadata-example", HelpText = "Generate example metadata file. Argument is output file name.")] public string GenerateMetadataExample { get; set; } [Option('p', "processing-area", HelpText = "Directory to place temporary files and logs.")] public string ProcessingArea { get; set; } [Option('o', "output-directory", HelpText = "Directory to place created package and test report.")] public string OutputDirectory { get; set; } //[Option('v', "verbose", HelpText = "Print details during execution.")] //public bool Verbose { get; set; } internal string GetUsage() { var result = new Parser().ParseArguments<CommandLineOptions>("".Split()); var helptext = HelpText.AutoBuild(result, help => { help.AddOptions(result); return help; }, example => { return example; }); return helptext; } } }
using System; using CommandLine; using CommandLine.Text; namespace Arkivverket.Arkade.Cli { /// <summary> /// Using CommandLine library for parsing options. See https://github.com/gsscoder/commandline/wiki/ /// </summary> internal class CommandLineOptions { [Option('a', "archive", HelpText = "Archive directory or file (.tar) to process.")] public string Archive { get; set; } [Option('t', "type", HelpText = "Archive type, valid values: noark3, noark4, noark5 or fagsystem")] public string ArchiveType { get; set; } [Option('m', "metadata-file", HelpText = "File with metadata to add to package.")] public string MetadataFile { get; set; } [Option('g', "generate-metadata-example", HelpText = "Generate example metadata file. Argument is output file name.")] public string GenerateMetadataExample { get; set; } [Option('p', "processing-area", HelpText = "Directory to place temporary files and logs.")] public string ProcessingArea { get; set; } [Option('o', "output-directory", HelpText = "Directory to place created package and test report.")] public string OutputDirectory { get; set; } [Option('v', "verbose", HelpText = "Print details during execution.")] public bool Verbose { get; set; } internal string GetUsage() { var result = new Parser().ParseArguments<CommandLineOptions>("".Split()); var helptext = HelpText.AutoBuild(result, help => { help.AddOptions(result); return help; }, example => { return example; }); return helptext; } } }
agpl-3.0
C#
9a9bf263fdab8bb129172e6d65f75be2ad9b4512
replace tcp and http with https for TLS connection
ahmetalpbalkan/Docker.DotNet,jterry75/Docker.DotNet,jterry75/Docker.DotNet
Docker.DotNet/DockerClientConfiguration.cs
Docker.DotNet/DockerClientConfiguration.cs
using System; namespace Docker.DotNet { public class DockerClientConfiguration { public Uri EndpointBaseUri { get; private set; } public Credentials Credentials { get; private set; } public DockerClientConfiguration(Uri endpoint) : this(endpoint, new AnonymousCredentials()) { } public DockerClientConfiguration(Uri endpoint, Credentials credentials) { if (endpoint == null) { throw new ArgumentNullException("endpoint"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } bool isTls = credentials is CertificateCredentials; this.EndpointBaseUri = SanitizeEndpoint(endpoint, isTls); this.Credentials = credentials; } public DockerClient CreateClient() { return this.CreateClient(null); } public DockerClient CreateClient(Version requestedApiVersion) { return new DockerClient(this, requestedApiVersion); } private static Uri SanitizeEndpoint(Uri endpoint, bool isTls) { UriBuilder builder = new UriBuilder(endpoint); if (isTls) { builder.Scheme = "https"; } else if (builder.Scheme.Equals("tcp", StringComparison.InvariantCultureIgnoreCase)) { builder.Scheme = "http"; } return builder.Uri; } } }
using System; namespace Docker.DotNet { public class DockerClientConfiguration { public Uri EndpointBaseUri { get; private set; } public Credentials Credentials { get; private set; } public DockerClientConfiguration(Uri endpoint) : this(endpoint, new AnonymousCredentials()) { } public DockerClientConfiguration(Uri endpoint, Credentials credentials) { if (endpoint == null) { throw new ArgumentNullException("endpoint"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.EndpointBaseUri = SanitizeEndpoint(endpoint); this.Credentials = credentials; } public DockerClient CreateClient() { return this.CreateClient(null); } public DockerClient CreateClient(Version requestedApiVersion) { return new DockerClient(this, requestedApiVersion); } private static Uri SanitizeEndpoint(Uri endpoint) { UriBuilder builder = new UriBuilder(endpoint); if (builder.Scheme.Equals("tcp", StringComparison.InvariantCultureIgnoreCase)) { builder.Scheme = "http"; } return builder.Uri; } } }
apache-2.0
C#
4fb36109ed999d41b9e71553a5dbcd1cc9cb0b26
enable sync
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.WebCore/Program.cs
src/Firehose.WebCore/Program.cs
using Firehose.Web.Infrastructure; using Microsoft.AspNetCore.Rewrite; using Microsoft.Extensions.DependencyInjection.Extensions; using System.Reflection; var builder = WebApplication.CreateBuilder(args); builder.WebHost.ConfigureKestrel(serverOptions => { serverOptions.AllowSynchronousIO = true; }); builder.Services.AddReverseProxy().LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")); builder.Services.AddSingleton<NewCombinedFeedSource>(); var members = Assembly.GetCallingAssembly().GetTypes() .Where(type => typeof(IAmACommunityMember).IsAssignableFrom(type) && !type.IsInterface); foreach (var member in members) builder.Services.AddSingleton(typeof(IAmACommunityMember), member); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); //app.UseSystemWebAdapters(); app.MapDefaultControllerRoute(); //app.MapReverseProxy(); app.Run();
using Firehose.Web.Infrastructure; using Microsoft.AspNetCore.Rewrite; using Microsoft.Extensions.DependencyInjection.Extensions; using System.Reflection; var builder = WebApplication.CreateBuilder(args); builder.Services.AddReverseProxy().LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")); builder.Services.AddSingleton<NewCombinedFeedSource>(); var members = Assembly.GetCallingAssembly().GetTypes() .Where(type => typeof(IAmACommunityMember).IsAssignableFrom(type) && !type.IsInterface); foreach (var member in members) builder.Services.AddSingleton(typeof(IAmACommunityMember), member); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); //app.UseSystemWebAdapters(); app.MapDefaultControllerRoute(); //app.MapReverseProxy(); app.Run();
mit
C#
318b71a0ae152ddc83d576ddecbca77862161c29
Update src/TestStack.Seleno.Tests/PageObjects/Actions/Controls/When_updating_TextBox_value.cs
bendetat/TestStack.Seleno,bendetat/TestStack.Seleno,dennisroche/TestStack.Seleno,random82/TestStack.Seleno,dennisroche/TestStack.Seleno,TestStack/TestStack.Seleno,random82/TestStack.Seleno,TestStack/TestStack.Seleno
src/TestStack.Seleno.Tests/PageObjects/Actions/Controls/When_updating_TextBox_value.cs
src/TestStack.Seleno.Tests/PageObjects/Actions/Controls/When_updating_TextBox_value.cs
using System; using NSubstitute; using TestStack.Seleno.PageObjects.Controls; namespace TestStack.Seleno.Tests.PageObjects.Actions.Controls { class When_updating_TextBox_value : HtmlControlSpecificationFor<TextBox> { private readonly DateTime _the03rdOfJanuary2012At21h21 = new DateTime(2012, 01, 03, 21, 21, 00); private readonly string _expectedScriptToBeExecuted = string.Format("$('#Modified').val('{0}')",_the03rdOfJanuary2012At21h21.ToString(CultureInfo.CurrentCulture)); public When_updating_TextBox_value() : base(x => x.Modified) { } public void When_updating_the_TextBox_value() { SUT.ReplaceInputValueWith(_the03rdOfJanuary2012At21h21); } public void Then_script_executor_should_execute_relevant_script_to_replace_the_value() { ScriptExecutor .Received() .ExecuteScript(_expectedScriptToBeExecuted); } } }
using System; using NSubstitute; using TestStack.Seleno.PageObjects.Controls; namespace TestStack.Seleno.Tests.PageObjects.Actions.Controls { class When_updating_TextBox_value : HtmlControlSpecificationFor<TextBox> { private readonly DateTime _the03rdOfJanuary2012At21h21 = new DateTime(2012, 01, 03, 21, 21, 00); public When_updating_TextBox_value() : base(x => x.Modified) { } public void When_updating_the_TextBox_value() { SUT.ReplaceInputValueWith(_the03rdOfJanuary2012At21h21); } public void Then_script_executor_should_execute_relevant_script_to_replace_the_value() { ScriptExecutor .Received() .ExecuteScript("$('#Modified').val('03/01/2012 21:21:00')"); } } }
mit
C#
d758e3897d5bb354ebdd7dd85f6eea00036cac58
Increment version.
EliotVU/Unreal-Library
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
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( "UELib" )] [assembly: AssemblyDescription( "UELib provides methods for deserializing and decompiling Unreal package files." )] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany( "" )] [assembly: AssemblyProduct( "UELib" )] [assembly: AssemblyCopyright( "Copyright 2010 - 2012 Eliot van Uytfanghe." )] [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( "0eb1c54e-8955-4c8d-98d3-16285f114f16" )] // 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.9.0" )] [assembly: AssemblyFileVersion( "1.0.9.0" )]
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( "UELib" )] [assembly: AssemblyDescription( "UELib provides methods for deserializing and decompiling Unreal package files." )] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany( "" )] [assembly: AssemblyProduct( "UELib" )] [assembly: AssemblyCopyright( "Copyright 2010 - 2012 Eliot van Uytfanghe." )] [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( "0eb1c54e-8955-4c8d-98d3-16285f114f16" )] // 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.8.176" )] [assembly: AssemblyFileVersion( "1.0.8.176" )]
mit
C#
842961979b069e6118a5d9af1057987b981a8f67
Enable nullable reference types for ErrorMessageList by explicitly acknowleging the potential for private null values.
plioi/parsley
src/Parsley/ErrorMessageList.cs
src/Parsley/ErrorMessageList.cs
namespace Parsley; public class ErrorMessageList { public static readonly ErrorMessageList Empty = new(); readonly ErrorMessage? head; readonly ErrorMessageList? tail; ErrorMessageList() { head = null; tail = null; } ErrorMessageList(ErrorMessage head, ErrorMessageList tail) { this.head = head; this.tail = tail; } public ErrorMessageList With(ErrorMessage errorMessage) { return new ErrorMessageList(errorMessage, this); } public ErrorMessageList Merge(ErrorMessageList errors) { var result = this; foreach (var error in errors.All<ErrorMessage>()) result = result.With(error); return result; } public override string ToString() { var expectationErrors = new List<string>(All<ExpectedErrorMessage>() .Select(error => error.Expectation) .Distinct() .OrderBy(expectation => expectation)); var backtrackErrors = All<BacktrackErrorMessage>().ToArray(); if (!expectationErrors.Any() && !backtrackErrors.Any()) { var unknownError = All<UnknownErrorMessage>().FirstOrDefault(); if (unknownError != null) return unknownError.ToString(); return ""; } var parts = new List<string>(); if (expectationErrors.Any()) { var suffixes = Separators(expectationErrors.Count - 1).Concat(new[] { " expected" }); parts.Add(string.Join("", expectationErrors.Zip(suffixes, (error, suffix) => error + suffix))); } if (backtrackErrors.Any()) parts.Add(string.Join(" ", backtrackErrors.Select(backtrack => $"[{backtrack}]"))); return string.Join(" ", parts); } static IEnumerable<string> Separators(int count) { if (count <= 0) return Enumerable.Empty<string>(); return Enumerable.Repeat(", ", count - 1).Concat(new[] { " or " }); } IEnumerable<T> All<T>() where T : ErrorMessage { if (head is T match) yield return match; if (tail != null) foreach (var message in tail.All<T>()) yield return message; } }
#nullable disable namespace Parsley; public class ErrorMessageList { public static readonly ErrorMessageList Empty = new(); readonly ErrorMessage head; readonly ErrorMessageList tail; ErrorMessageList() { head = null; tail = null; } ErrorMessageList(ErrorMessage head, ErrorMessageList tail) { this.head = head; this.tail = tail; } public ErrorMessageList With(ErrorMessage errorMessage) { return new ErrorMessageList(errorMessage, this); } public ErrorMessageList Merge(ErrorMessageList errors) { var result = this; foreach (var error in errors.All<ErrorMessage>()) result = result.With(error); return result; } public override string ToString() { var expectationErrors = new List<string>(All<ExpectedErrorMessage>() .Select(error => error.Expectation) .Distinct() .OrderBy(expectation => expectation)); var backtrackErrors = All<BacktrackErrorMessage>().ToArray(); if (!expectationErrors.Any() && !backtrackErrors.Any()) { var unknownError = All<UnknownErrorMessage>().FirstOrDefault(); if (unknownError != null) return unknownError.ToString(); return ""; } var parts = new List<string>(); if (expectationErrors.Any()) { var suffixes = Separators(expectationErrors.Count - 1).Concat(new[] { " expected" }); parts.Add(string.Join("", expectationErrors.Zip(suffixes, (error, suffix) => error + suffix))); } if (backtrackErrors.Any()) parts.Add(string.Join(" ", backtrackErrors.Select(backtrack => $"[{backtrack}]"))); return string.Join(" ", parts); } static IEnumerable<string> Separators(int count) { if (count <= 0) return Enumerable.Empty<string>(); return Enumerable.Repeat(", ", count - 1).Concat(new[] { " or " }); } IEnumerable<T> All<T>() where T : ErrorMessage { if (this != Empty) { if (head is T match) yield return match; foreach (var message in tail.All<T>()) yield return message; } } }
mit
C#