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
12cf7cf6133e3428a90f42c18b9ec73d61880b05
add a fallback value for game client language, in case if res/text/settings.xml file is not existed
smellyriver/tank-inspector-pro,smellyriver/tank-inspector-pro,smellyriver/tank-inspector-pro
src/Smellyriver.TankInspector.Pro/Repository/LocalGameClientLocalization.cs
src/Smellyriver.TankInspector.Pro/Repository/LocalGameClientLocalization.cs
using System.IO; using Smellyriver.TankInspector.Common.Text; using Smellyriver.TankInspector.IO.Gettext; using Smellyriver.TankInspector.IO.XmlDecoding; namespace Smellyriver.TankInspector.Pro.Repository { public class LocalGameClientLocalization : IRepositoryLocalization { private readonly LocalizationDatabase _localizationDatabase; public string Language { get; } public LocalGameClientLocalization(string textSettingsFile, string textFolder) { _localizationDatabase = new LocalizationDatabase(textFolder); if (File.Exists(textSettingsFile)) // this file might not be existed on some game clients { using (var reader = new BigworldXmlReader(textSettingsFile)) { reader.ReadStartElement(); reader.ReadToNextSibling("clientLangID"); reader.ReadStartElement("clientLangID"); this.Language = reader.Value; } } else { this.Language = "en-us"; } } public string GetLocalizedString(string key) { return _localizationDatabase.GetText(key); } public string GetLocalizedNationName(string nation) { return this.GetLocalizedString(string.Format("#menu:nations/{0}", nation)); } public string GetLocalizedTankName(string nation, string key) { return this.GetLocalizedString(string.Format("#{0}_vehicles:{1}", nation, key)); } public string GetLocalizedClassName(string @class) { if (@class == "observer") return "Observer"; return this.GetLocalizedString(string.Format("#item_types:vehicle/tags/{0}/name", NameConvension.CamelToCStyle(@class, true))); } } }
using Smellyriver.TankInspector.Common.Text; using Smellyriver.TankInspector.IO.Gettext; using Smellyriver.TankInspector.IO.XmlDecoding; namespace Smellyriver.TankInspector.Pro.Repository { public class LocalGameClientLocalization : IRepositoryLocalization { private readonly LocalizationDatabase _localizationDatabase; public string Language { get; } public LocalGameClientLocalization(string textSettingsFile, string textFolder) { _localizationDatabase = new LocalizationDatabase(textFolder); using (var reader = new BigworldXmlReader(textSettingsFile)) { reader.ReadStartElement(); reader.ReadToNextSibling("clientLangID"); reader.ReadStartElement("clientLangID"); this.Language = reader.Value; } } public string GetLocalizedString(string key) { return _localizationDatabase.GetText(key); } public string GetLocalizedNationName(string nation) { return this.GetLocalizedString(string.Format("#menu:nations/{0}", nation)); } public string GetLocalizedTankName(string nation, string key) { return this.GetLocalizedString(string.Format("#{0}_vehicles:{1}", nation, key)); } public string GetLocalizedClassName(string @class) { if (@class == "observer") return "Observer"; return this.GetLocalizedString(string.Format("#item_types:vehicle/tags/{0}/name", NameConvension.CamelToCStyle(@class, true))); } } }
mit
C#
0e80a2d52dd4148b1b8ca2ca6a555858296c15c9
fix using
elyen3824/myfinanalysis-data
data-provider/run.csx
data-provider/run.csx
using System.Net; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); string symbol = GetValueFromQuery(req, "symbol"); string start = GetValueFromQuery(req, "start"); string end = GetValueFromQuery(req, "end"); // Get request body dynamic data = await req.Content.ReadAsAsync<object>(); // Set name to query string or body data string[] symbols = data?.symbols; HttpResponseMessage result = GetResponse(req, symbol, symbols, start, end); return result; } private static string GetValueFromQuery(HttpRequestMessage req, string key) { return req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, key, true) == 0) .Value; } private static HttpResponseMessage GetResponse(HttpRequestMessage req, string symbol, string[] symbols, string start, string end) { if(symbol == null && symbols == null) return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body"); dynamic urls = GetUrls(symbol, symbols, start, end); return req.CreateResponse(HttpStatusCode.OK, urls); } private static dynamic GetUrls(string symbol, string[] symbols, string start, string end) { if(symbol !=null) return $"https://www.quandl.com/api/v3/datasets/WIKI/{symbol}/data.json?start_date={start}&end_date={end}&collapse=daily&transform=cumul"; return string.Empty; }
#r "System.Web.Http" using System.Net; using System.Net.Http; using System.Threading.Tasks; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); // parse query parameter string name = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0) .Value; string symbol = GetValueFromQuery(req, "symbol"); string start = GetValueFromQuery(req, "start"); string end = GetValueFromQuery(req, "end"); // Get request body dynamic data = await req.Content.ReadAsAsync<object>(); // Set name to query string or body data string[] symbols = data?.symbols; HttpResponseMessage result = GetResponse(req, symbol, symbols, start, end); return result; } private static string GetValueFromQuery(HttpRequestMessage req, string key) { return req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, key, true) == 0) .Value; } private static HttpResponseMessage GetResponse(HttpRequestMessage req, string symbol, string[] symbols, string start, string end) { if(symbol == null && symbols == null) return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body"); dynamic urls = GetUrls(symbol, symbols, start, end); return req.CreateResponse(HttpStatusCode.OK, urls); } private static dynamic GetUrls(string symbol, string[] symbols, string start, string end) { if(symbol !=null) return $"https://www.quandl.com/api/v3/datasets/WIKI/{symbol}/data.json?start_date={start}&end_date={end}&collapse=daily&transform=cumul"; return string.Empty; }
mit
C#
5035fa39b72bfbd6c22bd487fe7b21fb56fb9a79
Fix inaccurate error tooltip
TorchAPI/Torch
Torch/TorchPluginBase.cs
Torch/TorchPluginBase.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using NLog; using Torch.API; using Torch.API.Plugins; namespace Torch { public abstract class TorchPluginBase : ITorchPlugin { public string StoragePath { get; internal set; } public PluginManifest Manifest { get; internal set; } public Guid Id => Manifest.Guid; public string Version => Manifest.Version; public string Name => Manifest.Name; public ITorchBase Torch { get; internal set; } public virtual void Init(ITorchBase torch) { Torch = torch; } public virtual void Update() { } public PluginState State { get; } = PluginState.Enabled; public virtual void Dispose() { } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using NLog; using Torch.API; using Torch.API.Plugins; namespace Torch { public abstract class TorchPluginBase : ITorchPlugin { public string StoragePath { get; internal set; } public PluginManifest Manifest { get; internal set; } public Guid Id => Manifest.Guid; public string Version => Manifest.Version; public string Name => Manifest.Name; public ITorchBase Torch { get; internal set; } public virtual void Init(ITorchBase torch) { Torch = torch; } public virtual void Update() { } public PluginState State { get; } public virtual void Dispose() { } } }
apache-2.0
C#
5b501cc0e309c1e17f50820e6753e2d48dec2141
Increment version to 1.1.0.25
jcvandan/XeroAPI.Net,MatthewSteeples/XeroAPI.Net,TDaphneB/XeroAPI.Net,XeroAPI/XeroAPI.Net
source/XeroApi/Properties/AssemblyInfo.cs
source/XeroApi/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("XeroApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xero")] [assembly: AssemblyProduct("XeroApi")] [assembly: AssemblyCopyright("Copyright © Xero 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")] // 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.1.0.25")] [assembly: AssemblyFileVersion("1.1.0.25")]
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("XeroApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Xero")] [assembly: AssemblyProduct("XeroApi")] [assembly: AssemblyCopyright("Copyright © Xero 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")] // 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.1.0.24")] [assembly: AssemblyFileVersion("1.1.0.24")]
mit
C#
5d6c8326541640cbcb9e0820704584d3947eda7b
Update Index.cshtml
ikezili/mvc-pagination,ikezili/mvc-pagination
demo/MVCPagination/Views/Home/Index.cshtml
demo/MVCPagination/Views/Home/Index.cshtml
@{ ViewBag.Title = "MVC Pagination"; } @using MVCPagination.Components @{ var modelPaginning = new Pagination.ModelPaginning(); modelPaginning.Id = "mvc-pagination"; modelPaginning.TotalPages = 50; modelPaginning.StartPage = Convert.ToInt32(!String.IsNullOrEmpty(Request["page"]) ? Request["page"].ToString() : "1"); modelPaginning.VisiblePages = 5; modelPaginning.First = "Primeiro"; modelPaginning.Prev = "Anterior"; modelPaginning.Next = "Próximo"; modelPaginning.Last = "Último"; modelPaginning.Href = "?page={{pagenumber}}"; modelPaginning.ShowControl = true; modelPaginning.ShowPrevNext = true; modelPaginning.ShowFirstLast = true; modelPaginning.HrefVariable = "{{pagenumber}}"; } @using (Html.MVCPagination(modelPaginning)){ } <div id="page-content"> </div> @using (Html.MVCPagination(modelPaginning)) { } <script> $('.mvc-pagination').mvcPagination({ totalPages: @Html.Raw(modelPaginning.TotalPages), visiblePages: @Html.Raw(modelPaginning.VisiblePages), href: "@Html.Raw(modelPaginning.Href)", startPage: @Html.Raw(modelPaginning.StartPage), first: "@Html.Raw(modelPaginning.First)", prev: "@Html.Raw(modelPaginning.Prev)", next: "@Html.Raw(modelPaginning.Next)", last: "@Html.Raw(modelPaginning.Last)", showPrevNext: @Html.Raw(modelPaginning.ShowPrevNext.ToString().ToLower()), showFirstLast: @Html.Raw(modelPaginning.ShowFirstLast.ToString().ToLower()), showControl: @Html.Raw(modelPaginning.ShowControl.ToString().ToLower()), hrefVariable: "@Html.Raw(modelPaginning.HrefVariable)", onClick: function (event, page) { $('#page-content').text('Page ' + page); } }); </script>
@{ ViewBag.Title = "MVC Pagination"; } @using MVCPagination.Components @{ var modelPaginning = new Pagination.ModelPaginning(); modelPaginning.Id = "mvc-pagination"; modelPaginning.TotalPages = 50; modelPaginning.StartPage = Convert.ToInt32(!String.IsNullOrEmpty(Request["page"]) ? Request["page"].ToString() : "1"); modelPaginning.VisiblePages = 5; modelPaginning.First = "Primeiro"; modelPaginning.Prev = "Anterior"; modelPaginning.Next = "Próximo"; modelPaginning.Last = "Último"; modelPaginning.Href = "?page={{pagenumber}}"; modelPaginning.ShowControl = true; modelPaginning.ShowPrevNext = true; modelPaginning.ShowFirstLast = true; modelPaginning.HrefVariable = "{{pagenumber}}"; } @using (Html.MVCPagination(modelPaginning)){ } <div id="page-content"> </div> @using (Html.MVCPagination(modelPaginning)) { } <script> $('.mvc-pagination').mvcPagination({ totalPages: @Html.Raw(modelPaginning.TotalPages), visiblePages: @Html.Raw(modelPaginning.VisiblePages), href: "@Html.Raw(modelPaginning.Href)", startPage: @Html.Raw(modelPaginning.StartPage), first: "@Html.Raw(modelPaginning.First)", prev: "@Html.Raw(modelPaginning.Prev)", next: "@Html.Raw(modelPaginning.Next)", last: "@Html.Raw(modelPaginning.Last)", showPrevNext: @Html.Raw(modelPaginning.ShowPrevNext.ToString().ToLower()), showFirstLast: @Html.Raw(modelPaginning.ShowFirstLast.ToString().ToLower()), showControl: @Html.Raw(modelPaginning.ShowControl.ToString().ToLower()), hrefVariable: "@Html.Raw(modelPaginning.HrefVariable)"; onClick: function (event, page) { $('#page-content').text('Page ' + page); } }); </script>
apache-2.0
C#
2f0a6934c0261af1db0a52e81414df4350759c95
Fix type of auto-properties
CurrencyCloud/currencycloud-net
Source/CurrencyCloud/Entity/ConversionSplit.cs
Source/CurrencyCloud/Entity/ConversionSplit.cs
using System; using Newtonsoft.Json; namespace CurrencyCloud.Entity { public class ConversionSplit : Entity { [JsonConstructor] public ConversionSplit() { } public ConversionSplitDetails ParentConversion { get; set; } public ConversionSplitDetails ChildConversion { get; set; } public string ToJSON() { var obj = new[] { new { ParentConversion, ChildConversion } }; return JsonConvert.SerializeObject(obj); } public override bool Equals(object obj) { if (!(obj is ConversionSplit)) { return false; } var conversionSplit = obj as ConversionSplit; return ParentConversion == conversionSplit.ParentConversion && ChildConversion == conversionSplit.ChildConversion; } public override int GetHashCode() { var hash = 11; hash = hash * 101 + ParentConversion.Id.GetHashCode(); hash = hash * 101 + ChildConversion.Id.GetHashCode(); return hash; } } }
using System; using Newtonsoft.Json; namespace CurrencyCloud.Entity { public class ConversionSplit : Entity { [JsonConstructor] public ConversionSplit() { } public Conversion ParentConversion { get; set; } public Conversion ChildConversion { get; set; } public string ToJSON() { var obj = new[] { new { ParentConversion, ChildConversion } }; return JsonConvert.SerializeObject(obj); } public override bool Equals(object obj) { if (!(obj is ConversionSplit)) { return false; } var conversionSplit = obj as ConversionSplit; return ParentConversion == conversionSplit.ParentConversion && ChildConversion == conversionSplit.ChildConversion; } public override int GetHashCode() { var hash = 11; hash = hash * 101 + ParentConversion.Id.GetHashCode(); hash = hash * 101 + ChildConversion.Id.GetHashCode(); return hash; } } }
mit
C#
da47c542737a8a570280076692700d8a379d0b35
add cannot understand
adipatl/ken,adipatl/ken,adipatl/ken
KenBot/Ai/KenAi.cs
KenBot/Ai/KenAi.cs
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Builder.Luis; using Microsoft.Bot.Builder.Luis.Models; namespace Ken { [LuisModel("829ee634-ba62-4240-baf7-70a66163ab01", "d018c3a25fcc49889b863595ceef2ffd")] [Serializable] public class KenAi : LuisDialog<object> { public const string EntityStockSymbol = "StockSymbol"; [LuisIntent("None")] public async Task None(IDialogContext context, LuisResult result) { //string message = $"Sorry I did not understand: " + string.Join(", ", result.Intents.Select(i => i.Intent)); string message = $"Sorry I did not understand - I can do only say Hi"; await context.PostAsync(message); context.Wait(MessageReceived); } [LuisIntent("Greeting")] public async Task GetStockPrice(IDialogContext context, LuisResult result) { EntityRecommendation symbol; await context.PostAsync($"Hi There"); context.Wait(MessageReceived); } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Builder.Luis; using Microsoft.Bot.Builder.Luis.Models; namespace Ken { [LuisModel("829ee634-ba62-4240-baf7-70a66163ab01", "d018c3a25fcc49889b863595ceef2ffd")] [Serializable] public class KenAi : LuisDialog<object> { public const string EntityStockSymbol = "StockSymbol"; [LuisIntent("")] public async Task None(IDialogContext context, LuisResult result) { string message = $"Sorry I did not understand: " + string.Join(", ", result.Intents.Select(i => i.Intent)); await context.PostAsync(message); context.Wait(MessageReceived); } [LuisIntent("Greeting")] public async Task GetStockPrice(IDialogContext context, LuisResult result) { EntityRecommendation symbol; await context.PostAsync($"Hi There"); context.Wait(MessageReceived); } } }
mit
C#
0d92eb6e37eea7ddc7d6b87aed63b3266255b6f3
Verify if .paket\paket.exe exists if not, try downloading using .paket\paket.bootstrapper.exe else fail
hmemcpy/Paket.VisualStudio,fsprojects/Paket.VisualStudio
src/Paket.VisualStudio/Utils/PaketLauncher.cs
src/Paket.VisualStudio/Utils/PaketLauncher.cs
using System.Diagnostics; using System.IO; namespace Paket.VisualStudio.Utils { public static class PaketLauncher { const string PAKET_EXE = ".paket\\paket.exe"; const string PAKET_BOOTSTRAPPER_EXE = ".paket\\paket.bootstrapper.exe"; const string PAKET_RELEASE_URL = "https://github.com/fsprojects/Paket/releases"; const string PAKET_GETTING_STARTED_URL = "https://fsprojects.github.io/Paket/getting-started.html"; private static int LaunchProcess(string SolutionDirectory, string FileName, string PaketSubCommand, DataReceivedEventHandler PaketDataReceivedHandler) { Process process = new Process(); process.StartInfo.FileName = SolutionDirectory + FileName; process.StartInfo.Arguments = PaketSubCommand; process.StartInfo.UseShellExecute = false; process.StartInfo.WorkingDirectory = SolutionDirectory; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.OutputDataReceived += PaketDataReceivedHandler; process.ErrorDataReceived += PaketDataReceivedHandler; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); return process.ExitCode; } public static void LaunchPaket(string SolutionDirectory, string PaketSubCommand, DataReceivedEventHandler PaketDataReceivedHandler) { if (!File.Exists(SolutionDirectory + PAKET_EXE)) { //If .paket\paket.exe is not found under the solution dir, try launching paket.bootstrapper.exe if (File.Exists(SolutionDirectory + PAKET_BOOTSTRAPPER_EXE)) { int ExitCode = LaunchProcess(SolutionDirectory, PAKET_BOOTSTRAPPER_EXE, "", PaketDataReceivedHandler); if (ExitCode != 0) /* If something went wrong with paket.bootstrapper.exe e.g. couldn't download paket.exe due to proxy auth error * then we should not execute the command that was originally issued for paket.exe. */ throw new System.Exception("paket.bootstrapper.exe terminated abnormally."); } else throw new FileNotFoundException( @"Could not locate .paket\paket.exe and .paket\paket.bootstrapper.exe under the solution " + SolutionDirectory + "\nTo download the binaries, visit " + PAKET_RELEASE_URL + "\nTo know more about Paket, visit " + PAKET_GETTING_STARTED_URL + "\n"); } /* At this point, all is well .paket\paket.exe exists or .paket\paket.bootstrapper.exe downloaded it successfully. * Now issue the original command to .paket\paket.exe */ LaunchProcess(SolutionDirectory, PAKET_EXE, PaketSubCommand, PaketDataReceivedHandler); } } }
using System.Diagnostics; namespace Paket.VisualStudio.Utils { public static class PaketLauncher { public static void LaunchPaket(string SolutionDirectory, string PaketSubCommand, DataReceivedEventHandler PaketDataReceivedHandler) { Process process = new Process(); process.StartInfo.FileName = SolutionDirectory + ".paket\\paket.exe"; process.StartInfo.Arguments = PaketSubCommand; process.StartInfo.UseShellExecute = false; process.StartInfo.WorkingDirectory = SolutionDirectory; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.OutputDataReceived += PaketDataReceivedHandler; process.ErrorDataReceived += PaketDataReceivedHandler; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); } } }
mit
C#
85c2da8a57f75987a13d35aa40aa442e3bc5b762
Add coment
dorayaki4369/CutImageFromVideo
MainWindow.xaml.cs
MainWindow.xaml.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace CutImageFromMovie { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } /** * MovieList : Drag&Drop */ private void MovieList_Drop(object sender, DragEventArgs e) { var list = DataContext as SettingData; var files = e.Data.GetData(DataFormats.FileDrop) as string[]; if (files == null) return; foreach (var s in files) { list?.MovieFileNames.Add(s); } } private void MovieList_PreviewDragOver(object sender, DragEventArgs e) { e.Effects = e.Data.GetDataPresent(DataFormats.FileDrop, true) ? DragDropEffects.Copy : DragDropEffects.None; e.Handled = true; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace CutImageFromMovie { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void MovieList_Drop(object sender, DragEventArgs e) { var list = DataContext as SettingData; var files = e.Data.GetData(DataFormats.FileDrop) as string[]; if (files == null) return; foreach (var s in files) { list?.MovieFileNames.Add(s); } } private void MovieList_PreviewDragOver(object sender, DragEventArgs e) { e.Effects = e.Data.GetDataPresent(DataFormats.FileDrop, true) ? DragDropEffects.Copy : DragDropEffects.None; e.Handled = true; } } }
mit
C#
1f3aa695bfa5db5f54f5479a647785d91762a488
Use stream in using scope
appharbor/appharbor-cli
src/AppHarbor/ApplicationConfiguration.cs
src/AppHarbor/ApplicationConfiguration.cs
using System; using System.IO; using AppHarbor.Model; namespace AppHarbor { public class ApplicationConfiguration { private readonly IFileSystem _fileSystem; private readonly IGitExecutor _gitExecutor; public ApplicationConfiguration(IFileSystem fileSystem, IGitExecutor gitExecutor) { _fileSystem = fileSystem; _gitExecutor = gitExecutor; } public string GetApplicationId() { var directory = Directory.GetCurrentDirectory(); var appharborConfigurationFile = new FileInfo(Path.Combine(directory, ".appharbor")); try { using (var stream = _fileSystem.OpenRead(appharborConfigurationFile.FullName)) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } catch (FileNotFoundException) { throw new ApplicationConfigurationException("Application is not configured"); } } public void SetupApplication(string id, User user) { var repositoryUrl = string.Format("https://{0}@appharbor.com/{1}.git", user.Username, id); try { _gitExecutor.Execute(string.Format("remote add appharbor https://{0}@appharbor.com/{1}.git", user.Username, id), new DirectoryInfo(Directory.GetCurrentDirectory())); Console.WriteLine("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master"); return; } catch (InvalidOperationException) { } Console.WriteLine("Couldn't add appharbor repository as a git remote. Repository URL is: {0}", repositoryUrl); } } }
using System; using System.IO; using AppHarbor.Model; namespace AppHarbor { public class ApplicationConfiguration { private readonly IFileSystem _fileSystem; private readonly IGitExecutor _gitExecutor; public ApplicationConfiguration(IFileSystem fileSystem, IGitExecutor gitExecutor) { _fileSystem = fileSystem; _gitExecutor = gitExecutor; } public string GetApplicationId() { var directory = Directory.GetCurrentDirectory(); var appharborConfigurationFile = new FileInfo(Path.Combine(directory, ".appharbor")); try { var stream = _fileSystem.OpenRead(appharborConfigurationFile.FullName); using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } catch (FileNotFoundException) { throw new ApplicationConfigurationException("Application is not configured"); } } public void SetupApplication(string id, User user) { var repositoryUrl = string.Format("https://{0}@appharbor.com/{1}.git", user.Username, id); try { _gitExecutor.Execute(string.Format("remote add appharbor https://{0}@appharbor.com/{1}.git", user.Username, id), new DirectoryInfo(Directory.GetCurrentDirectory())); Console.WriteLine("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master"); return; } catch (InvalidOperationException) { } Console.WriteLine("Couldn't add appharbor repository as a git remote. Repository URL is: {0}", repositoryUrl); } } }
mit
C#
b482f2e900fa2e3ac16fda0e0bc8de4a39fb8e11
Add modifiers
fredatgithub/Crypto
SearchAllCombinaisons/Program.cs
SearchAllCombinaisons/Program.cs
using System; namespace SearchAllCombinaisons { public class Program { private static readonly char[] PossibleCharacters = {'0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '[', ']', '{', '}', ';', ':', ',', '.', '<', '>', '/', '?' }; private static string _findPassword; private static int _combi; public static void Main() { int count; Console.WriteLine("Enter your Password"); _findPassword = Console.ReadLine(); DateTime today = DateTime.Now; Console.WriteLine("START:\t{0}", today.ToString("yyyy-MM-dd_HH:mm:ss")); for (count = 0; count <= 15; count++) { Recurse(count, 0, ""); } } private static void Recurse(int length, int position, string baseString) { for (int count = 0; count < PossibleCharacters.Length; count++) { _combi++; if (position < length - 1) { Recurse(length, position + 1, baseString + PossibleCharacters[count]); } if (baseString + PossibleCharacters[count] == _findPassword) { DateTime today = DateTime.Now; Console.WriteLine("END:\t{0}\nCombi:\t{1}", today.ToString("yyyy-MM-dd_HH:mm:ss"), _combi); Console.WriteLine("Press a key to exit:"); Console.ReadLine(); Environment.Exit(0); } Console.WriteLine(_combi); } } } }
using System; namespace SearchAllCombinaisons { class Program { static readonly char[] PossibleCharacters = {'0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '[', ']', '{', '}', ';', ':', ',', '.', '<', '>', '/', '?' }; static string _findPassword; static int _combi; static void Main() { int count; Console.WriteLine("Enter your Password"); _findPassword = Console.ReadLine(); DateTime today = DateTime.Now; Console.WriteLine("START:\t{0}", today.ToString("yyyy-MM-dd_HH:mm:ss")); for (count = 0; count <= 15; count++) { Recurse(count, 0, ""); } } static void Recurse(int length, int position, string baseString) { for (int count = 0; count < PossibleCharacters.Length; count++) { _combi++; if (position < length - 1) { Recurse(length, position + 1, baseString + PossibleCharacters[count]); } if (baseString + PossibleCharacters[count] == _findPassword) { DateTime today = DateTime.Now; Console.WriteLine("END:\t{0}\nCombi:\t{1}", today.ToString("yyyy-MM-dd_HH:mm:ss"), _combi); Console.WriteLine("Press a key to exit:"); Console.ReadLine(); Environment.Exit(0); } Console.WriteLine(_combi); } } } }
mit
C#
810cc50896b5e3a98092db6347230ac8aff2b6fc
fix - build
pavelekNET/DesignPatterns
StructuralDesignPatterns/StructuralDesignPatterns/Adapter/Helpers/TokenBasedAuthentication.cs
StructuralDesignPatterns/StructuralDesignPatterns/Adapter/Helpers/TokenBasedAuthentication.cs
using System; namespace StructuralDesignPatterns.Adapter.Helpers { public class TokenBasedAuthentication { public Guid SignIn(string userName, string password) { return Guid.NewGuid(); } public Guid GetUserToken(string userName) { return Guid.NewGuid(); } public string GetUserName(Guid userToken) { return string.Empty; } public void DestroyUserToken(Guid userToken) { } } }
using System; namespace StructuralDesignPatterns.Adapter.Helpers { public class TokenBasedAuthentication { public Guid SignIn(string userName, string password) { return Guid.NewGuid(); } public Guid GetUserToken(string userName) { return Guid.NewGuid()` } public string GetUserName(Guid userToken) { return string.Empty; } public void DestroyUserToken(Guid userToken) { } } }
mit
C#
fd7862e2836cf2fdeec475331198ee3835d3ee3e
Replace npmcdn.com with unpkg.com
oldskoolfan/mvctest,oldskoolfan/mvctest
Views/Accounts/AddAccount.cshtml
Views/Accounts/AddAccount.cshtml
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="~/js/add-account.js"></script> <fieldset> <legend>Add Account</legend> <label for="nickname">Nickname: <input id="nickname" type="text" /> </label> <label>Type: <input name="account-type" type="radio" value="checking"/>Checking <input name="account-type" type="radio" value="savings"/>Savings </label> <label for="balance">Balance: <input id="balance" type="text" /> </label> <button id="submit" onclick="submitAccount()">Save</button> <button id="clear" onclick="clearForm()">Clear</button> </fieldset>
<script src="https://npmcdn.com/axios/dist/axios.min.js"></script> <script src="~/js/add-account.js"></script> <fieldset> <legend>Add Account</legend> <label for="nickname">Nickname: <input id="nickname" type="text" /> </label> <label>Type: <input name="account-type" type="radio" value="checking"/>Checking <input name="account-type" type="radio" value="savings"/>Savings </label> <label for="balance">Balance: <input id="balance" type="text" /> </label> <button id="submit" onclick="submitAccount()">Save</button> <button id="clear" onclick="clearForm()">Clear</button> </fieldset>
mit
C#
1d9198b81116df056e7f23e8baa730a32a47c116
Use the logger for writing to the console.
FloodProject/flood,FloodProject/flood,FloodProject/flood
src/Editor/Editor.Client/ServerManager.cs
src/Editor/Editor.Client/ServerManager.cs
using System; using System.Threading; using Flood.Editor.Server; namespace Flood.Editor { public class ServerManager { public EditorServer Server { get; private set; } private ManualResetEventSlim serverCreatedEvent; private void RunBuiltinServer() { serverCreatedEvent.Set(); Server.Serve(); } public void CreateBuiltinServer() { Log.Info("Initializing the built-in editor server..."); serverCreatedEvent = new ManualResetEventSlim(); Server = new EditorServer(); System.Threading.Tasks.Task.Run((Action)RunBuiltinServer); serverCreatedEvent.Wait(); } } }
using System; using System.Threading; using Flood.Editor.Server; namespace Flood.Editor { public class ServerManager { public EditorServer Server { get; private set; } private ManualResetEventSlim serverCreatedEvent; private void RunBuiltinServer() { serverCreatedEvent.Set(); Server.Serve(); } public void CreateBuiltinServer() { Console.WriteLine("Initializing the built-in editor server..."); serverCreatedEvent = new ManualResetEventSlim(); Server = new EditorServer(); System.Threading.Tasks.Task.Run((Action)RunBuiltinServer); serverCreatedEvent.Wait(); } } }
bsd-2-clause
C#
36e578790e0e5ca9e0fe5ffa9b20ce6b0d246999
Use non-temp parameter name
JakeGinnivan/GitVersion,GitTools/GitVersion,ParticularLabs/GitVersion,ermshiperete/GitVersion,GitTools/GitVersion,JakeGinnivan/GitVersion,JakeGinnivan/GitVersion,ermshiperete/GitVersion,gep13/GitVersion,dazinator/GitVersion,ParticularLabs/GitVersion,ermshiperete/GitVersion,asbjornu/GitVersion,asbjornu/GitVersion,ermshiperete/GitVersion,gep13/GitVersion,JakeGinnivan/GitVersion,dazinator/GitVersion
src/GitVersionCore/TemplateManager.cs
src/GitVersionCore/TemplateManager.cs
namespace GitVersion { using System; using System.Collections.Generic; using System.IO; using System.Linq; using GitVersionCore.Extensions; enum TemplateType { VersionAssemblyInfoResources, GitVersionInformationResources } class TemplateManager { readonly Dictionary<string, string> templates; readonly Dictionary<string, string> addFormats; public TemplateManager(TemplateType templateType) { templates = GetEmbeddedTemplates(templateType, "Templates").ToDictionary(k => Path.GetExtension(k), v => v); addFormats = GetEmbeddedTemplates(templateType, "AddFormats").ToDictionary(k => Path.GetExtension(k), v => v); } public string GetTemplateFor(string fileExtension) { string result = null; string template; if (templates.TryGetValue(fileExtension, out template) && template != null) { result = template.ReadAsStringFromEmbeddedResource<TemplateManager>(); } return result; } public string GetAddFormatFor(string fileExtension) { string result = null; string addFormat; if(addFormats.TryGetValue(fileExtension, out addFormat) && addFormat != null) { result = addFormat.ReadAsStringFromEmbeddedResource<TemplateManager>(); } return result; } public bool IsSupported(string fileExtension) { if (fileExtension == null) { throw new ArgumentNullException(nameof(fileExtension)); } return addFormats.Keys.Contains(fileExtension, StringComparer.OrdinalIgnoreCase); } static IEnumerable<string> GetEmbeddedTemplates(TemplateType templateType, string templateCategory) { foreach (var name in typeof(TemplateManager).Assembly.GetManifestResourceNames()) { if (name.Contains(templateType.ToString()) && name.Contains(templateCategory)) { yield return name; } } } } }
namespace GitVersion { using System; using System.Collections.Generic; using System.IO; using System.Linq; using GitVersionCore.Extensions; enum TemplateType { VersionAssemblyInfoResources, GitVersionInformationResources } class TemplateManager { readonly Dictionary<string, string> templates; readonly Dictionary<string, string> addFormats; public TemplateManager(TemplateType templateType) { templates = GetEmbeddedTemplates(templateType, "Templates").ToDictionary(k => Path.GetExtension(k), v => v); addFormats = GetEmbeddedTemplates(templateType, "AddFormats").ToDictionary(k => Path.GetExtension(k), v => v); } public string GetTemplateFor(string fileExtension) { string result = null; string template; if (templates.TryGetValue(fileExtension, out template) && template != null) { result = template.ReadAsStringFromEmbeddedResource<TemplateManager>(); } return result; } public string GetAddFormatFor(string fileExtension) { string result = null; string addFormat; if(addFormats.TryGetValue(fileExtension, out addFormat) && addFormat != null) { result = addFormat.ReadAsStringFromEmbeddedResource<TemplateManager>(); } return result; } public bool IsSupported(string fileExtension) { if (fileExtension == null) { throw new ArgumentNullException(nameof(fileExtension)); } return addFormats.Keys.Contains(fileExtension, StringComparer.OrdinalIgnoreCase); } static IEnumerable<string> GetEmbeddedTemplates(TemplateType templateType, string blah) { foreach (var name in typeof(TemplateManager).Assembly.GetManifestResourceNames()) { if (name.Contains(templateType.ToString()) && name.Contains(blah)) { yield return name; } } } } }
mit
C#
702a8b91e99b35a03ea14b9032a348f00a19921d
Make bitmap loading cache the image
distantcam/WPFConverters
src/WPFConverters/BitmapImageConverter.cs
src/WPFConverters/BitmapImageConverter.cs
using System; using System.Globalization; using System.Windows; using System.Windows.Media.Imaging; namespace WPFConverters { public class BitmapImageConverter : BaseConverter { protected override object OnConvert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string) return LoadImage(new Uri((string)value, UriKind.RelativeOrAbsolute)); if (value is Uri) return LoadImage((Uri)value); return DependencyProperty.UnsetValue; } private BitmapImage LoadImage(Uri uri) { var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.UriSource = uri; image.EndInit(); return image; } } }
using System; using System.Globalization; using System.Windows; using System.Windows.Media.Imaging; namespace WPFConverters { public class BitmapImageConverter : BaseConverter { protected override object OnConvert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string) return new BitmapImage(new Uri((string)value, UriKind.RelativeOrAbsolute)); if (value is Uri) return new BitmapImage((Uri)value); return DependencyProperty.UnsetValue; } } }
mit
C#
2b58b1e89220144f669f306fce375f73a596698d
Use google API key in async test.
Troncho/Geocoding.net,harsimranb/Geocoding.net,chadly/Geocoding.net
src/Tests/GoogleAsyncGeocoderTest.cs
src/Tests/GoogleAsyncGeocoderTest.cs
using System.Configuration; using System.Linq; using Geocoding.Google; using Xunit; using Xunit.Extensions; namespace Geocoding.Tests { public class GoogleAsyncGeocoderTest : AsyncGeocoderTest { GoogleGeocoder geoCoder; protected override IAsyncGeocoder CreateAsyncGeocoder() { geoCoder = new GoogleGeocoder { ApiKey = ConfigurationManager.AppSettings["googleApiKey"] }; return geoCoder; } [Theory] [InlineData("United States", GoogleAddressType.Country)] [InlineData("Illinois, US", GoogleAddressType.AdministrativeAreaLevel1)] [InlineData("New York, New York", GoogleAddressType.Locality)] [InlineData("90210, US", GoogleAddressType.PostalCode)] [InlineData("1600 pennsylvania ave washington dc", GoogleAddressType.StreetAddress)] public void CanParseAddressTypes(string address, GoogleAddressType type) { geoCoder.GeocodeAsync(address).ContinueWith(task => { GoogleAddress[] addresses = task.Result.ToArray(); Assert.Equal(type, addresses[0].Type); }); } } }
using System.Linq; using Geocoding.Google; using Xunit; using Xunit.Extensions; namespace Geocoding.Tests { public class GoogleAsyncGeocoderTest : AsyncGeocoderTest { GoogleGeocoder geoCoder; protected override IAsyncGeocoder CreateAsyncGeocoder() { geoCoder = new GoogleGeocoder(); return geoCoder; } [Theory] [InlineData("United States", GoogleAddressType.Country)] [InlineData("Illinois, US", GoogleAddressType.AdministrativeAreaLevel1)] [InlineData("New York, New York", GoogleAddressType.Locality)] [InlineData("90210, US", GoogleAddressType.PostalCode)] [InlineData("1600 pennsylvania ave washington dc", GoogleAddressType.StreetAddress)] public void CanParseAddressTypes(string address, GoogleAddressType type) { geoCoder.GeocodeAsync(address).ContinueWith(task => { GoogleAddress[] addresses = task.Result.ToArray(); Assert.Equal(type, addresses[0].Type); }); } } }
mit
C#
b46c0768dbee668b57d89d0be8db741e8534288b
Modify DescriptionAttribute to use PropertyAttribute
danielmarbach/nunit,modulexcite/nunit,ChrisMaddock/nunit,dicko2/nunit,Green-Bug/nunit,mikkelbu/nunit,Green-Bug/nunit,acco32/nunit,agray/nunit,jhamm/nunit,dicko2/nunit,pcalin/nunit,mikkelbu/nunit,Green-Bug/nunit,pflugs30/nunit,zmaruo/nunit,michal-franc/nunit,appel1/nunit,jadarnel27/nunit,JustinRChou/nunit,JustinRChou/nunit,jhamm/nunit,modulexcite/nunit,Therzok/nunit,akoeplinger/nunit,dicko2/nunit,pflugs30/nunit,NarohLoyahl/nunit,agray/nunit,ChrisMaddock/nunit,elbaloo/nunit,Therzok/nunit,acco32/nunit,agray/nunit,mjedrzejek/nunit,cPetru/nunit-params,OmicronPersei/nunit,nunit/nunit,Suremaker/nunit,passaro/nunit,ArsenShnurkov/nunit,NikolayPianikov/nunit,danielmarbach/nunit,cPetru/nunit-params,JohanO/nunit,jnm2/nunit,jeremymeng/nunit,NarohLoyahl/nunit,acco32/nunit,jadarnel27/nunit,Therzok/nunit,jeremymeng/nunit,Suremaker/nunit,ggeurts/nunit,ArsenShnurkov/nunit,pcalin/nunit,nunit/nunit,pcalin/nunit,NikolayPianikov/nunit,passaro/nunit,mjedrzejek/nunit,NarohLoyahl/nunit,jnm2/nunit,OmicronPersei/nunit,appel1/nunit,elbaloo/nunit,JohanO/nunit,elbaloo/nunit,ggeurts/nunit,jhamm/nunit,zmaruo/nunit,modulexcite/nunit,JohanO/nunit,michal-franc/nunit,passaro/nunit,ArsenShnurkov/nunit,jeremymeng/nunit,akoeplinger/nunit,danielmarbach/nunit,michal-franc/nunit,nivanov1984/nunit,akoeplinger/nunit,nivanov1984/nunit,zmaruo/nunit
src/framework/DescriptionAttribute.cs
src/framework/DescriptionAttribute.cs
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; namespace NUnit.Framework { /// <summary> /// Attribute used to provide descriptive text about a /// test case or fixture. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false)] public sealed class DescriptionAttribute : PropertyAttribute { public DescriptionAttribute(string description) : base(description) { } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; namespace NUnit.Framework { /// <summary> /// Attribute used to provide descriptive text about a /// test case or fixture. /// </summary> [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Assembly, AllowMultiple=false)] public class DescriptionAttribute : Attribute { string description; /// <summary> /// Construct the attribute /// </summary> /// <param name="description">Text describing the test</param> public DescriptionAttribute(string description) { this.description=description; } /// <summary> /// Gets the test description /// </summary> public string Description { get { return description; } } } }
mit
C#
ba298f4269063461c90cdf11184bd3e85fac390d
Fix typos.
jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr
test/HelloCoreClrApp.Test/Data/DatabaseOptionsBuilderFactoryTest.cs
test/HelloCoreClrApp.Test/Data/DatabaseOptionsBuilderFactoryTest.cs
using System; using FluentAssertions; using HelloCoreClrApp.Data; using Microsoft.EntityFrameworkCore; using Xunit; namespace HelloCoreClrApp.Test.Data { public class DatabaseOptionsBuilderFactoryTest { [Fact] public void SqliteConnectionStringShouldReturnConfiguredBuilderTest() { var builder = DatabaseOptionsBuilderFactory .CreateDatabaseOptionsBuilder("Filename=somefile.db"); builder.Should().BeOfType<DbContextOptionsBuilder<GreetingDbContext>>(); builder.IsConfigured.Should().BeTrue(); } [Fact] public void MariaDbConnectionStringShouldReturnConfiguredBuilderTest() { var builder = DatabaseOptionsBuilderFactory .CreateDatabaseOptionsBuilder("Server=someserver;database=helloworld"); builder.Should().BeOfType<DbContextOptionsBuilder<GreetingDbContext>>(); builder.IsConfigured.Should().BeTrue(); } [Fact] public void InvalidConnectionStringShouldThrowTest() { Assert.Throws<NotSupportedException>(() => DatabaseOptionsBuilderFactory .CreateDatabaseOptionsBuilder("invalid connection string")); } } }
using System; using FluentAssertions; using HelloCoreClrApp.Data; using Microsoft.EntityFrameworkCore; using Xunit; namespace HelloCoreClrApp.Test.Data { public class DatabaseOptionsBuilderFactoryTest { [Fact] public void SqliteConnectionstringShouldReturnConfguredBuilderTest() { var builder = DatabaseOptionsBuilderFactory .CreateDatabaseOptionsBuilder("Filename=somefile.db"); builder.Should().BeOfType<DbContextOptionsBuilder<GreetingDbContext>>(); builder.IsConfigured.Should().BeTrue(); } [Fact] public void MariaDbConnectionstringShouldReturnConfguredBuilderTest() { var builder = DatabaseOptionsBuilderFactory .CreateDatabaseOptionsBuilder("Server=someserver;database=helloworld"); builder.Should().BeOfType<DbContextOptionsBuilder<GreetingDbContext>>(); builder.IsConfigured.Should().BeTrue(); } [Fact] public void InvalidConnectionstringShouldThrowTest() { Assert.Throws<NotSupportedException>(() => DatabaseOptionsBuilderFactory .CreateDatabaseOptionsBuilder("invalid connectionstring")); } } }
mit
C#
6d94aaddb7a3cf38422af267c5dc698f71b69c2b
Fix test
henkmollema/Dommel
test/Dommel.IntegrationTests/MultiMapTests.cs
test/Dommel.IntegrationTests/MultiMapTests.cs
using System.Threading.Tasks; using Xunit; namespace Dommel.IntegrationTests { [Collection("Database")] public class MultiMapTests { [Theory] [ClassData(typeof(DatabaseTestData))] public async Task GetAsync(DatabaseDriver database) { using (var con = database.GetConnection()) { var product = await con.GetAsync<Product, Category, Product>(1, (p, c) => { p.Category = c; return p; }); Assert.NotNull(product); Assert.NotEmpty(product.Name); Assert.NotNull(product.Category); Assert.NotNull(product.Category.Name); } } } }
using System.Threading.Tasks; using Xunit; namespace Dommel.IntegrationTests { [Collection("Database")] public class MultiMapTests { [Theory] [ClassData(typeof(DatabaseTestData))] public async Task GetAsync(DatabaseDriver database) { using (var con = database.GetConnection()) { var product = await con.GetAsync<Product, Category, Product>((p, c) => { p.Category = c; return p; }, 1); Assert.NotNull(product); Assert.NotEmpty(product.Name); Assert.NotNull(product.Category); Assert.NotNull(product.Category.Name); } } } }
mit
C#
db7602b5ea3cb9915fc48acfa3b62ed1eb5ff94b
Allow for multiple instances of redis running on the same server but different ports.
LeCantaloop/StackExchange.Redis.Extensions,imperugo/StackExchange.Redis.Extensions,imperugo/StackExchange.Redis.Extensions
src/StackExchange.Redis.Extensions.Core/Configuration/RedisHostCollection.cs
src/StackExchange.Redis.Extensions.Core/Configuration/RedisHostCollection.cs
using System.Configuration; namespace StackExchange.Redis.Extensions.Core.Configuration { /// <summary> /// Configuration Element Collection for <see cref="RedisHost"/> /// </summary> public class RedisHostCollection : ConfigurationElementCollection { /// <summary> /// Gets or sets the <see cref="RedisHost"/> at the specified index. /// </summary> /// <value> /// The <see cref="RedisHost"/>. /// </value> /// <param name="index">The index.</param> /// <returns></returns> public RedisHost this[int index] { get { return BaseGet(index) as RedisHost; } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } /// <summary> /// Creates the new element. /// </summary> /// <returns></returns> protected override ConfigurationElement CreateNewElement() { return new RedisHost(); } /// <summary> /// Gets the element key. /// </summary> /// <param name="element">The element.</param> /// <returns></returns> protected override object GetElementKey(ConfigurationElement element) { return string.Format("{0}:{1}", ((RedisHost)element).Host, ((RedisHost)element).CachePort); } } }
using System.Configuration; namespace StackExchange.Redis.Extensions.Core.Configuration { /// <summary> /// Configuration Element Collection for <see cref="RedisHost"/> /// </summary> public class RedisHostCollection : ConfigurationElementCollection { /// <summary> /// Gets or sets the <see cref="RedisHost"/> at the specified index. /// </summary> /// <value> /// The <see cref="RedisHost"/>. /// </value> /// <param name="index">The index.</param> /// <returns></returns> public RedisHost this[int index] { get { return BaseGet(index) as RedisHost; } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } /// <summary> /// Creates the new element. /// </summary> /// <returns></returns> protected override ConfigurationElement CreateNewElement() { return new RedisHost(); } /// <summary> /// Gets the element key. /// </summary> /// <param name="element">The element.</param> /// <returns></returns> protected override object GetElementKey(ConfigurationElement element) { return ((RedisHost)element).Host; } } }
mit
C#
0b78a326d6a739d7045e3890b74f8d52c5ab9279
Fix up badly spelled test
gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT
LINQToTTree/LINQToTTreeLib.Tests/Expressions/SubExpressionReplacementTest.cs
LINQToTTree/LINQToTTreeLib.Tests/Expressions/SubExpressionReplacementTest.cs
using LINQToTTreeLib.Expressions; using Microsoft.Pex.Framework; using Microsoft.Pex.Framework.Validation; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Diagnostics; using System.Linq.Expressions; namespace LINQToTTreeLib.Tests.ResultOperators { [TestClass] [PexClass(typeof(SubExpressionReplacement))] public partial class SubExpressionReplacementTest { [TestInitialize] public void TestInit() { TestUtils.ResetLINQLibrary(); } [TestCleanup] public void TestDone() { MEFUtilities.MyClassDone(); } [PexMethod, PexAllowedException(typeof(ArgumentNullException))] public Expression TestReplacement(Expression source, Expression pattern, Expression replacement) { return source.ReplaceSubExpression(pattern, replacement); } [TestMethod] public void TestSimpleReplacement() { var arr = Expression.Parameter(typeof(int[]), "myarr"); var param = Expression.Parameter(typeof(int), "dude"); var expr = Expression.ArrayIndex(arr, param); var rep = Expression.Parameter(typeof(int), "fork"); var result = expr.ReplaceSubExpression(param, rep); Debug.WriteLine("Expression: " + result.ToString()); Assert.IsFalse(result.ToString().Contains("dude"), "Contains the dude variable"); } } }
using System; using System.Diagnostics; using System.Linq.Expressions; using LINQToTTreeLib.Expressions; using Microsoft.Pex.Framework; using Microsoft.Pex.Framework.Validation; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LINQToTTreeLib.Tests.ResultOperators { [TestClass] [PexClass(typeof(SubExpressionReplacement))] public partial class SubExpressionReplacementTest { [TestInitialize] public void TestInit() { TestUtils.ResetLINQLibrary(); } [TestCleanup] public void TestDone() { MEFUtilities.MyClassDone(); } [PexMethod, PexAllowedException(typeof(ArgumentNullException))] public Expression TestReplacement(Expression source, Expression pattern, Expression replacement) { return source.ReplaceSubExpression(pattern, replacement); } [TestMethod] public void TestSimpleReplacement() { var arr = Expression.Parameter(typeof(int[]), "myarr"); var param = Expression.Parameter(typeof(int), "dude"); var expr = Expression.ArrayIndex(arr, param); var rep = Expression.Parameter(typeof(int), "fork"); var result = expr.ReplaceSubExpression(param, rep); Debg.WriteLine("Expression: " + result.ToString()); Assert.IsFalse(result.ToString().Contains("dude"), "Contains the dude variable"); } } }
lgpl-2.1
C#
bb96bc94772e0909fb92e00f2fee4fb5c475e051
Fix FixedAddressValueTypeTest test
wtgodbe/corefx,parjong/corefx,ravimeda/corefx,krytarowski/corefx,krk/corefx,ericstj/corefx,ericstj/corefx,jlin177/corefx,DnlHarvey/corefx,weltkante/corefx,rjxby/corefx,richlander/corefx,nchikanov/corefx,dotnet-bot/corefx,Jiayili1/corefx,stone-li/corefx,the-dwyer/corefx,ravimeda/corefx,Petermarcu/corefx,seanshpark/corefx,richlander/corefx,alexperovich/corefx,cydhaselton/corefx,zhenlan/corefx,stephenmichaelf/corefx,DnlHarvey/corefx,parjong/corefx,billwert/corefx,billwert/corefx,rjxby/corefx,krk/corefx,JosephTremoulet/corefx,alexperovich/corefx,nchikanov/corefx,alexperovich/corefx,tijoytom/corefx,mmitche/corefx,dhoehna/corefx,stephenmichaelf/corefx,nchikanov/corefx,krk/corefx,seanshpark/corefx,mmitche/corefx,gkhanna79/corefx,yizhang82/corefx,nchikanov/corefx,mmitche/corefx,Jiayili1/corefx,axelheer/corefx,ravimeda/corefx,weltkante/corefx,ptoonen/corefx,rubo/corefx,mazong1123/corefx,Jiayili1/corefx,marksmeltzer/corefx,nbarbettini/corefx,richlander/corefx,Jiayili1/corefx,alexperovich/corefx,cydhaselton/corefx,dotnet-bot/corefx,tijoytom/corefx,alexperovich/corefx,axelheer/corefx,wtgodbe/corefx,ptoonen/corefx,rahku/corefx,krytarowski/corefx,the-dwyer/corefx,marksmeltzer/corefx,richlander/corefx,shimingsg/corefx,shimingsg/corefx,stone-li/corefx,zhenlan/corefx,stone-li/corefx,Petermarcu/corefx,zhenlan/corefx,axelheer/corefx,krytarowski/corefx,ravimeda/corefx,MaggieTsang/corefx,the-dwyer/corefx,marksmeltzer/corefx,richlander/corefx,nbarbettini/corefx,dotnet-bot/corefx,rahku/corefx,tijoytom/corefx,YoupHulsebos/corefx,the-dwyer/corefx,elijah6/corefx,twsouthwick/corefx,nbarbettini/corefx,rjxby/corefx,Jiayili1/corefx,nbarbettini/corefx,seanshpark/corefx,rjxby/corefx,tijoytom/corefx,ViktorHofer/corefx,weltkante/corefx,Ermiar/corefx,alexperovich/corefx,mazong1123/corefx,marksmeltzer/corefx,jlin177/corefx,twsouthwick/corefx,wtgodbe/corefx,alexperovich/corefx,ericstj/corefx,rahku/corefx,dhoehna/corefx,krytarowski/corefx,axelheer/corefx,Jiayili1/corefx,Petermarcu/corefx,stone-li/corefx,ViktorHofer/corefx,tijoytom/corefx,krk/corefx,ericstj/corefx,JosephTremoulet/corefx,rjxby/corefx,axelheer/corefx,ptoonen/corefx,dotnet-bot/corefx,dotnet-bot/corefx,cydhaselton/corefx,marksmeltzer/corefx,nbarbettini/corefx,elijah6/corefx,krytarowski/corefx,Ermiar/corefx,fgreinacher/corefx,stephenmichaelf/corefx,krk/corefx,yizhang82/corefx,zhenlan/corefx,mazong1123/corefx,mazong1123/corefx,billwert/corefx,BrennanConroy/corefx,YoupHulsebos/corefx,dhoehna/corefx,weltkante/corefx,rahku/corefx,elijah6/corefx,tijoytom/corefx,fgreinacher/corefx,Jiayili1/corefx,DnlHarvey/corefx,rubo/corefx,weltkante/corefx,JosephTremoulet/corefx,ViktorHofer/corefx,the-dwyer/corefx,twsouthwick/corefx,mmitche/corefx,lggomez/corefx,zhenlan/corefx,YoupHulsebos/corefx,cydhaselton/corefx,mmitche/corefx,billwert/corefx,seanshpark/corefx,dhoehna/corefx,krk/corefx,stephenmichaelf/corefx,gkhanna79/corefx,dotnet-bot/corefx,rahku/corefx,ericstj/corefx,lggomez/corefx,yizhang82/corefx,krk/corefx,ViktorHofer/corefx,MaggieTsang/corefx,parjong/corefx,parjong/corefx,MaggieTsang/corefx,Ermiar/corefx,billwert/corefx,wtgodbe/corefx,ericstj/corefx,ptoonen/corefx,MaggieTsang/corefx,mmitche/corefx,Ermiar/corefx,wtgodbe/corefx,parjong/corefx,lggomez/corefx,mazong1123/corefx,billwert/corefx,krytarowski/corefx,weltkante/corefx,gkhanna79/corefx,richlander/corefx,elijah6/corefx,the-dwyer/corefx,lggomez/corefx,stone-li/corefx,stephenmichaelf/corefx,ViktorHofer/corefx,BrennanConroy/corefx,elijah6/corefx,stephenmichaelf/corefx,DnlHarvey/corefx,axelheer/corefx,YoupHulsebos/corefx,jlin177/corefx,Petermarcu/corefx,stone-li/corefx,gkhanna79/corefx,elijah6/corefx,gkhanna79/corefx,seanshpark/corefx,nchikanov/corefx,elijah6/corefx,JosephTremoulet/corefx,nbarbettini/corefx,yizhang82/corefx,zhenlan/corefx,stone-li/corefx,rahku/corefx,richlander/corefx,Ermiar/corefx,mazong1123/corefx,mmitche/corefx,YoupHulsebos/corefx,dotnet-bot/corefx,Ermiar/corefx,DnlHarvey/corefx,gkhanna79/corefx,JosephTremoulet/corefx,rubo/corefx,ericstj/corefx,fgreinacher/corefx,marksmeltzer/corefx,the-dwyer/corefx,JosephTremoulet/corefx,MaggieTsang/corefx,nbarbettini/corefx,shimingsg/corefx,lggomez/corefx,mazong1123/corefx,ViktorHofer/corefx,twsouthwick/corefx,marksmeltzer/corefx,shimingsg/corefx,DnlHarvey/corefx,ravimeda/corefx,parjong/corefx,Petermarcu/corefx,jlin177/corefx,jlin177/corefx,BrennanConroy/corefx,parjong/corefx,DnlHarvey/corefx,MaggieTsang/corefx,lggomez/corefx,tijoytom/corefx,rahku/corefx,nchikanov/corefx,ViktorHofer/corefx,ptoonen/corefx,wtgodbe/corefx,stephenmichaelf/corefx,jlin177/corefx,MaggieTsang/corefx,nchikanov/corefx,rjxby/corefx,twsouthwick/corefx,dhoehna/corefx,dhoehna/corefx,weltkante/corefx,gkhanna79/corefx,rjxby/corefx,seanshpark/corefx,twsouthwick/corefx,rubo/corefx,rubo/corefx,shimingsg/corefx,yizhang82/corefx,zhenlan/corefx,YoupHulsebos/corefx,shimingsg/corefx,yizhang82/corefx,ptoonen/corefx,Ermiar/corefx,twsouthwick/corefx,shimingsg/corefx,cydhaselton/corefx,cydhaselton/corefx,cydhaselton/corefx,Petermarcu/corefx,JosephTremoulet/corefx,ravimeda/corefx,lggomez/corefx,wtgodbe/corefx,YoupHulsebos/corefx,ravimeda/corefx,Petermarcu/corefx,yizhang82/corefx,jlin177/corefx,krytarowski/corefx,seanshpark/corefx,billwert/corefx,ptoonen/corefx,fgreinacher/corefx,dhoehna/corefx
src/System.Runtime/tests/System/Runtime/CompilerServices/RuntimeHelpersTests.netstandard1.7.cs
src/System.Runtime/tests/System/Runtime/CompilerServices/RuntimeHelpersTests.netstandard1.7.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. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Xunit; namespace System.Runtime.CompilerServices.Tests { public struct Age { public int years; public int months; } public class FixedClass { [FixedAddressValueType] public static Age FixedAge; public static unsafe IntPtr AddressOfFixedAge() { fixed (Age* pointer = &FixedAge) { return (IntPtr)pointer; } } } public static partial class RuntimeHelpersTests { [Fact] public static void FixedAddressValueTypeTest() { // Get addresses of static Age fields. IntPtr fixedPtr1 = FixedClass.AddressOfFixedAge(); // Garbage collection. GC.Collect(3, GCCollectionMode.Forced, true, true); GC.WaitForPendingFinalizers(); // Get addresses of static Age fields after garbage collection. IntPtr fixedPtr2 = FixedClass.AddressOfFixedAge(); Assert.Equal(fixedPtr1, fixedPtr2); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; using Xunit; namespace System.Runtime.CompilerServices.Tests { public struct Age { public int years; public int months; } public class FreeClass { public static Age FreeAge; public static unsafe IntPtr AddressOfFreeAge() { fixed (Age* pointer = &FreeAge) { return (IntPtr) pointer; } } } public class FixedClass { [FixedAddressValueType] public static Age FixedAge; public static unsafe IntPtr AddressOfFixedAge() { fixed (Age* pointer = &FixedAge) { return (IntPtr) pointer; } } } public static partial class RuntimeHelpersTests { [Fact] public static void FixedAddressValueTypeTest() { // Get addresses of static Age fields. IntPtr freePtr1 = FreeClass.AddressOfFreeAge(); IntPtr fixedPtr1 = FixedClass.AddressOfFixedAge(); // Garbage collection. GC.Collect(3, GCCollectionMode.Forced, true, true); GC.WaitForPendingFinalizers(); // Get addresses of static Age fields after garbage collection. IntPtr freePtr2 = FreeClass.AddressOfFreeAge(); IntPtr fixedPtr2 = FixedClass.AddressOfFixedAge(); Assert.True(freePtr1 != freePtr2 && fixedPtr1 == fixedPtr2); } } }
mit
C#
9d2a395be0d804e1c2a9f01d044ae130a3448d2a
Fix chatbox crash (#8204)
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Client/Chat/ChatSystem.cs
Content.Client/Chat/ChatSystem.cs
using Content.Client.Chat.Managers; using Content.Client.Chat.UI; using Content.Client.Examine; using Content.Shared.Chat; using Content.Shared.Examine; using Robust.Client.Player; using Robust.Shared.Map; namespace Content.Client.Chat; public sealed class ChatSystem : SharedChatSystem { [Dependency] private readonly IChatManager _manager = default!; [Dependency] private readonly IPlayerManager _player = default!; [Dependency] private readonly ExamineSystem _examineSystem = default!; public override void FrameUpdate(float frameTime) { base.FrameUpdate(frameTime); var player = _player.LocalPlayer?.ControlledEntity; var predicate = static (EntityUid uid, (EntityUid compOwner, EntityUid? attachedEntity) data) => uid == data.compOwner || uid == data.attachedEntity; var bubbles = _manager.GetSpeechBubbles(); var playerPos = player != null ? Transform(player.Value).MapPosition : MapCoordinates.Nullspace; var occluded = player != null && _examineSystem.IsOccluded(player.Value); foreach (var (ent, bubs) in bubbles) { if (Deleted(ent)) { SetBubbles(bubs, false); continue; } if (ent == player) { SetBubbles(bubs, true); continue; } var otherPos = Transform(ent).MapPosition; if (occluded && !ExamineSystemShared.InRangeUnOccluded( playerPos, otherPos, 0f, (ent, player), predicate)) { SetBubbles(bubs, false); continue; } SetBubbles(bubs, true); } } private void SetBubbles(List<SpeechBubble> bubbles, bool value) { foreach (var bubble in bubbles) { bubble.Visible = value; } } }
using Content.Client.Chat.Managers; using Content.Client.Chat.UI; using Content.Client.Examine; using Content.Shared.Chat; using Content.Shared.Examine; using Robust.Client.Player; using Robust.Shared.Map; namespace Content.Client.Chat; public sealed class ChatSystem : SharedChatSystem { [Dependency] private readonly IChatManager _manager = default!; [Dependency] private readonly IPlayerManager _player = default!; [Dependency] private readonly ExamineSystem _examineSystem = default!; public override void FrameUpdate(float frameTime) { base.FrameUpdate(frameTime); var player = _player.LocalPlayer?.ControlledEntity; var predicate = static (EntityUid uid, (EntityUid compOwner, EntityUid? attachedEntity) data) => uid == data.compOwner || uid == data.attachedEntity; var bubbles = _manager.GetSpeechBubbles(); var playerPos = player != null ? Transform(player.Value).MapPosition : MapCoordinates.Nullspace; var occluded = player != null && _examineSystem.IsOccluded(player.Value); foreach (var (ent, bubs) in bubbles) { if (ent == player) { SetBubbles(bubs, true); continue; } var otherPos = Transform(ent).MapPosition; if (occluded && !ExamineSystemShared.InRangeUnOccluded( playerPos, otherPos, 0f, (ent, player), predicate)) { SetBubbles(bubs, false); continue; } SetBubbles(bubs, true); } } private void SetBubbles(List<SpeechBubble> bubbles, bool value) { foreach (var bubble in bubbles) { bubble.Visible = value; } } }
mit
C#
04a42619ac298c02154bbee8037bfc7c648ecaa0
Fix build error
ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP
src/DotNetCore.CAP.Dashboard/LocalRequestsOnlyAuthorizationFilter.cs
src/DotNetCore.CAP.Dashboard/LocalRequestsOnlyAuthorizationFilter.cs
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Threading.Tasks; using DotNetCore.CAP.Internal; namespace DotNetCore.CAP.Dashboard { public class LocalRequestsOnlyAuthorizationFilter : IDashboardAuthorizationFilter { public Task<bool> AuthorizeAsync(DashboardContext context) { var ipAddress = context.Request.RemoteIpAddress; // if unknown, assume not local if (string.IsNullOrEmpty(ipAddress)) { return Task.FromResult(false); } // check if localhost if (ipAddress == "127.0.0.1" || ipAddress == "0.0.0.1") { return Task.FromResult(true); } // compare with local address if (ipAddress == context.Request.LocalIpAddress) { return Task.FromResult(true); } // check if private ip if (Helper.IsInnerIP(ipAddress)) { return Task.FromResult(true); } return Task.FromResult(false); } } }
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using DotNetCore.CAP.Internal; namespace DotNetCore.CAP.Dashboard { public class LocalRequestsOnlyAuthorizationFilter : IDashboardAuthorizationFilter { public bool Authorize(DashboardContext context) { var ipAddress = context.Request.RemoteIpAddress; // if unknown, assume not local if (string.IsNullOrEmpty(ipAddress)) { return false; } // check if localhost if (ipAddress == "127.0.0.1" || ipAddress == "0.0.0.1") { return true; } // compare with local address if (ipAddress == context.Request.LocalIpAddress) { return true; } // check if private ip if (Helper.IsInnerIP(ipAddress)) { return true; } return false; } } }
mit
C#
a9a9d06cba6e1bcd2de9cf2e00935baf53544d7e
fix type-o
FatJohn/UnicornToolkit
DemoApp/DemoApp.DotNet/Program.cs
DemoApp/DemoApp.DotNet/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Unicorn; namespace DemoApp.DotNet { class Program { static void Main(string[] args) { PlatformService.Log = new NullLogService(); var result = Task.Run(async () => { var parameter = new GoogleSearchParameter { Timeout = TimeSpan.FromMilliseconds(300), q = "周杰倫", }; var service = new GoogleSearchService(); return await service.InvokeAsync(parameter); }).Result; Console.WriteLine(result.Content); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Unicorn; namespace DemoApp.DotNet { class Program { static void Main(string[] args) { PlatformService.Log = new NullLogService(); var resutl = Task.Run(async () => { var parameter = new GoogleSearchParameter { Timeout = TimeSpan.FromMilliseconds(300), q = "周杰倫", }; var service = new GoogleSearchService(); var result = await service.InvokeAsync(parameter); return result; }).Result; Console.WriteLine(resutl.Content); Console.ReadLine(); } } }
mit
C#
368261a339f3a8e84079241a2f0798fd93962e0f
Update version number.
Damnae/storybrew
editor/Properties/AssemblyInfo.cs
editor/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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [assembly: AssemblyCopyright("Copyright © Damnae 2016")] [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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.38.*")]
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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [assembly: AssemblyCopyright("Copyright © Damnae 2016")] [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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.37.*")]
mit
C#
00ad220951c0fa949bbe3dc05d90249862fd3330
update session guid added to merchantofferDto
Paymentsense/Dapper.SimpleSave
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Merchant/MerchantOfferDto.cs
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Merchant/MerchantOfferDto.cs
using System.Runtime.Serialization; using PS.Mothership.Core.Common.Template.Gen; using PS.Mothership.Core.Common.Template.Opp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PS.Mothership.Core.Common.Dto.Merchant { [DataContract] public class MerchantOfferDto { [DataMember] public Guid CustomerGuid { get; set; } [DataMember] public Guid OfferGuid { get; set; } [DataMember] public string Reference { get; set; } [DataMember] public string Description { get; set; } //[DataMember] //public GenOpportunityStatus Status { get; set; } //[DataMember] //public string StatusDescription //{ // get // { // return GenOpportunityStatusCollection.GenOpportunityStatusList.Single(x => x.EnumValue == Status.EnumValue).EnumDescription; // } //} [DataMember] public decimal Credit { get; set; } [DataMember] public decimal Debit { get; set; } [DataMember] public int DurationKey { get; set; } [DataMember] public string DurationDescription { get; set; } [DataMember] public DateTimeOffset UpdateDate { get; set; } [DataMember] public string UpdateUsername { get; set; } [DataMember] public Guid UpdateSessionGuid { get; set; } } }
using System.Runtime.Serialization; using PS.Mothership.Core.Common.Template.Gen; using PS.Mothership.Core.Common.Template.Opp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PS.Mothership.Core.Common.Dto.Merchant { [DataContract] public class MerchantOfferDto { [DataMember] public Guid CustomerGuid { get; set; } [DataMember] public Guid OfferGuid { get; set; } [DataMember] public string Reference { get; set; } [DataMember] public string Description { get; set; } //[DataMember] //public GenOpportunityStatus Status { get; set; } //[DataMember] //public string StatusDescription //{ // get // { // return GenOpportunityStatusCollection.GenOpportunityStatusList.Single(x => x.EnumValue == Status.EnumValue).EnumDescription; // } //} [DataMember] public decimal Credit { get; set; } [DataMember] public decimal Debit { get; set; } [DataMember] public int DurationKey { get; set; } [DataMember] public string DurationDescription { get; set; } [DataMember] public DateTimeOffset UpdateDate { get; set; } [DataMember] public string UpdateUsername { get; set; } } }
mit
C#
d91cdb9fbe01763818dcf6344fddf794b88cdb17
Correct test
modulexcite/lokad-cqrs
Framework/Lokad.Cqrs.Portable.Tests/Synthetic/Given_duplicate_configuration.cs
Framework/Lokad.Cqrs.Portable.Tests/Synthetic/Given_duplicate_configuration.cs
using System.Runtime.Serialization; using System.Threading; using Lokad.Cqrs.Build; using Lokad.Cqrs.Build.Engine; using Lokad.Cqrs.Core.Dispatch.Events; using Lokad.Cqrs.Core.Reactive; using Lokad.Cqrs.Feature.HandlerClasses; using NUnit.Framework; namespace Lokad.Cqrs.Synthetic { [TestFixture] public sealed class Given_duplicate_configuration { // ReSharper disable InconsistentNaming [DataContract] public sealed class Message : IMessage { } [Test] public void Dulicate_message_is_detected() { var builder = new CqrsEngineBuilder(); builder.Memory(m => { m.AddMemorySender("in", s => s.IdGenerator(() => "same")); m.AddMemoryRouter("in", c => "memory:null"); }); var observer = new ImmediateEventsObserver(); builder.Advanced.Observers.Add(observer); using (var token = new CancellationTokenSource()) using (var build = builder.Build()) { var sender = build.Resolve<IMessageSender>(); sender.SendOne(new Message()); sender.SendOne(new Message()); observer.Event += @event => { var e = @event as EnvelopeDuplicateDiscarded; if (e != null) { token.Cancel(); } }; build.Start(token.Token); token.Token.WaitHandle.WaitOne(10000); Assert.IsTrue(token.IsCancellationRequested); } } } }
using System.Threading; using Lokad.Cqrs.Build; using Lokad.Cqrs.Build.Engine; using Lokad.Cqrs.Core.Dispatch.Events; using Lokad.Cqrs.Core.Reactive; using NUnit.Framework; namespace Lokad.Cqrs.Synthetic { [TestFixture] public sealed class Given_duplicate_configuration { // ReSharper disable InconsistentNaming public sealed class Message { } [Test] public void Dulicate_message_is_detected() { var builder = new CqrsEngineBuilder(); builder.Memory(m => { m.AddMemorySender("in", s => s.IdGenerator(() => "same")); m.AddMemoryRouter("in", c => "memory:null"); }); var observer = new ImmediateEventsObserver(); builder.Advanced.Observers.Add(observer); using (var token = new CancellationTokenSource()) using (var build = builder.Build()) { var sender = build.Resolve<IMessageSender>(); sender.SendOne(new Message()); sender.SendOne(new Message()); observer.Event += @event => { var e = @event as EnvelopeDuplicateDiscarded; if (e != null) { token.Cancel(); } }; build.Start(token.Token); token.Token.WaitHandle.WaitOne(10000); Assert.IsTrue(token.IsCancellationRequested); } } } }
bsd-3-clause
C#
7852e8c67b4a84391583cf6fde0aa6f0fb799309
update portal self update
Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal
Master/Appleseed/Projects/PortableAreas/SelfUpdater/Properties/AssemblyInfo.cs
Master/Appleseed/Projects/PortableAreas/SelfUpdater/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Web; // 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("SelfUpdater")] [assembly: AssemblyDescription("Appleseed Portal and Content Management System : Portal Self Update")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ANANT Corporation")] [assembly: AssemblyProduct("SelfUpdater")] [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("1bbaa317-aebe-425c-8db3-a1aee724365d")] // 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")] [assembly: PreApplicationStartMethod(typeof(SelfUpdater.Initializer), "Initialize")]
using System.Reflection; using System.Runtime.InteropServices; using System.Web; // 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("SelfUpdater")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ANANT Corporation")] [assembly: AssemblyProduct("SelfUpdater")] [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("1bbaa317-aebe-425c-8db3-a1aee724365d")] // 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")] [assembly: PreApplicationStartMethod(typeof(SelfUpdater.Initializer), "Initialize")]
apache-2.0
C#
99756a301f215e1346a122046473321b5753d94a
Add group to the soldier list, replacing id as the first element
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
BatteryCommander.Web/Views/Soldier/List.cshtml
BatteryCommander.Web/Views/Soldier/List.cshtml
@model IEnumerable<BatteryCommander.Common.Models.Soldier> @{ ViewBag.Title = "List"; } <h2>@ViewBag.Title</h2> @Html.ActionLink("Include Inactive Soldiers", "List", new { activeOnly = false }) @Html.ActionLink("Add a Soldier", "Edit") @Html.ActionLink("Bulk Add/Edit Soldiers", "Bulk") <table class="table table-striped"> <tr> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().Group)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().Rank)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().LastName)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().FirstName)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().MOS)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().IsDutyMOSQualified)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().Status)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().Notes)</th> <th></th> </tr> @foreach (var soldier in Model) { <tr> <td>@Html.DisplayFor(s => soldier.Group)</td> <td>@Html.DisplayFor(s => soldier.Rank)</td> <td>@Html.DisplayFor(s => soldier.LastName)</td> <td>@Html.DisplayFor(s => soldier.FirstName)</td> <td>@Html.DisplayFor(s => soldier.MOS)</td> <td>@Html.DisplayFor(s => soldier.IsDutyMOSQualified)</td> <td>@Html.DisplayFor(s => soldier.Status)</td> <td>@Html.DisplayFor(s => soldier.Notes)</td> <td>@Html.ActionLink("View", "View", new { soldierId = soldier.Id })</td> </tr> } </table>
@model IEnumerable<BatteryCommander.Common.Models.Soldier> @{ ViewBag.Title = "List"; } <h2>@ViewBag.Title</h2> @Html.ActionLink("Include Inactive Soldiers", "List", new { activeOnly = false }) @Html.ActionLink("Add a Soldier", "Edit") @Html.ActionLink("Bulk Add/Edit Soldiers", "Bulk") <table class="table table-striped"> <tr> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().Id)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().Rank)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().LastName)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().FirstName)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().MOS)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().IsDutyMOSQualified)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().Status)</th> <th>@Html.DisplayNameFor(s => s.FirstOrDefault().Notes)</th> <th></th> </tr> @foreach (var soldier in Model) { <tr> <td>@Html.ActionLink("" + soldier.Id, "View", new { soldierId = soldier.Id })</td> <td>@Html.DisplayFor(s => soldier.Rank)</td> <td>@Html.DisplayFor(s => soldier.LastName)</td> <td>@Html.DisplayFor(s => soldier.FirstName)</td> <td>@Html.DisplayFor(s => soldier.MOS)</td> <td>@Html.DisplayFor(s => soldier.IsDutyMOSQualified)</td> <td>@Html.DisplayFor(s => soldier.Status)</td> <td>@Html.DisplayFor(s => soldier.Notes)</td> <td>@Html.ActionLink("View", "View", new { soldierId = soldier.Id })</td> </tr> } </table>
mit
C#
a90f9074540d20f7e937211f621a9d59022d5774
Increase nuget package version to 1.0.0-beta05
Jericho/CakeMail.RestClient
CakeMail.RestClient/Properties/AssemblyInfo.cs
CakeMail.RestClient/Properties/AssemblyInfo.cs
using System.Reflection; // 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("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0-beta05")]
using System.Reflection; // 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("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0-beta04")]
mit
C#
e9e0731ce2d1f2f5dcc0216b65943ca854a92b24
Update ValuesOut.cs
EricZimmerman/RegistryPlugins
RegistryPlugin.Adobe/ValuesOut.cs
RegistryPlugin.Adobe/ValuesOut.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.Adobe { public class ValuesOut:IValueOut { public ValuesOut(string productName, string productVersion, string fullPath, DateTimeOffset lastOpened, string fileName, int fileSize, string fileSource, int pageCount) { ProductName = productName; ProductVersion = productVersion; FullPath = fullPath; LastOpened = lastOpened; FileName = fileName; FileSize = fileSize; FileSource = fileSource; PageCount = pageCount; } public string ProductName { get; } public string ProductVersion { get; } public string FullPath { get; } public DateTimeOffset LastOpened { get; } public string FileName { get; } public int FileSize { get; } public string FileSource { get; } public int PageCount { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"Product: {ProductName} {ProductVersion}"; public string BatchValueData2 => $"FullPath: {FullPath}"; public string BatchValueData3 => $"LastOpened: {LastOpened}"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.Adobe { public class ValuesOut:IValueOut { public ValuesOut(string productName, string productVersion, string fullPath, DateTimeOffset lastOpened, string fileName, int fileSize, string fileSource, int pageCount) { ProductName = productName; ProductVersion = productVersion; FullPath = fullPath; LastOpened = lastOpened; FileName = fileName; FileSize = fileSize; FileSource = fileSource; PageCount = pageCount; } public string ProductName { get; } public string ProductVersion { get; } public string FullPath { get; } public DateTimeOffset LastOpened { get; } public string FileName { get; } public int FileSize { get; } public string FileSource { get; } public int PageCount { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"Product: {ProductName} {ProductVersion}"; public string BatchValueData2 => $"FullPath: {FullPath}"; public string BatchValueData3 => $"LastOpened {LastOpened}"; } }
mit
C#
faf6737218f051bfa35f470e32ef0dc0c407473d
Use shell execute for run action.
simontaylor81/HomeAutomation,simontaylor81/HomeAutomation,simontaylor81/HomeAutomation,simontaylor81/HomeAutomation,simontaylor81/HomeAutomation
MediaCentreServer/Controllers/RunController.cs
MediaCentreServer/Controllers/RunController.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace MediaCentreServer.Controllers { // Controller for running an application. public class RunController : ApiController { // POST /api/run?path=... public HttpResponseMessage Post(string path) { var startInfo = new ProcessStartInfo(path); try { Process.Start(startInfo); return Request.CreateResponse(HttpStatusCode.NoContent); } catch (Exception) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Failed to launch process"); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace MediaCentreServer.Controllers { // Controller for running an application. public class RunController : ApiController { // POST /api/run?path=... public void Post(string path) { var startInfo = new ProcessStartInfo(path); startInfo.UseShellExecute = false; Process.Start(startInfo); } } }
mit
C#
71ba0f9476006ec4877c2e15f2454c2ecf57c2df
Add cookie
RSuter/NSwag,RSuter/NSwag,quails4Eva/NSwag,RSuter/NSwag,quails4Eva/NSwag,quails4Eva/NSwag,RSuter/NSwag,RSuter/NSwag,quails4Eva/NSwag
src/NSwag.Core/OpenApiParameterKind.cs
src/NSwag.Core/OpenApiParameterKind.cs
//----------------------------------------------------------------------- // <copyright file="SwaggerParameterKind.cs" company="NSwag"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license> // <author>Rico Suter, [email protected]</author> //----------------------------------------------------------------------- using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace NSwag { /// <summary>Enumeration of the parameter kinds. </summary> [JsonConverter(typeof(StringEnumConverter))] public enum OpenApiParameterKind { /// <summary>An undefined kind.</summary> [EnumMember(Value = "undefined")] Undefined, /// <summary>A JSON object as POST or PUT body (only one parameter of this type is allowed). </summary> [EnumMember(Value = "body")] Body, /// <summary>A query key-value pair. </summary> [EnumMember(Value = "query")] Query, /// <summary>An URL path placeholder. </summary> [EnumMember(Value = "path")] Path, /// <summary>A HTTP header parameter.</summary> [EnumMember(Value = "header")] Header, /// <summary>A form data parameter.</summary> [EnumMember(Value = "formData")] FormData, /// <summary>A model binding parameter (either form data, path or query; by default query; generated by Swashbuckle).</summary> [EnumMember(Value = "modelbinding")] ModelBinding, /// <summary>A cookie. </summary> [EnumMember(Value = "cookie")] Cookie, } }
//----------------------------------------------------------------------- // <copyright file="SwaggerParameterKind.cs" company="NSwag"> // Copyright (c) Rico Suter. All rights reserved. // </copyright> // <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license> // <author>Rico Suter, [email protected]</author> //----------------------------------------------------------------------- using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace NSwag { /// <summary>Enumeration of the parameter kinds. </summary> [JsonConverter(typeof(StringEnumConverter))] public enum OpenApiParameterKind { /// <summary>An undefined kind.</summary> [EnumMember(Value = "undefined")] Undefined, /// <summary>A JSON object as POST or PUT body (only one parameter of this type is allowed). </summary> [EnumMember(Value = "body")] Body, /// <summary>A query key-value pair. </summary> [EnumMember(Value = "query")] Query, /// <summary>An URL path placeholder. </summary> [EnumMember(Value = "path")] Path, /// <summary>A HTTP header parameter.</summary> [EnumMember(Value = "header")] Header, /// <summary>A form data parameter.</summary> [EnumMember(Value = "formData")] FormData, /// <summary>A model binding parameter (either form data, path or query; by default query; generated by Swashbuckle).</summary> [EnumMember(Value = "modelbinding")] ModelBinding, } }
mit
C#
afd80a8c727256a99e499287a66208909e9d4a36
Update HttpContextAccessor.cs
jtkech/Orchard,sfmskywalker/Orchard,OrchardCMS/Orchard,jchenga/Orchard,jimasp/Orchard,jersiovic/Orchard,LaserSrl/Orchard,Codinlab/Orchard,grapto/Orchard.CloudBust,sfmskywalker/Orchard,aaronamm/Orchard,yersans/Orchard,li0803/Orchard,mvarblow/Orchard,brownjordaninternational/OrchardCMS,johnnyqian/Orchard,brownjordaninternational/OrchardCMS,abhishekluv/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,omidnasri/Orchard,Lombiq/Orchard,TalaveraTechnologySolutions/Orchard,TalaveraTechnologySolutions/Orchard,omidnasri/Orchard,phillipsj/Orchard,tobydodds/folklife,Dolphinsimon/Orchard,sfmskywalker/Orchard,AdvantageCS/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,rtpHarry/Orchard,Fogolan/OrchardForWork,SouleDesigns/SouleDesigns.Orchard,IDeliverable/Orchard,jchenga/Orchard,hannan-azam/Orchard,vairam-svs/Orchard,geertdoornbos/Orchard,JRKelso/Orchard,xkproject/Orchard,vairam-svs/Orchard,ehe888/Orchard,jagraz/Orchard,omidnasri/Orchard,JRKelso/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,tobydodds/folklife,bedegaming-aleksej/Orchard,fassetar/Orchard,li0803/Orchard,li0803/Orchard,SzymonSel/Orchard,neTp9c/Orchard,LaserSrl/Orchard,Codinlab/Orchard,sfmskywalker/Orchard,jagraz/Orchard,Dolphinsimon/Orchard,omidnasri/Orchard,grapto/Orchard.CloudBust,Praggie/Orchard,ehe888/Orchard,yersans/Orchard,SouleDesigns/SouleDesigns.Orchard,armanforghani/Orchard,OrchardCMS/Orchard,TalaveraTechnologySolutions/Orchard,AdvantageCS/Orchard,mvarblow/Orchard,phillipsj/Orchard,jersiovic/Orchard,neTp9c/Orchard,omidnasri/Orchard,phillipsj/Orchard,IDeliverable/Orchard,xkproject/Orchard,armanforghani/Orchard,yersans/Orchard,Serlead/Orchard,grapto/Orchard.CloudBust,jtkech/Orchard,ehe888/Orchard,vairam-svs/Orchard,sfmskywalker/Orchard,rtpHarry/Orchard,jersiovic/Orchard,SouleDesigns/SouleDesigns.Orchard,jchenga/Orchard,tobydodds/folklife,omidnasri/Orchard,ehe888/Orchard,jersiovic/Orchard,xkproject/Orchard,rtpHarry/Orchard,JRKelso/Orchard,rtpHarry/Orchard,omidnasri/Orchard,OrchardCMS/Orchard,grapto/Orchard.CloudBust,Lombiq/Orchard,SzymonSel/Orchard,geertdoornbos/Orchard,Serlead/Orchard,abhishekluv/Orchard,jtkech/Orchard,gcsuk/Orchard,jimasp/Orchard,omidnasri/Orchard,Codinlab/Orchard,bedegaming-aleksej/Orchard,brownjordaninternational/OrchardCMS,johnnyqian/Orchard,SouleDesigns/SouleDesigns.Orchard,bedegaming-aleksej/Orchard,sfmskywalker/Orchard,mvarblow/Orchard,Fogolan/OrchardForWork,hannan-azam/Orchard,abhishekluv/Orchard,geertdoornbos/Orchard,phillipsj/Orchard,tobydodds/folklife,Lombiq/Orchard,TalaveraTechnologySolutions/Orchard,SouleDesigns/SouleDesigns.Orchard,gcsuk/Orchard,jersiovic/Orchard,jagraz/Orchard,brownjordaninternational/OrchardCMS,jagraz/Orchard,neTp9c/Orchard,gcsuk/Orchard,JRKelso/Orchard,vairam-svs/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,hbulzy/Orchard,IDeliverable/Orchard,SzymonSel/Orchard,ehe888/Orchard,AdvantageCS/Orchard,omidnasri/Orchard,geertdoornbos/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,TalaveraTechnologySolutions/Orchard,abhishekluv/Orchard,TalaveraTechnologySolutions/Orchard,Fogolan/OrchardForWork,aaronamm/Orchard,neTp9c/Orchard,mvarblow/Orchard,geertdoornbos/Orchard,armanforghani/Orchard,AdvantageCS/Orchard,Praggie/Orchard,Lombiq/Orchard,JRKelso/Orchard,johnnyqian/Orchard,gcsuk/Orchard,bedegaming-aleksej/Orchard,phillipsj/Orchard,xkproject/Orchard,SzymonSel/Orchard,Serlead/Orchard,Fogolan/OrchardForWork,IDeliverable/Orchard,jagraz/Orchard,jimasp/Orchard,Serlead/Orchard,LaserSrl/Orchard,hbulzy/Orchard,yersans/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,AdvantageCS/Orchard,aaronamm/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,aaronamm/Orchard,LaserSrl/Orchard,LaserSrl/Orchard,aaronamm/Orchard,IDeliverable/Orchard,fassetar/Orchard,fassetar/Orchard,OrchardCMS/Orchard,neTp9c/Orchard,jimasp/Orchard,jimasp/Orchard,Lombiq/Orchard,hannan-azam/Orchard,Dolphinsimon/Orchard,SzymonSel/Orchard,rtpHarry/Orchard,hannan-azam/Orchard,sfmskywalker/Orchard,jchenga/Orchard,grapto/Orchard.CloudBust,Praggie/Orchard,Codinlab/Orchard,Dolphinsimon/Orchard,bedegaming-aleksej/Orchard,Serlead/Orchard,xkproject/Orchard,TalaveraTechnologySolutions/Orchard,abhishekluv/Orchard,TalaveraTechnologySolutions/Orchard,Fogolan/OrchardForWork,jtkech/Orchard,li0803/Orchard,armanforghani/Orchard,johnnyqian/Orchard,brownjordaninternational/OrchardCMS,fassetar/Orchard,vairam-svs/Orchard,hbulzy/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,yersans/Orchard,grapto/Orchard.CloudBust,fassetar/Orchard,johnnyqian/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,Codinlab/Orchard,hbulzy/Orchard,tobydodds/folklife,abhishekluv/Orchard,armanforghani/Orchard,Praggie/Orchard,mvarblow/Orchard,hannan-azam/Orchard,OrchardCMS/Orchard,li0803/Orchard,jtkech/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,gcsuk/Orchard,sfmskywalker/Orchard,tobydodds/folklife,hbulzy/Orchard,jchenga/Orchard,Dolphinsimon/Orchard,Praggie/Orchard
src/Orchard/Mvc/HttpContextAccessor.cs
src/Orchard/Mvc/HttpContextAccessor.cs
using System; using System.Runtime.Remoting.Messaging; using System.Web; namespace Orchard.Mvc { public class HttpContextAccessor : IHttpContextAccessor { private HttpContextBase _httpContext; public HttpContextBase Current() { var httpContext = GetStaticProperty(); return !IsBackgroundHttpContext(httpContext) ? new HttpContextWrapper(httpContext) : _httpContext ?? CallContext.LogicalGetData("HttpContext") as HttpContextBase; } public void Set(HttpContextBase httpContext) { _httpContext = httpContext; } private static bool IsBackgroundHttpContext(HttpContext httpContext) { return httpContext == null || httpContext.Items.Contains(MvcModule.IsBackgroundHttpContextKey); } private static HttpContext GetStaticProperty() { var httpContext = HttpContext.Current; if (httpContext == null) { return null; } try { // The "Request" property throws at application startup on IIS integrated pipeline mode. if (httpContext.Request == null) { return null; } } catch (Exception) { return null; } return httpContext; } } }
using System; using System.Web; namespace Orchard.Mvc { public class HttpContextAccessor : IHttpContextAccessor { private HttpContextBase _httpContext; public HttpContextBase Current() { var httpContext = GetStaticProperty(); return !IsBackgroundHttpContext(httpContext) ? new HttpContextWrapper(httpContext) : _httpContext; } public void Set(HttpContextBase httpContext) { _httpContext = httpContext; } private static bool IsBackgroundHttpContext(HttpContext httpContext) { return httpContext == null || httpContext.Items.Contains(BackgroundHttpContextFactory.IsBackgroundHttpContextKey); } private static HttpContext GetStaticProperty() { var httpContext = HttpContext.Current; if (httpContext == null) { return null; } try { // The "Request" property throws at application startup on IIS integrated pipeline mode. if (httpContext.Request == null) { return null; } } catch (Exception) { return null; } return httpContext; } } }
bsd-3-clause
C#
b087c95581e960f80fa26af370aceb15dadf251e
Use a frozen clock for catcher trails
ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu
osu.Game.Rulesets.Catch/UI/CatcherTrail.cs
osu.Game.Rulesets.Catch/UI/CatcherTrail.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Pooling; using osu.Framework.Timing; using osuTK; namespace osu.Game.Rulesets.Catch.UI { /// <summary> /// A trail of the catcher. /// It also represents a hyper dash afterimage. /// </summary> public class CatcherTrail : PoolableDrawable { public CatcherAnimationState AnimationState { set => body.AnimationState.Value = value; } private readonly SkinnableCatcher body; public CatcherTrail() { Size = new Vector2(CatcherArea.CATCHER_SIZE); Origin = Anchor.TopCentre; Blending = BlendingParameters.Additive; InternalChild = body = new SkinnableCatcher { // Using a frozen clock because trails should not be animated when the skin has an animated catcher. // TODO: The animation should be frozen at the animation frame at the time of the trail generation. Clock = new FramedClock(new ManualClock()), }; } protected override void FreeAfterUse() { ClearTransforms(); base.FreeAfterUse(); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Pooling; using osuTK; namespace osu.Game.Rulesets.Catch.UI { /// <summary> /// A trail of the catcher. /// It also represents a hyper dash afterimage. /// </summary> // TODO: Trails shouldn't be animated when the skin has an animated catcher. // The animation should be frozen at the animation frame at the time of the trail generation. public class CatcherTrail : PoolableDrawable { public CatcherAnimationState AnimationState { set => body.AnimationState.Value = value; } private readonly SkinnableCatcher body; public CatcherTrail() { Size = new Vector2(CatcherArea.CATCHER_SIZE); Origin = Anchor.TopCentre; Blending = BlendingParameters.Additive; InternalChild = body = new SkinnableCatcher(); } protected override void FreeAfterUse() { ClearTransforms(); base.FreeAfterUse(); } } }
mit
C#
f375db368f1ac0208d7dd4dd5497da93ec6ab448
Remove useless null check
peppy/osu,peppy/osu,smoogipoo/osu,peppy/osu,EVAST9919/osu,NeoAdonis/osu,2yangk23/osu,EVAST9919/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu,2yangk23/osu,ppy/osu,johnneijzen/osu,smoogipooo/osu,ppy/osu,peppy/osu-new,UselessToucan/osu,ppy/osu
osu.Game/Users/Drawables/UpdateableFlag.cs
osu.Game/Users/Drawables/UpdateableFlag.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Events; using osu.Game.Overlays; namespace osu.Game.Users.Drawables { public class UpdateableFlag : ModelBackedDrawable<Country> { public Country Country { get => Model; set => Model = value; } /// <summary> /// Whether to show a place holder on null country. /// </summary> public bool ShowPlaceholderOnNull = true; public UpdateableFlag(Country country = null) { Country = country; } protected override Drawable CreateDrawable(Country country) { if (country == null && !ShowPlaceholderOnNull) return null; return new DrawableFlag(country) { RelativeSizeAxes = Axes.Both, }; } [Resolved(canBeNull: true)] private RankingsOverlay rankingsOverlay { get; set; } protected override bool OnClick(ClickEvent e) { rankingsOverlay?.ShowCountry(Country); return true; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Events; using osu.Game.Overlays; namespace osu.Game.Users.Drawables { public class UpdateableFlag : ModelBackedDrawable<Country> { public Country Country { get => Model; set => Model = value; } /// <summary> /// Whether to show a place holder on null country. /// </summary> public bool ShowPlaceholderOnNull = true; public UpdateableFlag(Country country = null) { Country = country; } protected override Drawable CreateDrawable(Country country) { if (country == null && !ShowPlaceholderOnNull) return null; return new DrawableFlag(country) { RelativeSizeAxes = Axes.Both, }; } [Resolved(canBeNull: true)] private RankingsOverlay rankingsOverlay { get; set; } protected override bool OnClick(ClickEvent e) { if (Country != null) rankingsOverlay?.ShowCountry(Country); return true; } } }
mit
C#
744f77c528da3e8e5ef753e96974386c61e23466
fix VersionFilterAttribute
AlejandroCano/framework,avifatal/framework,signumsoftware/framework,avifatal/framework,signumsoftware/framework,AlejandroCano/framework
Signum.React/Filters/VersionFilterAttribute.cs
Signum.React/Filters/VersionFilterAttribute.cs
using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Web; namespace Signum.React.Filters { public class VersionFilterAttribute : ActionFilterAttribute { //In Global.asax: VersionFilterAttribute.CurrentVersion = CustomAssembly.GetName().Version.ToString() public static string CurrentVersion = Assembly.GetEntryAssembly().GetName().Version.ToString(); public override void OnActionExecuted(ActionExecutedContext context) { base.OnActionExecuted(context); if (context.HttpContext.Response != null) context.HttpContext.Response.Headers.Add("X-App-Version", CurrentVersion); } } }
using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Web; namespace Signum.React.Filters { public class VersionFilterAttribute : ActionFilterAttribute { //In Global.asax: VersionFilterAttribute.CurrentVersion = CustomAssembly.GetName().Version.ToString() public static string CurrentVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); public override void OnActionExecuted(ActionExecutedContext context) { base.OnActionExecuted(context); if (context.HttpContext.Response != null) context.HttpContext.Response.Headers.Add("X-App-Version", CurrentVersion); } } }
mit
C#
1028b8acd91c2aa84f2dd57bfd6ab4514db89922
Implement WPF IComboBoxEntryBackend.SetTextColumn
residuum/xwt,directhex/xwt,mono/xwt,lytico/xwt,mminns/xwt,hwthomas/xwt,iainx/xwt,steffenWi/xwt,cra0zy/xwt,sevoku/xwt,hamekoz/xwt,antmicro/xwt,mminns/xwt,akrisiun/xwt,TheBrainTech/xwt
Xwt.WPF/Xwt.WPFBackend/ComboBoxEntryBackend.cs
Xwt.WPF/Xwt.WPFBackend/ComboBoxEntryBackend.cs
// // ComboBoxEntryBackend.cs // // Author: // Eric Maupin <[email protected]> // // Copyright (c) 2012 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Windows.Data; using Xwt.Backends; using WindowsComboBox = System.Windows.Controls.ComboBox; namespace Xwt.WPFBackend { public class ComboBoxEntryBackend : ComboBoxBackend, IComboBoxEntryBackend { public ComboBoxEntryBackend() { ComboBox.IsEditable = true; this.textBackend = new ComboBoxTextEntryBackend (ComboBox); } public ITextEntryBackend TextEntryBackend { get { return this.textBackend; } } public void SetTextColumn (int column) { if (ComboBox.DisplayMemberPath != null) ComboBox.DisplayMemberPath = ".[" + column + "]"; } private readonly ComboBoxTextEntryBackend textBackend; } }
// // ComboBoxEntryBackend.cs // // Author: // Eric Maupin <[email protected]> // // Copyright (c) 2012 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Windows.Data; using Xwt.Backends; using WindowsComboBox = System.Windows.Controls.ComboBox; namespace Xwt.WPFBackend { public class ComboBoxEntryBackend : ComboBoxBackend, IComboBoxEntryBackend { public ComboBoxEntryBackend() { ComboBox.IsEditable = true; this.textBackend = new ComboBoxTextEntryBackend (ComboBox); } public ITextEntryBackend TextEntryBackend { get { return this.textBackend; } } private readonly ComboBoxTextEntryBackend textBackend; } }
mit
C#
366f9120cef48871e96ede0ddf7db4a3b88a4623
Bump build number.
DeathCradle/Terraria-s-Dedicated-Server-Mod,DeathCradle/Terraria-s-Dedicated-Server-Mod,DeathCradle/Terraria-s-Dedicated-Server-Mod,DeathCradle/Terraria-s-Dedicated-Server-Mod
Terraria_Server/Server/Statics.cs
Terraria_Server/Server/Statics.cs
using System; using System.IO; namespace Terraria_Server { public static class Statics { public const int BUILD = 26; public const int CURRENT_TERRARIA_RELEASE = 12; public static string CURRENT_TERRARIA_RELEASE_STR = CURRENT_TERRARIA_RELEASE.ToString(); private const String WORLDS = "Worlds"; private const String PLAYERS = "Players"; private const String PLUGINS = "Plugins"; private const String DATA = "Data"; public static bool cmdMessages = true; public static bool keepRunning = false; public static bool IsActive = false; public static bool serverStarted = false; public static String SavePath = Environment.CurrentDirectory; public static String WorldPath { get { return SavePath + Path.DirectorySeparatorChar + WORLDS; } } public static String PlayerPath { get { return SavePath + Path.DirectorySeparatorChar + PLAYERS; } } public static String PluginPath { get { return SavePath + Path.DirectorySeparatorChar + PLUGINS; } } public static String DataPath { get { return SavePath + Path.DirectorySeparatorChar + DATA; } } } }
using System; using System.IO; namespace Terraria_Server { public static class Statics { public const int BUILD = 24; public const int CURRENT_TERRARIA_RELEASE = 12; public static string CURRENT_TERRARIA_RELEASE_STR = CURRENT_TERRARIA_RELEASE.ToString(); private const String WORLDS = "Worlds"; private const String PLAYERS = "Players"; private const String PLUGINS = "Plugins"; private const String DATA = "Data"; public static bool cmdMessages = true; public static bool keepRunning = false; public static bool IsActive = false; public static bool serverStarted = false; public static String SavePath = Environment.CurrentDirectory; public static String WorldPath { get { return SavePath + Path.DirectorySeparatorChar + WORLDS; } } public static String PlayerPath { get { return SavePath + Path.DirectorySeparatorChar + PLAYERS; } } public static String PluginPath { get { return SavePath + Path.DirectorySeparatorChar + PLUGINS; } } public static String DataPath { get { return SavePath + Path.DirectorySeparatorChar + DATA; } } } }
mit
C#
9288f1430b6237d80316c85986f3f416359a7138
Fix to Expiry Processor constructor to ensure compilation under C# 6
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/SFA.DAS.Commitments.AcademicYearEndProcessor.WebJob/Updater/AcademicYearEndExpiryProcessor.cs
src/SFA.DAS.Commitments.AcademicYearEndProcessor.WebJob/Updater/AcademicYearEndExpiryProcessor.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using SFA.DAS.Commitments.Domain.Data; using SFA.DAS.Commitments.Domain.Entities.DataLock; using SFA.DAS.Commitments.Domain.Interfaces; using SFA.DAS.NLog.Logger; namespace SFA.DAS.Commitments.AcademicYearEndProcessor.WebJob.Updater { public class AcademicYearEndExpiryProcessor : IAcademicYearEndExpiryProcessor { private readonly ILog _logger; private readonly IAcademicYearDateProvider _academicYearProvider; private readonly IDataLockRepository _dataLockRepository; private readonly ICurrentDateTime _currentDateTime; private List<DataLockStatus> _expirableDatalocks = new List<DataLockStatus>(); public AcademicYearEndExpiryProcessor(ILog logger, IAcademicYearDateProvider academicYearProvider, IDataLockRepository dataLockRepository, ICurrentDateTime currentDateTime) { if (logger == null) throw new ArgumentException(nameof(logger)); if (dataLockRepository == null) throw new ArgumentException(nameof(dataLockRepository)); if (currentDateTime == null) throw new ArgumentException(nameof(currentDateTime)); if (academicYearProvider == null) throw new ArgumentException(nameof(academicYearProvider)); _logger = logger; _dataLockRepository = dataLockRepository; _currentDateTime = currentDateTime; _academicYearProvider = academicYearProvider; } public async Task RunUpdate() { _logger.Info($"{nameof(AcademicYearEndExpiryProcessor)} run at {_currentDateTime.Now} for Academic Year CurrentAcademicYearStartDate: {_academicYearProvider.CurrentAcademicYearStartDate}, CurrentAcademicYearEndDate: {_academicYearProvider.CurrentAcademicYearEndDate}, LastAcademicYearFundingPeriod: {_academicYearProvider.LastAcademicYearFundingPeriod}"); _expirableDatalocks = await _dataLockRepository.GetExpirableDataLocks(_academicYearProvider.CurrentAcademicYearStartDate); if (_expirableDatalocks.Any()) { foreach (var expirableDatalock in _expirableDatalocks) { await _dataLockRepository.UpdateExpirableDataLocks(expirableDatalock.ApprenticeshipId, expirableDatalock.PriceEpisodeIdentifier, _currentDateTime.Now); } } _logger.Info($"{nameof(AcademicYearEndExpiryProcessor)} expired {_expirableDatalocks.Count} items"); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using SFA.DAS.Commitments.Domain.Data; using SFA.DAS.Commitments.Domain.Entities.DataLock; using SFA.DAS.Commitments.Domain.Interfaces; using SFA.DAS.NLog.Logger; namespace SFA.DAS.Commitments.AcademicYearEndProcessor.WebJob.Updater { public class AcademicYearEndExpiryProcessor : IAcademicYearEndExpiryProcessor { private readonly ILog _logger; private readonly IAcademicYearDateProvider _academicYearProvider; private readonly IDataLockRepository _dataLockRepository; private readonly ICurrentDateTime _currentDateTime; private List<DataLockStatus> _expirableDatalocks = new List<DataLockStatus>(); [SuppressMessage("ReSharper", "MergeConditionalExpression")] // prevents R# causing C#7 future shock public AcademicYearEndExpiryProcessor(ILog logger, IAcademicYearDateProvider academicYearProvider, IDataLockRepository dataLockRepository, ICurrentDateTime currentDateTime) { _logger = logger != null ? logger : throw new ArgumentException(nameof(logger)); _dataLockRepository = dataLockRepository != null ? dataLockRepository : throw new ArgumentException(nameof(dataLockRepository)); _currentDateTime = currentDateTime != null ? currentDateTime : throw new ArgumentException(nameof(currentDateTime)); _academicYearProvider = academicYearProvider != null ? academicYearProvider : throw new ArgumentException(nameof(academicYearProvider)); } public async Task RunUpdate() { _logger.Info($"{nameof(AcademicYearEndExpiryProcessor)} run at {_currentDateTime.Now} for Academic Year CurrentAcademicYearStartDate: {_academicYearProvider.CurrentAcademicYearStartDate}, CurrentAcademicYearEndDate: {_academicYearProvider.CurrentAcademicYearEndDate}, LastAcademicYearFundingPeriod: {_academicYearProvider.LastAcademicYearFundingPeriod}"); _expirableDatalocks = await _dataLockRepository.GetExpirableDataLocks(_academicYearProvider.CurrentAcademicYearStartDate); if (_expirableDatalocks.Any()) { foreach (var expirableDatalock in _expirableDatalocks) { await _dataLockRepository.UpdateExpirableDataLocks(expirableDatalock.ApprenticeshipId, expirableDatalock.PriceEpisodeIdentifier, _currentDateTime.Now); } } _logger.Info($"{nameof(AcademicYearEndExpiryProcessor)} expired {_expirableDatalocks.Count} items"); } } }
mit
C#
0879f6b8fb54fe33bcfe5f237168377d345b164b
Add new function
ruben69695/Net-UtilityLibrary
UtilityLibraries/StringLibrary.cs
UtilityLibraries/StringLibrary.cs
using System; using System.Collections.Generic; using System.Text; namespace UtilityLibraries { /// <summary> /// Static class that offers universal functions with Strings for .NET Standard Platform (Continuous updating class) /// </summary> public static class StringLibrary { /// <summary> /// Checks and returns true if the string starts with Upper letter /// </summary> /// <param name="str">String to check</param> /// <returns>bool</returns> public static bool StartsWithUpper(this String str) { if (String.IsNullOrWhiteSpace(str)) return false; Char ch = str[0]; return (Char.IsUpper(ch)); } /// <summary> /// Returns a random string from a list /// </summary> /// <param name="lsWords">String list</param> /// <returns>String</returns> public static String randomWord(List<String> lsWords) { if (lsWords == null || lsWords.Count <= 0) return ""; Random R = new Random(); return lsWords[R.Next(0, lsWords.Count - 1)]; } } }
using System; using System.Collections.Generic; using System.Text; namespace UtilityLibraries { /// <summary> /// Static class that offers universal functions with Strings for .NET Standard Platform (Continuous updating class) /// </summary> public static class StringLibrary { /// <summary> /// Checks and returns true if the string starts with Upper letter /// </summary> /// <param name="str">String to check</param> /// <returns>bool</returns> public static bool StartsWithUpper(this String str) { if (String.IsNullOrWhiteSpace(str)) return false; Char ch = str[0]; return (Char.IsUpper(ch)); } } }
mit
C#
cde3d9c08ba8e3b9af8e8e6192c9febdfa306baa
Change precedence order to favour playlist as a source for beatmap count
peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu
osu.Game/Screens/OnlinePlay/Lounge/Components/PlaylistCountPill.cs
osu.Game/Screens/OnlinePlay/Lounge/Components/PlaylistCountPill.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using Humanizer; using osu.Framework.Allocation; using osu.Framework.Extensions.LocalisationExtensions; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Graphics.Containers; namespace osu.Game.Screens.OnlinePlay.Lounge.Components { /// <summary> /// A pill that displays the playlist item count. /// </summary> public class PlaylistCountPill : OnlinePlayComposite { private OsuTextFlowContainer count; public PlaylistCountPill() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { InternalChild = new PillContainer { Child = count = new OsuTextFlowContainer(s => s.Font = OsuFont.GetFont(size: 12)) { AutoSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, } }; } protected override void LoadComplete() { base.LoadComplete(); PlaylistItemStats.BindValueChanged(_ => updateCount(), true); Playlist.BindCollectionChanged((_, __) => updateCount(), true); } private void updateCount() { int activeItems = Playlist.Count > 0 || PlaylistItemStats.Value == null // For now, use the playlist as the source of truth if it has any items. // This allows the count to display correctly on the room screen (after joining a room). ? Playlist.Count(i => !i.Expired) : PlaylistItemStats.Value.CountActive; count.Clear(); count.AddText(activeItems.ToLocalisableString(), s => s.Font = s.Font.With(weight: FontWeight.Bold)); count.AddText(" "); count.AddText("Beatmap".ToQuantity(activeItems, ShowQuantityAs.None)); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using Humanizer; using osu.Framework.Allocation; using osu.Framework.Extensions.LocalisationExtensions; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Graphics.Containers; namespace osu.Game.Screens.OnlinePlay.Lounge.Components { /// <summary> /// A pill that displays the playlist item count. /// </summary> public class PlaylistCountPill : OnlinePlayComposite { private OsuTextFlowContainer count; public PlaylistCountPill() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { InternalChild = new PillContainer { Child = count = new OsuTextFlowContainer(s => s.Font = OsuFont.GetFont(size: 12)) { AutoSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, } }; } protected override void LoadComplete() { base.LoadComplete(); PlaylistItemStats.BindValueChanged(_ => updateCount(), true); Playlist.BindCollectionChanged((_, __) => updateCount(), true); } private void updateCount() { int activeItems = PlaylistItemStats.Value?.CountActive ?? Playlist.Count; count.Clear(); count.AddText(activeItems.ToLocalisableString(), s => s.Font = s.Font.With(weight: FontWeight.Bold)); count.AddText(" "); count.AddText("Beatmap".ToQuantity(activeItems, ShowQuantityAs.None)); } } }
mit
C#
7d232563070eab4648a5a7d39f0cee00643d5072
Enable NRT
weltkante/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,diryboy/roslyn,diryboy/roslyn,mavasani/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,dotnet/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,sharwell/roslyn,mavasani/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn
src/Analyzers/Core/CodeFixes/UseInferredMemberName/AbstractUseInferredMemberNameCodeFixProvider.cs
src/Analyzers/Core/CodeFixes/UseInferredMemberName/AbstractUseInferredMemberNameCodeFixProvider.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. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseInferredMemberName { internal abstract class AbstractUseInferredMemberNameCodeFixProvider : SyntaxEditorBasedCodeFixProvider { protected abstract void LanguageSpecificRemoveSuggestedNode(SyntaxEditor editor, SyntaxNode node); public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseInferredMemberNameDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var node = root.FindNode(diagnostic.Location.SourceSpan); LanguageSpecificRemoveSuggestedNode(editor, node); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_inferred_member_name, createChangedDocument, AnalyzersResources.Use_inferred_member_name) { } } } }
// 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 disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseInferredMemberName { internal abstract class AbstractUseInferredMemberNameCodeFixProvider : SyntaxEditorBasedCodeFixProvider { protected abstract void LanguageSpecificRemoveSuggestedNode(SyntaxEditor editor, SyntaxNode node); public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseInferredMemberNameDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var node = root.FindNode(diagnostic.Location.SourceSpan); LanguageSpecificRemoveSuggestedNode(editor, node); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_inferred_member_name, createChangedDocument, AnalyzersResources.Use_inferred_member_name) { } } } }
mit
C#
70f305562164245be4cd89cb5fc9706c5a9696d7
Support null source value
Stonefinch/AzureIntro,Stonefinch/AzureIntro
src/AzureIntro.WebJobs.QueueTrigger/TraceWriters/SqlTraceWriter.cs
src/AzureIntro.WebJobs.QueueTrigger/TraceWriters/SqlTraceWriter.cs
using Microsoft.Azure.WebJobs.Host; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; namespace AzureIntro.WebJobs.QueueTrigger.TraceWriters { public class SqlTraceWriter : TraceWriter { private string SqlConnectionString { get; set; } private string LogTableName { get; set; } public SqlTraceWriter(TraceLevel level, string sqlConnectionString, string logTableName) : base(level) { this.SqlConnectionString = sqlConnectionString; this.LogTableName = logTableName; } public override void Trace(TraceEvent traceEvent) { using (var sqlConnection = this.CreateConnection()) { sqlConnection.Open(); using (var cmd = new SqlCommand(string.Format("insert into {0} ([Source], [Timestamp], [Level], [Message], [Exception], [Properties]) values (@Source, @Timestamp, @Level, @Message, @Exception, @Properties)", this.LogTableName), sqlConnection)) { cmd.Parameters.AddWithValue("Source", traceEvent.Source ?? ""); cmd.Parameters.AddWithValue("Timestamp", traceEvent.Timestamp); cmd.Parameters.AddWithValue("Level", traceEvent.Level.ToString()); cmd.Parameters.AddWithValue("Message", traceEvent.Message ?? ""); cmd.Parameters.AddWithValue("Exception", traceEvent.Exception?.ToString() ?? ""); cmd.Parameters.AddWithValue("Properties", string.Join("; ", traceEvent.Properties.Select(x => x.Key + ", " + x.Value?.ToString()).ToList()) ?? ""); cmd.ExecuteNonQuery(); } } } private SqlConnection CreateConnection() { return new SqlConnection(this.SqlConnectionString); } } }
using Microsoft.Azure.WebJobs.Host; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; namespace AzureIntro.WebJobs.QueueTrigger.TraceWriters { public class SqlTraceWriter : TraceWriter { private string SqlConnectionString { get; set; } private string LogTableName { get; set; } public SqlTraceWriter(TraceLevel level, string sqlConnectionString, string logTableName) : base(level) { this.SqlConnectionString = sqlConnectionString; this.LogTableName = logTableName; } public override void Trace(TraceEvent traceEvent) { using (var sqlConnection = this.CreateConnection()) { sqlConnection.Open(); using (var cmd = new SqlCommand(string.Format("insert into {0} ([Source], [Timestamp], [Level], [Message], [Exception], [Properties]) values (@Source, @Timestamp, @Level, @Message, @Exception, @Properties)", this.LogTableName), sqlConnection)) { cmd.Parameters.AddWithValue("Source", traceEvent.Source); cmd.Parameters.AddWithValue("Timestamp", traceEvent.Timestamp); cmd.Parameters.AddWithValue("Level", traceEvent.Level.ToString()); cmd.Parameters.AddWithValue("Message", traceEvent.Message ?? ""); cmd.Parameters.AddWithValue("Exception", traceEvent.Exception?.ToString() ?? ""); cmd.Parameters.AddWithValue("Properties", string.Join("; ", traceEvent.Properties.Select(x => x.Key + ", " + x.Value?.ToString()).ToList()) ?? ""); cmd.ExecuteNonQuery(); } } } private SqlConnection CreateConnection() { return new SqlConnection(this.SqlConnectionString); } } }
apache-2.0
C#
4a4830c717373ac7742fe3d64741a4cd674a8906
Update cake dependencies
ppy/osu,johnneijzen/osu,2yangk23/osu,smoogipoo/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,EVAST9919/osu,ZLima12/osu,peppy/osu,ppy/osu,ZLima12/osu,EVAST9919/osu,2yangk23/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,peppy/osu,johnneijzen/osu,UselessToucan/osu
build/build.cake
build/build.cake
#addin "nuget:?package=CodeFileSanity&version=0.0.33" #addin "nuget:?package=JetBrains.ReSharper.CommandLineTools&version=2019.2.1" #tool "nuget:?package=NVika.MSBuild&version=1.0.1" var nVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First(); /////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Build"); var configuration = Argument("configuration", "Release"); var rootDirectory = new DirectoryPath(".."); var solution = rootDirectory.CombineWithFilePath("osu.sln"); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Compile") .Does(() => { DotNetCoreBuild(solution.FullPath, new DotNetCoreBuildSettings { Configuration = configuration, }); }); Task("Test") .IsDependentOn("Compile") .Does(() => { var testAssemblies = GetFiles(rootDirectory + "/**/*.Tests/bin/**/*.Tests.dll"); DotNetCoreVSTest(testAssemblies, new DotNetCoreVSTestSettings { Logger = AppVeyor.IsRunningOnAppVeyor ? "Appveyor" : $"trx", Parallel = true, ToolTimeout = TimeSpan.FromMinutes(10), }); }); // windows only because both inspectcore and nvika depend on net45 Task("InspectCode") .WithCriteria(IsRunningOnWindows()) .IsDependentOn("Compile") .Does(() => { InspectCode(solution, new InspectCodeSettings { CachesHome = "inspectcode", OutputFile = "inspectcodereport.xml", }); int returnCode = StartProcess(nVikaToolPath, $@"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors"); if (returnCode != 0) throw new Exception($"inspectcode failed with return code {returnCode}"); }); Task("CodeFileSanity") .Does(() => { ValidateCodeSanity(new ValidateCodeSanitySettings { RootDirectory = rootDirectory.FullPath, IsAppveyorBuild = AppVeyor.IsRunningOnAppVeyor }); }); Task("Build") .IsDependentOn("CodeFileSanity") .IsDependentOn("InspectCode") .IsDependentOn("Test"); RunTarget(target);
#addin "nuget:?package=CodeFileSanity&version=0.0.21" #addin "nuget:?package=JetBrains.ReSharper.CommandLineTools&version=2019.1.1" #tool "nuget:?package=NVika.MSBuild&version=1.0.1" var nVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First(); /////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Build"); var configuration = Argument("configuration", "Release"); var rootDirectory = new DirectoryPath(".."); var solution = rootDirectory.CombineWithFilePath("osu.sln"); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Compile") .Does(() => { DotNetCoreBuild(solution.FullPath, new DotNetCoreBuildSettings { Configuration = configuration, }); }); Task("Test") .IsDependentOn("Compile") .Does(() => { var testAssemblies = GetFiles(rootDirectory + "/**/*.Tests/bin/**/*.Tests.dll"); DotNetCoreVSTest(testAssemblies, new DotNetCoreVSTestSettings { Logger = AppVeyor.IsRunningOnAppVeyor ? "Appveyor" : $"trx", Parallel = true, ToolTimeout = TimeSpan.FromMinutes(10), }); }); // windows only because both inspectcore and nvika depend on net45 Task("InspectCode") .WithCriteria(IsRunningOnWindows()) .IsDependentOn("Compile") .Does(() => { InspectCode(solution, new InspectCodeSettings { CachesHome = "inspectcode", OutputFile = "inspectcodereport.xml", }); int returnCode = StartProcess(nVikaToolPath, $@"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors"); if (returnCode != 0) throw new Exception($"inspectcode failed with return code {returnCode}"); }); Task("CodeFileSanity") .Does(() => { ValidateCodeSanity(new ValidateCodeSanitySettings { RootDirectory = rootDirectory.FullPath, IsAppveyorBuild = AppVeyor.IsRunningOnAppVeyor }); }); Task("Build") .IsDependentOn("CodeFileSanity") .IsDependentOn("InspectCode") .IsDependentOn("Test"); RunTarget(target);
mit
C#
38c0d5dd958d189bbeef105791975fdcf85db176
Test Fixes
jjb3rd/Freshdesk.Net
Freshdesk.Tests/UserTests.cs
Freshdesk.Tests/UserTests.cs
/* * Copyright 2015 Beckersoft, Inc. * * Author(s): * John Becker ([email protected]) * * 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 NUnit.Framework; namespace Freshdesk.Tests { [TestFixture] public class UserTests { Freshdesk.FreshdeskService freshdeskService = new Freshdesk.FreshdeskService(Settings.FreshdeskApiKey, Settings.FreshdeskUri); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Freshdesk"), Test] public void FreshdeskCreateContact() { Freshdesk.GetUserResponse userResponse = freshdeskService.CreateUser(new Freshdesk.CreateUserRequest() { User = new Freshdesk.User() { Name = "Road Runner", Email = "[email protected]" } }); Assert.IsNotNull(userResponse); Assert.IsNotNull(userResponse.User); } } }
/* * Copyright 2015 Beckersoft, Inc. * * Author(s): * John Becker ([email protected]) * * 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 NUnit.Framework; namespace Freshdesk.Tests { [TestFixture] public class UserTests { Freshdesk.FreshdeskService freshdeskService = new Freshdesk.FreshdeskService(Settings.FreshdeskApiKey, Settings.FreshdeskUri); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Freshdesk"), Test] public void FreshdeskCreateContact() { Freshdesk.GetUserResponse userResponse = freshdeskService.CreateUser(new Freshdesk.CreateUserRequest() { User = new Freshdesk.User() { Name = "Wil E. Coyote", Email = "[email protected]" } }); Assert.IsNotNull(userResponse); Assert.IsNotNull(userResponse.User); } } }
apache-2.0
C#
b52337c64e9f4f6b542da7429bc2042ef5eeae5e
Remove check for bearer on generic ApiController definition
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Controllers/API/ApiController.cs
Battery-Commander.Web/Controllers/API/ApiController.cs
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace BatteryCommander.Web.Controllers.API { [Route("api/[controller]"), Authorize(AuthenticationSchemes = "Auth0,Cookies")] public class ApiController : Controller { protected readonly Database db; public ApiController(Database db) { this.db = db; } } }
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace BatteryCommander.Web.Controllers.API { [Route("api/[controller]"), Authorize(AuthenticationSchemes = "Auth0,Bearer,Cookies")] public class ApiController : Controller { protected readonly Database db; public ApiController(Database db) { this.db = db; } } }
mit
C#
0fc9f5a513214aebbbee0983c0e9f49fea4309e0
Fix PrintViewApi
InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform
InfinniPlatform.FlowDocument/PrintView/PrintViewApi.cs
InfinniPlatform.FlowDocument/PrintView/PrintViewApi.cs
using System; using System.IO; using InfinniPlatform.Core.Metadata; using InfinniPlatform.Core.PrintView; using InfinniPlatform.Sdk.Dynamic; using InfinniPlatform.Sdk.PrintView; using InfinniPlatform.Sdk.Serialization; namespace InfinniPlatform.FlowDocument.PrintView { /// <summary> /// Предоставляет методы для работы с печатными представлениями. /// </summary> internal sealed class PrintViewApi : IPrintViewApi { public PrintViewApi(IMetadataApi metadataApi, IPrintViewBuilder printViewBuilder) { _metadataApi = metadataApi; _printViewBuilder = printViewBuilder; } private readonly IMetadataApi _metadataApi; private readonly IPrintViewBuilder _printViewBuilder; public byte[] Build(string documentType, string printViewName, object printViewSource, PrintViewFileFormat priiViewFormat = PrintViewFileFormat.Pdf) { if (string.IsNullOrEmpty(documentType)) { throw new ArgumentNullException(nameof(documentType)); } if (string.IsNullOrEmpty(printViewName)) { throw new ArgumentNullException(nameof(printViewName)); } //Build view name //TODO Move to static files? var bytes = File.ReadAllBytes($"content\\metadata\\PrintViews\\{documentType}\\{printViewName}.json"); var printViewMetadata = JsonObjectSerializer.Default.Deserialize<DynamicWrapper>(bytes); if (printViewMetadata == null) { throw new ArgumentException($"Print view '{documentType}/{printViewName}' not found."); } var printViewData = _printViewBuilder.BuildFile(printViewMetadata, printViewSource, priiViewFormat); return printViewData; } } }
using System; using InfinniPlatform.Core.Metadata; using InfinniPlatform.Core.PrintView; using InfinniPlatform.Sdk.PrintView; namespace InfinniPlatform.FlowDocument.PrintView { /// <summary> /// Предоставляет методы для работы с печатными представлениями. /// </summary> internal sealed class PrintViewApi : IPrintViewApi { public PrintViewApi(IMetadataApi metadataApi, IPrintViewBuilder printViewBuilder) { _metadataApi = metadataApi; _printViewBuilder = printViewBuilder; } private readonly IMetadataApi _metadataApi; private readonly IPrintViewBuilder _printViewBuilder; public byte[] Build(string documentType, string printViewName, object printViewSource, PrintViewFileFormat priiViewFormat = PrintViewFileFormat.Pdf) { if (string.IsNullOrEmpty(documentType)) { throw new ArgumentNullException(nameof(documentType)); } if (string.IsNullOrEmpty(printViewName)) { throw new ArgumentNullException(nameof(printViewName)); } //Build view name var printViewMetadata = _metadataApi.GetMetadata($"PrintViews.{documentType}.{printViewName}"); if (printViewMetadata == null) { throw new ArgumentException($"Print view '{documentType}/{printViewName}' not found."); } var printViewData = _printViewBuilder.BuildFile(printViewMetadata, printViewSource, priiViewFormat); return printViewData; } } }
agpl-3.0
C#
cd00e0e215f650aa232d07465bee39e98da4fd01
Refactor Keys.
JohanLarsson/Gu.Wpf.Validation
Gu.Wpf.Validation/PropertyGrid/Keys.cs
Gu.Wpf.Validation/PropertyGrid/Keys.cs
namespace Gu.Wpf.Validation { using System.Runtime.CompilerServices; using System.Windows; public static class Keys { public static ResourceKey SettingsListStyleKey { get; } = CreateKey(); public static ResourceKey NestedListStyleKey { get; } = CreateKey(); public static ResourceKey HeaderStyleKey { get; } = CreateKey(); public static ResourceKey SettingStyleKey { get; } = CreateKey(); public static ResourceKey PlainTemplateKey { get; } = CreateKey(); public static ResourceKey SymbolTemplateKey { get; } = CreateKey(); public static object HelpTextAndSymbolTemplateKey { get; } = CreateKey(); public static object SymbolPathStyleKey { get; } = CreateKey(); public static object HelpErrorTextAndSymbolTemplateKey { get; } = CreateKey(); public static object HelpTemplateKey { get; } = CreateKey(); public static ResourceKey SettingStyleSelectorKey { get; } = CreateKey(); public static ResourceKey ErrorSymbolTemplateSelectorKey { get; } = CreateKey(); public static ResourceKey CheckmarkGeometryKey { get; } = CreateKey(); public static ResourceKey ErrorGeometryKey { get; } = CreateKey(); public static ResourceKey RequiredGeometryKey { get; } = CreateKey(); public static ResourceKey QuestionGeometryKey { get; } = CreateKey(); public static object ErrorTextAndSymbolTemplateKey { get; } = CreateKey(); public static object ErrorTemplateSelectorKey { get; } = CreateKey(); public static object ErrorTemplateKey { get; } = CreateKey(); private static ComponentResourceKey CreateKey([CallerMemberName] string caller = null) { return new ComponentResourceKey(typeof(Keys), caller); ; } } }
namespace Gu.Wpf.Validation { using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Windows; public static class Keys { private static readonly Dictionary<string, ComponentResourceKey> Cache = new Dictionary<string, ComponentResourceKey>(); public static ResourceKey SettingsListStyleKey { get { return Get(); } } public static ResourceKey NestedListStyleKey { get { return Get(); } } public static ResourceKey HeaderStyleKey { get { return Get(); } } public static ResourceKey SettingStyleKey { get { return Get(); } } public static ResourceKey PlainTemplateKey { get { return Get(); } } public static ResourceKey SymbolTemplateKey { get { return Get(); } } public static object HelpTextAndSymbolTemplateKey { get { return Get(); } } public static object SymbolPathStyleKey { get { return Get(); } } public static object HelpErrorTextAndSymbolTemplateKey { get { return Get(); } } public static object HelpTemplateKey { get { return Get(); } } public static ResourceKey SettingStyleSelectorKey { get { return Get(); } } public static ResourceKey ErrorSymbolTemplateSelectorKey { get { return Get(); } } public static ResourceKey CheckmarkGeometryKey { get { return Get(); } } public static ResourceKey ErrorGeometryKey { get { return Get(); } } public static ResourceKey RequiredGeometryKey { get { return Get(); } } public static ResourceKey QuestionGeometryKey { get { return Get(); } } public static object ErrorTextAndSymbolTemplateKey { get { return Get(); } } public static object ErrorTemplateSelectorKey { get { return Get(); } } public static object ErrorTemplateKey { get { return Get(); } } private static ComponentResourceKey Get([CallerMemberName] string caller = null) { ComponentResourceKey key; if (!Cache.TryGetValue(caller, out key)) { key = new ComponentResourceKey(typeof(Keys), caller); Cache.Add(caller, key); } return key; } } }
mit
C#
f9bfaf0ea091a1011310a80232a3ede90e3d9dda
Fix status label updating (update method not called if control is not visible)
ethanmoffat/EndlessClient
EndlessClient/UIControls/StatusBarLabel.cs
EndlessClient/UIControls/StatusBarLabel.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using EndlessClient.HUD; using EndlessClient.Rendering; using EOLib; using Microsoft.Xna.Framework; using XNAControls; namespace EndlessClient.UIControls { public class StatusBarLabel : XNALabel { private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000; private readonly IStatusLabelTextProvider _statusLabelTextProvider; public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider, IStatusLabelTextProvider statusLabelTextProvider) : base(Constants.FontSize07) { _statusLabelTextProvider = statusLabelTextProvider; DrawArea = new Rectangle(97, clientWindowSizeProvider.Height - 24, 1, 1); } protected override bool ShouldUpdate() { if (Text != _statusLabelTextProvider.StatusText) { Text = _statusLabelTextProvider.StatusText; Visible = true; } if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS) Visible = false; return base.ShouldUpdate(); } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using EndlessClient.HUD; using EndlessClient.Rendering; using EOLib; using Microsoft.Xna.Framework; using XNAControls; namespace EndlessClient.UIControls { public class StatusBarLabel : XNALabel { private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000; private readonly IStatusLabelTextProvider _statusLabelTextProvider; public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider, IStatusLabelTextProvider statusLabelTextProvider) : base(Constants.FontSize07) { _statusLabelTextProvider = statusLabelTextProvider; DrawArea = new Rectangle(97, clientWindowSizeProvider.Height - 24, 1, 1); } protected override void OnUpdateControl(GameTime gameTime) { if (Text != _statusLabelTextProvider.StatusText) { Text = _statusLabelTextProvider.StatusText; Visible = true; } if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS) Visible = false; base.OnUpdateControl(gameTime); } } }
mit
C#
258898a078ba03279c2326639666b7acf63b0825
Add fields for PPU registers.
DanTup/DaNES
DaNES.Emulation/Ppu.cs
DaNES.Emulation/Ppu.cs
using System.Drawing; namespace DanTup.DaNES.Emulation { class Ppu { public Memory Ram { get; } public Bitmap Screen { get; } // PPU Control bool NmiEnable; bool PpuMasterSlave; bool SpriteHeight; bool BackgroundTileSelect; bool SpriteTileSelect; bool IncrementMode; bool NameTableSelect1; bool NameTableSelect0; // PPU Mask bool TintBlue; bool TintGreen; bool TintRed; bool ShowSprites; bool ShowBackground; bool ShowLeftSprites; bool ShowLeftBackground; bool Greyscale; // PPU Status bool VBlank; bool Sprite0Hit; bool SpriteOverflow; byte OamAddress { get; } byte OamData { get; } byte PpuScroll { get; } byte PpuAddr { get; } byte PpuData { get; } byte OamDma { get; } public Ppu(Memory ram, Bitmap screen) { Ram = ram; Screen = screen; for (var x = 0; x < 256; x++) { for (var y = 0; y < 240; y++) { Screen.SetPixel(x, y, Color.FromArgb(x, y, 128)); } } } public void Step() { } } }
using System.Drawing; namespace DanTup.DaNES.Emulation { class Ppu { public Memory Ram { get; } public Bitmap Screen { get; } public Ppu(Memory ram, Bitmap screen) { Ram = ram; Screen = screen; for (var x = 0; x < 256; x++) { for (var y = 0; y < 240; y++) { Screen.SetPixel(x, y, Color.FromArgb(x, y, 128)); } } } public void Step() { } } }
mit
C#
4795170c6044bc7092b4c78b687f5a5bdc880088
Add back the default json converter locally to ensure it's actually used
peppy/osu,smoogipooo/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,ppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu
osu.Game/IO/Serialization/IJsonSerializable.cs
osu.Game/IO/Serialization/IJsonSerializable.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using Newtonsoft.Json; using osu.Framework.IO.Serialization; namespace osu.Game.IO.Serialization { public interface IJsonSerializable { } public static class JsonSerializableExtensions { public static string Serialize(this IJsonSerializable obj) => JsonConvert.SerializeObject(obj, CreateGlobalSettings()); public static T Deserialize<T>(this string objString) => JsonConvert.DeserializeObject<T>(objString, CreateGlobalSettings()); public static void DeserializeInto<T>(this string objString, T target) => JsonConvert.PopulateObject(objString, target, CreateGlobalSettings()); /// <summary> /// Creates the default <see cref="JsonSerializerSettings"/> that should be used for all <see cref="IJsonSerializable"/>s. /// </summary> /// <returns></returns> public static JsonSerializerSettings CreateGlobalSettings() => new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented, ObjectCreationHandling = ObjectCreationHandling.Replace, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Converters = new List<JsonConverter> { new Vector2Converter() }, ContractResolver = new KeyContractResolver() }; } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using Newtonsoft.Json; namespace osu.Game.IO.Serialization { public interface IJsonSerializable { } public static class JsonSerializableExtensions { public static string Serialize(this IJsonSerializable obj) => JsonConvert.SerializeObject(obj, CreateGlobalSettings()); public static T Deserialize<T>(this string objString) => JsonConvert.DeserializeObject<T>(objString, CreateGlobalSettings()); public static void DeserializeInto<T>(this string objString, T target) => JsonConvert.PopulateObject(objString, target, CreateGlobalSettings()); /// <summary> /// Creates the default <see cref="JsonSerializerSettings"/> that should be used for all <see cref="IJsonSerializable"/>s. /// </summary> /// <returns></returns> public static JsonSerializerSettings CreateGlobalSettings() => new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented, ObjectCreationHandling = ObjectCreationHandling.Replace, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, ContractResolver = new KeyContractResolver() }; } }
mit
C#
16e7b7bc4cb50308710542d5134829c5f5800fa2
Add testing for impersonation
Seddryck/Idunn.SqlServer
IdunnSql.Testing.Acceptance/ProgramTest.cs
IdunnSql.Testing.Acceptance/ProgramTest.cs
using IdunnSql.Console; using IdunnSql.Core.Model; using IdunnSql.Core.Template.StringTemplate; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace IdunnSql.Testing.Acceptance { [TestFixture] public class ProgramTest { [Test] public void Main_Generate_Succesful() { var source = ResourceOnDisk.CreatePhysicalFile("Sample.xml", "IdunnSql.Testing.Acceptance.Resources.Sample.xml"); var destination = Path.ChangeExtension(source, ".sql"); var args = new List<string>(); args.Add("generate"); args.Add($"--source={source}"); args.Add($"--destination={destination}"); var result = Program.Main(args.ToArray()); Assert.That(result, Is.EqualTo(0)); } [Test] public void Main_GenerateWithImpersonate_Succesful() { var source = ResourceOnDisk.CreatePhysicalFile("Sample.xml", "IdunnSql.Testing.Acceptance.Resources.Sample.xml"); var destination = Path.ChangeExtension(source, ".impersonate.sql"); var args = new List<string>(); args.Add("generate"); args.Add($"--source={source}"); args.Add($"--destination={destination}"); args.Add($"--principal=Proxy_ETL"); var result = Program.Main(args.ToArray()); Assert.That(result, Is.EqualTo(0)); } } }
using IdunnSql.Console; using IdunnSql.Core.Model; using IdunnSql.Core.Template.StringTemplate; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace IdunnSql.Testing.Acceptance { [TestFixture] public class ProgramTest { [Test] public void Main_Generate_Succesful() { var source = ResourceOnDisk.CreatePhysicalFile("Sample.xml", "IdunnSql.Testing.Acceptance.Resources.Sample.xml"); var destination = Path.ChangeExtension(source, ".sql"); var args = new List<string>(); args.Add("generate"); args.Add($"--source={source}"); args.Add($"--destination={destination}"); var result = Program.Main(args.ToArray()); Assert.That(result, Is.EqualTo(0)); } } }
apache-2.0
C#
91851decf160d1001a5cf4c3e6c9eaca3678eab5
Change RSA_OAEP to RSA-OAEP
AzCiS/azure-sdk-for-net,marcoippel/azure-sdk-for-net,samtoubia/azure-sdk-for-net,enavro/azure-sdk-for-net,vladca/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,juvchan/azure-sdk-for-net,smithab/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,kagamsft/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,oaastest/azure-sdk-for-net,amarzavery/azure-sdk-for-net,AuxMon/azure-sdk-for-net,kagamsft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,namratab/azure-sdk-for-net,nemanja88/azure-sdk-for-net,vladca/azure-sdk-for-net,juvchan/azure-sdk-for-net,gubookgu/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,rohmano/azure-sdk-for-net,pattipaka/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,marcoippel/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,shipram/azure-sdk-for-net,dominiqa/azure-sdk-for-net,xindzhan/azure-sdk-for-net,namratab/azure-sdk-for-net,olydis/azure-sdk-for-net,herveyw/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,hyonholee/azure-sdk-for-net,pomortaz/azure-sdk-for-net,nathannfan/azure-sdk-for-net,gubookgu/azure-sdk-for-net,pinwang81/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,samtoubia/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,robertla/azure-sdk-for-net,pattipaka/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,mabsimms/azure-sdk-for-net,gubookgu/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,hyonholee/azure-sdk-for-net,shuagarw/azure-sdk-for-net,dasha91/azure-sdk-for-net,shutchings/azure-sdk-for-net,akromm/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,relmer/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,ogail/azure-sdk-for-net,bgold09/azure-sdk-for-net,nacaspi/azure-sdk-for-net,shipram/azure-sdk-for-net,hovsepm/azure-sdk-for-net,pinwang81/azure-sdk-for-net,pomortaz/azure-sdk-for-net,pankajsn/azure-sdk-for-net,jamestao/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,stankovski/azure-sdk-for-net,markcowl/azure-sdk-for-net,djyou/azure-sdk-for-net,nathannfan/azure-sdk-for-net,samtoubia/azure-sdk-for-net,djyou/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,smithab/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,begoldsm/azure-sdk-for-net,pomortaz/azure-sdk-for-net,juvchan/azure-sdk-for-net,shuagarw/azure-sdk-for-net,abhing/azure-sdk-for-net,amarzavery/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,alextolp/azure-sdk-for-net,guiling/azure-sdk-for-net,btasdoven/azure-sdk-for-net,nacaspi/azure-sdk-for-net,olydis/azure-sdk-for-net,cwickham3/azure-sdk-for-net,relmer/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,r22016/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,djyou/azure-sdk-for-net,stankovski/azure-sdk-for-net,akromm/azure-sdk-for-net,namratab/azure-sdk-for-net,shuagarw/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,Nilambari/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,mihymel/azure-sdk-for-net,begoldsm/azure-sdk-for-net,rohmano/azure-sdk-for-net,shipram/azure-sdk-for-net,akromm/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,alextolp/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,mihymel/azure-sdk-for-net,makhdumi/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,rohmano/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jtlibing/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,zaevans/azure-sdk-for-net,lygasch/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,btasdoven/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,oburlacu/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,pilor/azure-sdk-for-net,lygasch/azure-sdk-for-net,yoreddy/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,vladca/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,herveyw/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,tpeplow/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,guiling/azure-sdk-for-net,ogail/azure-sdk-for-net,oburlacu/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,mabsimms/azure-sdk-for-net,nathannfan/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,robertla/azure-sdk-for-net,pinwang81/azure-sdk-for-net,ailn/azure-sdk-for-net,hovsepm/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,abhing/azure-sdk-for-net,ailn/azure-sdk-for-net,makhdumi/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,oburlacu/azure-sdk-for-net,robertla/azure-sdk-for-net,jamestao/azure-sdk-for-net,pankajsn/azure-sdk-for-net,AzCiS/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,xindzhan/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,peshen/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,jtlibing/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,begoldsm/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,AuxMon/azure-sdk-for-net,scottrille/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,naveedaz/azure-sdk-for-net,bgold09/azure-sdk-for-net,btasdoven/azure-sdk-for-net,zaevans/azure-sdk-for-net,herveyw/azure-sdk-for-net,ailn/azure-sdk-for-net,makhdumi/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,atpham256/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,yoreddy/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,xindzhan/azure-sdk-for-net,enavro/azure-sdk-for-net,pankajsn/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,jamestao/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,enavro/azure-sdk-for-net,peshen/azure-sdk-for-net,naveedaz/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,scottrille/azure-sdk-for-net,AuxMon/azure-sdk-for-net,hovsepm/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,nemanja88/azure-sdk-for-net,marcoippel/azure-sdk-for-net,oaastest/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,pattipaka/azure-sdk-for-net,dasha91/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,ogail/azure-sdk-for-net,tpeplow/azure-sdk-for-net,hyonholee/azure-sdk-for-net,samtoubia/azure-sdk-for-net,cwickham3/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,cwickham3/azure-sdk-for-net,pilor/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,dominiqa/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,atpham256/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,atpham256/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,nemanja88/azure-sdk-for-net,bgold09/azure-sdk-for-net,relmer/azure-sdk-for-net,tpeplow/azure-sdk-for-net,dasha91/azure-sdk-for-net,kagamsft/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,dominiqa/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,AzCiS/azure-sdk-for-net,naveedaz/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,Nilambari/azure-sdk-for-net,jtlibing/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,pilor/azure-sdk-for-net,abhing/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,amarzavery/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,r22016/azure-sdk-for-net,mabsimms/azure-sdk-for-net,shutchings/azure-sdk-for-net,r22016/azure-sdk-for-net,shutchings/azure-sdk-for-net,mihymel/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,olydis/azure-sdk-for-net,peshen/azure-sdk-for-net,lygasch/azure-sdk-for-net,yoreddy/azure-sdk-for-net,smithab/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,jamestao/azure-sdk-for-net,Nilambari/azure-sdk-for-net,oaastest/azure-sdk-for-net,guiling/azure-sdk-for-net,hyonholee/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,zaevans/azure-sdk-for-net,scottrille/azure-sdk-for-net,alextolp/azure-sdk-for-net,hyonholee/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net
src/KeyVault/Microsoft.Azure.KeyVault/WebKey/JsonWebKeyEncryptionAlgorithms.cs
src/KeyVault/Microsoft.Azure.KeyVault/WebKey/JsonWebKeyEncryptionAlgorithms.cs
// // Copyright © Microsoft Corporation, 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION // ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A // PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache License, Version 2.0 for the specific language // governing permissions and limitations under the License. namespace Microsoft.Azure.KeyVault.WebKey { /// <summary> /// Supported JsonWebKey algorithms /// </summary> public static class JsonWebKeyEncryptionAlgorithm { public const string RSAOAEP = "RSA-OAEP"; public const string RSA15 = "RSA1_5"; /// <summary> /// All algorithms names. Use clone to avoid FxCop violation /// </summary> public static string[] AllAlgorithms { get { return (string[])_allAlgorithms.Clone(); } } private static readonly string[] _allAlgorithms = { RSA15, RSAOAEP }; } }
// // Copyright © Microsoft Corporation, 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION // ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A // PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache License, Version 2.0 for the specific language // governing permissions and limitations under the License. namespace Microsoft.Azure.KeyVault.WebKey { /// <summary> /// Supported JsonWebKey algorithms /// </summary> public static class JsonWebKeyEncryptionAlgorithm { public const string RSAOAEP = "RSA_OAEP"; public const string RSA15 = "RSA1_5"; /// <summary> /// All algorithms names. Use clone to avoid FxCop violation /// </summary> public static string[] AllAlgorithms { get { return (string[])_allAlgorithms.Clone(); } } private static readonly string[] _allAlgorithms = { RSA15, RSAOAEP }; } }
apache-2.0
C#
16a07e417ce653bfa310b0f6eee7cb82c6f2a2dc
update code for raven 3
agrc/deq-enviro,agrc/deq-enviro,agrc/deq-enviro,agrc/deq-enviro
api/Search.Api/Bootstrapper.cs
api/Search.Api/Bootstrapper.cs
using System.Net; using Nancy; using Nancy.Bootstrapper; using Nancy.TinyIoc; using Newtonsoft.Json; using Raven.Client; using Raven.Client.Document; using Search.Api.Config; using Search.Api.Index; using Search.Api.Serializers; using Search.Api.Services; namespace Search.Api { public class Bootstrapper : DefaultNancyBootstrapper { // The bootstrapper enables you to reconfigure the composition of the framework, // by overriding the various methods and properties. // For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper public Bootstrapper() { // Configure Store to point to your external RavenDB instance. // For simpliclity, we'll use an embedded instance instead Store = new DocumentStore { ConnectionStringName = "RavenDb" }.Initialize(); RavenConfig.Register(typeof (UserByIdIndex), Store); } public virtual IDocumentStore Store { get; private set; } protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); AutoMapperConfig.RegisterMaps(); } protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); container.Register(typeof (JsonSerializer), typeof (JsonSerializerOptions)); } protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context) { base.ConfigureRequestContainer(container, context); container.Register(Store.OpenSession()); container.Register<IQuerySoeService>(new QuerySoeServiceAsync()); } } }
using System.Net; using Nancy; using Nancy.Bootstrapper; using Nancy.TinyIoc; using Newtonsoft.Json; using Raven.Client; using Raven.Client.Document; using Search.Api.Config; using Search.Api.Index; using Search.Api.Serializers; using Search.Api.Services; namespace Search.Api { public class Bootstrapper : DefaultNancyBootstrapper { // The bootstrapper enables you to reconfigure the composition of the framework, // by overriding the various methods and properties. // For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper public Bootstrapper() { // Configure Store to point to your external RavenDB instance. // For simpliclity, we'll use an embedded instance instead Store = new DocumentStore { ConnectionStringName = "RavenDb" }.Initialize(); Store.JsonRequestFactory.ConfigureRequest += (sender, args) => { args.Request.PreAuthenticate = true; ((HttpWebRequest) args.Request).UnsafeAuthenticatedConnectionSharing = true; }; RavenConfig.Register(typeof (UserByIdIndex), Store); } public virtual IDocumentStore Store { get; private set; } protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); AutoMapperConfig.RegisterMaps(); } protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); container.Register(typeof (JsonSerializer), typeof (JsonSerializerOptions)); } protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context) { base.ConfigureRequestContainer(container, context); container.Register(Store.OpenSession()); container.Register<IQuerySoeService>(new QuerySoeServiceAsync()); } } }
mit
C#
041eda7e74a012bf5fa21e9859840ba110738d4b
Set Secret.cs so it will not be modified by default. This means we can put sensitive information in it, and it won't go into source control
AiBattleground/BotWars,AiBattleground/BotWars
Source/Server/NetBots.WebServer.Host/Models/Secrets.cs
Source/Server/NetBots.WebServer.Host/Models/Secrets.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace NetBotsHostProject.Models { public static class Secrets { private static readonly Dictionary<string,string> _secrets = new Dictionary<string, string>() { {"gitHubClientIdDev", "placeHolder"}, {"gitHubClientSecretDev", "placeHolder"} }; public static string GetSecret(string key) { if (_secrets.ContainsKey(key)) { return _secrets[key]; } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace NetBotsHostProject.Models { public static class Secrets { private static readonly Dictionary<string,string> _secrets = new Dictionary<string, string>() { {"gitHubClientIdDev", "placeholder"}, {"gitHubClientSecretDev", "placeholder"} }; public static string GetSecret(string key) { if (_secrets.ContainsKey(key)) { return _secrets[key]; } return null; } } }
mit
C#
79aff4739afb5a901db52f54911229395fe5ab56
Fix issue with tag retrieval (#739)
Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/SchemaPropertiesDto.cs
backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/SchemaPropertiesDto.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using Squidex.Infrastructure.Collections; using Squidex.Infrastructure.Validation; namespace Squidex.Areas.Api.Controllers.Schemas.Models { public sealed class SchemaPropertiesDto { /// <summary> /// Optional label for the editor. /// </summary> [LocalizedStringLength(100)] public string? Label { get; set; } /// <summary> /// Hints to describe the schema. /// </summary> [LocalizedStringLength(1000)] public string? Hints { get; set; } /// <summary> /// The url to a the sidebar plugin for content lists. /// </summary> public string? ContentsSidebarUrl { get; set; } /// <summary> /// The url to a the sidebar plugin for content items. /// </summary> public string? ContentSidebarUrl { get; set; } /// <summary> /// The url to the editor plugin. /// </summary> public string? ContentEditorUrl { get; set; } /// <summary> /// True to validate the content items on publish. /// </summary> public bool ValidateOnPublish { get; set; } /// <summary> /// Tags for automation processes. /// </summary> public ImmutableList<string>? Tags { get; set; } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Collections.Immutable; using Squidex.Infrastructure.Validation; namespace Squidex.Areas.Api.Controllers.Schemas.Models { public sealed class SchemaPropertiesDto { /// <summary> /// Optional label for the editor. /// </summary> [LocalizedStringLength(100)] public string? Label { get; set; } /// <summary> /// Hints to describe the schema. /// </summary> [LocalizedStringLength(1000)] public string? Hints { get; set; } /// <summary> /// The url to a the sidebar plugin for content lists. /// </summary> public string? ContentsSidebarUrl { get; set; } /// <summary> /// The url to a the sidebar plugin for content items. /// </summary> public string? ContentSidebarUrl { get; set; } /// <summary> /// The url to the editor plugin. /// </summary> public string? ContentEditorUrl { get; set; } /// <summary> /// True to validate the content items on publish. /// </summary> public bool ValidateOnPublish { get; set; } /// <summary> /// Tags for automation processes. /// </summary> public ImmutableList<string>? Tags { get; set; } } }
mit
C#
696f096845a879e37aae0ff4033cfed66db955b1
Add missing documentation
martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode
2015/day-06/AdventOfCode.Day6/Instruction.cs
2015/day-06/AdventOfCode.Day6/Instruction.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Instruction.cs" company="https://github.com/martincostello/adventofcode"> // Martin Costello (c) 2015 // </copyright> // <license> // See license.txt in the project root for license information. // </license> // <summary> // Instruction.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace MartinCostello.AdventOfCode.Day6 { using System.Drawing; using System.Globalization; /// <summary> /// The base class for instructions. /// </summary> internal abstract class Instruction : IInstruction { /// <inheritdoc /> public abstract void Act(LightGrid grid); /// <summary> /// Parses the specified origin and termination points, as strings, to a bounding rectangle. /// </summary> /// <param name="origin">The origin point of the bounding rectangle, as a <see cref="string"/>.</param> /// <param name="termination">The termination point of the bounding rectangle, as a <see cref="string"/>.</param> /// <returns>A bounding <see cref="Rectangle"/> parsed from <paramref name="origin"/> and <paramref name="termination"/>.</returns> protected static Rectangle ParseBounds(string origin, string termination) { // Determine the termination and origin points of the bounds of the lights to operate on string[] originPoints = origin.Split(','); string[] terminationPoints = termination.Split(','); int left = int.Parse(originPoints[0], NumberStyles.Integer, CultureInfo.InvariantCulture); int bottom = int.Parse(originPoints[1], NumberStyles.Integer, CultureInfo.InvariantCulture); int right = int.Parse(terminationPoints[0], NumberStyles.Integer, CultureInfo.InvariantCulture); int top = int.Parse(terminationPoints[1], NumberStyles.Integer, CultureInfo.InvariantCulture); // Add one to the termination point so that the grid always has a width of at least one light return Rectangle.FromLTRB(left, bottom, right + 1, top + 1); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Instruction.cs" company="https://github.com/martincostello/adventofcode"> // Martin Costello (c) 2015 // </copyright> // <license> // See license.txt in the project root for license information. // </license> // <summary> // Instruction.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace MartinCostello.AdventOfCode.Day6 { using System.Drawing; using System.Globalization; /// <summary> /// The base class for instructions. /// </summary> internal abstract class Instruction : IInstruction { /// <inheritdoc /> public abstract void Act(LightGrid grid); protected static Rectangle ParseBounds(string origin, string termination) { // Determine the termination and origin points of the bounds of the lights to operate on string[] originPoints = origin.Split(','); string[] terminationPoints = termination.Split(','); int left = int.Parse(originPoints[0], NumberStyles.Integer, CultureInfo.InvariantCulture); int bottom = int.Parse(originPoints[1], NumberStyles.Integer, CultureInfo.InvariantCulture); int right = int.Parse(terminationPoints[0], NumberStyles.Integer, CultureInfo.InvariantCulture); int top = int.Parse(terminationPoints[1], NumberStyles.Integer, CultureInfo.InvariantCulture); // Add one to the termination point so that the grid always has a width of at least one light return Rectangle.FromLTRB(left, bottom, right + 1, top + 1); } } }
apache-2.0
C#
00e3d67de41386aad10638760a14256693b3a3cf
test (issue #15)
sergeyt/xserializer,sergeyt/xserializer
src/Tests/MiscTests.cs
src/Tests/MiscTests.cs
#if NUNIT using System.Xml.Linq; using NUnit.Framework; namespace TsvBits.Serialization.Tests { [TestFixture] public class MiscTests { [TestCase(@"<Entity><Value>test</Value><Unknown>abc</Unknown></Entity>", Result = "test")] [TestCase(@"<Entity><Unknown><nested>abc</nested></Unknown><Value>test</Value></Entity>", Result = "test")] public string SkipUnknownElement(string xml) { var scope = new Scope(); scope.Element<Entity>() .Elements() .Add(x => x.Value) .End(); var serializer = XSerializer.New(scope); var obj = new Entity(); serializer.ReadXmlString(xml, obj); return obj.Value; } [TestCase(@"<Entity><Value xmlns=""A"">test</Value></Entity>", Result = "test")] [TestCase(@"<Entity><Value xmlns=""B"">test</Value></Entity>", Result = "test")] [TestCase(@"<Entity><Text xmlns=""A"">test</Text></Entity>", Result = "test")] [TestCase(@"<Entity><Text xmlns=""B"">test</Text></Entity>", Result = "test")] [TestCase(@"<Entity><Value xmlns=""C"">test</Value></Entity>", Result = null)] [TestCase(@"<Entity><Text xmlns=""C"">test</Text></Entity>", Result = null)] [TestCase(@"<Entity><Value>test</Value></Entity>", Result = null)] [TestCase(@"<Entity><Text>test</Text></Entity>", Result = null)] public string MultiplePropertyNames(string xml) { var ns1 = XNamespace.Get("A"); var ns2 = XNamespace.Get("B"); var scope = new Scope(); scope.Element<Entity>() .Elements() .Add(x => x.Value, ns1 + "Value", ns2 + "Value", ns1 + "Text", ns2 + "Text") .End(); var serializer = XSerializer.New(scope); var obj = new Entity(); serializer.ReadXmlString(xml, obj); return obj.Value; } [TestCase(@"<Entity><Value>test</Value></Entity>", Result = "test")] [TestCase(@"<Ent><Value>test</Value></Ent>", Result = "test")] [TestCase(@"<E><Value>test</Value></E>", Result = "test")] public string MultipleElementNames(string xml) { var scope = new Scope(); scope.Element<Entity>("Entity", "Ent", "E") .Elements() .Add(x => x.Value) .End(); var serializer = XSerializer.New(scope); var obj = new Entity(); serializer.ReadXmlString(xml, obj); return obj.Value; } class Entity { public string Value; } } } #endif
#if NUNIT using System.Xml.Linq; using NUnit.Framework; namespace TsvBits.Serialization.Tests { [TestFixture] public class MiscTests { [TestCase(@"<Entity><Value>test</Value><Unknown>abc</Unknown></Entity>", Result = "test")] [TestCase(@"<Entity><Unknown><nested>abc</nested></Unknown><Value>test</Value></Entity>", Result = "test")] public string SkipUnknownElement(string xml) { var scope = new Scope(); scope.Element<Entity>() .Elements() .Add(x => x.Value) .End(); var serializer = XSerializer.New(scope); var obj = new Entity(); serializer.ReadXmlString(xml, obj); return obj.Value; } [TestCase(@"<Entity><Value xmlns=""A"">test</Value></Entity>", Result = "test")] [TestCase(@"<Entity><Value xmlns=""B"">test</Value></Entity>", Result = "test")] [TestCase(@"<Entity><Text xmlns=""A"">test</Text></Entity>", Result = "test")] [TestCase(@"<Entity><Text xmlns=""B"">test</Text></Entity>", Result = "test")] [TestCase(@"<Entity><Value xmlns=""C"">test</Value></Entity>", Result = null)] [TestCase(@"<Entity><Text xmlns=""C"">test</Text></Entity>", Result = null)] [TestCase(@"<Entity><Value>test</Value></Entity>", Result = null)] [TestCase(@"<Entity><Text>test</Text></Entity>", Result = null)] public string MultiplePropertyNames(string xml) { var ns1 = XNamespace.Get("A"); var ns2 = XNamespace.Get("B"); var scope = new Scope(); scope.Element<Entity>() .Elements() .Add(x => x.Value, ns1 + "Value", ns2 + "Value", ns1 + "Text", ns2 + "Text") .End(); var serializer = XSerializer.New(scope); var obj = new Entity(); serializer.ReadXmlString(xml, obj); return obj.Value; } class Entity { public string Value; } } } #endif
mit
C#
b4a6a6fbe06f77f8a91e7500598da05fe181c8e1
Change version up to 1.1.1
matiasbeckerle/breakout,matiasbeckerle/arkanoid,matiasbeckerle/perspektiva
source/Assets/Scripts/Loader.cs
source/Assets/Scripts/Loader.cs
using UnityEngine; using System.Reflection; [assembly: AssemblyVersion("1.1.1.*")] public class Loader : MonoBehaviour { /// <summary> /// DebugUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _debugUI; /// <summary> /// ModalDialog prefab to instantiate. /// </summary> [SerializeField] private GameObject _modalDialog; /// <summary> /// MainMenu prefab to instantiate. /// </summary> [SerializeField] private GameObject _mainMenu; /// <summary> /// InGameUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _inGameUI; /// <summary> /// SoundManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _soundManager; /// <summary> /// GameManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _gameManager; protected void Awake() { // Check if the instances have already been assigned to static variables or they are still null. if (DebugUI.Instance == null) { Instantiate(_debugUI); } if (ModalDialog.Instance == null) { Instantiate(_modalDialog); } if (MainMenu.Instance == null) { Instantiate(_mainMenu); } if (InGameUI.Instance == null) { Instantiate(_inGameUI); } if (SoundManager.Instance == null) { Instantiate(_soundManager); } if (GameManager.Instance == null) { Instantiate(_gameManager); } } }
using UnityEngine; using System.Reflection; [assembly: AssemblyVersion("1.1.0.*")] public class Loader : MonoBehaviour { /// <summary> /// DebugUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _debugUI; /// <summary> /// ModalDialog prefab to instantiate. /// </summary> [SerializeField] private GameObject _modalDialog; /// <summary> /// MainMenu prefab to instantiate. /// </summary> [SerializeField] private GameObject _mainMenu; /// <summary> /// InGameUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _inGameUI; /// <summary> /// SoundManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _soundManager; /// <summary> /// GameManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _gameManager; protected void Awake() { // Check if the instances have already been assigned to static variables or they are still null. if (DebugUI.Instance == null) { Instantiate(_debugUI); } if (ModalDialog.Instance == null) { Instantiate(_modalDialog); } if (MainMenu.Instance == null) { Instantiate(_mainMenu); } if (InGameUI.Instance == null) { Instantiate(_inGameUI); } if (SoundManager.Instance == null) { Instantiate(_soundManager); } if (GameManager.Instance == null) { Instantiate(_gameManager); } } }
unknown
C#
31514c8eff77c153e6863aaeb841956e9c63828a
Fix remaining comment spacing.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Rpc/JsonRpcService.cs
WalletWasabi.Gui/Rpc/JsonRpcService.cs
using System; using System.Collections.Generic; using System.Reflection; namespace WalletWasabi.Gui.Rpc { /// <summary> /// Base class for service classes. /// /// Provides two methods for responding to the clients with a **result** for valid /// requests or with **error** in case the request is invalid or there is a problem. /// /// Also, it loads and serves information about the service. It discovers /// (using reflection) the methods that have to be invoked and the parameters it /// receives. /// </summary> public class JsonRpcServiceMetadataProvider { // Keeps the directory of procedures' metadata private Dictionary<string, JsonRpcMethodMetadata> _proceduresDirectory = new Dictionary<string, JsonRpcMethodMetadata>(); private Type ServiceType { get; } public JsonRpcServiceMetadataProvider(Type serviceType) { ServiceType = serviceType; } /// <summary> /// Tries to return the metadata for a given procedure name. /// Returns true if found otherwise returns false. /// </summary> public bool TryGetMetadata(string methodName, out JsonRpcMethodMetadata metadata) { if (_proceduresDirectory.Count == 0) { LoadServiceMetadata(); } if (!_proceduresDirectory.TryGetValue(methodName, out metadata)) { metadata = null; return false; } return true; } private void LoadServiceMetadata() { foreach (var info in EnumerateServiceInfo()) { _proceduresDirectory.Add(info.Name, info); } } internal IEnumerable<JsonRpcMethodMetadata> EnumerateServiceInfo() { var publicMethods = ServiceType.GetMethods(); foreach (var methodInfo in publicMethods) { var attrs = methodInfo.GetCustomAttributes(); foreach (Attribute attr in attrs) { if (attr is JsonRpcMethodAttribute) { var parameters = new List<(string name, Type type)>(); foreach (var p in methodInfo.GetParameters()) { parameters.Add((p.Name, p.ParameterType)); } var jsonRpcMethodAttr = (JsonRpcMethodAttribute)attr; yield return new JsonRpcMethodMetadata(jsonRpcMethodAttr.Name, methodInfo, parameters); } } } } } }
using System; using System.Collections.Generic; using System.Reflection; namespace WalletWasabi.Gui.Rpc { ///<summary> /// Base class for service classes. /// /// Provides two methods for responding to the clients with a **result** for valid /// requests or with **error** in case the request is invalid or there is a problem. /// /// Also, it loads and serves information about the service. It discovers /// (using reflection) the methods that have to be invoked and the parameters it /// receives. ///</summary> public class JsonRpcServiceMetadataProvider { // Keeps the directory of procedures' metadata private Dictionary<string, JsonRpcMethodMetadata> _proceduresDirectory = new Dictionary<string, JsonRpcMethodMetadata>(); private Type ServiceType { get; } public JsonRpcServiceMetadataProvider(Type serviceType) { ServiceType = serviceType; } /// <summary> /// Tries to return the metadata for a given procedure name. /// Returns true if found otherwise returns false. /// </summary> public bool TryGetMetadata(string methodName, out JsonRpcMethodMetadata metadata) { if (_proceduresDirectory.Count == 0) { LoadServiceMetadata(); } if (!_proceduresDirectory.TryGetValue(methodName, out metadata)) { metadata = null; return false; } return true; } private void LoadServiceMetadata() { foreach (var info in EnumerateServiceInfo()) { _proceduresDirectory.Add(info.Name, info); } } internal IEnumerable<JsonRpcMethodMetadata> EnumerateServiceInfo() { var publicMethods = ServiceType.GetMethods(); foreach (var methodInfo in publicMethods) { var attrs = methodInfo.GetCustomAttributes(); foreach (Attribute attr in attrs) { if (attr is JsonRpcMethodAttribute) { var parameters = new List<(string name, Type type)>(); foreach (var p in methodInfo.GetParameters()) { parameters.Add((p.Name, p.ParameterType)); } var jsonRpcMethodAttr = (JsonRpcMethodAttribute)attr; yield return new JsonRpcMethodMetadata(jsonRpcMethodAttr.Name, methodInfo, parameters); } } } } } }
mit
C#
55d102fd2ed65b32205de6423f39f2f81ee1e0cc
Simplify foreach'es to a LINQ expression
boumenot/Grobid.NET
src/Grobid/PdfBlockExtractor.cs
src/Grobid/PdfBlockExtractor.cs
using System; using System.Collections.Generic; using System.Linq; using Grobid.PdfToXml; namespace Grobid.NET { public class PdfBlockExtractor<T> { private readonly BlockStateFactory factory; public PdfBlockExtractor() { this.factory = new BlockStateFactory(); } public IEnumerable<T> Extract(IEnumerable<Block> blocks, Func<BlockState, T> transform) { return from block in blocks from textBlock in block.TextBlocks let tokenBlocks = textBlock.TokenBlocks.SelectMany(x => x.Tokenize()) from tokenBlock in tokenBlocks select this.factory.Create(block, textBlock, tokenBlock) into blockState select transform(blockState); } } }
using System; using System.Collections.Generic; using System.Linq; using Grobid.PdfToXml; namespace Grobid.NET { public class PdfBlockExtractor<T> { private readonly BlockStateFactory factory; public PdfBlockExtractor() { this.factory = new BlockStateFactory(); } public IEnumerable<T> Extract(IEnumerable<Block> blocks, Func<BlockState, T> transform) { foreach (var block in blocks) { foreach (var textBlock in block.TextBlocks) { var tokenBlocks = textBlock.TokenBlocks.SelectMany(x => x.Tokenize()); foreach (var tokenBlock in tokenBlocks) { var blockState = this.factory.Create(block, textBlock, tokenBlock); yield return transform(blockState); } } } } } }
apache-2.0
C#
ea772c960a89844de445a14a5b9ed3bc0bc21d7b
remove stream copy
icarus-consulting/Yaapii.Atoms
src/Yaapii.Atoms/IO/ZipFiles.cs
src/Yaapii.Atoms/IO/ZipFiles.cs
using System.Collections; using System.Collections.Generic; using System.IO; using System.IO.Compression; using Yaapii.Atoms; using Yaapii.Atoms.Enumerable; using Yaapii.Atoms.Scalar; namespace Yaapii.Atoms.IO { /// <summary> /// The files in a ZIP archive. /// Note: Extraction is sticky. /// </summary> public sealed class ZipFiles : IEnumerable<string> { private readonly IScalar<IEnumerable<string>> files; /// <summary> /// The files in a ZIP archive. /// Note: Extraction is sticky. /// leaves zip stream open /// </summary> /// <param name="input"></param> public ZipFiles(IInput input) { this.files = new StickyScalar<IEnumerable<string>>(() => { IEnumerable<string> files; //var copy = new MemoryStream(); // I don't know if that is neccessary - code copied from bpa //input.Stream().Position = 0; //input.Stream().CopyTo(copy); //input.Stream().Position = 0; //copy.Position = 0; using (var zip = new ZipArchive(/*copy*/input.Stream(), ZipArchiveMode.Read, true)) { files = new Mapped<ZipArchiveEntry, string>( entry => entry.FullName, zip.Entries ); } input.Stream().Position = 0; return files; }); } public IEnumerator<string> GetEnumerator() { return this.files.Value().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
using System.Collections; using System.Collections.Generic; using System.IO; using System.IO.Compression; using Yaapii.Atoms; using Yaapii.Atoms.Enumerable; using Yaapii.Atoms.Scalar; namespace Yaapii.Atoms.IO { /// <summary> /// The files in a ZIP archive. /// Note: Extraction is sticky. /// </summary> public sealed class ZipFiles : IEnumerable<string> { private readonly IScalar<IEnumerable<string>> files; /// <summary> /// The files in a ZIP archive. /// Note: Extraction is sticky. /// </summary> /// <param name="input"></param> public ZipFiles(IInput input) { this.files = new StickyScalar<IEnumerable<string>>(() => { IEnumerable<string> files; var copy = new MemoryStream(); input.Stream().Position = 0; input.Stream().CopyTo(copy); input.Stream().Position = 0; copy.Position = 0; using (var zip = new ZipArchive(copy, ZipArchiveMode.Read, true)) { files = new Mapped<ZipArchiveEntry, string>( entry => entry.FullName, zip.Entries ); } return files; }); } public IEnumerator<string> GetEnumerator() { return this.files.Value().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
mit
C#
3f3ea9ceca219b600373959df35ed95dc1738729
Tidy up route declaration
stevehodgkiss/restful-routing,restful-routing/restful-routing,restful-routing/restful-routing,stevehodgkiss/restful-routing,stevehodgkiss/restful-routing,restful-routing/restful-routing
src/RestfulRouting/Mappers/DebugRouteMapper.cs
src/RestfulRouting/Mappers/DebugRouteMapper.cs
using System.Web.Routing; using RestfulRouting.RouteDebug; namespace RestfulRouting.Mappers { public class DebugRouteMapper : StandardMapper { string _path; public DebugRouteMapper(string path) { _path = path; } public override void RegisterRoutes(RouteCollection routeCollection) { Path(_path).To<RouteDebugController>(x => x.Index()); base.RegisterRoutes(routeCollection); Path(Join(_path, "resources/{name}")).To<RouteDebugController>(x => x.Resources(null)); base.RegisterRoutes(routeCollection); } } }
using System.Web.Routing; using RestfulRouting.RouteDebug; namespace RestfulRouting.Mappers { public class DebugRouteMapper : StandardMapper { string _path; public DebugRouteMapper(string path) { _path = path; } public override void RegisterRoutes(System.Web.Routing.RouteCollection routeCollection) { Path(_path).To<RouteDebugController>(x => x.Index()); // add resources url routeCollection.Add(new Route(_path + "/resources/{name}", new RouteValueDictionary(new {controller = GetControllerName<RouteDebugController>(), action = "resources"}), new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint("GET") }), new RouteValueDictionary(), RouteHandler)); base.RegisterRoutes(routeCollection); } } }
mit
C#
3afc86180ca9c4c7e5e3eeb9c7c3d49ddafeb1b0
Update vesion to 3.4.0.0 (#71)
adjackura/compute-image-windows,ning-yang/compute-image-windows,adjackura/compute-image-windows,illfelder/compute-image-windows,GoogleCloudPlatform/compute-image-windows,GoogleCloudPlatform/compute-image-windows,ning-yang/compute-image-windows,illfelder/compute-image-windows
agent/Common/Properties/VersionInfo.cs
agent/Common/Properties/VersionInfo.cs
/* * Copyright 2015 Google Inc. 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.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: AssemblyCompany("Google Inc")] [assembly: AssemblyCopyright("Copyright © 2015")] [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)] // Version information for an assembly consists of the following four values: // // Major Version: Large feature and functionality changes, or incompatible // API changes. // Minor Version: Add functionality without API changes. // Build Number: Bug fixes. // Revision: Minor changes or improvements such as style fixes. // // 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("3.4.0.0")] [assembly: AssemblyFileVersion("3.4.0.0")]
/* * Copyright 2015 Google Inc. 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.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: AssemblyCompany("Google Inc")] [assembly: AssemblyCopyright("Copyright © 2015")] [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)] // Version information for an assembly consists of the following four values: // // Major Version: Large feature and functionality changes, or incompatible // API changes. // Minor Version: Add functionality without API changes. // Build Number: Bug fixes. // Revision: Minor changes or improvements such as style fixes. // // 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("3.3.0.0")] [assembly: AssemblyFileVersion("3.3.0.0")]
apache-2.0
C#
efd79306e75512788f9bb66ff58993fe16296a84
fix pending download server selection
yar229/WebDavMailRuCloud
MailRuCloud/MailRuCloudApi/Base/Pending.cs
MailRuCloud/MailRuCloudApi/Base/Pending.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace YaR.MailRuCloud.Api.Base { class Pending<T> where T : class { private readonly List<PendingItem<T>> _items = new List<PendingItem<T>>(); private readonly int _maxLocks; private readonly Func<T> _valueFactory; public Pending(int maxLocks, Func<T> valueFactory) { _maxLocks = maxLocks; _valueFactory = valueFactory; } private readonly object _lock = new object(); public T Next(T current) { lock (_lock) { var item = null == current ? _items.FirstOrDefault(it => it.LockCount < _maxLocks) : _items.SkipWhile(it => !it.Equals(current)).Skip(1).FirstOrDefault(it => it.LockCount < _maxLocks); if (null == item) _items.Add(item = new PendingItem <T>{Item = _valueFactory(), LockCount = 0}); item.LockCount++; return item.Item; } } public void Free(T value) { if (null == value) return; lock (_lock) { foreach (var item in _items) if (item.Item.Equals(value)) { if (item.LockCount <= 0) throw new Exception("Pending item count <= 0"); if (item.LockCount > 0) item.LockCount--; } } } } class PendingItem<T> { public T Item { get; set; } public int LockCount { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace YaR.MailRuCloud.Api.Base { class Pending<T> where T : class { private readonly List<PendingItem<T>> _items = new List<PendingItem<T>>(); private readonly int _maxLocks; private readonly Func<T> _valueFactory; public Pending(int maxLocks, Func<T> valueFactory) { _maxLocks = maxLocks; _valueFactory = valueFactory; } private readonly object _lock = new object(); public T Next(T current) { lock (_lock) { var item = null == current ? _items.FirstOrDefault(it => it.LockCount < _maxLocks) : _items.SkipWhile(it => !it.Equals(current)).Skip(1).FirstOrDefault(); if (null == item) _items.Add(item = new PendingItem <T>{Item = _valueFactory(), LockCount = 0}); item.LockCount++; return item.Item; } } public void Free(T value) { if (null == value) return; lock (_lock) { foreach (var item in _items) if (item.Item.Equals(value)) { if (item.LockCount <= 0) throw new Exception("Pending item count <= 0"); if (item.LockCount > 0) item.LockCount--; } } } } class PendingItem<T> { public T Item { get; set; } public int LockCount { get; set; } } }
mit
C#
8f7577a314e6efadd3a62f15c1fdb3fa385f8c5a
Update EllipseShape.cs
Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Shapes/EllipseShape.cs
src/Core2D/Shapes/EllipseShape.cs
using System; using System.Collections.Generic; using Core2D.Data; using Core2D.Renderer; namespace Core2D.Shapes { /// <summary> /// Ellipse shape. /// </summary> public class EllipseShape : TextShape, IEllipseShape { /// <inheritdoc/> public override Type TargetType => typeof(IEllipseShape); /// <inheritdoc/> public override void DrawShape(object dc, IShapeRenderer renderer, double dx, double dy) { if (State.Flags.HasFlag(ShapeStateFlags.Visible)) { renderer.DrawEllipse(dc, this, dx, dy); } } /// <inheritdoc/> public override void DrawPoints(object dc, IShapeRenderer renderer, double dx, double dy) { if (State.Flags.HasFlag(ShapeStateFlags.Visible)) { base.DrawPoints(dc, renderer, dx, dy); } } /// <inheritdoc/> public override void Bind(IDataFlow dataFlow, object db, object r) { var record = Data?.Record ?? r; dataFlow.Bind(this, db, record); base.Bind(dataFlow, db, record); } /// <inheritdoc/> public override object Copy(IDictionary<object, object> shared) { throw new NotImplementedException(); } /// <inheritdoc/> public override bool IsDirty() { var isDirty = base.IsDirty(); return isDirty; } /// <inheritdoc/> public override void Invalidate() { base.Invalidate(); } } }
using System; using System.Collections.Generic; using Core2D.Data; using Core2D.Renderer; namespace Core2D.Shapes { /// <summary> /// Ellipse shape. /// </summary> public class EllipseShape : TextShape, IEllipseShape { /// <inheritdoc/> public override Type TargetType => typeof(IEllipseShape); /// <inheritdoc/> public override void DrawShape(object dc, IShapeRenderer renderer, double dx, double dy) { if (State.Flags.HasFlag(ShapeStateFlags.Visible)) { renderer.DrawEllipse(dc, this, dx, dy); #if !USE_DRAW_NODES // TODO: base.DrawShape(dc, renderer, dx, dy); #endif } } /// <inheritdoc/> public override void DrawPoints(object dc, IShapeRenderer renderer, double dx, double dy) { if (State.Flags.HasFlag(ShapeStateFlags.Visible)) { base.DrawPoints(dc, renderer, dx, dy); } } /// <inheritdoc/> public override void Bind(IDataFlow dataFlow, object db, object r) { var record = Data?.Record ?? r; dataFlow.Bind(this, db, record); base.Bind(dataFlow, db, record); } /// <inheritdoc/> public override object Copy(IDictionary<object, object> shared) { throw new NotImplementedException(); } /// <inheritdoc/> public override bool IsDirty() { var isDirty = base.IsDirty(); return isDirty; } /// <inheritdoc/> public override void Invalidate() { base.Invalidate(); } } }
mit
C#
e126fd3ed60273dfd720c3977cb79889fb9c16d7
Complete implementation AlbumsRepo.
CassandraDied/SimpleRestService
src/DataLayer/AlbumsRepository.cs
src/DataLayer/AlbumsRepository.cs
using System.Collections.Generic; using System.Threading.Tasks; using DataLayer.Contract; using DataLayer.Contract.Models; using System.Net.Http; using System; using Newtonsoft.Json; using System.Linq; namespace DataLayer { public class AlbumsRepository : IAlbumsRepository { private static HttpClient _client = new HttpClient(); // TODO use IoC private const string RESOURCE = "albums"; private const int PAGE_SIZE = 5; public async Task<Album> FindAlbum(string albumId) { if (string.IsNullOrEmpty(albumId)) throw new ArgumentNullException(nameof(albumId)); var req = Constants.FakeDataHost + RESOURCE + "/" + albumId; return await GetOne(req); } public async Task<IEnumerable<Album>> GetAlbums(int page) { // well, the service does not support paging or navigation, so we have to retrieve everything // I don't see any reason why I should implement any optimisations here like caching or something similar, as it is not a programming problem I need to solve, but data storage var req = Constants.FakeDataHost + RESOURCE; return await GetMany(req, page); } public async Task<IEnumerable<Album>> GetAlbumsForUser(string userId, int page) { if (string.IsNullOrEmpty(userId)) throw new ArgumentNullException(nameof(userId)); // not nice situation here: we want to work only with albums here, but have to work with users too // the reason why it is here and not in users repo is that any developer that would want to look at how we retrieve albums for user will probably look at this repo first string usersResource = "users"; var req = Constants.FakeDataHost + usersResource + "/" + userId + "/" + RESOURCE; return await GetMany(req, page); } private async Task<IEnumerable<Album>> GetMany(string req, int page) { var resp = await _client.GetStringAsync(req); if (string.IsNullOrEmpty(resp)) return Enumerable.Empty<Album>(); var deserialized = JsonConvert.DeserializeObject<IEnumerable<Album>>(resp); return deserialized.Skip(page * PAGE_SIZE).ToArray(); } private async Task<Album> GetOne(string req) { var resp = await _client.GetStringAsync(req); if (string.IsNullOrEmpty(resp)) return null; return JsonConvert.DeserializeObject<Album>(resp); } } }
using System.Collections.Generic; using System.Threading.Tasks; using DataLayer.Contract; using DataLayer.Contract.Models; using System.Net.Http; using System; using Newtonsoft.Json; namespace DataLayer { public class AlbumsRepository : IAlbumsRepository { private static HttpClient _client = new HttpClient(); // TODO use IoC public async Task<Album> FindAlbum(string albumId) { if (string.IsNullOrEmpty(albumId)) throw new ArgumentNullException(nameof(albumId)); var req = Constants.FakeDataHost + "albums/" + albumId; var resp = await _client.GetStringAsync(req); if (string.IsNullOrEmpty(resp)) return null; return JsonConvert.DeserializeObject<Album>(resp); } public Task<IEnumerable<Album>> GetAlbums(int page) { throw new System.NotImplementedException(); } public Task<IEnumerable<Album>> GetAlbumsForUser(string userId, int page) { throw new System.NotImplementedException(); } } }
mit
C#
b3e7ca47cad2971433616ccdea6883c8b5b825e6
Add timer for email sending
mattgwagner/CertiPay.Common
CertiPay.Common/Notifications/ISMSService.cs
CertiPay.Common/Notifications/ISMSService.cs
using CertiPay.Common.Logging; using System; using System.Threading.Tasks; using Twilio; namespace CertiPay.Common.Notifications { /// <summary> /// Send an SMS message to the given recipient. /// </summary> /// <remarks> /// Implementation may be sent into background processing. /// </remarks> public interface ISMSService : INotificationSender<SMSNotification> { // Task SendAsync(T notification); } public class SmsService : ISMSService { private static readonly ILog Log = LogManager.GetLogger<ISMSService>(); private readonly String _twilioAccountSId; private readonly String _twilioAuthToken; private readonly String _twilioSourceNumber; public SmsService(TwilioConfig config) { this._twilioAccountSId = config.AccountSid; this._twilioAuthToken = config.AuthToken; this._twilioSourceNumber = config.SourceNumber; } public Task SendAsync(SMSNotification notification) { using (Log.Timer("SMSNotification.SendAsync")) { Log.Info("Sending SMSNotification {@Notification}", notification); // TODO Add error handling var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken); foreach (var recipient in notification.Recipients) { client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content); } return Task.FromResult(0); } } public class TwilioConfig { public String AccountSid { get; set; } public String AuthToken { get; set; } public String SourceNumber { get; set; } } } }
using CertiPay.Common.Logging; using System; using System.Threading.Tasks; using Twilio; namespace CertiPay.Common.Notifications { /// <summary> /// Send an SMS message to the given recipient. /// </summary> /// <remarks> /// Implementation may be sent into background processing. /// </remarks> public interface ISMSService : INotificationSender<SMSNotification> { // Task SendAsync(T notification); } public class SmsService : ISMSService { private static readonly ILog Log = LogManager.GetLogger<ISMSService>(); private readonly String _twilioAccountSId; private readonly String _twilioAuthToken; private readonly String _twilioSourceNumber; public SmsService(String twilioAccountSid, String twilioAuthToken, String twilioSourceNumber) { this._twilioAccountSId = twilioAccountSid; this._twilioAuthToken = twilioAuthToken; this._twilioSourceNumber = twilioSourceNumber; } public Task SendAsync(SMSNotification notification) { using (Log.Timer("SMSNotification.SendAsync")) { Log.Info("Sending SMSNotification {@Notification}", notification); // TODO Add error handling var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken); foreach (var recipient in notification.Recipients) { client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content); } return Task.FromResult(0); } } } }
mit
C#
1033c42d0156db660f53b3ca113741ca3cc23b37
Make Tablet and Desktop device types report as Desktop
pingzing/digi-transit-10
DigiTransit10/Helpers/DeviceTypeHelper.cs
DigiTransit10/Helpers/DeviceTypeHelper.cs
using Windows.System.Profile; using Windows.UI.ViewManagement; namespace DigiTransit10.Helpers { public static class DeviceTypeHelper { public static DeviceFormFactorType GetDeviceFormFactorType() { switch (AnalyticsInfo.VersionInfo.DeviceFamily) { case "Windows.Mobile": return DeviceFormFactorType.Phone; case "Windows.Desktop": return DeviceFormFactorType.Desktop; case "Windows.Universal": return DeviceFormFactorType.IoT; case "Windows.Team": return DeviceFormFactorType.SurfaceHub; default: return DeviceFormFactorType.Other; } } } public enum DeviceFormFactorType { Phone, Desktop, Tablet, IoT, SurfaceHub, Other } }
using Windows.System.Profile; using Windows.UI.ViewManagement; namespace DigiTransit10.Helpers { public static class DeviceTypeHelper { public static DeviceFormFactorType GetDeviceFormFactorType() { switch (AnalyticsInfo.VersionInfo.DeviceFamily) { case "Windows.Mobile": return DeviceFormFactorType.Phone; case "Windows.Desktop": return UIViewSettings.GetForCurrentView().UserInteractionMode == UserInteractionMode.Mouse ? DeviceFormFactorType.Desktop : DeviceFormFactorType.Tablet; case "Windows.Universal": return DeviceFormFactorType.IoT; case "Windows.Team": return DeviceFormFactorType.SurfaceHub; default: return DeviceFormFactorType.Other; } } } public enum DeviceFormFactorType { Phone, Desktop, Tablet, IoT, SurfaceHub, Other } }
mit
C#
04eb1d877d5334f9eb8a2b93afe90a53f0bcf6ee
remove duplicated public keys (#1326)
open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet
src/OpenTelemetry/AssemblyInfo.cs
src/OpenTelemetry/AssemblyInfo.cs
// <copyright file="AssemblyInfo.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // 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. // </copyright> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("OpenTelemetry.Tests" + AssemblyInfo.PublicKey)] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2" + AssemblyInfo.MoqPublicKey)] [assembly: InternalsVisibleTo("Benchmarks" + AssemblyInfo.PublicKey)] #if SIGNED internal static class AssemblyInfo { public const string PublicKey = ", PublicKey=002400000480000094000000060200000024000052534131000400000100010051c1562a090fb0c9f391012a32198b5e5d9a60e9b80fa2d7b434c9e5ccb7259bd606e66f9660676afc6692b8cdc6793d190904551d2103b7b22fa636dcbb8208839785ba402ea08fc00c8f1500ccef28bbf599aa64ffb1e1d5dc1bf3420a3777badfe697856e9d52070a50c3ea5821c80bef17ca3acffa28f89dd413f096f898"; public const string MoqPublicKey = ", PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7"; } #else internal static class AssemblyInfo { public const string PublicKey = ""; public const string MoqPublicKey = ""; } #endif
// <copyright file="AssemblyInfo.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // 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. // </copyright> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("OpenTelemetry.Tests" + AssemblyInfo.PublicKey)] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2" + AssemblyInfo.MoqPublicKey)] [assembly: InternalsVisibleTo("Benchmarks" + AssemblyInfo.BenchmarksPublicKey)] #if SIGNED internal static class AssemblyInfo { public const string PublicKey = ", PublicKey=002400000480000094000000060200000024000052534131000400000100010051C1562A090FB0C9F391012A32198B5E5D9A60E9B80FA2D7B434C9E5CCB7259BD606E66F9660676AFC6692B8CDC6793D190904551D2103B7B22FA636DCBB8208839785BA402EA08FC00C8F1500CCEF28BBF599AA64FFB1E1D5DC1BF3420A3777BADFE697856E9D52070A50C3EA5821C80BEF17CA3ACFFA28F89DD413F096F898"; public const string MoqPublicKey = ", PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7"; public const string BenchmarksPublicKey = ", PublicKey=002400000480000094000000060200000024000052534131000400000100010051c1562a090fb0c9f391012a32198b5e5d9a60e9b80fa2d7b434c9e5ccb7259bd606e66f9660676afc6692b8cdc6793d190904551d2103b7b22fa636dcbb8208839785ba402ea08fc00c8f1500ccef28bbf599aa64ffb1e1d5dc1bf3420a3777badfe697856e9d52070a50c3ea5821c80bef17ca3acffa28f89dd413f096f898"; } #else internal static class AssemblyInfo { public const string PublicKey = ""; public const string MoqPublicKey = ""; public const string BenchmarksPublicKey = ""; } #endif
apache-2.0
C#
ddbc71ab3a398214a932ed4ceeee8090f102b62b
Format the build script
DuFF14/OSVR-Unity,JeroMiya/OSVR-Unity,grobm/OSVR-Unity,grobm/OSVR-Unity,OSVR/OSVR-Unity
OSVR-Unity/Assets/Editor/OSVRUnityBuild.cs
OSVR-Unity/Assets/Editor/OSVRUnityBuild.cs
using UnityEditor; using System.Collections; public class OSVRUnityBuild { static void build() { string[] assets = { "Assets/OSVRUnity", "Assets/Plugins" }; AssetDatabase.ExportPackage(assets, "OSVR-Unity.unitypackage", ExportPackageOptions.IncludeDependencies | ExportPackageOptions.Recurse); } }
using UnityEditor; using System.Collections; public class OSVRUnityBuild { static void build() { string[] assets = { "Assets/OSVRUnity", "Assets/Plugins" }; AssetDatabase.ExportPackage(assets, "OSVR-Unity.unitypackage", ExportPackageOptions.IncludeDependencies | ExportPackageOptions.Recurse); } }
apache-2.0
C#
41c6981d12798538c6e12600ccc6ba52c2f3a32d
更新版本2.2.2.34
Laforeta/KanColleCacher,hakuame/KanColleCacher,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.2.2.34"; 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.2.1.31"; 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#
1b87767472bea0910e6dd34f5749a98e6f48c90e
Fix bug in test where key value was not being set.
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/MusicStore.Test/GenreMenuComponentTest.cs
test/MusicStore.Test/GenreMenuComponentTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc.ViewComponents; using Microsoft.Data.Entity; using Microsoft.Extensions.DependencyInjection; using MusicStore.Models; using Xunit; namespace MusicStore.Components { public class GenreMenuComponentTest { private readonly IServiceProvider _serviceProvider; public GenreMenuComponentTest() { var services = new ServiceCollection(); services.AddEntityFramework() .AddInMemoryDatabase() .AddDbContext<MusicStoreContext>(options => options.UseInMemoryDatabase()); _serviceProvider = services.BuildServiceProvider(); } [Fact] public async Task GenreMenuComponent_Returns_NineGenres() { // Arrange var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>(); var genreMenuComponent = new GenreMenuComponent(dbContext); PopulateData(dbContext); // Act var result = await genreMenuComponent.InvokeAsync(); // Assert Assert.NotNull(result); var viewResult = Assert.IsType<ViewViewComponentResult>(result); Assert.Null(viewResult.ViewName); var genreResult = Assert.IsType<List<Genre>>(viewResult.ViewData.Model); Assert.Equal(9, genreResult.Count); } private static void PopulateData(MusicStoreContext context) { var genres = Enumerable.Range(1, 10).Select(n => new Genre { GenreId = n }); context.AddRange(genres); context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc.ViewComponents; using Microsoft.Data.Entity; using Microsoft.Extensions.DependencyInjection; using MusicStore.Models; using Xunit; namespace MusicStore.Components { public class GenreMenuComponentTest { private readonly IServiceProvider _serviceProvider; public GenreMenuComponentTest() { var services = new ServiceCollection(); services.AddEntityFramework() .AddInMemoryDatabase() .AddDbContext<MusicStoreContext>(options => options.UseInMemoryDatabase()); _serviceProvider = services.BuildServiceProvider(); } [Fact] public async Task GenreMenuComponent_Returns_NineGenres() { // Arrange var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>(); var genreMenuComponent = new GenreMenuComponent(dbContext); PopulateData(dbContext); // Act var result = await genreMenuComponent.InvokeAsync(); // Assert Assert.NotNull(result); var viewResult = Assert.IsType<ViewViewComponentResult>(result); Assert.Null(viewResult.ViewName); var genreResult = Assert.IsType<List<Genre>>(viewResult.ViewData.Model); Assert.Equal(9, genreResult.Count); } private static void PopulateData(MusicStoreContext context) { var genres = Enumerable.Range(1, 10).Select(n => new Genre()); context.AddRange(genres); context.SaveChanges(); } } }
apache-2.0
C#
536ad8ee256c50cf7ec44c941c1e55504b58905b
Fix DebuggerExtensions (#84)
nanoframework/nf-debugger,Eclo/nf-debugger
source/nanoFramework.Tools.DebugLibrary.Shared/Extensions/DebuggerExtensions.cs
source/nanoFramework.Tools.DebugLibrary.Shared/Extensions/DebuggerExtensions.cs
// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // using System.Threading.Tasks; namespace nanoFramework.Tools.Debugger.Extensions { public static class DebuggerExtensions { /// <summary> /// Check if device is in initialized state. /// </summary> /// <param name="debugEngine"></param> /// <returns></returns> public static async Task<bool> IsDeviceInInitializeStateAsync(this Engine debugEngine) { var result = await debugEngine.SetExecutionModeAsync(0, 0); if (result.success) { var currentState = (result.currentExecutionMode & WireProtocol.Commands.Debugging_Execution_ChangeConditions.c_State_Mask); return (currentState == WireProtocol.Commands.Debugging_Execution_ChangeConditions.c_State_Initialize); } else { return false; } } /// <summary> /// Check if device execution state is: program exited. /// </summary> /// <param name="debugEngine"></param> /// <returns></returns> public static async Task<bool> IsDeviceInExitedStateAsync(this Engine debugEngine) { var result = await debugEngine.SetExecutionModeAsync(0, 0); if (result.success) { var currentState = (result.currentExecutionMode & WireProtocol.Commands.Debugging_Execution_ChangeConditions.c_State_Mask); return (currentState == WireProtocol.Commands.Debugging_Execution_ChangeConditions.c_State_ProgramExited); } else { return false; } } } }
// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // using System.Threading.Tasks; namespace nanoFramework.Tools.Debugger.Extensions { public static class DebuggerExtensions { /// <summary> /// Check if device is in initialized state. /// </summary> /// <param name="debugEngine"></param> /// <returns></returns> public static async Task<bool> IsDeviceInInitializeStateAsync(this Engine debugEngine) { var result = await debugEngine.SetExecutionModeAsync(0, 0); if (result.success) { var currentState = (result.currentExecutionMode & WireProtocol.Commands.Debugging_Execution_ChangeConditions.c_State_Mask); return (currentState != WireProtocol.Commands.Debugging_Execution_ChangeConditions.c_State_Initialize); } else { return false; } } /// <summary> /// Check if device execution state is: program exited. /// </summary> /// <param name="debugEngine"></param> /// <returns></returns> public static async Task<bool> IsDeviceInExitedStateAsync(this Engine debugEngine) { var result = await debugEngine.SetExecutionModeAsync(0, 0); if (result.success) { var currentState = (result.currentExecutionMode & WireProtocol.Commands.Debugging_Execution_ChangeConditions.c_State_Mask); return (currentState != WireProtocol.Commands.Debugging_Execution_ChangeConditions.c_State_ProgramExited); } else { return false; } } } }
mit
C#
d4759c3d1f2aeb8686cc02014a3a4f9e4c701b31
Remove comments
Cimpress-MCP/serilog-sinks-awscloudwatch
src/Serilog.Sinks.AwsCloudWatch/LogStreamNameProvider/ILogStreamNameProvider.cs
src/Serilog.Sinks.AwsCloudWatch/LogStreamNameProvider/ILogStreamNameProvider.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Serilog.Sinks.AwsCloudWatch { public interface ILogStreamNameProvider { /// <summary> /// Gets the log stream name. /// </summary> /// <returns></returns> string GetLogStreamName(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Serilog.Sinks.AwsCloudWatch { /// <summary> /// /// </summary> public interface ILogStreamNameProvider { /// <summary> /// Gets the log stream name. /// </summary> /// <returns></returns> string GetLogStreamName(); } }
apache-2.0
C#
b76c0cd5bd014362e1578ba652f3c3737467f117
Work on keyword completion.
rsdn/nitra,rsdn/nitra,JetBrains/Nitra,JetBrains/Nitra
Nitra.Visualizer/LiteralCompletionData.cs
Nitra.Visualizer/LiteralCompletionData.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ICSharpCode.AvalonEdit.CodeCompletion; using ICSharpCode.AvalonEdit.Document; using ICSharpCode.AvalonEdit.Editing; namespace Nitra.Visualizer { class LiteralCompletionData : ICompletionData { public NSpan Span { get; private set; } public LiteralCompletionData(NSpan span, string text) { this.Span = span; this.Text = text; } public System.Windows.Media.ImageSource Image { get { return null; } } public string Text { get; private set; } // Use this property if you want to show a fancy UIElement in the list. public object Content { get { return this.Text; } } public object Description { get { return "Description for " + this.Text; } } public double Priority { get { return 0.0; } } public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { var line = textArea.Document.GetLineByOffset(Span.EndPos); var lineText = textArea.Document.GetText(line); var end = Span.EndPos - line.Offset; for (; end < lineText.Length; end++) { var ch = lineText[end]; if (!char.IsLetterOrDigit(ch)) break; } textArea.Document.Replace(Span.StartPos, end + line.Offset - Span.StartPos, this.Text); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ICSharpCode.AvalonEdit.CodeCompletion; using ICSharpCode.AvalonEdit.Document; using ICSharpCode.AvalonEdit.Editing; namespace Nitra.Visualizer { class LiteralCompletionData : ICompletionData { public NSpan Span { get; private set; } public LiteralCompletionData(NSpan span, string text) { this.Span = span; this.Text = text; } public System.Windows.Media.ImageSource Image { get { return null; } } public string Text { get; private set; } // Use this property if you want to show a fancy UIElement in the list. public object Content { get { return this.Text; } } public object Description { get { return "Description for " + this.Text; } } public double Priority { get { return 0.0; } } public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(Span.StartPos, Span.Length, this.Text); } } }
apache-2.0
C#
a8ada2f5d9463afea789b567fd6b2b3862903824
Make RecordTokenToStringAdapter.ToString return empty string instead of Null.
mccarthyrb/libpalaso,chrisvire/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso,marksvc/libpalaso,sillsdev/libpalaso,mccarthyrb/libpalaso,mccarthyrb/libpalaso,tombogle/libpalaso,hatton/libpalaso,gmartin7/libpalaso,marksvc/libpalaso,JohnThomson/libpalaso,hatton/libpalaso,andrew-polk/libpalaso,darcywong00/libpalaso,JohnThomson/libpalaso,glasseyes/libpalaso,chrisvire/libpalaso,glasseyes/libpalaso,chrisvire/libpalaso,ermshiperete/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,gmartin7/libpalaso,ddaspit/libpalaso,glasseyes/libpalaso,andrew-polk/libpalaso,marksvc/libpalaso,tombogle/libpalaso,gtryus/libpalaso,ddaspit/libpalaso,sillsdev/libpalaso,gtryus/libpalaso,ermshiperete/libpalaso,chrisvire/libpalaso,JohnThomson/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,andrew-polk/libpalaso,ddaspit/libpalaso,hatton/libpalaso,darcywong00/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,JohnThomson/libpalaso,sillsdev/libpalaso,gmartin7/libpalaso,darcywong00/libpalaso,ddaspit/libpalaso,hatton/libpalaso,ermshiperete/libpalaso,gtryus/libpalaso
Palaso/Data/RecordTokenToStringAdapter.cs
Palaso/Data/RecordTokenToStringAdapter.cs
namespace Palaso.Data { public class RecordTokenToStringAdapter<T> where T:class, new() { private RecordToken<T> _recordToken = null; private string _fieldToShow = null; public RecordTokenToStringAdapter(string fieldToShow, RecordToken<T> recordToken) { _recordToken = recordToken; _fieldToShow = fieldToShow; } public RecordToken<T> AdaptedRecordToken { get { return _recordToken; } } public override string ToString() { var s = (string) AdaptedRecordToken[_fieldToShow]; if(s==null) return string.Empty; //WinForms things that expect a string can give pretty useless errors when given null (e.g. list view) return s; } } }
namespace Palaso.Data { public class RecordTokenToStringAdapter<T> where T:class, new() { private RecordToken<T> _recordToken = null; private string _fieldToShow = null; public RecordTokenToStringAdapter(string fieldToShow, RecordToken<T> recordToken) { _recordToken = recordToken; _fieldToShow = fieldToShow; } public RecordToken<T> AdaptedRecordToken { get { return _recordToken; } } public override string ToString() { return (string) AdaptedRecordToken[_fieldToShow]; } } }
mit
C#
1b92322fabbe17ac2a824039009a1a5c304e19eb
Fix regression & enable ClearInitLocals in System.Text.RegularExpressions (#27146)
gregkalapos/corert,gregkalapos/corert,gregkalapos/corert,gregkalapos/corert
src/System.Private.CoreLib/shared/System/Collections/Generic/ValueListBuilder.cs
src/System.Private.CoreLib/shared/System/Collections/Generic/ValueListBuilder.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. using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Collections.Generic { internal ref partial struct ValueListBuilder<T> { private Span<T> _span; private T[] _arrayFromPool; private int _pos; public ValueListBuilder(Span<T> initialSpan) { _span = initialSpan; _arrayFromPool = null; _pos = 0; } public int Length => _pos; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(T item) { int pos = _pos; if (pos >= _span.Length) Grow(); _span[pos] = item; _pos = pos + 1; } public ReadOnlySpan<T> AsReadOnlySpan() { return _span.Slice(0, _pos); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { if (_arrayFromPool != null) { ArrayPool<T>.Shared.Return(_arrayFromPool); _arrayFromPool = null; } } private void Grow() { T[] array = ArrayPool<T>.Shared.Rent(_span.Length * 2); bool success = _span.TryCopyTo(array); Debug.Assert(success); T[] toReturn = _arrayFromPool; _span = _arrayFromPool = array; if (toReturn != null) { ArrayPool<T>.Shared.Return(toReturn); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Collections.Generic { internal ref struct ValueListBuilder<T> { private Span<T> _span; private T[] _arrayFromPool; private int _pos; public ValueListBuilder(Span<T> initialSpan) { _span = initialSpan; _arrayFromPool = null; _pos = 0; } public int Length => _pos; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(T item) { int pos = _pos; if (pos >= _span.Length) Grow(); _span[pos] = item; _pos = pos + 1; } public ReadOnlySpan<T> AsReadOnlySpan() { return _span.Slice(0, _pos); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { if (_arrayFromPool != null) { ArrayPool<T>.Shared.Return(_arrayFromPool); _arrayFromPool = null; } } private void Grow() { T[] array = ArrayPool<T>.Shared.Rent(_span.Length * 2); bool success = _span.TryCopyTo(array); Debug.Assert(success); T[] toReturn = _arrayFromPool; _span = _arrayFromPool = array; if (toReturn != null) { ArrayPool<T>.Shared.Return(toReturn); } } } }
mit
C#
1873bf244f5159294769a83cf66a98003f0ce841
Rewrite and make it public for use in server.
AIWolfSharp/AIWolf_NET
AIWolfLib/DataConverter.cs
AIWolfLib/DataConverter.cs
// // DataConverter.cs // // Copyright (c) 2016 Takashi OTSUKI // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using System; using System.Linq; using System.Collections.Generic; namespace AIWolf.Lib { /// <summary> /// Encodes object and decodes packet string. /// </summary> public static class DataConverter { static JsonSerializerSettings serializerSetting; /// <summary> /// Initializes this class. /// </summary> static DataConverter() { serializerSetting = new JsonSerializerSettings() { // Sort. ContractResolver = new OrderedContractResolver() }; // Do not convert enum into integer. serializerSetting.Converters.Add(new StringEnumConverter()); } /// <summary> /// Serializes the given object into the JSON string. /// </summary> /// <param name="obj">The object to be serialized.</param> /// <returns>The JSON string serialized from the given object.</returns> public static string Serialize(object obj) => JsonConvert.SerializeObject(obj, serializerSetting); /// <summary> /// Deserializes the given JSON string into the object of type T. /// </summary> /// <typeparam name="T">The type of object returned.</typeparam> /// <param name="json">The JSON string to be deserialized.</param> /// <returns>The object of type T deserialized from the JSON string.</returns> public static T Deserialize<T>(string json) => JsonConvert.DeserializeObject<T>(json, serializerSetting); class OrderedContractResolver : DefaultContractResolver { protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) => base.CreateProperties(type, memberSerialization).OrderBy(p => p.PropertyName).ToList(); } } }
// // DataConverter.cs // // Copyright (c) 2016 Takashi OTSUKI // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using System.Linq; namespace AIWolf.Lib { /// <summary> /// Encodes object and decodes packet string. /// </summary> static class DataConverter { static JsonSerializerSettings serializerSetting; /// <summary> /// Initializes this class. /// </summary> static DataConverter() { serializerSetting = new JsonSerializerSettings(); // Sort. serializerSetting.ContractResolver = new OrderedContractResolver(); // Do not convert enum into integer. serializerSetting.Converters.Add(new StringEnumConverter()); } /// <summary> /// Serializes the given object into the JSON string. /// </summary> /// <param name="obj">The object to be serialized.</param> /// <returns>The JSON string serialized from the given object.</returns> public static string Serialize(object obj) { return JsonConvert.SerializeObject(obj, serializerSetting); } /// <summary> /// Deserializes the given JSON string into the object of type T. /// </summary> /// <typeparam name="T">The type of object returned.</typeparam> /// <param name="json">The JSON string to be deserialized.</param> /// <returns>The object of type T deserialized from the JSON string.</returns> public static T Deserialize<T>(string json) { return (T)JsonConvert.DeserializeObject<T>(json, serializerSetting); } class OrderedContractResolver : DefaultContractResolver { protected override System.Collections.Generic.IList<JsonProperty> CreateProperties(System.Type type, MemberSerialization memberSerialization) { return base.CreateProperties(type, memberSerialization).OrderBy(p => p.PropertyName).ToList(); } } } }
mit
C#
54968bb2bc856925371547a908a2e77c2b001a36
remove whitespace
thyn/haproxy-api
HaProxyApi.Client/Parsers/ShowErrorParser.cs
HaProxyApi.Client/Parsers/ShowErrorParser.cs
using System; using System.Globalization; using System.Text.RegularExpressions; using HAProxyApi.Client.Models; namespace HAProxyApi.Client.Parsers { public class ShowErrorParser { public IShowErrorResponse Parse(string rawShowErrorResult) { var result = new ShowErrorResponse() { Raw = rawShowErrorResult, }; if (!string.IsNullOrEmpty(rawShowErrorResult)) { var match = Regex.Match(rawShowErrorResult, @"Total events captured on \[(?<date>.+)\].+: (?<total>\d+)", RegexOptions.Multiline); if (match.Success) { result.CapturedOn = DateTime.ParseExact(match.Groups["date"].Value, @"dd/MMM/yyyy:HH:mm:ss.fff", CultureInfo.InvariantCulture); result.TotalEvents = Int32.Parse(match.Groups["total"].Value); } } return result; } } }
using System; using System.Globalization; using System.Text.RegularExpressions; using HAProxyApi.Client.Models; namespace HAProxyApi.Client.Parsers { public class ShowErrorParser { public IShowErrorResponse Parse(string rawShowErrorResult) { var result = new ShowErrorResponse() { Raw = rawShowErrorResult, }; if (!string.IsNullOrEmpty(rawShowErrorResult)) { var match = Regex.Match(rawShowErrorResult, @" Total events captured on \[(?<date>.+)\].+: (?<total>\d+)", RegexOptions.Multiline); if (match.Success) { result.CapturedOn = DateTime.ParseExact(match.Groups["date"].Value, @"dd/MMM/yyyy:HH:mm:ss.fff", CultureInfo.InvariantCulture); result.TotalEvents = Int32.Parse(match.Groups["total"].Value); } } return result; } } }
mit
C#
daa3803956ce5eb5de911845da274f6f841fcdb9
Add assert
DinoV/azure-sdk-tools,markcowl/azure-sdk-tools,akromm/azure-sdk-tools,Madhukarc/azure-sdk-tools,DinoV/azure-sdk-tools,Madhukarc/azure-sdk-tools,akromm/azure-sdk-tools,DinoV/azure-sdk-tools,markcowl/azure-sdk-tools,akromm/azure-sdk-tools,markcowl/azure-sdk-tools,akromm/azure-sdk-tools,DinoV/azure-sdk-tools,Madhukarc/azure-sdk-tools,DinoV/azure-sdk-tools,markcowl/azure-sdk-tools,Madhukarc/azure-sdk-tools,akromm/azure-sdk-tools,markcowl/azure-sdk-tools,Madhukarc/azure-sdk-tools
WindowsAzurePowershell/src/Management.Test/CloudService/Utilities/GeneralTests.cs
WindowsAzurePowershell/src/Management.Test/CloudService/Utilities/GeneralTests.cs
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.Test.CloudService.Utilities { using System; using System.IO; using Microsoft.WindowsAzure.Management.Test.Utilities.Common; using Microsoft.WindowsAzure.Management.Utilities.CloudService; using Microsoft.WindowsAzure.Management.Utilities.Common; using Microsoft.WindowsAzure.Management.Utilities.Common.XmlSchema.ServiceDefinitionSchema; using VisualStudio.TestTools.UnitTesting; [TestClass] public class GeneralTests : TestBase { [TestMethod] public void SerializationTestWithGB18030() { // Setup string outputFileName = "outputFile.txt"; ServiceDefinition serviceDefinition = General.DeserializeXmlFile<ServiceDefinition>( Testing.GetTestResourcePath("GB18030ServiceDefinition.csdef")); // Test File.Create(outputFileName).Close(); General.SerializeXmlFile<ServiceDefinition>(serviceDefinition, outputFileName); // Assert // If reached this point means the test passed Assert.IsTrue(true); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.Test.CloudService.Utilities { using System; using System.IO; using Microsoft.WindowsAzure.Management.Test.Utilities.Common; using Microsoft.WindowsAzure.Management.Utilities.CloudService; using Microsoft.WindowsAzure.Management.Utilities.Common; using Microsoft.WindowsAzure.Management.Utilities.Common.XmlSchema.ServiceDefinitionSchema; using VisualStudio.TestTools.UnitTesting; [TestClass] public class GeneralTests : TestBase { [TestMethod] public void SerializationTestWithGB18030() { // Setup string outputFileName = "outputFile.txt"; ServiceDefinition serviceDefinition = General.DeserializeXmlFile<ServiceDefinition>( Testing.GetTestResourcePath("GB18030ServiceDefinition.csdef")); // Test File.Create(outputFileName).Close(); General.SerializeXmlFile<ServiceDefinition>(serviceDefinition, outputFileName); } } }
apache-2.0
C#
c40dd91e966fb3c7f372d4e263ac7ae4bff0fd40
Fix bug with range.
tiagomartines11/ggj17
Assets/Scripts/Launcher.cs
Assets/Scripts/Launcher.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Launcher : MonoBehaviour { public int[] projectileAngles; public float aimDistance = 3; float activeAngle = 0.0f; private PointBehaviour point; public float angularSpeed = 2.0f; GameObject aimContainer; // Use this for initialization void Start () { ///save references point = gameObject.GetComponent<PointBehaviour>(); ///code activeAngle = 0; aimContainer = new GameObject (); foreach (int angle in projectileAngles) { GameObject container = new GameObject (); GameObject instance = Instantiate (Resources.Load ("aimprefab", typeof(GameObject))) as GameObject; instance.transform.parent = container.transform; container.transform.parent = aimContainer.transform; container.transform.localPosition = new Vector3 (0, 0, 0); Quaternion rot = new Quaternion (); rot.eulerAngles = new Vector3 (0, 0, angle); container.transform.rotation = rot; instance.transform.localPosition = new Vector3 (aimDistance, 0, 0); } aimContainer.transform.parent = this.transform; aimContainer.transform.localPosition = new Vector3 (0, 0, 0); } void OnMouseDown(){ if (enabled && point.activated && point.Ammo > 0) { launch(); point.Ammo -= 1; } } // Update is called once per frame void Update () { if (activeAngle < 360) activeAngle += angularSpeed; else activeAngle = 0; Quaternion rot = new Quaternion (); rot.eulerAngles = new Vector3 (0, 0, activeAngle); aimContainer.transform.rotation = rot; } void OnDisable() { GameObject.Destroy(aimContainer); enabled = false; } void launch() { // Collider2D [] colliders = Physics2D.OverlapCircleAll(this.transform.position, 1f); // if(colliders.Length > 0) // { // // enemies within 1m of the player // Debug.Log(colliders.Length); // // Mathf.Sin( // }; foreach (int angle in projectileAngles) { GameObject projectile = Instantiate (Resources.Load ("Projectile", typeof(GameObject))) as GameObject; projectile.GetComponent<Projectile> ().SetupProjectile (point.Range, activeAngle + angle); projectile.transform.parent = this.transform; projectile.transform.localPosition = Vector3.zero; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Launcher : MonoBehaviour { public int[] projectileAngles; public float aimDistance = 3; float activeAngle = 0.0f; private PointBehaviour point; public float angularSpeed = 2.0f; GameObject aimContainer; // Use this for initialization void Start () { ///save references point = gameObject.GetComponent<PointBehaviour>(); ///code activeAngle = 0; aimContainer = new GameObject (); foreach (int angle in projectileAngles) { GameObject container = new GameObject (); GameObject instance = Instantiate (Resources.Load ("aimprefab", typeof(GameObject))) as GameObject; instance.transform.parent = container.transform; container.transform.parent = aimContainer.transform; container.transform.localPosition = new Vector3 (0, 0, 0); Quaternion rot = new Quaternion (); rot.eulerAngles = new Vector3 (0, 0, angle); container.transform.rotation = rot; instance.transform.localPosition = new Vector3 (1.0f, 0, 0); } aimContainer.transform.parent = this.transform; aimContainer.transform.localPosition = new Vector3 (0, 0, 0); } void OnMouseDown(){ if (point.activated && point.Ammo > 0) { launch(); point.Ammo -= 1; } } // Update is called once per frame void Update () { if (activeAngle < 360) activeAngle += angularSpeed; else activeAngle = 0; Quaternion rot = new Quaternion (); rot.eulerAngles = new Vector3 (0, 0, activeAngle); aimContainer.transform.rotation = rot; } void OnDisable() { GameObject.Destroy(aimContainer); enabled = false; } void launch() { // Collider2D [] colliders = Physics2D.OverlapCircleAll(this.transform.position, 1f); // if(colliders.Length > 0) // { // // enemies within 1m of the player // Debug.Log(colliders.Length); // // Mathf.Sin( // }; foreach (int angle in projectileAngles) { GameObject projectile = Instantiate (Resources.Load ("Projectile", typeof(GameObject))) as GameObject; projectile.GetComponent<Projectile> ().SetupProjectile (aimDistance, activeAngle + angle); projectile.transform.parent = this.transform; projectile.transform.localPosition = Vector3.zero; } } }
apache-2.0
C#
170575d4e285c64d8ce04d660c42c397889bba82
バージョン番号を更新、年号を更新、不要な参照を削除。
t-miyake/OutlookOkan
SetupCustomAction/Properties/AssemblyInfo.cs
SetupCustomAction/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("SetupCustomAction")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Noraneko Inc.")] [assembly: AssemblyProduct("SetupCustomAction")] [assembly: AssemblyCopyright("Copyright © Noraneko Inc. 2021")] [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("de0ddc03-116b-4e2c-af47-9f06fd99d391")] // 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.1.0.0")] [assembly: AssemblyFileVersion("1.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("SetupCustomAction")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Noraneko Inc.")] [assembly: AssemblyProduct("SetupCustomAction")] [assembly: AssemblyCopyright("Copyright © Noraneko Inc. 2020")] [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("de0ddc03-116b-4e2c-af47-9f06fd99d391")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
30870882fdccb4837ebf903647aab8abd05d524e
Set ContentLength in ConnectResponse explicitly to properly handle HTTP 1.0
titanium007/Titanium-Web-Proxy,justcoding121/Titanium-Web-Proxy,titanium007/Titanium
Titanium.Web.Proxy/Http/ConnectResponse.cs
Titanium.Web.Proxy/Http/ConnectResponse.cs
using StreamExtended; using System; using System.Net; namespace Titanium.Web.Proxy.Http { public class ConnectResponse : Response { public ServerHelloInfo ServerHelloInfo { get; set; } /// <summary> /// Creates a successfull CONNECT response /// </summary> /// <param name="httpVersion"></param> /// <returns></returns> internal static ConnectResponse CreateSuccessfullConnectResponse(Version httpVersion) { var response = new ConnectResponse { HttpVersion = httpVersion, StatusCode = (int)HttpStatusCode.OK, StatusDescription = "Connection Established" }; // Set ContentLength explicitly to properly handle HTTP 1.0 response.ContentLength = 0; return response; } } }
using StreamExtended; using System; using System.Net; namespace Titanium.Web.Proxy.Http { public class ConnectResponse : Response { public ServerHelloInfo ServerHelloInfo { get; set; } /// <summary> /// Creates a successfull CONNECT response /// </summary> /// <param name="httpVersion"></param> /// <returns></returns> internal static ConnectResponse CreateSuccessfullConnectResponse(Version httpVersion) { var response = new ConnectResponse { HttpVersion = httpVersion, StatusCode = (int)HttpStatusCode.OK, StatusDescription = "Connection Established" }; return response; } } }
mit
C#
e10fc48a6568482e41c0c3c7dcffd0ede5cc93c7
Remove some trash
vostok/core
Vostok.Core/Metrics/MetricConfiguration.cs
Vostok.Core/Metrics/MetricConfiguration.cs
using System; using System.Collections.Generic; using Vostok.Commons.Collections; namespace Vostok.Metrics { public class MetricConfiguration : IMetricConfiguration { public IMetricEventReporter Reporter { get; set; } public ISet<string> ContextFieldsWhitelist { get; } = new ConcurrentSet<string>(StringComparer.Ordinal); } }
using System; using System.Collections.Generic; using Vostok.Commons.Collections; namespace Vostok.Metrics { public class MetricConfiguration : IMetricConfiguration { public IMetricEventReporter Reporter { get; set; } public string Environment { get; set; } public ISet<string> ContextFieldsWhitelist { get; } = new ConcurrentSet<string>(StringComparer.Ordinal); } }
mit
C#
2250ac23063cb2f644818ca8a307482d3dde8f84
update version num
KevinWG/OS.Social,KevinWG/OSS.Social
WX/OS.Social.WX/Properties/AssemblyInfo.cs
WX/OS.Social.WX/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("OS.Social.WX")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OS.Social.WX")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("d9f2075e-8fdc-4734-b2cb-02399f982867")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.8.2.0")] [assembly: AssemblyFileVersion("0.8.2.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("OS.Social.WX")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OS.Social.WX")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("d9f2075e-8fdc-4734-b2cb-02399f982867")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
8eaf8dd0337c60f0f4caac337ea051bfafe227df
Add `OptionExtensions.Invoke`
Weingartner/SolidworksAddinFramework
SolidworksAddinFramework/OptionExtensions.cs
SolidworksAddinFramework/OptionExtensions.cs
using System; using System.Collections.Generic; using System.Collections.Immutable; using LanguageExt; using static LanguageExt.Prelude; namespace SolidworksAddinFramework { public static class OptionExtensions { /// <summary> /// Get the value from an option. If it is none /// then a null reference exception will be raised. /// Don't use this in production please. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="option"></param> /// <returns></returns> public static T __Value__<T>(this Option<T> option) { return option.Match (v => v , () => { throw new NullReferenceException(); }); } public static Option<ImmutableList<T>> Sequence<T>(this IEnumerable<Option<T>> p) { return p.Fold( Prelude.Optional(ImmutableList<T>.Empty), (state, itemOpt) => from item in itemOpt from list in state select list.Add(item)); } /// <summary> /// Invokes the action if it is there. /// </summary> /// <param name="a"></param> public static void Invoke(this Option<Action> a) { a.IfSome(fn => fn()); } /// <summary> /// Fluent version Optional /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static Option<T> ToOption<T>(this T obj) { return Optional(obj); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using LanguageExt; using static LanguageExt.Prelude; namespace SolidworksAddinFramework { public static class OptionExtensions { /// <summary> /// Get the value from an option. If it is none /// then a null reference exception will be raised. /// Don't use this in production please. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="option"></param> /// <returns></returns> public static T __Value__<T>(this Option<T> option) { return option.Match (v => v , () => { throw new NullReferenceException(); }); } public static Option<ImmutableList<T>> Sequence<T>(this IEnumerable<Option<T>> p) { return p.Fold( Prelude.Optional(ImmutableList<T>.Empty), (state, itemOpt) => from item in itemOpt from list in state select list.Add(item)); } /// <summary> /// Fluent version Optional /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static Option<T> ToOption<T>(this T obj) { return Optional(obj); } } }
mit
C#
7f6e6f5a08d2d9d8287c5594b1f9e9956b6f1d24
Use type filtering when searching matching content for BestBets
SergVro/FindExportImport,SergVro/FindExportImport,SergVro/FindExportImport
Vro.FindExportImport/Stores/SearchService.cs
Vro.FindExportImport/Stores/SearchService.cs
using System; using System.Linq; using EPiServer; using EPiServer.Core; using EPiServer.Find; using EPiServer.Find.Framework; using EPiServer.ServiceLocation; using Vro.FindExportImport.Models; namespace Vro.FindExportImport.Stores { public interface ISearchService { ContentReference FindMatchingContent(BestBetEntity bestBetEntity); } [ServiceConfiguration(typeof(ISearchService))] public class SearchService : ISearchService { public ContentReference FindMatchingContent(BestBetEntity bestBetEntity) { var searchQuery = SearchClient.Instance .Search<IContent>() .Filter(x => x.Name.Match(bestBetEntity.TargetName)); if (bestBetEntity.TargetType.Equals(Helpers.PageBestBetSelector)) { searchQuery = searchQuery.Filter(x => x.MatchTypeHierarchy(typeof(PageData))); } else if (bestBetEntity.TargetType.Equals(Helpers.CommerceBestBetSelector)) { // resolving type from string to avoid referencing Commerce assemblies var commerceCatalogEntryType = Type.GetType("EPiServer.Commerce.Catalog.ContentTypes.EntryContentBase, EPiServer.Business.Commerce"); searchQuery = searchQuery.Filter(x => x.MatchTypeHierarchy(commerceCatalogEntryType)); } var searchResults = searchQuery.Select(c => c.ContentLink).Take(1).GetResult(); return searchResults.Hits.FirstOrDefault()?.Document; } } }
using System.Linq; using EPiServer.Core; using EPiServer.Find; using EPiServer.Find.Framework; using EPiServer.ServiceLocation; using Vro.FindExportImport.Models; namespace Vro.FindExportImport.Stores { public interface ISearchService { ContentReference FindMatchingContent(BestBetEntity bestBetEntity); } [ServiceConfiguration(typeof(ISearchService))] public class SearchService : ISearchService { public ContentReference FindMatchingContent(BestBetEntity bestBetEntity) { var searchQuery = SearchClient.Instance .Search<IContent>() .Filter(x => x.Name.Match(bestBetEntity.TargetName)); if (bestBetEntity.TargetType.Equals(Helpers.PageBestBetSelector)) { searchQuery = searchQuery.Filter(x => !x.ContentLink.ProviderName.Exists()); } else if (bestBetEntity.TargetType.Equals(Helpers.CommerceBestBetSelector)) { searchQuery = searchQuery.Filter(x => x.ContentLink.ProviderName.Match("CatalogContent")); } var searchResults = searchQuery.Select(c => c.ContentLink).Take(1).GetResult(); return searchResults.Hits.FirstOrDefault()?.Document; } } }
mit
C#
2add8f2eed378f9b137e420228b1d5762bcaabb0
Add class attribute.
dougludlow/umbraco-navbuilder,dougludlow/umbraco-navbuilder
src/Cob.Umb.NavBuilder/NavNodeTraverser.cs
src/Cob.Umb.NavBuilder/NavNodeTraverser.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace Cob.Umb.NavBuilder { class NavNodeTraverser { private NavNode root; public NavNodeTraverser(NavNode root) { this.root = root; } public string Traverse() { return Traverse(this.root); } private string Traverse(NavNode node) { StringBuilder menu = new StringBuilder(); if (node.IsTraverseable) { menu.Append(string.Format("<ul{0}>", GetRootCssClasses(node))); foreach (var child in node.Children) { string name = HttpUtility.HtmlEncode(child.Name); string nameOrImage = (child.HasImage) ? string.Format("<img src=\"{0}\" alt=\"{1}\" />", child.Image, name) : name; string classes = (child.CssClasses == "") ? "" : string.Format(" class=\"{0}\"", child.CssClasses); string target = (child.HasTarget) ? string.Format(" target=\"{0}\"", child.Target) : ""; menu.Append(string.Format("<li{0}><a href=\"{1}\"{2}>{3}</a>", classes, child.Url, target, nameOrImage)); menu.Append(Traverse(child)); menu.Append("</li>"); } menu.Append("</ul>"); } return menu.ToString(); } private string GetRootCssClasses(NavNode node) { return node.Options.RootCssClasses.Count > 0 ? string.Format(" class=\"{0}\"", string.Join(" ", node.Options.RootCssClasses)) : ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace Cob.Umb.NavBuilder { class NavNodeTraverser { private NavNode root; public NavNodeTraverser(NavNode root) { this.root = root; } public string Traverse() { return Traverse(this.root); } private string Traverse(NavNode node) { StringBuilder menu = new StringBuilder(); if (node.IsTraverseable) { menu.Append(string.Format("<ul{0}>", GetRootCssClasses(node))); foreach (var child in node.Children) { string name = HttpUtility.HtmlEncode(child.Name); string nameOrImage = (child.HasImage) ? string.Format("<img src=\"{0}\" alt=\"{1}\" />", child.Image, name) : name; string classes = (child.CssClasses == "") ? "" : string.Format(" class=\"{0}\"", child.CssClasses); string target = (child.HasTarget) ? string.Format(" target=\"{0}\"", child.Target) : ""; menu.Append(string.Format("<li{0}><a href=\"{1}\"{2}>{3}</a>", classes, child.Url, target, nameOrImage)); menu.Append(Traverse(child)); menu.Append("</li>"); } menu.Append("</ul>"); } return menu.ToString(); } private string GetRootCssClasses(NavNode node) { return node.Options.RootCssClasses.Count > 0 ? " " + string.Join(" ", node.Options.RootCssClasses) : ""; } } }
mit
C#
8071ed8bc03b6619dafc1c35f68e8e74e49d6916
update version to 1.5.1.0
todor-dk/HTML-Renderer,windygu/HTML-Renderer,tinygg/graphic-HTML-Renderer,windygu/HTML-Renderer,slagou/HTML-Renderer,drickert5/HTML-Renderer,ArthurHub/HTML-Renderer,evitself/HTML-Renderer,todor-dk/HTML-Renderer,evitself/HTML-Renderer,tinygg/graphic-HTML-Renderer,Perspex/HTML-Renderer,drickert5/HTML-Renderer,verdesgrobert/HTML-Renderer,todor-dk/HTML-Renderer,ArthurHub/HTML-Renderer,Perspex/HTML-Renderer,verdesgrobert/HTML-Renderer,slagou/HTML-Renderer,tinygg/graphic-HTML-Renderer
Source/SharedAssemblyInfo.cs
Source/SharedAssemblyInfo.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("HTML Renderer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Open source hosted on CodePlex")] [assembly: AssemblyProduct("HTML Renderer")] [assembly: AssemblyCopyright("Copyright © 2008")] [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("ec8a9e7e-9a9d-43c3-aa97-f6f505b1d3ed")] // Version information for an assembly consists of the following four values: [assembly: AssemblyVersion("1.5.1.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("HTML Renderer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Open source hosted on CodePlex")] [assembly: AssemblyProduct("HTML Renderer")] [assembly: AssemblyCopyright("Copyright © 2008")] [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("ec8a9e7e-9a9d-43c3-aa97-f6f505b1d3ed")] // Version information for an assembly consists of the following four values: [assembly: AssemblyVersion("1.5.0.5")]
bsd-3-clause
C#
e2bac7171a282de238c699093986a35ea1e3c5f2
Add null check to RefSpec
GitTools/GitVersion,GitTools/GitVersion,asbjornu/GitVersion,asbjornu/GitVersion,gep13/GitVersion,gep13/GitVersion
src/GitVersion.LibGit2Sharp/Git/RefSpec.cs
src/GitVersion.LibGit2Sharp/Git/RefSpec.cs
using GitVersion.Extensions; using GitVersion.Helpers; namespace GitVersion; public class RefSpec : IRefSpec { private static readonly LambdaEqualityHelper<IRefSpec> equalityHelper = new(x => x.Specification); private static readonly LambdaKeyComparer<IRefSpec, string> comparerHelper = new(x => x.Specification); private readonly LibGit2Sharp.RefSpec innerRefSpec; internal RefSpec(LibGit2Sharp.RefSpec refSpec) => this.innerRefSpec = refSpec.NotNull(); public int CompareTo(IRefSpec other) => comparerHelper.Compare(this, other); public bool Equals(IRefSpec? other) => equalityHelper.Equals(this, other); public string Specification => this.innerRefSpec.Specification; public RefSpecDirection Direction => (RefSpecDirection)this.innerRefSpec.Direction; public string Source => this.innerRefSpec.Source; public string Destination => this.innerRefSpec.Destination; public override bool Equals(object obj) => Equals((obj as IRefSpec)); public override int GetHashCode() => equalityHelper.GetHashCode(this); public override string ToString() => Specification; }
using GitVersion.Helpers; namespace GitVersion; public class RefSpec : IRefSpec { private static readonly LambdaEqualityHelper<IRefSpec> equalityHelper = new(x => x.Specification); private static readonly LambdaKeyComparer<IRefSpec, string> comparerHelper = new(x => x.Specification); private readonly LibGit2Sharp.RefSpec innerRefSpec; internal RefSpec(LibGit2Sharp.RefSpec refSpec) => this.innerRefSpec = refSpec; public int CompareTo(IRefSpec other) => comparerHelper.Compare(this, other); public bool Equals(IRefSpec? other) => equalityHelper.Equals(this, other); public override bool Equals(object obj) => Equals((obj as IRefSpec)); public override int GetHashCode() => equalityHelper.GetHashCode(this); public override string ToString() => Specification; public string Specification => this.innerRefSpec.Specification; public RefSpecDirection Direction => (RefSpecDirection)this.innerRefSpec.Direction; public string Source => this.innerRefSpec.Source; public string Destination => this.innerRefSpec.Destination; }
mit
C#
62df0ec7d4c50b58a1bbcfdb2004a2bec10584de
Handle external files with File instead
naoey/osu,smoogipoo/osu,DrabWeb/osu,DrabWeb/osu,peppy/osu,NeoAdonis/osu,EVAST9919/osu,DrabWeb/osu,2yangk23/osu,naoey/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,johnneijzen/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,naoey/osu,ZLima12/osu,ZLima12/osu,peppy/osu-new,2yangk23/osu,ppy/osu,ppy/osu,peppy/osu,UselessToucan/osu,peppy/osu
osu.Game/Rulesets/Scoring/ScoreStore.cs
osu.Game/Rulesets/Scoring/ScoreStore.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.IO; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.IPC; using osu.Game.Rulesets.Scoring.Legacy; namespace osu.Game.Rulesets.Scoring { public class ScoreStore : DatabaseBackedStore, ICanAcceptFiles { private readonly Storage storage; private readonly BeatmapManager beatmaps; private readonly RulesetStore rulesets; private const string replay_folder = @"replays"; public event Action<Score> ScoreImported; // ReSharper disable once NotAccessedField.Local (we should keep a reference to this so it is not finalised) private ScoreIPCChannel ipc; public ScoreStore(Storage storage, DatabaseContextFactory factory, IIpcHost importHost = null, BeatmapManager beatmaps = null, RulesetStore rulesets = null) : base(factory) { this.storage = storage; this.beatmaps = beatmaps; this.rulesets = rulesets; if (importHost != null) ipc = new ScoreIPCChannel(importHost, this); } public string[] HandledExtensions => new[] { ".osr" }; public void Import(params string[] paths) { foreach (var path in paths) { var score = ReadReplayFile(path); if (score != null) ScoreImported?.Invoke(score); } } public Score ReadReplayFile(string replayFilename) { Stream stream; if (File.Exists(replayFilename)) { // Handle replay with File since it is outside of storage stream = File.OpenRead(replayFilename); } else if (storage.Exists(Path.Combine(replay_folder, replayFilename))) { stream = storage.GetStream(Path.Combine(replay_folder, replayFilename)); } else { Logger.Log($"Replay file {replayFilename} cannot be found", LoggingTarget.Information, LogLevel.Error); return null; } using (stream) return new DatabasedLegacyScoreParser(rulesets, beatmaps).Parse(stream); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.IO; using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.IPC; using osu.Game.Rulesets.Scoring.Legacy; namespace osu.Game.Rulesets.Scoring { public class ScoreStore : DatabaseBackedStore, ICanAcceptFiles { private readonly Storage storage; private readonly BeatmapManager beatmaps; private readonly RulesetStore rulesets; private const string replay_folder = @"replays"; public event Action<Score> ScoreImported; // ReSharper disable once NotAccessedField.Local (we should keep a reference to this so it is not finalised) private ScoreIPCChannel ipc; public ScoreStore(Storage storage, DatabaseContextFactory factory, IIpcHost importHost = null, BeatmapManager beatmaps = null, RulesetStore rulesets = null) : base(factory) { this.storage = storage; this.beatmaps = beatmaps; this.rulesets = rulesets; if (importHost != null) ipc = new ScoreIPCChannel(importHost, this); } public string[] HandledExtensions => new[] { ".osr" }; public void Import(params string[] paths) { foreach (var path in paths) { var score = ReadReplayFile(path); if (score != null) ScoreImported?.Invoke(score); } } public Score ReadReplayFile(string replayFilename) { using (Stream s = storage.GetStream(Path.Combine(replay_folder, replayFilename))) return new DatabasedLegacyScoreParser(rulesets, beatmaps).Parse(s); } } }
mit
C#
d9e222f0a94e0606f12696fd9053c48130c2b1a9
Fix MamlSyntax
PowerShell/platyPS,PowerShell/platyPS,PowerShell/platyPS
src/Markdown.MAML/Model/MAML/MamlSyntax.cs
src/Markdown.MAML/Model/MAML/MamlSyntax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Markdown.MAML.Model.MAML { public class MamlSyntax { public List<MamlParameter> Parameters { get { return _parameters; } } private List<MamlParameter> _parameters = new List<MamlParameter>(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Markdown.MAML.Model.MAML { public class MamlSyntax { public string Name { get; set; } public MamlParameter parameter { get; set; } } }
mit
C#
6ab20e3f9274dca6e3c2172a36e1249d50a8e0f1
rework toolbar activation
Kerbas-ad-astra/KSP_Contract_Window,DMagic1/KSP_Contract_Window
contractToolbar.cs
contractToolbar.cs
#region license /*The MIT License (MIT) Contract Toolbar- Addon for toolbar interface Copyright (c) 2014 DMagic KSP Plugin Framework by TriggerAu, 2014: http://forum.kerbalspaceprogram.com/threads/66503-KSP-Plugin-Framework 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 using System.IO; using UnityEngine; using Toolbar; namespace ContractsWindow { [KSPAddonImproved(KSPAddonImproved.Startup.EditorAny | KSPAddonImproved.Startup.TimeElapses, false)] class contractToolbar : MonoBehaviour { private IButton contractButton; internal contractToolbar() { if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER) { contractButton = ToolbarManager.Instance.add("ContractsWindow", "ContractManager"); if (File.Exists(Path.Combine(new DirectoryInfo(KSPUtil.ApplicationRootPath).FullName, "GameData/Contracts Window/Textures/ContractsIcon.png").Replace("\\", "/"))) contractButton.TexturePath = "Contracts Window/Textures/ContractsIcon"; else contractButton.TexturePath = "000_Toolbar/resize-cursor"; contractButton.ToolTip = "Contract Manager"; contractButton.OnClick += (e) => { contractScenario.Instance.cWin.Visible = !contractScenario.Instance.cWin.Visible; contractScenario.Instance.setWindowVisible(contractScenario.Instance.cWin.Visible); }; } else return; } internal void OnDestroy() { contractButton.Destroy(); } } }
#region license /*The MIT License (MIT) Contract Toolbar- Addon for toolbar interface Copyright (c) 2014 DMagic KSP Plugin Framework by TriggerAu, 2014: http://forum.kerbalspaceprogram.com/threads/66503-KSP-Plugin-Framework 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 using System.IO; using UnityEngine; using Toolbar; namespace ContractsWindow { [KSPAddonImproved(KSPAddonImproved.Startup.EditorAny | KSPAddonImproved.Startup.TimeElapses, false)] class contractToolbar : MonoBehaviour { private IButton contractButton; internal contractToolbar() { if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER) { contractButton = ToolbarManager.Instance.add("ContractsWindow", "ContractManager"); if (File.Exists(Path.Combine(new DirectoryInfo(KSPUtil.ApplicationRootPath).FullName, "GameData/Contracts Window/Textures/ContractsIcon.png").Replace("\\", "/"))) contractButton.TexturePath = "Contracts Window/Textures/ContractsIcon"; else contractButton.TexturePath = "000_Toolbar/resize-cursor"; contractButton.ToolTip = "Contract Manager"; contractButton.OnClick += (e) => { contractsWindow.IsVisible = !contractsWindow.IsVisible; contractScenario.Instance.setWindowVisible(contractsWindow.IsVisible); }; } else return; } internal void OnDestroy() { contractButton.Destroy(); } } }
mit
C#
66616f510d601a91707f28d3501f967fb09899f7
Support new Navigation Service
Mark-RSK/FreshMvvm,bbqchickenrobot/FreshMvvm,asednev/FreshMvvm,keannan5390/FreshMvvm,rid00z/FreshMvvm
samples/FreshMvvmSampleApp/FreshMvvmSampleApp/Navigation/CustomImplementedNav.cs
samples/FreshMvvmSampleApp/FreshMvvmSampleApp/Navigation/CustomImplementedNav.cs
using System; using FreshMvvm; using Xamarin.Forms; using System.Collections.Generic; using System.Threading.Tasks; namespace FreshMvvmSampleApp { /// <summary> /// This is a sample custom implemented Navigation. It combines a MasterDetail and a TabbedPage. /// </summary> public class CustomImplementedNav : Xamarin.Forms.MasterDetailPage, IFreshNavigationService { FreshTabbedNavigationContainer _tabbedNavigationPage; Page _contactsPage, _quotesPage; public CustomImplementedNav () { SetupTabbedPage (); CreateMenuPage ("Menu"); RegisterNavigation (); } void SetupTabbedPage() { _tabbedNavigationPage = new FreshTabbedNavigationContainer (); _contactsPage = _tabbedNavigationPage.AddTab<ContactListPageModel> ("Contacts", "contacts.png"); _quotesPage = _tabbedNavigationPage.AddTab<QuoteListPageModel> ("Quotes", "document.png"); this.Detail = _tabbedNavigationPage; } protected void RegisterNavigation() { FreshIOC.Container.Register<IFreshNavigationService> (this); } protected void CreateMenuPage(string menuPageTitle) { var _menuPage = new ContentPage (); _menuPage.Title = menuPageTitle; var listView = new ListView(); listView.ItemsSource = new string[] { "Contacts", "Quotes", "Modal Demo" }; listView.ItemSelected += async (sender, args) => { switch ((string)args.SelectedItem) { case "Contacts": _tabbedNavigationPage.CurrentPage = _contactsPage; break; case "Quotes": _tabbedNavigationPage.CurrentPage = _quotesPage; break; case "Modal Demo": var modalPage = FreshPageModelResolver.ResolvePageModel<ModalPageModel>(); await PushPage(modalPage, null, true); break; default: break; } IsPresented = false; }; _menuPage.Content = listView; Master = new NavigationPage(_menuPage) { Title = "Menu" }; } public virtual async Task PushPage (Xamarin.Forms.Page page, FreshBasePageModel model, bool modal = false, bool animated = true) { if (modal) await Navigation.PushModalAsync (new NavigationPage(page), animated); else await ((NavigationPage)_tabbedNavigationPage.CurrentPage).PushAsync (page, animated); } public virtual async Task PopPage (bool modal = false, bool animate = true) { if (modal) await Navigation.PopModalAsync (); else await ((NavigationPage)_tabbedNavigationPage.CurrentPage).PopAsync (); } public virtual async Task PopToRoot (bool animate = true) { await ((NavigationPage)_tabbedNavigationPage.CurrentPage).PopToRootAsync (animate); } } }
using System; using FreshMvvm; using Xamarin.Forms; using System.Collections.Generic; using System.Threading.Tasks; namespace FreshMvvmSampleApp { /// <summary> /// This is a sample custom implemented Navigation. It combines a MasterDetail and a TabbedPage. /// </summary> public class CustomImplementedNav : Xamarin.Forms.MasterDetailPage, IFreshNavigationService { FreshTabbedNavigationContainer _tabbedNavigationPage; Page _contactsPage, _quotesPage; public CustomImplementedNav () { SetupTabbedPage (); CreateMenuPage ("Menu"); RegisterNavigation (); } void SetupTabbedPage() { _tabbedNavigationPage = new FreshTabbedNavigationContainer (); _contactsPage = _tabbedNavigationPage.AddTab<ContactListPageModel> ("Contacts", "contacts.png"); _quotesPage = _tabbedNavigationPage.AddTab<QuoteListPageModel> ("Quotes", "document.png"); this.Detail = _tabbedNavigationPage; } protected void RegisterNavigation() { FreshIOC.Container.Register<IFreshNavigationService> (this); } protected void CreateMenuPage(string menuPageTitle) { var _menuPage = new ContentPage (); _menuPage.Title = menuPageTitle; var listView = new ListView(); listView.ItemsSource = new string[] { "Contacts", "Quotes", "Modal Demo" }; listView.ItemSelected += async (sender, args) => { switch ((string)args.SelectedItem) { case "Contacts": _tabbedNavigationPage.CurrentPage = _contactsPage; break; case "Quotes": _tabbedNavigationPage.CurrentPage = _quotesPage; break; case "Modal Demo": var modalPage = FreshPageModelResolver.ResolvePageModel<ModalPageModel>(); await PushPage(modalPage, null, true); break; default: break; } IsPresented = false; }; _menuPage.Content = listView; Master = new NavigationPage(_menuPage) { Title = "Menu" }; } public virtual async Task PushPage (Xamarin.Forms.Page page, FreshBasePageModel model, bool modal = false, bool animated = true) { if (modal) await Navigation.PushModalAsync (new NavigationPage(page), animated); else await ((NavigationPage)_tabbedNavigationPage.CurrentPage).PushAsync (page, animated); } public virtual async Task PopPage (bool modal = false, bool animate = true) { if (modal) await Navigation.PopModalAsync (); else await ((NavigationPage)_tabbedNavigationPage.CurrentPage).PopAsync (); } } }
apache-2.0
C#
63b8d232f2580d535259ff91e6023fa567276497
Update FileAccessLevel.cs
A51UK/File-Repository
File-Repository/Enum/FileAccessLevel.cs
File-Repository/Enum/FileAccessLevel.cs
/* * Copyright 2017 Craig Lee Mark Adams Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * * */ using System; using System.Collections.Generic; using System.Text; namespace File_Repository { public enum FileAccessLevel { _public, _private } }
/* * Copyright 2017 Criag Lee Mark Adams Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * * */ using System; using System.Collections.Generic; using System.Text; namespace File_Repository { public enum FileAccessLevel { _public, _private } }
apache-2.0
C#
2ee3e97e59ecc55a7fece47234462651f96b0e82
Add ignore_empty_value to set processor (#4915)
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/Ingest/Processors/SetProcessor.cs
src/Nest/Ingest/Processors/SetProcessor.cs
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using System.Linq.Expressions; using System.Runtime.Serialization; using Elasticsearch.Net.Utf8Json; namespace Nest { /// <summary> /// Sets one field and associates it with the specified value. /// If the field already exists, its value will be replaced with the provided one. /// </summary> [InterfaceDataContract] public interface ISetProcessor : IProcessor { /// <summary> /// The field to insert, upsert, or update. Supports template snippets. /// </summary> [DataMember(Name ="field")] Field Field { get; set; } /// <summary> /// The value to be set for the field. Supports template snippets. /// </summary> [DataMember(Name ="value")] [JsonFormatter(typeof(SourceWriteFormatter<>))] object Value { get; set; } /// <summary> /// If processor will update fields with pre-existing non-null-valued field. /// When set to false, such fields will not be touched. /// Default is <c>true</c> /// </summary> [DataMember(Name = "override")] bool? Override { get; set; } /// <summary> /// If <c>true</c> and value is a template snippet that evaluates to null or the /// empty string, the processor quietly exits without modifying the document. /// Defaults to <c>false</c>. /// <para /> /// Valid in Elasticsearch 7.9.0+ /// </summary> [DataMember(Name = "ignore_empty_value")] bool? IgnoreEmptyValue { get; set; } } /// <inheritdoc cref="ISetProcessor" /> public class SetProcessor : ProcessorBase, ISetProcessor { /// <inheritdoc /> public Field Field { get; set; } /// <inheritdoc /> public object Value { get; set; } /// <inheritdoc /> public bool? Override { get; set; } /// <inheritdoc /> public bool? IgnoreEmptyValue { get; set; } protected override string Name => "set"; } /// <inheritdoc cref="ISetProcessor" /> public class SetProcessorDescriptor<T> : ProcessorDescriptorBase<SetProcessorDescriptor<T>, ISetProcessor>, ISetProcessor where T : class { protected override string Name => "set"; Field ISetProcessor.Field { get; set; } object ISetProcessor.Value { get; set; } bool? ISetProcessor.Override { get; set; } bool? ISetProcessor.IgnoreEmptyValue { get; set; } /// <inheritdoc cref="ISetProcessor.Field"/> public SetProcessorDescriptor<T> Field(Field field) => Assign(field, (a, v) => a.Field = v); /// <inheritdoc cref="ISetProcessor.Field"/> public SetProcessorDescriptor<T> Field<TValue>(Expression<Func<T, TValue>> objectPath) => Assign(objectPath, (a, v) => a.Field = v); /// <inheritdoc cref="ISetProcessor.Value"/> public SetProcessorDescriptor<T> Value<TValue>(TValue value) => Assign(value, (a, v) => a.Value = v); /// <inheritdoc cref="ISetProcessor.Override"/> public SetProcessorDescriptor<T> Override(bool? @override = true) => Assign(@override, (a, v) => a.Override = v); /// <inheritdoc cref="ISetProcessor.IgnoreEmptyValue"/> public SetProcessorDescriptor<T> IgnoreEmptyValue(bool? ignoreEmptyValue = true) => Assign(ignoreEmptyValue, (a, v) => a.IgnoreEmptyValue = v); } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using System.Linq.Expressions; using System.Runtime.Serialization; using Elasticsearch.Net.Utf8Json; namespace Nest { /// <summary> /// Sets one field and associates it with the specified value. /// If the field already exists, its value will be replaced with the provided one. /// </summary> [InterfaceDataContract] public interface ISetProcessor : IProcessor { /// <summary> /// The field to insert, upsert, or update. Supports template snippets. /// </summary> [DataMember(Name ="field")] Field Field { get; set; } /// <summary> /// The value to be set for the field. Supports template snippets. /// </summary> [DataMember(Name ="value")] [JsonFormatter(typeof(SourceWriteFormatter<>))] object Value { get; set; } /// <summary> /// If processor will update fields with pre-existing non-null-valued field. /// When set to false, such fields will not be touched. /// Default is <c>true</c> /// </summary> [DataMember(Name = "override")] bool? Override { get; set; } } /// <inheritdoc cref="ISetProcessor" /> public class SetProcessor : ProcessorBase, ISetProcessor { /// <inheritdoc /> public Field Field { get; set; } /// <inheritdoc /> public object Value { get; set; } /// <inheritdoc /> public bool? Override { get; set; } protected override string Name => "set"; } /// <inheritdoc cref="ISetProcessor" /> public class SetProcessorDescriptor<T> : ProcessorDescriptorBase<SetProcessorDescriptor<T>, ISetProcessor>, ISetProcessor where T : class { protected override string Name => "set"; Field ISetProcessor.Field { get; set; } object ISetProcessor.Value { get; set; } bool? ISetProcessor.Override { get; set; } /// <inheritdoc cref="ISetProcessor.Field"/> public SetProcessorDescriptor<T> Field(Field field) => Assign(field, (a, v) => a.Field = v); /// <inheritdoc cref="ISetProcessor.Field"/> public SetProcessorDescriptor<T> Field<TValue>(Expression<Func<T, TValue>> objectPath) => Assign(objectPath, (a, v) => a.Field = v); /// <inheritdoc cref="ISetProcessor.Value"/> public SetProcessorDescriptor<T> Value<TValue>(TValue value) => Assign(value, (a, v) => a.Value = v); /// <inheritdoc cref="ISetProcessor.Override"/> public SetProcessorDescriptor<T> Override(bool? @override = true) => Assign(@override, (a, v) => a.Override = v); } }
apache-2.0
C#