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
2588d3308570d21bf3cfff5e23df5e210ed6aa39
Bump version to 0.6.4
quisquous/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,sqt/cactbot,sqt/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot
CactbotOverlay/Properties/AssemblyInfo.cs
CactbotOverlay/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CactbotOverlay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CactbotOverlay")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")] // Version: // - Major Version // - Minor Version // - Build Number // - Revision // GitHub has only 3 version components, so Revision should always be 0. [assembly: AssemblyVersion("0.6.4.0")] [assembly: AssemblyFileVersion("0.6.4.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CactbotOverlay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CactbotOverlay")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")] // Version: // - Major Version // - Minor Version // - Build Number // - Revision // GitHub has only 3 version components, so Revision should always be 0. [assembly: AssemblyVersion("0.6.3.0")] [assembly: AssemblyFileVersion("0.6.3.0")]
apache-2.0
C#
235b8512e61dec909ee8fce35f56d5fdb5a558e1
change hello message
Isantipov/mqpi,Isantipov/mqpi
mqpi/Program.cs
mqpi/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Xml; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace mqpi { public class Program { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program)); public static void Main(string[] args) { Console.WriteLine("hello"); var executingAssemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var currentDirectory = Directory.GetCurrentDirectory(); Console.WriteLine($"{nameof(executingAssemblyDir)}:{executingAssemblyDir}"); Console.WriteLine($"{nameof(currentDirectory)}:{currentDirectory}"); // ReSharper disable once InconsistentNaming var log4netConfig = new XmlDocument(); log4netConfig.Load(File.OpenRead(Path.Combine(executingAssemblyDir, "log4net.config"))); var repo = log4net.LogManager.CreateRepository( Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy)); log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]); log.Info("mqpi is launching"); BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseUrls("http://*:5000") .Build(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Xml; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace mqpi { public class Program { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program)); public static void Main(string[] args) { Console.WriteLine("hello"); var executingAssemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var currentDirectory = Directory.GetCurrentDirectory(); Console.WriteLine($"{nameof(executingAssemblyDir)}:{executingAssemblyDir}"); Console.WriteLine($"{nameof(currentDirectory)}:{currentDirectory}"); // ReSharper disable once InconsistentNaming var log4netConfig = new XmlDocument(); log4netConfig.Load(File.OpenRead(Path.Combine(executingAssemblyDir, "log4net.config"))); var repo = log4net.LogManager.CreateRepository( Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy)); log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]); log.Info("Application - Main is invoked"); BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseUrls("http://*:5000") .Build(); } }
mit
C#
69fae13cf2ad6b2ed5f5162ae46dbf159121dbff
Exclude Seadragon.config.js from combining because it does substitution.
darilek/AjaxControlToolkit,DevExpress/AjaxControlToolkit,DevExpress/AjaxControlToolkit,darilek/AjaxControlToolkit,DevExpress/AjaxControlToolkit
Server/AjaxControlToolkit/Properties/AssemblyInfo.cs
Server/AjaxControlToolkit/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Web.UI; using AjaxControlToolkit; // Dependency Attribute for assemblies [assembly: DependencyAttribute("System.Web,", LoadHint.Always)] [assembly: DependencyAttribute("System.Web.Ajax,", LoadHint.Always)] [assembly: DependencyAttribute("System.Web.Extensions,", LoadHint.Always)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)] [assembly: TagPrefix("AjaxControlToolkit", "asp")] [assembly: AllowPartiallyTrustedCallers] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("3.0.31106.*")] [assembly: AssemblyFileVersion("3.0.31106.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ScriptCombine(ExcludeScripts = "Slider.SliderBehavior_resource.js,Seadragon.Seadragon.Config.js")] // CDN Path // http[s]://ajax.microsoft.com/ajax/beta/0910/extended/*
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Web.UI; using AjaxControlToolkit; // Dependency Attribute for assemblies [assembly: DependencyAttribute("System.Web,", LoadHint.Always)] [assembly: DependencyAttribute("System.Web.Ajax,", LoadHint.Always)] [assembly: DependencyAttribute("System.Web.Extensions,", LoadHint.Always)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)] [assembly: TagPrefix("AjaxControlToolkit", "asp")] [assembly: AllowPartiallyTrustedCallers] [assembly: ComVisible(false)] [assembly: System.CLSCompliant(true)] [assembly: AssemblyVersion("3.0.31106.*")] [assembly: AssemblyFileVersion("3.0.31106.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ScriptCombine(ExcludeScripts = "Slider.SliderBehavior_resource.js")] // CDN Path // http[s]://ajax.microsoft.com/ajax/beta/0910/extended/*
bsd-3-clause
C#
6308152008fb19a774ef781cfbda4a476f5e4109
Update Eggbert's name to Eggbertx
Radnen/spherestudio,Radnen/spherestudio
SphereStudio.Base/Versioning.cs
SphereStudio.Base/Versioning.cs
using System; namespace SphereStudio { // note: `const` is resolved at compile time in the referencing assembly. this is // desirable for built-in plugins to avoid them dynamically adopting the version number // of the Sphere Studio installation they're running against. /// <summary> /// Provides versioning information for Sphere Studio. /// </summary> public static class Versioning { /// <summary> /// The name of the IDE used for branding. /// </summary> public const string Name = "Sphere Studio"; /// <summary> /// The name of the author used for branding. /// </summary> public const string Author = "Spherical Community"; /// <summary> /// The version number of the software. /// </summary> public const string Version = "X.X.X"; /// <summary> /// A string indicating the copyright holder and year(s) of copyright. /// </summary> public const string Copyright = "2013-2017 S.E.G."; /// <summary> /// A short description of the software along with a list of contributors. /// </summary> public const string Credits = "A modern game development environment for Sphere, coded in C# and sporting many useful features like debugging, support for compilers, plugins, and more.\r\n\r\n" + "DEVELOPERS\r\n" + " Andrew Helenius ('Radnen')\r\n" + " Bruce Pascoe ('Fat Cerberus')\r\n\r\n" + "TESTERS\r\n" + " DaVince\r\n" + " Eggbertx\r\n" + " Flying Jester"; } }
using System; namespace SphereStudio { // note: `const` is resolved at compile time in the referencing assembly. this is // desirable for built-in plugins to avoid them dynamically adopting the version number // of the Sphere Studio installation they're running against. /// <summary> /// Provides versioning information for Sphere Studio. /// </summary> public static class Versioning { /// <summary> /// The name of the IDE used for branding. /// </summary> public const string Name = "Sphere Studio"; /// <summary> /// The name of the author used for branding. /// </summary> public const string Author = "Spherical Community"; /// <summary> /// The version number of the software. /// </summary> public const string Version = "X.X.X"; /// <summary> /// A string indicating the copyright holder and year(s) of copyright. /// </summary> public const string Copyright = "2013-2017 S.E.G."; /// <summary> /// A short description of the software along with a list of contributors. /// </summary> public const string Credits = "A modern game development environment for Sphere, coded in C# and sporting many useful features like debugging, support for compilers, plugins, and more.\r\n\r\n" + "DEVELOPERS\r\n" + " Andrew Helenius ('Radnen')\r\n" + " Bruce Pascoe ('Fat Cerberus')\r\n\r\n" + "TESTERS\r\n" + " DaVince\r\n" + " Eggbert\r\n" + " Flying Jester"; } }
mit
C#
8e438662b215c39b2849cad3b2a501f32f49d649
Revert "Merge Update"
pontusdacke/SyncedMG
Synced/Synced/Interface/Text.cs
Synced/Synced/Interface/Text.cs
// Text.cs // Introduced: 2015-04-28 // Last edited: 2015-04-29 // Edited by: // Pontus Magnusson using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Synced.Static_Classes; namespace Synced.Interface { class Label : DrawableGameComponent { #region Variables string _content; Rectangle _rectangle; SpriteFont _font; DrawingHelper.Alignment _alignment; #endregion #region Properties SpriteBatch _spriteBatch { get { return (SpriteBatch)Game.Services.GetService(typeof(SpriteBatch)); } } public DrawingHelper.Alignment Alignment { get { return _alignment; } set { _alignment = value; } } public string Content { get { return _content; } set { _content = value; } } public SpriteFont SetFont { set { _font = value; } } #endregion public Label(string content, Rectangle rectangle, Game game) : base(game) { _content = content; _rectangle = rectangle; _alignment = DrawingHelper.Alignment.Center; DrawOrder = (int)DrawingHelper.DrawingLevel.Top; } public override void Draw(GameTime gameTime) { _spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.None, RasterizerState.CullNone, null, ResolutionManager.GetTransformationMatrix()); DrawingHelper.DrawString(_spriteBatch, _font, _content, _rectangle, DrawingHelper.Alignment.Center, 3, Color.Black); _spriteBatch.End(); base.Draw(gameTime); } } }
mit
C#
1a55968880ca8397abd6afeba30234fe2b7fd500
add connect by username and password
Xarlot/NGitLab,maikebing/NGitLab
NGitLab/NGitLab/GitLabClient.cs
NGitLab/NGitLab/GitLabClient.cs
using NGitLab.Impl; using NGitLab.Models; namespace NGitLab { public class GitLabClient { readonly Api api; public readonly INamespaceClient Groups; public readonly IIssueClient Issues; public readonly IProjectClient Projects; public readonly IUserClient Users; GitLabClient(string hostUrl, string apiToken) { api = new Api(hostUrl, apiToken); Users = new UserClient(api); Projects = new ProjectClient(api); Issues = new IssueClient(api); Groups = new NamespaceClient(api); } public static GitLabClient Connect(string hostUrl, string username, string password) { var api = new Api(hostUrl, ""); var session = api.Post().To<Session>($"/session?login={username}&password={password}"); return Connect(hostUrl, session.PrivateToken); } public static GitLabClient Connect(string hostUrl, string apiToken) { return new GitLabClient(hostUrl, apiToken); } public IRepositoryClient GetRepository(int projectId) { return new RepositoryClient(api, projectId); } public IMergeRequestClient GetMergeRequest(int projectId) { return new MergeRequestClient(api, projectId); } } }
using NGitLab.Impl; namespace NGitLab { public class GitLabClient { readonly Api api; public readonly INamespaceClient Groups; public readonly IIssueClient Issues; public readonly IProjectClient Projects; public readonly IUserClient Users; GitLabClient(string hostUrl, string apiToken) { api = new Api(hostUrl, apiToken); Users = new UserClient(api); Projects = new ProjectClient(api); Issues = new IssueClient(api); Groups = new NamespaceClient(api); } public static GitLabClient Connect(string hostUrl, string apiToken) { return new GitLabClient(hostUrl, apiToken); } public IRepositoryClient GetRepository(int projectId) { return new RepositoryClient(api, projectId); } public IMergeRequestClient GetMergeRequest(int projectId) { return new MergeRequestClient(api, projectId); } } }
mit
C#
e12c4b33872fe4802b5142ea9161c7f32443646e
Remove unused usings
StollD/Planetary-Diversity
src/main/Templates.cs
src/main/Templates.cs
using System; using System.Linq; using UnityEngine; namespace PlanetaryDiversity { [KSPAddon(KSPAddon.Startup.PSystemSpawn, true)] public class Templates : MonoBehaviour { /// <summary> /// The scaled space mesh of jool /// </summary> public static Mesh ReferenceGeosphere { get; set; } /// <summary> /// Whether Kopernicus is installed and we have access to its OnDemand features /// </summary> public static Boolean IsKopernicusInstalled { get; set; } /// <summary> /// All loaded types /// </summary> public static Type[] Types { get; set; } void Start() { // If Kopernicus is loaded, we have to use it's ReferenceGeosphere, because we have no chance to get the unmodified version before it might get changed by Kopernicus Types = AssemblyLoader.loadedAssemblies.SelectMany(s => s.assembly.GetTypes()).ToArray(); Type templates = Types.FirstOrDefault(t => t.Name == "Templates" && t.Namespace == "Kopernicus"); if (templates != null) { ReferenceGeosphere = templates.GetProperty("ReferenceGeosphere").GetValue(null, null) as Mesh; IsKopernicusInstalled = true; } else { // We need to get the body for Jool (to steal it's mesh) PSystemBody Jool = Utility.FindBody(PSystemManager.Instance.systemPrefab.rootBody, "Jool"); // Return it's mesh ReferenceGeosphere = Jool.scaledVersion.GetComponent<MeshFilter>().sharedMesh; } Destroy(this); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace PlanetaryDiversity { [KSPAddon(KSPAddon.Startup.PSystemSpawn, true)] public class Templates : MonoBehaviour { /// <summary> /// The scaled space mesh of jool /// </summary> public static Mesh ReferenceGeosphere { get; set; } /// <summary> /// Whether Kopernicus is installed and we have access to its OnDemand features /// </summary> public static Boolean IsKopernicusInstalled { get; set; } /// <summary> /// All loaded types /// </summary> public static Type[] Types { get; set; } void Start() { // If Kopernicus is loaded, we have to use it's ReferenceGeosphere, because we have no chance to get the unmodified version before it might get changed by Kopernicus Types = AssemblyLoader.loadedAssemblies.SelectMany(s => s.assembly.GetTypes()).ToArray(); Type templates = Types.FirstOrDefault(t => t.Name == "Templates" && t.Namespace == "Kopernicus"); if (templates != null) { ReferenceGeosphere = templates.GetProperty("ReferenceGeosphere").GetValue(null, null) as Mesh; IsKopernicusInstalled = true; } else { // We need to get the body for Jool (to steal it's mesh) PSystemBody Jool = Utility.FindBody(PSystemManager.Instance.systemPrefab.rootBody, "Jool"); // Return it's mesh ReferenceGeosphere = Jool.scaledVersion.GetComponent<MeshFilter>().sharedMesh; } Destroy(this); } } }
mit
C#
022a60d6018e653381b7d534a4592df0ef268fc5
exit on thrown exception
quandl/quandl-excel-windows
Quandl.Excel.Console/Program.cs
Quandl.Excel.Console/Program.cs
using System; using System.IO; namespace Quandl.Excel.Console { internal class Program { // Installation package will handle the case which disable second re-install // RegisterExcelAddIn function will handle the case when the Quandl excel add-in registry key created before install private static void Main(string[] args) { try { if (args.Length == 0) return; if (args[0].Equals("register")) { SetupHelp.RegisterExcelAddin(); return; } if (args[0].Equals("unregister")) { SetupHelp.UnRegisterExcelAddin(); return; } } catch (Exception e) { using (StreamWriter w = File.AppendText(GetTempPath() + @".\quandl_excel_install_error_log.txt")) { Log(e.Message, w); return; } } throw new Exception("Could not identify command to use. Please use either `register` or `unregister`."); } private static void Log(string logMessage, TextWriter w) { w.Write("\r\nLog Entry : "); w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString()); w.WriteLine(" :{0}", logMessage); w.WriteLine("-------------------------------"); } private static string GetTempPath() { string path = System.Environment.GetEnvironmentVariable("TEMP"); if (!path.EndsWith("\\")) path += "\\"; return path; } } }
using System; using System.IO; namespace Quandl.Excel.Console { internal class Program { // Installation package will handle the case which disable second re-install // RegisterExcelAddIn function will handle the case when the Quandl excel add-in registry key created before install private static void Main(string[] args) { try { if (args.Length == 0) return; if (args[0].Equals("register")) { SetupHelp.RegisterExcelAddin(); return; } if (args[0].Equals("unregister")) { SetupHelp.UnRegisterExcelAddin(); return; } } catch (Exception e) { using (StreamWriter w = File.AppendText(GetTempPath() + @".\quandl_excel_install_error_log.txt")) { Log(e.Message, w); } } throw new Exception("Could not identify command to use. Please use either `register` or `unregister`."); } private static void Log(string logMessage, TextWriter w) { w.Write("\r\nLog Entry : "); w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString()); w.WriteLine(" :{0}", logMessage); w.WriteLine("-------------------------------"); } private static string GetTempPath() { string path = System.Environment.GetEnvironmentVariable("TEMP"); if (!path.EndsWith("\\")) path += "\\"; return path; } } }
mit
C#
c490dba7b3e0e22202ab861e0132a5779d818f0f
Fix crash on local score display
peppy/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,peppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu
osu.Game/Scoring/ScoreStore.cs
osu.Game/Scoring/ScoreStore.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 Microsoft.EntityFrameworkCore; using osu.Framework.Platform; using osu.Game.Database; namespace osu.Game.Scoring { public class ScoreStore : MutableDatabaseBackedStoreWithFileIncludes<ScoreInfo, ScoreFileInfo> { public ScoreStore(IDatabaseContextFactory factory, Storage storage) : base(factory, storage) { } protected override IQueryable<ScoreInfo> AddIncludesForConsumption(IQueryable<ScoreInfo> query) => base.AddIncludesForConsumption(query) .Include(s => s.Beatmap) .Include(s => s.Beatmap).ThenInclude(b => b.Metadata) .Include(s => s.Beatmap).ThenInclude(b => b.BeatmapSet).ThenInclude(s => s.Metadata) .Include(s => s.Ruleset); } }
// 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 Microsoft.EntityFrameworkCore; using osu.Framework.Platform; using osu.Game.Database; namespace osu.Game.Scoring { public class ScoreStore : MutableDatabaseBackedStoreWithFileIncludes<ScoreInfo, ScoreFileInfo> { public ScoreStore(IDatabaseContextFactory factory, Storage storage) : base(factory, storage) { } protected override IQueryable<ScoreInfo> AddIncludesForConsumption(IQueryable<ScoreInfo> query) => base.AddIncludesForConsumption(query) .Include(s => s.Beatmap) .Include(s => s.Ruleset); } }
mit
C#
bfdc1177d0db0b043fa48efabeab4717b39af6ea
Update ComBytes.cs
halex2005/diadocsdk-csharp,halex2005/diadocsdk-csharp,diadoc/diadocsdk-csharp,diadoc/diadocsdk-csharp
src/Com/ComBytes.cs
src/Com/ComBytes.cs
using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Diadoc.Api.Com { [ComVisible(true)] [Guid("AC96A3DD-E099-44CC-ABD5-11C303307159")] public interface IComBytes { byte[] Bytes { get; set; } void ReadFromFile(string path); void SaveToFile(string path); void ReadFromText(string text); } [ComVisible(true)] [ProgId("Diadoc.Api.ComBytes")] [Guid("97D998E3-E603-4450-A027-EA774091BE72")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(IComBytes))] public class ComBytes : SafeComObject, IComBytes { public byte[] Bytes { get; set; } public void ReadFromFile(string path) { Bytes = File.ReadAllBytes(path); } public void ReadFromText(string text) { Bytes = Encoding.UTF8.GetBytes(text); } public void SaveToFile(string path) { if (Bytes != null) { File.WriteAllBytes(path, Bytes); } } } }
using System.IO; using System.Runtime.InteropServices; namespace Diadoc.Api.Com { [ComVisible(true)] [Guid("AC96A3DD-E099-44CC-ABD5-11C303307159")] public interface IComBytes { byte[] Bytes { get; set; } void ReadFromFile(string path); void SaveToFile(string path); } [ComVisible(true)] [ProgId("Diadoc.Api.ComBytes")] [Guid("97D998E3-E603-4450-A027-EA774091BE72")] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(IComBytes))] public class ComBytes : SafeComObject, IComBytes { public byte[] Bytes { get; set; } public void ReadFromFile(string path) { Bytes = File.ReadAllBytes(path); } public void SaveToFile(string path) { if (Bytes != null) { File.WriteAllBytes(path, Bytes); } } } }
mit
C#
4e0bf907953d4ec2690c1e90465d97fed421f1a2
change nancy sample port
mnadel/Metrics.NET,Recognos/Metrics.NET,etishor/Metrics.NET,huoxudong125/Metrics.NET,MetaG8/Metrics.NET,Liwoj/Metrics.NET,ntent-ad/Metrics.NET,cvent/Metrics.NET,DeonHeyns/Metrics.NET,alhardy/Metrics.NET,etishor/Metrics.NET,huoxudong125/Metrics.NET,alhardy/Metrics.NET,Recognos/Metrics.NET,MetaG8/Metrics.NET,ntent-ad/Metrics.NET,cvent/Metrics.NET,DeonHeyns/Metrics.NET,mnadel/Metrics.NET,MetaG8/Metrics.NET,Liwoj/Metrics.NET
Samples/NancyFx.Sample/Program.cs
Samples/NancyFx.Sample/Program.cs
using System; using System.Diagnostics; using Metrics.Samples; using Metrics.Utils; using Nancy.Hosting.Self; using Newtonsoft.Json; namespace NancyFx.Sample { class Program { static void Main(string[] args) { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; using (ActionScheduler scheduler = new ActionScheduler()) using (var host = new NancyHost(new Uri("http://localhost:8090"))) { host.Start(); Console.WriteLine("Nancy Running at http://localhost:8090"); Console.WriteLine("Press any key to exit"); Process.Start("http://localhost:8090/metrics/"); SampleMetrics.RunSomeRequests(); scheduler.Start(TimeSpan.FromMilliseconds(500), () => SampleMetrics.RunSomeRequests()); HealthChecksSample.RegisterHealthChecks(); Console.ReadKey(); } } } }
using System; using System.Diagnostics; using Metrics.Samples; using Metrics.Utils; using Nancy.Hosting.Self; using Newtonsoft.Json; namespace NancyFx.Sample { class Program { static void Main(string[] args) { JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented }; using (ActionScheduler scheduler = new ActionScheduler()) using (var host = new NancyHost(new Uri("http://localhost:12345"))) { host.Start(); Console.WriteLine("Nancy Running at http://localhost:12345"); Console.WriteLine("Press any key to exit"); Process.Start("http://localhost:12345/metrics/"); SampleMetrics.RunSomeRequests(); scheduler.Start(TimeSpan.FromMilliseconds(500), () => SampleMetrics.RunSomeRequests()); HealthChecksSample.RegisterHealthChecks(); Console.ReadKey(); } } } }
apache-2.0
C#
c3781eab01947388cb3831ae898f649a15b5b8b0
remove commented out code
agrc/daq-web-framework,agrc/daq-web-framework,agrc/daq-web-framework,agrc/daq-web-framework
api/Services/EdocsRepository.cs
api/Services/EdocsRepository.cs
using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; using daq_api.Contracts; using daq_api.Models; using Dapper; namespace daq_api.Services { public class EdocsRepository : IRepository { private string ConnectionString { get; set; } public EdocsRepository() { ConnectionString = ConfigurationManager.ConnectionStrings["edocs"].ConnectionString; } public async Task<IEnumerable<EDocEntry>> Get(string facility) { using (var session = new SqlConnection(ConnectionString)) { var results = await session.QueryAsync<EDocEntry>("SELECT id, facility_name as name, branch, title, r_folder_path + '/' + object_name + '.' + i_full_format as path, CAST(document_date as datetime) as documentdate FROM Combined_DAQ where facility_number=@facility ORDER BY documentdate", new { facility }); return results; } } public EDocEntry Get(int id) { using (var session = new SqlConnection(ConnectionString)) { return session.Query<EDocEntry>("SELECT id, title, r_folder_path + '/' + object_name + '.' + i_full_format as path FROM Combined_DAQ where id = @id", new { id }).Single(); } } } }
using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; using daq_api.Contracts; using daq_api.Models; using Dapper; namespace daq_api.Services { public class EdocsRepository : IRepository { private string ConnectionString { get; set; } public EdocsRepository() { ConnectionString = ConfigurationManager.ConnectionStrings["edocs"].ConnectionString; } public async Task<IEnumerable<EDocEntry>> Get(string facility) { using (var session = new SqlConnection(ConnectionString)) { var results = await session.QueryAsync<EDocEntry>("SELECT id, facility_name as name, branch, title, r_folder_path + '/' + object_name + '.' + i_full_format as path, CAST(document_date as datetime) as documentdate FROM Combined_DAQ where facility_number=@facility ORDER BY documentdate", new { facility }); return results; //.Select(mapped => new EDocEntry(mapped, facilityId)).ToList(); } } // public IEnumerable<EDocEntry> Get(IEnumerable<int> ids) // { // using (var session = new SqlConnection(ConnectionString)) // { // return session.Query<EDocEntry>("SELECT id, title, r_folder_path + '/' + object_name + '.' + i_full_format as path FROM Combined_DAQ where id IN @ids", new // { // ids // }).ToList(); // } // } public EDocEntry Get(int id) { using (var session = new SqlConnection(ConnectionString)) { return session.Query<EDocEntry>("SELECT id, title, r_folder_path + '/' + object_name + '.' + i_full_format as path FROM Combined_DAQ where id = @id", new { id }).Single(); } } } }
mit
C#
b4540ace4ab73da0b21ea273829dbce6ce01abb1
Revert making UserCredentials a struct
msbahrul/EventStore,ianbattersby/EventStore,ianbattersby/EventStore,msbahrul/EventStore,ianbattersby/EventStore,ianbattersby/EventStore,msbahrul/EventStore,msbahrul/EventStore,ianbattersby/EventStore,msbahrul/EventStore,msbahrul/EventStore
src/EventStore/EventStore.ClientAPI/SystemData/UserCredentials.cs
src/EventStore/EventStore.ClientAPI/SystemData/UserCredentials.cs
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using EventStore.ClientAPI.Common.Utils; namespace EventStore.ClientAPI.SystemData { /// <summary> /// A username/password pair used for authentication and /// authorization to perform operations over an <see cref="IEventStoreConnection"/>. /// </summary> public class UserCredentials { /// <summary> /// The username /// </summary> public readonly string Username; /// <summary> /// The password /// </summary> public readonly string Password; /// <summary> /// Constructs a new <see cref="UserCredentials"/>. /// </summary> /// <param name="username"></param> /// <param name="password"></param> public UserCredentials(string username, string password) { Ensure.NotNull(username, "username"); Ensure.NotNull(password, "password"); Username = username; Password = password; } } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using EventStore.ClientAPI.Common.Utils; namespace EventStore.ClientAPI.SystemData { /// <summary> /// A username/password pair used for authentication and /// authorization to perform operations over an <see cref="IEventStoreConnection"/>. /// </summary> public struct UserCredentials { /// <summary> /// The username /// </summary> public readonly string Username; /// <summary> /// The password /// </summary> public readonly string Password; /// <summary> /// Constructs a new <see cref="UserCredentials"/>. /// </summary> /// <param name="username"></param> /// <param name="password"></param> public UserCredentials(string username, string password) { Ensure.NotNull(username, "username"); Ensure.NotNull(password, "password"); Username = username; Password = password; } } }
bsd-3-clause
C#
d70f99cc0aa2040ea9f317d0306c264d50159f08
Remove Sqlite latest compile job workaround
tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server
src/Tgstation.Server.Host/Extensions/DatabaseContextExtensions.cs
src/Tgstation.Server.Host/Extensions/DatabaseContextExtensions.cs
using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Host.Database; using Tgstation.Server.Host.Models; namespace Tgstation.Server.Host.Extensions { /// <summary> /// Extensions for the <see cref="IDatabaseContext"/> <see langword="class"/>. /// </summary> static class DatabaseContextExtensions { /// <summary> /// Get the most recent <see cref="CompileJob"/> for a given <paramref name="instance"/> from a given <paramref name="databaseContext"/>. /// </summary> /// <param name="databaseContext">The <see cref="IDatabaseContext"/>.</param> /// <param name="instance">The <see cref="Instance"/> to search for <see cref="CompileJob"/>s.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation.</param> /// <returns>A <see cref="Task{TResult}"/> resulting in the most recent <see cref="CompileJob"/> associated with the given <paramref name="instance"/> from the <paramref name="databaseContext"/>.</returns> public static Task<CompileJob> MostRecentCompletedCompileJobOrDefault( this IDatabaseContext databaseContext, Api.Models.Instance instance, CancellationToken cancellationToken) { if (databaseContext == null) throw new ArgumentNullException(nameof(databaseContext)); return databaseContext .CompileJobs .Where(x => x.Job.Instance.Id == instance.Id) .OrderByDescending(x => x.Job.StoppedAt) .FirstOrDefaultAsync(cancellationToken); } } }
using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Host.Configuration; using Tgstation.Server.Host.Database; using Tgstation.Server.Host.Models; namespace Tgstation.Server.Host.Extensions { /// <summary> /// Extensions for the <see cref="IDatabaseContext"/> <see langword="class"/>. /// </summary> static class DatabaseContextExtensions { /// <summary> /// Get the most recent <see cref="CompileJob"/> for a given <paramref name="instance"/> from a given <paramref name="databaseContext"/>. /// </summary> /// <param name="databaseContext">The <see cref="IDatabaseContext"/>.</param> /// <param name="instance">The <see cref="Instance"/> to search for <see cref="CompileJob"/>s.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation.</param> /// <returns>A <see cref="Task{TResult}"/> resulting in the most recent <see cref="CompileJob"/> associated with the given <paramref name="instance"/> from the <paramref name="databaseContext"/>.</returns> public static async Task<CompileJob> MostRecentCompletedCompileJobOrDefault( this IDatabaseContext databaseContext, Api.Models.Instance instance, CancellationToken cancellationToken) { if (databaseContext == null) throw new ArgumentNullException(nameof(databaseContext)); var baseQuery = databaseContext .CompileJobs .Where(x => x.Job.Instance.Id == instance.Id); if (databaseContext.DatabaseType == DatabaseType.Sqlite) { // This is a hack // This is a hack and I hate it // SQLite can't order by DateTimeOffset so we have to do it ourselves // I decided to make this space efficient because "webscale" DateTimeOffset? mostRecentCompileJobStoppedAt = null; long? mostRecentCompileJobId = null; await baseQuery .Include(cj => cj.Job) .Select(cj => new CompileJob { Id = cj.Id, Job = new Job { StoppedAt = cj.Job.StoppedAt } }) .ForEachAsync(compileJob => { if (!mostRecentCompileJobId.HasValue || mostRecentCompileJobStoppedAt.Value < compileJob.Job.StoppedAt.Value) { mostRecentCompileJobStoppedAt = compileJob.Job.StoppedAt; mostRecentCompileJobId = compileJob.Id; } }, cancellationToken) .ConfigureAwait(false); if (!mostRecentCompileJobId.HasValue) return default; return await databaseContext .CompileJobs .Where(cj => cj.Id == mostRecentCompileJobId.Value) .FirstOrDefaultAsync(cancellationToken) .ConfigureAwait(false); } return await baseQuery .OrderByDescending(x => x.Job.StoppedAt) .FirstOrDefaultAsync(cancellationToken) .ConfigureAwait(false); } } }
agpl-3.0
C#
58cccb380bf324c4b066c61bad29d54ed491de51
Use GUID for component name
LibertyLocked/RestRPC,LibertyLocked/RestRPC,LibertyLocked/RestRPC,LibertyLocked/RestRPC
WebScriptHook.Terminal/Program.cs
WebScriptHook.Terminal/Program.cs
using System; using System.Threading; using WebScriptHook.Framework; using WebScriptHook.Framework.BuiltinPlugins; using WebScriptHook.Terminal.Plugins; namespace WebScriptHook.Terminal { class Program { static WebScriptHookComponent wshComponent; static void Main(string[] args) { string componentName = Guid.NewGuid().ToString(); wshComponent = new WebScriptHookComponent(componentName, new RemoteSettings("ws", "localhost", "25555", "/componentws")); // Register custom plugins wshComponent.PluginManager.RegisterPlugin(new Echo()); wshComponent.PluginManager.RegisterPlugin(new PluginList()); wshComponent.PluginManager.RegisterPlugin(new PrintToScreen()); // Start WSH component wshComponent.Start(); // Print all registered plugins Console.WriteLine("Registered plugins on \"" + wshComponent.Name + "\":"); var pluginIDs = wshComponent.PluginManager.PluginIDs; foreach (var pluginID in pluginIDs) { Console.WriteLine(pluginID); } // TODO: Use a timer instead of Sleep while (true) { wshComponent.Update(); Thread.Sleep(20); } } } }
using System; using System.Threading; using WebScriptHook.Framework; using WebScriptHook.Framework.BuiltinPlugins; using WebScriptHook.Terminal.Plugins; namespace WebScriptHook.Terminal { class Program { static WebScriptHookComponent wshComponent; static void Main(string[] args) { string componentName = "testbench"; //Guid.NewGuid().ToString(); wshComponent = new WebScriptHookComponent(componentName, new RemoteSettings("ws", "localhost", "25555", "/componentws")); // Register custom plugins wshComponent.PluginManager.RegisterPlugin(new Echo()); wshComponent.PluginManager.RegisterPlugin(new PluginList()); wshComponent.PluginManager.RegisterPlugin(new PrintToScreen()); // Start WSH component wshComponent.Start(); // Print all registered plugins Console.WriteLine("Registered plugins on \"" + wshComponent.Name + "\":"); var pluginIDs = wshComponent.PluginManager.PluginIDs; foreach (var pluginID in pluginIDs) { Console.WriteLine(pluginID); } // TODO: Use a timer instead of Sleep while (true) { wshComponent.Update(); Thread.Sleep(20); } } } }
mit
C#
ba01f372055b547e198ec1da77d15986ff084d1f
Update MusicSystem.cs
Figglewatts/LSDRevamped
LSDR/Assets/Scripts/Audio/MusicSystem.cs
LSDR/Assets/Scripts/Audio/MusicSystem.cs
using System; using System.IO; using LSDR.IO; using LSDR.Util; using Torii.Audio; using Torii.Resource; using Torii.Util; using UnityEngine; namespace LSDR.Audio { [CreateAssetMenu(menuName="System/MusicSystem")] public class MusicSystem : ScriptableObject { public string CurrentSong { get; private set; } public string CurrentArtist { get; private set; } public AudioSource PlayRandomSongFromDirectory(string dir) { var clip = getRandomSongFromDirectory(dir); return AudioPlayer.Instance.PlayClip(clip, loop: true, mixerGroup: "Music"); } public AudioSource PlayRandomSongFromDirectory(AudioSource source, string dir) { var clip = getRandomSongFromDirectory(dir); source.clip = clip; source.Play(); return source; } private AudioClip getRandomSongFromDirectory(string dir) { var files = Directory.GetFiles(dir, "*.ogg", SearchOption.AllDirectories); var randomFile = RandUtil.From(files); setMetadataFromFilePath(randomFile); Debug.Log($"Now playing: {CurrentSong} by {CurrentArtist}"); return ResourceManager.Load<ToriiAudioClip>(randomFile, "scene"); } private void setMetadataFromFilePath(string filePath) { var filename = Path.GetFileNameWithoutExtension(filePath); if (filename != null) if (filename.Contains(" - ")) { { var splitFilename = filename.Split(new[] {" - "}, 2, StringSplitOptions.RemoveEmptyEntries); CurrentArtist = splitFilename[0]; CurrentSong = splitFilename[1]; return; } } else { CurrentArtist = "UNKNOWN ARTIST"; CurrentSong = filename; } } } }
using System; using System.IO; using LSDR.IO; using LSDR.Util; using Torii.Audio; using Torii.Resource; using Torii.Util; using UnityEngine; namespace LSDR.Audio { [CreateAssetMenu(menuName="System/MusicSystem")] public class MusicSystem : ScriptableObject { public string CurrentSong { get; private set; } public string CurrentArtist { get; private set; } public AudioSource PlayRandomSongFromDirectory(string dir) { var clip = getRandomSongFromDirectory(dir); return AudioPlayer.Instance.PlayClip(clip, loop: true, mixerGroup: "Music"); } public AudioSource PlayRandomSongFromDirectory(AudioSource source, string dir) { var clip = getRandomSongFromDirectory(dir); source.clip = clip; source.Play(); return source; } private AudioClip getRandomSongFromDirectory(string dir) { var files = Directory.GetFiles(dir, "*.ogg", SearchOption.AllDirectories); var randomFile = RandUtil.From(files); setMetadataFromFilePath(randomFile); Debug.Log($"Now playing: {CurrentSong} by {CurrentArtist}"); return ResourceManager.Load<ToriiAudioClip>(randomFile, "scene"); } private void setMetadataFromFilePath(string filePath) { var filename = Path.GetFileNameWithoutExtension(filePath); if (filename != null) { var splitFilename = filename.Split(new[] {" - "}, 2, StringSplitOptions.RemoveEmptyEntries); CurrentArtist = splitFilename[0]; CurrentSong = splitFilename[1]; } } } }
mit
C#
844857addc5b769613d5dd4c61de5d9f972b5b34
Rename GotoRegionAsFlatModule -> GotoRegionModule
corngood/omnisharp-server,corngood/omnisharp-server,x335/omnisharp-server,OmniSharp/omnisharp-server,syl20bnr/omnisharp-server,mispencer/OmniSharpServer,syl20bnr/omnisharp-server,x335/omnisharp-server,svermeulen/omnisharp-server
OmniSharp/GotoRegion/GotoRegionModule.cs
OmniSharp/GotoRegion/GotoRegionModule.cs
using Nancy; using Nancy.ModelBinding; namespace OmniSharp.GotoRegion { public class GotoRegionModule : NancyModule { public GotoRegionModule (GotoRegionHandler handler) { Post["/gotoregion"] = x => { var req = this.Bind<Common.Request>(); var members = handler.GetFileRegions(req); return Response.AsJson(members); }; } } }
using Nancy; using Nancy.ModelBinding; namespace OmniSharp.GotoRegion { public class GotoRegionAsFlatModule : NancyModule { public GotoRegionAsFlatModule (GotoRegionHandler handler) { Post["/gotoregion"] = x => { var req = this.Bind<Common.Request>(); var members = handler.GetFileRegions(req); return Response.AsJson(members); }; } } }
mit
C#
5cb3b646b21fdc67545e0f7b88eb64e79540d683
Add primary key to completed steps db table
rapidcore/rapidcore,rapidcore/rapidcore
src/postgresql/main/Migration/Internal/PostgreSqlSchemaCreator.cs
src/postgresql/main/Migration/Internal/PostgreSqlSchemaCreator.cs
using Dapper; using RapidCore.Migration; using RapidCore.PostgreSql.Internal; using System.Threading.Tasks; namespace RapidCore.PostgreSql.Migration.Internal { public static class PostgreSqlSchemaCreator { public static async Task CreateSchemaIfNotExists(IMigrationContext context) { var db = ((PostgreSqlMigrationContext)context).ConnectionProvider.Default(); ; await db.ExecuteAsync($@"CREATE TABLE IF NOT EXISTS {PostgreSqlConstants.MigrationInfoTableName} ( id serial not null constraint migrationinfo_pkey primary key, Name varchar(255) unique, MigrationCompleted boolean, TotalMigrationTimeInMs int8, CompletedAtUtc timestamp );"); await db.ExecuteAsync($@"CREATE TABLE IF NOT EXISTS {PostgreSqlConstants.CompletedStepsTableName} ( StepName varchar(255), MigrationInfoId integer references { PostgreSqlConstants.MigrationInfoTableName } (id), PRIMARY KEY (StepName, MigrationInfoId) );"); } } }
using Dapper; using RapidCore.Migration; using RapidCore.PostgreSql.Internal; using System.Threading.Tasks; namespace RapidCore.PostgreSql.Migration.Internal { public static class PostgreSqlSchemaCreator { public static async Task CreateSchemaIfNotExists(IMigrationContext context) { var db = ((PostgreSqlMigrationContext)context).ConnectionProvider.Default(); ; await db.ExecuteAsync($@"CREATE TABLE IF NOT EXISTS {PostgreSqlConstants.MigrationInfoTableName} ( id serial not null constraint migrationinfo_pkey primary key, Name varchar(255) unique, MigrationCompleted boolean, TotalMigrationTimeInMs int8, CompletedAtUtc timestamp );"); await db.ExecuteAsync($@"CREATE TABLE IF NOT EXISTS {PostgreSqlConstants.CompletedStepsTableName} ( StepName varchar(255), MigrationInfoId integer references { PostgreSqlConstants.MigrationInfoTableName } (id), unique (StepName, MigrationInfoId) );"); } } }
mit
C#
5f029eeeedea6fbbc6294cbae134982f380d9048
Allow regex discovery
StevenThuriot/ErrorCode
ErrorCode/Discover.cs
ErrorCode/Discover.cs
using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using ErrorCode.Domain; using System.Text.RegularExpressions; namespace ErrorCode { static class Discover { static Regex _assemblyFilter = new Regex(@".*tests?\.(dll|exe)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); public static IReadOnlyCollection<TestAssembly> Tests() => Tests(_assemblyFilter); public static IReadOnlyCollection<TestAssembly> Tests(Regex assemblyFilter) { var tests = Directory.GetFiles(Directory.GetCurrentDirectory()) .Where(x => assemblyFilter.IsMatch(Path.GetFileName(x))) .Select(Assembly.LoadFrom) .Select(x => new TestAssembly(x)) .ToArray(); return tests; } } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using ErrorCode.Domain; namespace ErrorCode { static class Discover { public static IReadOnlyCollection<TestAssembly> Tests(string assemblyFilter = "*test*.dll") { var tests = Directory.GetFiles(Directory.GetCurrentDirectory(), assemblyFilter) .Select(Assembly.LoadFrom) .Select(x => new TestAssembly(x)) .ToArray(); return tests; } } }
mit
C#
030535a67ba471d6620188966475337ce378761d
Add code to write quote XML file
fredatgithub/GetQuote
CreateXMLFile/Program.cs
CreateXMLFile/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace CreateXMLFile { internal static class Program { private static void Main() { const string fileName = "quotes-cleaned.txt"; const string XmlFileName = "quotes-XML.txt"; Dictionary<string, string> dicoQuotes = new Dictionary<string, string>(); dicoQuotes = LoadDictionary(fileName); // create XML file if (!File.Exists(XmlFileName)) { StreamWriter sw2 = new StreamWriter(XmlFileName, false); sw2.WriteLine(string.Empty); sw2.Close(); } StreamWriter sw = new StreamWriter(XmlFileName, false); foreach (KeyValuePair<string, string> keyValuePair in dicoQuotes) { sw.WriteLine(CreateOneQuote(keyValuePair.Value, keyValuePair.Key)); } sw.Close(); Console.WriteLine("Press a key to exit:"); Console.ReadKey(); } private static string CreateOneQuote(string author, string theQuote) { StringBuilder result = new StringBuilder(); result.Append("<Quote>"); result.Append(Environment.NewLine); result.Append("<Author>"); result.Append(author); result.Append("</Author>"); result.Append(Environment.NewLine); result.Append("<Language>French</Language>"); result.Append(Environment.NewLine); result.Append("<QuoteValue>"); result.Append(theQuote); result.Append("</QuoteValue>"); result.Append(Environment.NewLine); result.Append("</Quote>"); result.Append(Environment.NewLine); /* <Quote> <Author></Author> <Language>French</Language> <QuoteValue></QuoteValue> </Quote> */ return result.ToString(); } private static Dictionary<string, string> LoadDictionary(string fileName) { Dictionary<string, string> result = new Dictionary<string, string>(); if (!File.Exists(fileName)) return result; List<string> quotesList = new List<string>(); StreamReader sr = new StreamReader(fileName); string line = string.Empty; while ((line = sr.ReadLine()) != null) { quotesList.Add(line); } for (int i = 0; i < quotesList.Count; i = i + 2) { if (!result.ContainsKey(quotesList[i])) { result.Add(quotesList[i], quotesList[i + 1]); } //else //{ // Console.WriteLine(quotesList[i]); //} } return result; } } }
using System; using System.Collections.Generic; using System.IO; namespace CreateXMLFile { internal static class Program { private static void Main() { const string fileName = "quotes-cleaned.txt"; const string XmlFileName = "quotes-XML.txt"; Dictionary<string, string> dicoQuotes = new Dictionary<string, string>(); dicoQuotes = LoadDictionary(fileName); // create XML file if (!File.Exists(XmlFileName)) { StreamWriter sw2 = new StreamWriter(XmlFileName, false); sw2.WriteLine(string.Empty); sw2.Close(); } StreamWriter sw = new StreamWriter(XmlFileName, false); foreach (KeyValuePair<string, string> keyValuePair in dicoQuotes) { sw.WriteLine(string.Empty); } sw.Close(); Console.WriteLine("Press a key to exit:"); Console.ReadKey(); } private static string AddTag(string msg) { string result = string.Empty; /* *<Quote> <Author></Author> <Language>French</Language> <QuoteValue></QuoteValue> </Quote> */ return result; } private static Dictionary<string, string> LoadDictionary(string fileName) { Dictionary<string, string> result = new Dictionary<string, string>(); if (!File.Exists(fileName)) return result; List<string> quotesList = new List<string>(); StreamReader sr = new StreamReader(fileName); string line = string.Empty; while ((line = sr.ReadLine()) != null) { quotesList.Add(line); } for (int i = 0; i < quotesList.Count; i = i + 2) { if (!result.ContainsKey(quotesList[i])) { result.Add(quotesList[i], quotesList[i + 1]); } //else //{ // Console.WriteLine(quotesList[i]); //} } return result; } } }
mit
C#
cdceb81dc4cca379c665b570ebe8363d3f7fc712
Update PowerShellMetricTelemeter.cs
tiksn/TIKSN-Framework
TIKSN.Framework.Core/Analytics/Telemetry/PowerShellMetricTelemeter.cs
TIKSN.Framework.Core/Analytics/Telemetry/PowerShellMetricTelemeter.cs
using System.Management.Automation; using System.Threading.Tasks; namespace TIKSN.Analytics.Telemetry { public class PowerShellMetricTelemeter : IMetricTelemeter { private readonly Cmdlet cmdlet; public PowerShellMetricTelemeter(Cmdlet cmdlet) => this.cmdlet = cmdlet; public Task TrackMetricAsync(string metricName, decimal metricValue) { this.cmdlet.WriteVerbose($"METRIC: {metricName} - {metricValue}"); return Task.FromResult<object>(null); } } }
using System.Management.Automation; using System.Threading.Tasks; namespace TIKSN.Analytics.Telemetry { public class PowerShellMetricTelemeter : IMetricTelemeter { private readonly Cmdlet cmdlet; public PowerShellMetricTelemeter(Cmdlet cmdlet) => this.cmdlet = cmdlet; public Task TrackMetric(string metricName, decimal metricValue) { this.cmdlet.WriteVerbose($"METRIC: {metricName} - {metricValue}"); return Task.FromResult<object>(null); } } }
mit
C#
41aca7012eb7c5ee7b8ef06aba4e78ae4750e4ad
Set default value to PropertyMetadata
naotaco/BindingTest
BindingTest/Control/CheckboxControl.xaml.cs
BindingTest/Control/CheckboxControl.xaml.cs
using System.Windows; using System.Windows.Controls; namespace BindingTest.Control { public partial class CheckboxControl : UserControl { public bool Checked { get { return (bool)GetValue(CheckboxProperty); } set { SetValue(CheckboxProperty, value); _CheckBox.IsChecked = value; } } public static readonly DependencyProperty CheckboxProperty = DependencyProperty.Register( "Checked", typeof(bool), typeof(CheckboxControl), new PropertyMetadata(false, new PropertyChangedCallback(CheckboxControl.StateChanged))); private static void StateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { (d as CheckboxControl).Checked = (bool)e.NewValue; } public CheckboxControl() { InitializeComponent(); } private void _CheckBox_Checked(object sender, RoutedEventArgs e) { this.Checked = (bool)(sender as CheckBox).IsChecked; } private void _CheckBox_Unchecked(object sender, RoutedEventArgs e) { this.Checked = (bool)(sender as CheckBox).IsChecked; } } }
using System.Windows; using System.Windows.Controls; namespace BindingTest.Control { public partial class CheckboxControl : UserControl { public bool Checked { get { return (bool)GetValue(CheckboxProperty); } set { SetValue(CheckboxProperty, value); _CheckBox.IsChecked = value; } } public static readonly DependencyProperty CheckboxProperty = DependencyProperty.Register( "Checked", typeof(bool), typeof(CheckboxControl), new PropertyMetadata(new PropertyChangedCallback(CheckboxControl.StateChanged))); private static void StateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { (d as CheckboxControl).Checked = (bool)e.NewValue; } public CheckboxControl() { InitializeComponent(); } private void _CheckBox_Checked(object sender, RoutedEventArgs e) { this.Checked = (bool)(sender as CheckBox).IsChecked; } private void _CheckBox_Unchecked(object sender, RoutedEventArgs e) { this.Checked = (bool)(sender as CheckBox).IsChecked; } } }
mit
C#
30a245d361937a0206a2c1c4908295b999912f51
add TODOs
dimaaan/pgEdit
PgEdit/Program.cs
PgEdit/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace PgEdit { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { // TODO close ssh tunnels on program exit // TODO panel for quick reset, edit filters similar to EMS manager. Appers under table. // TODO table Fields: more details // TODO navigation: clicking by foreight key cell send user to row with primary key // TODO navigation: clicking by primary key cell opens menu with depend tables. selecting table send user to table with dependent rows filtered // TODO navigation: forward and backward buttons, support mouse additional buttons Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace PgEdit { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } } }
mit
C#
2b6aea290a3e5c177e1ca18012fda79f126e6e71
Update 404 page
k94ll13nn3/Strinken
docs/input/404.cshtml
docs/input/404.cshtml
@{ Layout = ""; } <!DOCTYPE html> <html lang="en"> <head> <!-- Simple HttpErrorPages | MIT X11 License | https://github.com/AndiDittrich/HttpErrorPages --> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>We've got some trouble | 404 - Resource not found</title> <style type="text/css">/*! normalize.css v5.0.0 | MIT License | github.com/necolas/normalize.css */html{font-family:sans-serif;line-height:1.15;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,footer,header,nav,section{display:block}h1{font-size:2em;margin:.67em 0}figcaption,figure,main{display:block}figure{margin:1em 40px}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent;-webkit-text-decoration-skip:objects}a:active,a:hover{outline-width:0}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:inherit}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}dfn{font-style:italic}mark{background-color:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}audio,video{display:inline-block}audio:not([controls]){display:none;height:0}img{border-style:none}svg:not(:root){overflow:hidden}button,input,optgroup,select,textarea{font-family:sans-serif;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type=reset],[type=submit],button,html [type=button]{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{display:inline-block;vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-cancel-button,[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details,menu{display:block}summary{display:list-item}canvas{display:inline-block}template{display:none}[hidden]{display:none}/*! Simple HttpErrorPages | MIT X11 License | https://github.com/AndiDittrich/HttpErrorPages */body,html{width:100%;height:100%;background-color:#21232a}body{color:#fff;text-align:center;text-shadow:0 2px 4px rgba(0,0,0,.5);padding:0;min-height:100%;-webkit-box-shadow:inset 0 0 75pt rgba(0,0,0,.8);box-shadow:inset 0 0 75pt rgba(0,0,0,.8);display:table;font-family:"Open Sans",Arial,sans-serif}h1{font-family:inherit;font-weight:500;line-height:1.1;color:inherit;font-size:36px}h1 small{font-size:68%;font-weight:400;line-height:1;color:#777}a{text-decoration:none;color:#fff;font-size:inherit;border-bottom:dotted 1px #707070}.lead{color:silver;font-size:21px;line-height:1.4}.cover{display:table-cell;vertical-align:middle;padding:0 20px}footer{position:fixed;width:100%;height:40px;left:0;bottom:0;color:#a0a0a0;font-size:14px}</style> </head> <body> <div class="cover"> <h1>Resource not found <small>Error 404</small></h1> <p class="lead">The requested resource could not be found but may be available again in the future.</p> <p><a [email protected]("/")>Home</a></p> </div> </body> <footer> <p>Page by: <a href=https://github.com/AndiDittrich/HttpErrorPages>AndiDittrich</a></p> </footer> </html>
Title: 404 NoSidebar: true NoContainer: true NoGutter: true --- <div class="jumbotron"> <div class="container"> <h1>404</h1> </div> </div>
mit
C#
4ede88414f25ddbecc6d0c7b47967c2c73489fc9
Bump library version to 1.9.0
Norbyte/lslib,Norbyte/lslib,Norbyte/lslib
LSLib/LS/Common.cs
LSLib/LS/Common.cs
using System; namespace LSLib.LS { public static class Common { public const int MajorVersion = 1; public const int MinorVersion = 9; public const int PatchVersion = 0; /// <summary> /// Returns the version number of the LSLib library /// </summary> public static string LibraryVersion() { return String.Format("{0}.{1}.{2}", MajorVersion, MinorVersion, PatchVersion); } } }
using System; namespace LSLib.LS { public static class Common { public const int MajorVersion = 1; public const int MinorVersion = 8; public const int PatchVersion = 6; /// <summary> /// Returns the version number of the LSLib library /// </summary> public static string LibraryVersion() { return String.Format("{0}.{1}.{2}", MajorVersion, MinorVersion, PatchVersion); } } }
mit
C#
e7ba9365a55adc32ca3e37dde46143968a7aa129
Update UsernamePasswordLoginRequest.cs
jerriep/auth0.net,auth0/auth0.net,auth0/auth0.net,jerriep/auth0.net,jerriep/auth0.net
src/Auth0.AuthenticationApi/Models/UsernamePasswordLoginRequest.cs
src/Auth0.AuthenticationApi/Models/UsernamePasswordLoginRequest.cs
using Newtonsoft.Json; namespace Auth0.AuthenticationApi.Models { /// <summary> /// Represents an active authentication request with SSO support. /// </summary> public class UsernamePasswordLoginRequest { /// <summary> /// Gets or sets the client (app) identifier. /// </summary> [JsonProperty("client_id")] public string ClientId { get; set; } /// <summary> /// Gets or sets the connection. /// </summary> [JsonProperty("connection")] public string Connection { get; set; } /// <summary> /// Gets or sets redirect uri. /// </summary> [JsonProperty("redirect_uri")] public string RedirectUri { get; set; } /// <summary> /// Gets or sets the response type. /// </summary> [JsonProperty("response_type")] public string ResponseType { get; set; } /// <summary> /// Gets or sets the identifier token. /// </summary> [JsonProperty("id_token")] public string IdToken { get; set; } /// <summary> /// Gets or sets the password. /// </summary> [JsonProperty("password")] public string Password { get; set; } /// <summary> /// Gets or sets the requested scope. /// </summary> [JsonProperty("scope")] public string Scope { get; set; } /// <summary> /// Gets or sets the username. /// </summary> [JsonProperty("username")] public string Username { get; set; } /// <summary> /// Gets or sets the tenant. /// </summary> [JsonProperty("tenant")] public string Tenant { get; set; } /// <summary> /// Gets or sets the device. /// </summary> [JsonProperty("device")] public string Device { get; set; } } }
using Newtonsoft.Json; namespace Auth0.AuthenticationApi.Models { /// <summary> /// Represents an active authentication request with SSO support. /// </summary> public class UsernamePasswordLoginRequest { /// <summary> /// Gets or sets the client (app) identifier. /// </summary> [JsonProperty("client_id")] public string ClientId { get; set; } /// <summary> /// Gets or sets the connection. /// </summary> [JsonProperty("connection")] public string Connection { get; set; } /// <summary> /// Gets or sets redirect uri. /// </summary> [JsonProperty("redirect_uri")] public string RedirectUri { get; set; } /// <summary> /// Gets or sets the response type. /// </summary> [JsonProperty("response_type")] public string ResponseType { get; set; } /// <summary> /// Gets or sets the identifier token. /// </summary> [JsonProperty("id_token")] public string IdToken { get; set; } /// <summary> /// Gets or sets the password. /// </summary> [JsonProperty("password")] public string Password { get; set; } /// <summary> /// Gets or sets the requested scope. /// </summary> [JsonProperty("scope")] public string Scope { get; set; } /// <summary> /// Gets or sets the username. /// </summary> [JsonProperty("username")] public string Username { get; set; } /// <summary> /// Gets or sets the tenant. /// </summary> [JsonProperty("tenant")] public string Tenant { get; set; } } }
mit
C#
7f0f745037d44a510287a4c47ee6898e8f34bee0
Update Link.cs
mcintyre321/SirenSharp
SirenSharp/Link.cs
SirenSharp/Link.cs
namespace SirenSharp { using System; using System.Collections.Generic; /// <summary> /// Links represent navigational transitions. /// </summary> public class Link { public Link () {} /// <summary> /// Initializes a new instance of the <see cref="Link"/> class with required properties. /// </summary> /// <param name="href">Hypermedia reference</param> /// <param name="rel">Unique relationship</param> public Link(Uri href, params string[] rel) { this.Rel = rel; this.Href = href; } /// <summary> /// Initializes a new instance of the <see cref="Link"/> class with required properties. /// </summary> /// <param name="href">Hypermedia reference</param> /// <param name="rel">Unique relationship</param> public Link(string href, params string[] rel) { this.Rel = rel; this.Href = new Uri(href, UriKind.Relative); } /// <summary> /// Gets or sets the unique relationship for a client to find this link. /// </summary> /// <remarks> /// Defines the relationship of the link to its entity, per Web Linking (RFC5899). MUST be an array of strings. Required. /// </remarks> public IEnumerable<string> Rel { get; set; } /// <summary> /// Gets or sets the hypermedia reference for a client to get. /// </summary> /// <remarks> /// The URI of the linked resource. Required. /// </remarks> public Uri Href { get; set; } } }
namespace SirenSharp { using System; using System.Collections.Generic; /// <summary> /// Links represent navigational transitions. /// </summary> public class Link { /// <summary> /// Initializes a new instance of the <see cref="Link"/> class with required properties. /// </summary> /// <param name="href">Hypermedia reference</param> /// <param name="rel">Unique relationship</param> public Link(Uri href, params string[] rel) { this.Rel = rel; this.Href = href; } /// <summary> /// Initializes a new instance of the <see cref="Link"/> class with required properties. /// </summary> /// <param name="href">Hypermedia reference</param> /// <param name="rel">Unique relationship</param> public Link(string href, params string[] rel) { this.Rel = rel; this.Href = new Uri(href, UriKind.Relative); } /// <summary> /// Gets or sets the unique relationship for a client to find this link. /// </summary> /// <remarks> /// Defines the relationship of the link to its entity, per Web Linking (RFC5899). MUST be an array of strings. Required. /// </remarks> public IEnumerable<string> Rel { get; set; } /// <summary> /// Gets or sets the hypermedia reference for a client to get. /// </summary> /// <remarks> /// The URI of the linked resource. Required. /// </remarks> public Uri Href { get; set; } } }
mit
C#
4772e2d91b421ca636d8ad0a506e6dacceb69db6
fix typo
joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
Joinrpg/Views/Shared/_LoginPartial.cshtml
Joinrpg/Views/Shared/_LoginPartial.cshtml
@using Microsoft.AspNet.Identity @if (Request.IsAuthenticated) { using (Html.BeginForm("LogOff", "Account", new {area = ""}, FormMethod.Post, new {id = "logoutForm", @class = "navbar-right",})) { @Html.AntiForgeryToken() <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <img src="https://www.gravatar.com/avatar/@ViewBag.GravatarHash?d=identicon&s=24"/>&nbsp;@ViewBag.UserDisplayName </a> <ul class="dropdown-menu"> <li>@Html.ActionLink("Профиль", "Me", "User", new {area = ""}, null)</li> <li>@Html.ActionLink("Аккаунт", "Index", "Manage", new {area = ""}, null)</li> <li><a href="http://docs.joinrpg.ru">Помощь</a></li> @if (User.IsInRole("admin")) { <li>@Html.ActionLink("Панель администратора", "Index", "AdminHome", new { area = "Admin" }, null)</li> } <li><a href="javascript:document.getElementById('logoutForm').submit()">Выйти</a></li> </ul> </li> </ul> } } else { <ul class="nav navbar-nav navbar-right"> <li>@Html.ActionLink("Регистрация", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li> <li>@Html.ActionLink("Войти", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> <li><a href="http://docs.joinrpg.ru">Помощь</a></li> </ul> }
g@using Microsoft.AspNet.Identity @if (Request.IsAuthenticated) { using (Html.BeginForm("LogOff", "Account", new {area = ""}, FormMethod.Post, new {id = "logoutForm", @class = "navbar-right",})) { @Html.AntiForgeryToken() <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <img src="https://www.gravatar.com/avatar/@ViewBag.GravatarHash?d=identicon&s=24"/>&nbsp;@ViewBag.UserDisplayName </a> <ul class="dropdown-menu"> <li>@Html.ActionLink("Профиль", "Me", "User", new {area = ""}, null)</li> <li>@Html.ActionLink("Аккаунт", "Index", "Manage", new {area = ""}, null)</li> <li><a href="http://docs.joinrpg.ru">Помощь</a></li> @if (User.IsInRole("admin")) { <li>@Html.ActionLink("Панель администратора", "Index", "AdminHome", new { area = "Admin" }, null)</li> } <li><a href="javascript:document.getElementById('logoutForm').submit()">Выйти</a></li> </ul> </li> </ul> } } else { <ul class="nav navbar-nav navbar-right"> <li>@Html.ActionLink("Регистрация", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li> <li>@Html.ActionLink("Войти", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> <li><a href="http://docs.joinrpg.ru">Помощь</a></li> </ul> }
mit
C#
8770d2f9faf01d911099f0430192880c3907923c
Revert "FontSettings.DefaultInstance"
aspose-words/Aspose.Words-for-.NET,asposewords/Aspose_Words_NET,asposewords/Aspose_Words_NET,asposewords/Aspose_Words_NET,aspose-words/Aspose.Words-for-.NET,aspose-words/Aspose.Words-for-.NET,aspose-words/Aspose.Words-for-.NET,asposewords/Aspose_Words_NET
Examples/CSharp/Rendering-Printing/SetTrueTypeFontsFolder.cs
Examples/CSharp/Rendering-Printing/SetTrueTypeFontsFolder.cs
using System; using System.IO; using System.Reflection; using Aspose.Words.Fonts; using Aspose.Words; using Aspose.Words.Saving; namespace CSharp.Rendering_and_Printing { class SetTrueTypeFontsFolder { public static void Run() { //ExStart:SetTrueTypeFontsFolder // The path to the documents directory. string dataDir = RunExamples.GetDataDir_RenderingAndPrinting(); Document doc = new Document(dataDir + "Rendering.doc"); FontSettings FontSettings = new FontSettings(); // Note that this setting will override any default font sources that are being searched by default. Now only these folders will be searched for // fonts when rendering or embedding fonts. To add an extra font source while keeping system font sources then use both FontSettings.GetFontSources and // FontSettings.SetFontSources instead. FontSettings.SetFontsFolder(@"C:\MyFonts\", false); dataDir = dataDir + "Rendering.SetFontsFolder_out_.pdf"; doc.Save(dataDir); //ExEnd:SetTrueTypeFontsFolder Console.WriteLine("\nTrue type fonts folder setup successfully.\nFile saved at " + dataDir); } } }
using System; using System.IO; using System.Reflection; using Aspose.Words.Fonts; using Aspose.Words; using Aspose.Words.Saving; namespace CSharp.Rendering_and_Printing { class SetTrueTypeFontsFolder { public static void Run() { //ExStart:SetTrueTypeFontsFolder // The path to the documents directory. string dataDir = RunExamples.GetDataDir_RenderingAndPrinting(); Document doc = new Document(dataDir + "Rendering.doc"); FontSettings FontSettings = new FontSettings(); // Note that this setting will override any default font sources that are being searched by default. Now only these folders will be searched for // fonts when rendering or embedding fonts. To add an extra font source while keeping system font sources then use both FontSettings.GetFontSources and // FontSettings.SetFontSources instead. FontSettings.SetFontsFolder(@"C:\MyFonts\", false); //FontSettings.DefaultInstance.SetFontsFolder(@"C:\MyFonts\", false); dataDir = dataDir + "Rendering.SetFontsFolder_out_.pdf"; doc.Save(dataDir); //ExEnd:SetTrueTypeFontsFolder Console.WriteLine("\nTrue type fonts folder setup successfully.\nFile saved at " + dataDir); } } }
mit
C#
966c6d1cdc6fba8c8b2a1c4566e1d8475eb715c8
Change stats link
stanriders/den0bot,stanriders/den0bot
den0bot/Modules/ModAnalytics.cs
den0bot/Modules/ModAnalytics.cs
// den0bot (c) StanR 2019 - MIT License using System; using System.Collections.Generic; using System.Threading.Tasks; using den0bot.Analytics.Data; using den0bot.Analytics.Data.Types; using den0bot.Util; namespace den0bot.Modules { public class ModAnalytics : IModule, IReceiveAllMessages { private static readonly List<Message> messageBuffer = new List<Message>(); private DateTime nextFlush = DateTime.Now; private const int buffer_flush_interval = 3; // minutes public ModAnalytics() { AddCommand(new Command { Name = "compot", Action = (msg) => $"https://stats.stanr.info/chat/{msg.Chat.Id}", Reply = true }); using (var db = new AnalyticsDatabase()) db.Database.EnsureCreated(); Log.Debug("Enabled"); } public Task ReceiveMessage(Telegram.Bot.Types.Message message) { if (message.Chat.Type != Telegram.Bot.Types.Enums.ChatType.Private) { messageBuffer.Add(new Message { TelegramId = message.MessageId, ChatId = message.Chat.Id, UserId = message.From.Id, Timestamp = message.Date.ToUniversalTime().Ticks, Type = message.Type.ToDbType(), Command = string.Empty, Length = message.Text?.Length ?? 0 }); } return Task.CompletedTask; } public override void Think() { if (messageBuffer.Count > 0 && nextFlush < DateTime.Now) { _ = Flush(); nextFlush = DateTime.Now.AddMinutes(buffer_flush_interval); } } private async Task Flush() { await using (var db = new AnalyticsDatabase()) { await db.Messages.AddRangeAsync(messageBuffer); await db.SaveChangesAsync(); messageBuffer.Clear(); } } public static void AddMessage(Message msg) { messageBuffer.Add(msg); } public static async Task AddGirl(long chatId, long userId) { await using (var db = new AnalyticsDatabase()) { await db.Girls.AddAsync(new Girl { ChatId = chatId, UserId = userId }); await db.SaveChangesAsync(); } } } }
// den0bot (c) StanR 2019 - MIT License using System; using System.Collections.Generic; using System.Threading.Tasks; using den0bot.Analytics.Data; using den0bot.Analytics.Data.Types; using den0bot.Util; namespace den0bot.Modules { public class ModAnalytics : IModule, IReceiveAllMessages { private static readonly List<Message> messageBuffer = new List<Message>(); private DateTime nextFlush = DateTime.Now; private const int buffer_flush_interval = 3; // minutes public ModAnalytics() { AddCommand(new Command { Name = "compot", Action = (msg) => $"https://stats.stanr.info/home/chat?chatId={msg.Chat.Id}", Reply = true }); using (var db = new AnalyticsDatabase()) db.Database.EnsureCreated(); Log.Debug("Enabled"); } public Task ReceiveMessage(Telegram.Bot.Types.Message message) { if (message.Chat.Type != Telegram.Bot.Types.Enums.ChatType.Private) { messageBuffer.Add(new Message { TelegramId = message.MessageId, ChatId = message.Chat.Id, UserId = message.From.Id, Timestamp = message.Date.ToUniversalTime().Ticks, Type = message.Type.ToDbType(), Command = string.Empty, Length = message.Text?.Length ?? 0 }); } return Task.CompletedTask; } public override void Think() { if (messageBuffer.Count > 0 && nextFlush < DateTime.Now) { _ = Flush(); nextFlush = DateTime.Now.AddMinutes(buffer_flush_interval); } } private async Task Flush() { await using (var db = new AnalyticsDatabase()) { await db.Messages.AddRangeAsync(messageBuffer); await db.SaveChangesAsync(); messageBuffer.Clear(); } } public static void AddMessage(Message msg) { messageBuffer.Add(msg); } public static async Task AddGirl(long chatId, long userId) { await using (var db = new AnalyticsDatabase()) { await db.Girls.AddAsync(new Girl { ChatId = chatId, UserId = userId }); await db.SaveChangesAsync(); } } } }
mit
C#
146b3b6cf0fe7ad35e03d043c03ec0ebd0590993
fix default mapzen map data format
reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap
unity/library/UtyMap.Unity/Maps/Providers/MapzenMapDataProvider.cs
unity/library/UtyMap.Unity/Maps/Providers/MapzenMapDataProvider.cs
using System; using System.IO; using UtyDepend; using UtyDepend.Config; using UtyMap.Unity.Core.Tiling; using UtyMap.Unity.Infrastructure.Diagnostic; using UtyMap.Unity.Infrastructure.IO; using UtyRx; namespace UtyMap.Unity.Maps.Providers { /// <summary> Downloads map data from mapzen servers. </summary> public class MapzenMapDataProvider : MapDataProvider, IConfigurable { private string _cachePath; private string _mapDataServerUri; private string _mapDataFormatExtension; private string _mapDataLayers; private string _mapDataApiKey; [Dependency] public MapzenMapDataProvider(IFileSystemService fileSystemService, INetworkService networkService, ITrace trace) : base(fileSystemService, networkService, trace) { } /// <inheritdoc /> public override IObservable<string> Get(Tile tile) { var filePath = Path.Combine(_cachePath, tile.QuadKey + _mapDataFormatExtension); var uri = String.Format(_mapDataServerUri, _mapDataLayers, tile.QuadKey.LevelOfDetail, tile.QuadKey.TileX, tile.QuadKey.TileY, _mapDataApiKey); return Get(tile, uri, filePath); } /// <inheritdoc /> public void Configure(IConfigSection configSection) { _mapDataServerUri = configSection.GetString(@"data/mapzen/server", null); _mapDataFormatExtension = "." + configSection.GetString(@"data/mapzen/format", "json"); _mapDataApiKey = configSection.GetString(@"data/mapzen/apikey", null); _mapDataLayers = configSection.GetString(@"data/mapzen/layers", null); _cachePath = configSection.GetString(@"data/cache", null); } } }
using System; using System.IO; using UtyDepend; using UtyDepend.Config; using UtyMap.Unity.Core.Tiling; using UtyMap.Unity.Infrastructure.Diagnostic; using UtyMap.Unity.Infrastructure.IO; using UtyRx; namespace UtyMap.Unity.Maps.Providers { /// <summary> Downloads map data from mapzen servers. </summary> public class MapzenMapDataProvider : MapDataProvider, IConfigurable { private string _cachePath; private string _mapDataServerUri; private string _mapDataFormatExtension; private string _mapDataLayers; private string _mapDataApiKey; [Dependency] public MapzenMapDataProvider(IFileSystemService fileSystemService, INetworkService networkService, ITrace trace) : base(fileSystemService, networkService, trace) { } /// <inheritdoc /> public override IObservable<string> Get(Tile tile) { var filePath = Path.Combine(_cachePath, tile.QuadKey + _mapDataFormatExtension); var uri = String.Format(_mapDataServerUri, _mapDataLayers, tile.QuadKey.LevelOfDetail, tile.QuadKey.TileX, tile.QuadKey.TileY, _mapDataApiKey); return Get(tile, uri, filePath); } /// <inheritdoc /> public void Configure(IConfigSection configSection) { _mapDataServerUri = configSection.GetString(@"data/mapzen/server", null); _mapDataFormatExtension = "." + configSection.GetString(@"data/mapzen/format", "xml"); _mapDataApiKey = configSection.GetString(@"data/mapzen/apikey", null); _mapDataLayers = configSection.GetString(@"data/mapzen/layers", null); _cachePath = configSection.GetString(@"data/cache", null); } } }
apache-2.0
C#
c87250b88a28e9d01eadb65eb88912d5d186798b
Fix disposal of TwoWay handler (#1400)
googleapis/google-api-dotnet-client,jskeet/google-api-dotnet-client,googleapis/google-api-dotnet-client,jskeet/google-api-dotnet-client,googleapis/google-api-dotnet-client,jskeet/google-api-dotnet-client
Src/Support/Google.Apis.Core/Http/TwoWayDelegatingHandler.cs
Src/Support/Google.Apis.Core/Http/TwoWayDelegatingHandler.cs
/* Copyright 2017 Google Inc 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.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Google.Apis.Http { /// <summary> /// An HttpMessageHandler that delegates to one of two inner handlers based on a condition /// checked on each request. /// </summary> internal sealed class TwoWayDelegatingHandler : DelegatingHandler { private readonly AccessibleDelegatingHandler _alternativeHandler; private readonly Func<HttpRequestMessage, bool> _useAlternative; private bool disposed = false; internal TwoWayDelegatingHandler(HttpMessageHandler normalHandler, HttpMessageHandler alternativeHandler, Func<HttpRequestMessage, bool> useAlternative) : base(normalHandler) { _alternativeHandler = new AccessibleDelegatingHandler(alternativeHandler); _useAlternative = useAlternative; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => _useAlternative(request) ? _alternativeHandler.InternalSendAsync(request, cancellationToken) : base.SendAsync(request, cancellationToken); protected override void Dispose(bool disposing) { if (disposing && !disposed) { disposed = true; _alternativeHandler.Dispose(); } base.Dispose(disposing); } /// <summary> /// Handler to wrap another, just so that we can effectively expose its SendAsync method. /// </summary> private sealed class AccessibleDelegatingHandler : DelegatingHandler { internal AccessibleDelegatingHandler(HttpMessageHandler innerHandler) : base(innerHandler) { } internal Task<HttpResponseMessage> InternalSendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => SendAsync(request, cancellationToken); } } }
/* Copyright 2017 Google Inc 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.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Google.Apis.Http { /// <summary> /// An HttpMessageHandler that delegates to one of two inner handlers based on a condition /// checked on each request. /// </summary> internal sealed class TwoWayDelegatingHandler : DelegatingHandler { private readonly AccessibleDelegatingHandler _alternativeHandler; private readonly Func<HttpRequestMessage, bool> _useAlternative; private bool disposed = false; internal TwoWayDelegatingHandler(HttpMessageHandler normalHandler, HttpMessageHandler alternativeHandler, Func<HttpRequestMessage, bool> useAlternative) : base(normalHandler) { _alternativeHandler = new AccessibleDelegatingHandler(alternativeHandler); _useAlternative = useAlternative; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => _useAlternative(request) ? _alternativeHandler.InternalSendAsync(request, cancellationToken) : base.SendAsync(request, cancellationToken); protected override void Dispose(bool disposing) { if (disposing && !disposed) { disposed = true; try { base.Dispose(); } finally { _alternativeHandler.Dispose(); } } } /// <summary> /// Handler to wrap another, just so that we can effectively expose its SendAsync method. /// </summary> private sealed class AccessibleDelegatingHandler : DelegatingHandler { internal AccessibleDelegatingHandler(HttpMessageHandler innerHandler) : base(innerHandler) { } internal Task<HttpResponseMessage> InternalSendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => SendAsync(request, cancellationToken); } } }
apache-2.0
C#
d19c8f56be69c913c95b72334b6cea5e9e7e71bf
Make RulesetInfo implement IEquatable since EqualityComparer was sometimes giving false negatives and causing Bindable observers to fire
DrabWeb/osu,ppy/osu,Damnae/osu,EVAST9919/osu,smoogipoo/osu,2yangk23/osu,naoey/osu,UselessToucan/osu,DrabWeb/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,ZLima12/osu,johnneijzen/osu,peppy/osu,UselessToucan/osu,Drezi126/osu,johnneijzen/osu,ppy/osu,ZLima12/osu,ppy/osu,EVAST9919/osu,naoey/osu,Frontear/osuKyzer,peppy/osu-new,Nabile-Rahmani/osu,smoogipoo/osu,peppy/osu,2yangk23/osu,naoey/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,DrabWeb/osu
osu.Game/Rulesets/RulesetInfo.cs
osu.Game/Rulesets/RulesetInfo.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using SQLite.Net.Attributes; namespace osu.Game.Rulesets { public class RulesetInfo : IEquatable<RulesetInfo> { [PrimaryKey, AutoIncrement] public int? ID { get; set; } [Indexed(Unique = true)] public string Name { get; set; } [Indexed(Unique = true)] public string InstantiationInfo { get; set; } [Indexed] public bool Available { get; set; } public virtual Ruleset CreateInstance() => (Ruleset)Activator.CreateInstance(Type.GetType(InstantiationInfo), this); public bool Equals(RulesetInfo other) { return this.ID == other.ID && this.Available == other.Available && this.Name == other.Name && this.InstantiationInfo == other.InstantiationInfo; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using SQLite.Net.Attributes; namespace osu.Game.Rulesets { public class RulesetInfo { [PrimaryKey, AutoIncrement] public int? ID { get; set; } [Indexed(Unique = true)] public string Name { get; set; } [Indexed(Unique = true)] public string InstantiationInfo { get; set; } [Indexed] public bool Available { get; set; } public virtual Ruleset CreateInstance() => (Ruleset)Activator.CreateInstance(Type.GetType(InstantiationInfo), this); } }
mit
C#
856f60169232370989d514b695abdf272d6182cf
Set today as default value
SanguPackage/TWTactics
TribalWars/Controls/Common/TimeConverterCalculatorControl.cs
TribalWars/Controls/Common/TimeConverterCalculatorControl.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace TribalWars.Controls { /// <summary> /// Adds addings time functionality to the TimeConverterControl /// </summary> public partial class TimeConverterCalculatorControl : UserControl { #region Constructors public TimeConverterCalculatorControl() { InitializeComponent(); } #endregion protected override void OnLoad(EventArgs e) { base.OnLoad(e); TimeConverter.Value = DateTime.Today; } #region Event Handlers /// <summary> /// Adds the time to the original date value /// </summary> private void AddTime_Click(object sender, EventArgs e) { if (ToAdd.Value.Hour == 0 && ToAdd.Value.Minute == 0 && ToAdd.Value.Second == 0) { MessageBox.Show("Specify the time in the right box (format: HH:MM:SS (hours, minutes, seconds)) to be added to the time in the box left." + Environment.NewLine + "This can be handy when you need to calculate the time to send your troops."); } else { var span = new TimeSpan(ToAdd.Value.Hour, ToAdd.Value.Minute, ToAdd.Value.Second); TimeConverter.Value = TimeConverter.Value.Add(span); } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace TribalWars.Controls { /// <summary> /// Adds addings time functionality to the TimeConverterControl /// </summary> public partial class TimeConverterCalculatorControl : UserControl { #region Constructors public TimeConverterCalculatorControl() { InitializeComponent(); } #endregion #region Event Handlers /// <summary> /// Adds the time to the original date value /// </summary> private void AddTime_Click(object sender, EventArgs e) { if (ToAdd.Value.Hour == 0 && ToAdd.Value.Minute == 0 && ToAdd.Value.Second == 0) { MessageBox.Show("Specify the time in the right box (format: HH:MM:SS (hours, minutes, seconds)) to be added to the time in the box left." + Environment.NewLine + "This can be handy when you need to calculate the time to send your troops."); } else { TimeSpan span = new TimeSpan(ToAdd.Value.Hour, ToAdd.Value.Minute, ToAdd.Value.Second); TimeConverter.Value = TimeConverter.Value.Add(span); } } #endregion } }
mit
C#
b2abb641661eee0c8cbc650a1e0fdd73b19ee9ae
Remove unused property Statement.StackTrace
lpatalas/NhLogAnalyzer
NhLogAnalyzer/Infrastructure/Statement.cs
NhLogAnalyzer/Infrastructure/Statement.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace NhLogAnalyzer.Infrastructure { public class Statement { private readonly int id; public int Id { get { return id; } } private readonly string fullSql; public string FullSql { get { return fullSql; } } private readonly string shortSql; public string ShortSql { get { return shortSql; } } private readonly IList<StackFrame> stackFrames; public IList<StackFrame> StackFrames { get { return stackFrames; } } private readonly DateTime timestamp; public DateTime Timestamp { get { return timestamp; } } public Statement(int id, string fullSql, string shortSql, DateTime timestamp) : this(id, fullSql, shortSql, timestamp, new List<StackFrame>()) { } public Statement(int id, string fullSql, string shortSql, DateTime timestamp, IList<StackFrame> stackFrames) { this.id = id; this.fullSql = fullSql; this.shortSql = shortSql; this.stackFrames = stackFrames; this.timestamp = timestamp; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace NhLogAnalyzer.Infrastructure { public class Statement { private readonly int id; public int Id { get { return id; } } private readonly string fullSql; public string FullSql { get { return fullSql; } } private readonly string shortSql; public string ShortSql { get { return shortSql; } } private readonly IList<StackFrame> stackFrames; public IList<StackFrame> StackFrames { get { return stackFrames; } } public string StackTrace { get { return string.Empty; } } private readonly DateTime timestamp; public DateTime Timestamp { get { return timestamp; } } public Statement(int id, string fullSql, string shortSql, DateTime timestamp) : this(id, fullSql, shortSql, timestamp, new List<StackFrame>()) { } public Statement(int id, string fullSql, string shortSql, DateTime timestamp, IList<StackFrame> stackFrames) { this.id = id; this.fullSql = fullSql; this.shortSql = shortSql; this.stackFrames = stackFrames; this.timestamp = timestamp; } } }
mit
C#
5ba569c9da9b2612c7d53751ae39a2771f4e2040
Remove duplicate bullet point
mmoening/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl
MatterControlLib/ConfigurationPage/PrintLeveling/LevelingStrings.cs
MatterControlLib/ConfigurationPage/PrintLeveling/LevelingStrings.cs
/* Copyright (c) 2018, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg; using MatterHackers.Localizations; namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling { public class LevelingStrings { private int stepNumber = 1; public LevelingStrings() { } public string HomingPageInstructions(bool useZProbe, bool heatBed) { string line1 = "The printer should now be 'homing'.".Localize(); if (heatBed) { line1 += " Once it is finished homing we will heat the bed.".Localize(); } if (useZProbe) { return line1; } else { return string.Format( "{0}\n\n{1}:\n\n\t• {2}\n\n{3}\n\n{4}", line1, "To complete the next few steps you will need".Localize(), "A sheet of paper".Localize(), "We will use this paper to measure the distance between the nozzle and the bed.".Localize(), "Click 'Next' to continue.".Localize()); } } public string CoarseInstruction2 => string.Format( "\t• {0}\n\t• {1}\n{2}", "Place the paper under the extruder".Localize(), "Using the above controls".Localize(), this.FineInstruction2); public string FineInstruction2 => string.Format( "\t• {0}\n\t• {0}\n\n{0}", "Press [Z-] until there is resistance to moving the paper".Localize(), "Press [Z+] once to release the paper".Localize(), "Finally click 'Next' to continue.".Localize()); public string GetStepString(int totalSteps) { return $"{"Step".Localize()} {stepNumber++} {"of".Localize()} {totalSteps}:"; } } }
/* Copyright (c) 2018, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg; using MatterHackers.Localizations; namespace MatterHackers.MatterControl.ConfigurationPage.PrintLeveling { public class LevelingStrings { private int stepNumber = 1; public LevelingStrings() { } public string HomingPageInstructions(bool useZProbe, bool heatBed) { string line1 = "The printer should now be 'homing'.".Localize(); if (heatBed) { line1 += " Once it is finished homing we will heat the bed.".Localize(); } if (useZProbe) { return line1; } else { return string.Format( "{0}\n\n{1}:\n\n\t• {2}\n\n{3}\n\n{4}", line1, "To complete the next few steps you will need".Localize(), "A sheet of paper".Localize(), "We will use this paper to measure the distance between the nozzle and the bed.".Localize(), "Click 'Next' to continue.".Localize()); } } public string CoarseInstruction2 => string.Format( "\t• {0}\n\t• {1}\n\t• {2}", "Place the paper under the extruder".Localize(), "Using the above controls".Localize(), this.FineInstruction2); public string FineInstruction2 => string.Format( "\t• {0}\n\t• {0}\n\n{0}", "Press [Z-] until there is resistance to moving the paper".Localize(), "Press [Z+] once to release the paper".Localize(), "Finally click 'Next' to continue.".Localize()); public string GetStepString(int totalSteps) { return $"{"Step".Localize()} {stepNumber++} {"of".Localize()} {totalSteps}:"; } } }
bsd-2-clause
C#
5e5a0cdb9374d26f58b7105c9538bed9f80393de
Remove DataPortal_Fetch from ReadOnlyBase to bring the class in line with BusinessBase. bugid: 867
jonnybee/csla,MarimerLLC/csla,rockfordlhotka/csla,BrettJaner/csla,MarimerLLC/csla,jonnybee/csla,ronnymgm/csla-light,JasonBock/csla,BrettJaner/csla,ronnymgm/csla-light,jonnybee/csla,MarimerLLC/csla,BrettJaner/csla,rockfordlhotka/csla,JasonBock/csla,rockfordlhotka/csla,JasonBock/csla,ronnymgm/csla-light
Source/Csla.test/Silverlight/Server/Security/SilverlightIdentity.cs
Source/Csla.test/Silverlight/Server/Security/SilverlightIdentity.cs
//----------------------------------------------------------------------- // <copyright file="SilverlightIdentity.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Csla.Serialization; using System.Runtime.Serialization; using Csla.DataPortalClient; using Csla.Core; namespace Csla.Testing.Business.Security { [Serializable()] public class SilverlightIdentity : Csla.Security.CslaIdentity { public SilverlightIdentity() {} #if SILVERLIGHT public void DataPortal_Fetch(object criteria, LocalProxy<SilverlightIdentity>.CompletedHandler completed) { Roles = new MobileList<string>(new string[] { "Admin Role", "User Role" }); IsAuthenticated = true; Name = "SilverlightIdentity"; AuthenticationType = "SilverLight"; completed(this, null); } #else protected void DataPortal_Fetch(object criteria) { if (((SilverlightPrincipal.Criteria)criteria).Name == "invalidusername") { Roles = new MobileList<string>(); IsAuthenticated = false; Name = string.Empty; AuthenticationType = "Csla"; } else { Roles = new MobileList<string>(new string[] { "Admin Role", "User Role" }); IsAuthenticated = true; Name = "SilverlightIdentity"; AuthenticationType = "SilverLight"; } } #endif } }
//----------------------------------------------------------------------- // <copyright file="SilverlightIdentity.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Csla.Serialization; using System.Runtime.Serialization; using Csla.DataPortalClient; using Csla.Core; namespace Csla.Testing.Business.Security { [Serializable()] public class SilverlightIdentity : Csla.Security.CslaIdentity { public SilverlightIdentity() {} #if SILVERLIGHT public void DataPortal_Fetch(object criteria, LocalProxy<SilverlightIdentity>.CompletedHandler completed) { Roles = new MobileList<string>(new string[] { "Admin Role", "User Role" }); IsAuthenticated = true; Name = "SilverlightIdentity"; AuthenticationType = "SilverLight"; completed(this, null); } #else protected override void DataPortal_Fetch(object criteria) { if (((SilverlightPrincipal.Criteria)criteria).Name == "invalidusername") { Roles = new MobileList<string>(); IsAuthenticated = false; Name = string.Empty; AuthenticationType = "Csla"; } else { Roles = new MobileList<string>(new string[] { "Admin Role", "User Role" }); IsAuthenticated = true; Name = "SilverlightIdentity"; AuthenticationType = "SilverLight"; } } #endif } }
mit
C#
acddc2a1a7afe3f6aaa58131e60912cc25841c40
convert ToCartesianCoordinates() to static
opcon/Substructio,opcon/Substructio
Core/Math/PolarVector.cs
Core/Math/PolarVector.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenTK; namespace Substructio.Core.Math { public class PolarVector { public double Radius { get; set; } public double Azimuth { get; set; } public PolarVector(double azimuth, double radius) { Azimuth = azimuth; Radius = radius; } public PolarVector() { Azimuth = 0; Radius = 0; } public Vector2 ToCartesianCoordinates() { //return new Vector2((float)(Radius * System.Math.Cos(Azimuth)), (float)(Radius * System.Math.Sin(Azimuth))); return PolarVector.ToCartesianCoordinates(this); } public static Vector2 ToCartesianCoordinates(PolarVector polarVector) { return new Vector2((float)(polarVector.Radius * System.Math.Cos(polarVector.Azimuth)), (float)(polarVector.Radius * System.Math.Sin(polarVector.Azimuth))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenTK; namespace Substructio.Core.Math { public class PolarVector { public double Radius { get; set; } public double Azimuth { get; set; } public PolarVector(double azimuth, double radius) { Azimuth = azimuth; Radius = radius; } public PolarVector() { Azimuth = 0; Radius = 0; } public Vector2 ToCartesianCoordinates() { return new Vector2((float)(Radius * System.Math.Cos(Azimuth)), (float)(Radius * System.Math.Sin(Azimuth))); } } }
mit
C#
57dd854d57737cc2317e3b531c4f57fb1760536e
Add ThenCreated overloads to Totem.Timeline.Mvc.When
bwatts/Totem,bwatts/Totem
src/Totem.Timeline.Mvc/When.cs
src/Totem.Timeline.Mvc/When.cs
using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Totem.Timeline.Mvc { /// <summary> /// Declares an HTTP response to the specific event type /// </summary> /// <typeparam name="TEvent">The type of event to which to respond</typeparam> public static class When<TEvent> where TEvent : Event { public static CommandWhen Then(Func<TEvent, IActionResult> respond) => new CommandWhen(typeof(TEvent), e => respond((TEvent) e)); public static CommandWhen Then(int statusCode) => Then(e => new StatusCodeResult(statusCode)); public static CommandWhen ThenOk => Then(e => new OkResult()); public static CommandWhen ThenCreated(Func<TEvent, string> getLocation, Func<TEvent, object> getValue) => Then(e => new CreatedResult(getLocation(e), getValue(e))); public static CommandWhen ThenCreated(Func<TEvent, string> getLocation) => Then(e => new CreatedResult(getLocation(e), null)); public static CommandWhen ThenCreated(Func<TEvent, Uri> getLocation, Func<TEvent, object> getValue) => Then(e => new CreatedResult(getLocation(e), getValue(e))); public static CommandWhen ThenCreated(Func<TEvent, Uri> getLocation) => Then(e => new CreatedResult(getLocation(e), null)); public static CommandWhen ThenBadRequest => Then(e => new BadRequestResult()); public static CommandWhen ThenNotFound => Then(e => new NotFoundResult()); public static CommandWhen ThenConflict => Then(StatusCodes.Status409Conflict); } }
using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Totem.Timeline.Mvc { /// <summary> /// Declares an HTTP response to the specific event type /// </summary> /// <typeparam name="TEvent">The type of event to which to respond</typeparam> public static class When<TEvent> where TEvent : Event { public static CommandWhen Then(Func<TEvent, IActionResult> respond) => new CommandWhen(typeof(TEvent), e => respond((TEvent) e)); public static CommandWhen Then(int statusCode) => Then(e => new StatusCodeResult(statusCode)); public static CommandWhen ThenOk => Then(e => new OkResult()); public static CommandWhen ThenBadRequest => Then(e => new BadRequestResult()); public static CommandWhen ThenNotFound => Then(e => new NotFoundResult()); public static CommandWhen ThenConflict => Then(StatusCodes.Status409Conflict); } }
mit
C#
87937a76084a41f456a06ca1e1031d6c327932cc
fix link
ParticularLabs/APIComparer,modernist/APIComparer,ParticularLabs/APIComparer,modernist/APIComparer
APIComparer/Program.cs
APIComparer/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; using APIComparer; using NuGet; class Program { static void Main() { var nugetCacheDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NuGet", "Cache"); var repo = new AggregateRepository(new[] { PackageRepositoryFactory.Default.CreateRepository(nugetCacheDirectory), PackageRepositoryFactory.Default.CreateRepository("https://www.nuget.org/api/v2"), PackageRepositoryFactory.Default.CreateRepository("https://www.myget.org/F/particular/"), }); var packageManager = new PackageManager(repo, "packages"); var newVersion = "5.0.0"; packageManager.InstallPackage("NServiceBus", SemanticVersion.Parse(newVersion)); packageManager.InstallPackage("NServiceBus.Host", SemanticVersion.Parse(newVersion)); packageManager.InstallPackage("NServiceBus.Interfaces", SemanticVersion.Parse("4.6.7")); packageManager.InstallPackage("NServiceBus", SemanticVersion.Parse("4.6.7")); packageManager.InstallPackage("NServiceBus.Host", SemanticVersion.Parse("4.6.7")); var leftAssemblyGroup = new List<string> { Path.Combine("packages", "NServiceBus.4.6.7", "lib", "net40", "NServiceBus.Core.dll"), Path.Combine("packages", "NServiceBus.Interfaces.4.6.7", "lib", "net40", "NServiceBus.dll"), Path.Combine("packages", "NServiceBus.Host.4.6.7", "lib", "net40", "NServiceBus.Host.exe") }; var rightAssemblyGroup = new List<string> { Path.Combine("packages", "NServiceBus." + newVersion, "lib", "net45", "NServiceBus.Core.dll"), Path.Combine("packages", "NServiceBus.Host." + newVersion, "lib", "net45", "NServiceBus.Host.exe"), }; var engine = new ComparerEngine(); var diff = engine.CreateDiff(leftAssemblyGroup, rightAssemblyGroup); var stringBuilder = new StringBuilder(); var formatter = new APIUpgradeToMarkdownFormatter(stringBuilder, "https://github.com/Particular/NServiceBus/blob/4.6.7/", "https://github.com/Particular/NServiceBus/blob/master/"); formatter.WriteOut(diff); File.WriteAllText("Result.md", stringBuilder.ToString()); } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using APIComparer; using NuGet; class Program { static void Main() { var nugetCacheDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NuGet", "Cache"); var repo = new AggregateRepository(new[] { PackageRepositoryFactory.Default.CreateRepository(nugetCacheDirectory), PackageRepositoryFactory.Default.CreateRepository("https://www.nuget.org/api/v2"), PackageRepositoryFactory.Default.CreateRepository("https://www.myget.org/F/particular/"), }); var packageManager = new PackageManager(repo, "packages"); var newVersion = "5.0.0"; packageManager.InstallPackage("NServiceBus", SemanticVersion.Parse(newVersion)); packageManager.InstallPackage("NServiceBus.Host", SemanticVersion.Parse(newVersion)); packageManager.InstallPackage("NServiceBus.Interfaces", SemanticVersion.Parse("4.6.7")); packageManager.InstallPackage("NServiceBus", SemanticVersion.Parse("4.6.7")); packageManager.InstallPackage("NServiceBus.Host", SemanticVersion.Parse("4.6.7")); var leftAssemblyGroup = new List<string> { Path.Combine("packages", "NServiceBus.4.6.7", "lib", "net40", "NServiceBus.Core.dll"), Path.Combine("packages", "NServiceBus.Interfaces.4.6.7", "lib", "net40", "NServiceBus.dll"), Path.Combine("packages", "NServiceBus.Host.4.6.7", "lib", "net40", "NServiceBus.Host.exe") }; var rightAssemblyGroup = new List<string> { Path.Combine("packages", "NServiceBus." + newVersion, "lib", "net45", "NServiceBus.Core.dll"), Path.Combine("packages", "NServiceBus.Host." + newVersion, "lib", "net45", "NServiceBus.Host.exe"), }; var engine = new ComparerEngine(); var diff = engine.CreateDiff(leftAssemblyGroup, rightAssemblyGroup); var stringBuilder = new StringBuilder(); var formatter = new APIUpgradeToMarkdownFormatter(stringBuilder, "https://github.com/Particular/NServiceBus/blob/4.6.7/", "https://github.com/Particular/NServiceBus/tree/master/"); formatter.WriteOut(diff); File.WriteAllText("Result.md", stringBuilder.ToString()); } }
mit
C#
1587b908354a760292fba84b8d7531e24b943af7
Use interface in UnityExtensions
ethanmoffat/EndlessClient
EOLib/UnityExtensions.cs
EOLib/UnityExtensions.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.Collections.Generic; using Microsoft.Practices.Unity; namespace EOLib { public static class UnityExtensions { public static void RegisterInstance<T>(this IUnityContainer container) { container.RegisterType<T>(new ContainerControlledLifetimeManager()); } public static void RegisterInstance<T, U>(this IUnityContainer container) where U : T { container.RegisterType<T, U>(new ContainerControlledLifetimeManager()); } public static void RegisterVaried<T, U>(this IUnityContainer container) where U : T { RegisterEnumerableIfNeeded<T, U>(container); container.RegisterType<T, U>(typeof(U).Name); } public static void RegisterInstanceVaried<T, U>(this IUnityContainer container) where U : T { RegisterEnumerableIfNeeded<T, U>(container); container.RegisterType<T, U>(typeof(U).Name, new ContainerControlledLifetimeManager()); } private static void RegisterEnumerableIfNeeded<T, U>(IUnityContainer container) where U : T { if (!container.IsRegistered(typeof(IEnumerable<T>))) { container.RegisterType<IEnumerable<T>>( new ContainerControlledLifetimeManager(), new InjectionFactory(c => c.ResolveAll<T>())); } } } }
// 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.Collections.Generic; using Microsoft.Practices.Unity; namespace EOLib { public static class UnityExtensions { public static void RegisterInstance<T>(this UnityContainer container) { container.RegisterType<T>(new ContainerControlledLifetimeManager()); } public static void RegisterInstance<T, U>(this UnityContainer container) where U : T { container.RegisterType<T, U>(new ContainerControlledLifetimeManager()); } public static void RegisterVaried<T, U>(this UnityContainer container) where U : T { RegisterEnumerableIfNeeded<T, U>(container); container.RegisterType<T, U>(typeof(U).Name); } public static void RegisterInstanceVaried<T, U>(this UnityContainer container) where U : T { RegisterEnumerableIfNeeded<T, U>(container); container.RegisterType<T, U>(typeof(U).Name, new ContainerControlledLifetimeManager()); } private static void RegisterEnumerableIfNeeded<T, U>(UnityContainer container) where U : T { if (!container.IsRegistered(typeof(IEnumerable<T>))) { container.RegisterType<IEnumerable<T>>( new ContainerControlledLifetimeManager(), new InjectionFactory(c => c.ResolveAll<T>())); } } } }
mit
C#
28f889eb4912c3e203e192dc15009495f46139a8
select cells
sagivo/Unity2d-Game
Assets/Scripts/Cell.cs
Assets/Scripts/Cell.cs
using UnityEngine; using System.Collections; public class Cell : BaseObj { public enum CellType {Empty, Player, Canon, Building}; public CellType Type; public bool Selected; SpriteRenderer sprite; //events public delegate void HitEvent(object sender, object args); public HitEvent OnHit; void Start(){ sprite = gameObject.GetComponent<SpriteRenderer>(); } void OnMouseEnter() { if (!Selected) sprite.color = Color.cyan; } void OnMouseExit() { if (!Selected) sprite.color = Color.white; } void OnMouseDown() { sprite.color = (sprite.color == Color.red) ? Color.white : Color.red; Selected = !Selected; } }
using UnityEngine; using System.Collections; public class Cell : BaseObj { public enum CellType {Empty, Player, Canon, Building}; public CellType Type; SpriteRenderer sprite; //events public delegate void HitEvent(object sender, object args); public HitEvent OnHit; void Start(){ sprite = gameObject.GetComponent<SpriteRenderer>(); } void OnMouseEnter() { sprite.color = Color.cyan; } void OnMouseExit() { sprite.color = Color.white; } }
apache-2.0
C#
6410e31a57af1765c5d9d36675080192666afb62
save toggle state
DMagic1/KSP_Contract_Window,Kerbas-ad-astra/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) => { contractsWindow.IsVisible = !contractsWindow.IsVisible; contractScenario.Instance.setWindowVisible(contractsWindow.IsVisible); }; } 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; } else return; } internal void OnDestroy() { contractButton.Destroy(); } } }
mit
C#
8aa78126fdfaba2131a40e94956b041176f7a49b
fix docs on ColorButton
NattyNarwhal/Colours
Colours/ColorButton.cs
Colours/ColorButton.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using GdiColor = System.Drawing.Color; namespace Colours { /// <summary> /// A button that takes the appearance of the colour it represents. /// </summary> public class ColorButton : Button { private RgbColor _color; /// <summary> /// Represents the color of the ColorButton. /// </summary> public RgbColor Color { get { return _color; } set { _color = value; BackColor = _color.ToGdiColor(); ForeColor = _color.GetBrightness() > 0.5 ? GdiColor.Black : GdiColor.White; } } /// <summary> /// Represents the color of the ColorButton, in HSV form. /// </summary> public HsvColor HsvColor { get { return new HsvColor(Color); } set { Color = value.ToRgb(); } } public ColorButton() : base() { FlatStyle = FlatStyle.Popup; Color = SystemColors.ButtonFace.ToRgbColor(); } public ColorButton(RgbColor c) : this() { Color = c; } public ColorButton(HsvColor c) : this() { HsvColor = c; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using GdiColor = System.Drawing.Color; namespace Colours { /// <summary> /// A button that takes the appearance of the colour it represents. /// </summary> public class ColorButton : Button { private RgbColor _color; /// <summary> /// Represents the /// </summary> public RgbColor Color { get { return _color; } set { _color = value; BackColor = _color.ToGdiColor(); ForeColor = _color.GetBrightness() > 0.5 ? GdiColor.Black : GdiColor.White; } } public HsvColor HsvColor { get { return new HsvColor(Color); } set { Color = value.ToRgb(); } } public ColorButton() : base() { FlatStyle = FlatStyle.Popup; Color = SystemColors.ButtonFace.ToRgbColor(); } public ColorButton(RgbColor c) : this() { Color = c; } public ColorButton(HsvColor c) : this() { HsvColor = c; } } }
mit
C#
ed982e8dd13f9f4657e1463a7bd19a7aac2f41f4
Make stacked hitcircles more visible when using default skin
UselessToucan/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,peppy/osu,ppy/osu,peppy/osu,smoogipoo/osu
osu.Game.Rulesets.Osu/Objects/Drawables/Pieces/RingPiece.cs
osu.Game.Rulesets.Osu/Objects/Drawables/Pieces/RingPiece.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.Containers; using osuTK; using osuTK.Graphics; using osu.Framework.Graphics.Shapes; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces { public class RingPiece : CircularContainer { public RingPiece() { Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2); Anchor = Anchor.Centre; Origin = Anchor.Centre; Masking = true; BorderThickness = 9; // roughly matches slider borders and makes stacked circles distinctly visible from each other. BorderColour = Color4.White; Child = new Box { AlwaysPresent = true, Alpha = 0, RelativeSizeAxes = Axes.Both }; } } }
// 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.Containers; using osuTK; using osuTK.Graphics; using osu.Framework.Graphics.Shapes; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces { public class RingPiece : CircularContainer { public RingPiece() { Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2); Anchor = Anchor.Centre; Origin = Anchor.Centre; Masking = true; BorderThickness = 10; BorderColour = Color4.White; Child = new Box { AlwaysPresent = true, Alpha = 0, RelativeSizeAxes = Axes.Both }; } } }
mit
C#
f57f2482d589838ba814c4ca77b553fa93111a1e
remove duplicate settings creation.
sillsdev/solid,sillsdev/solid,sillsdev/solid
src/SolidGui/Program.cs
src/SolidGui/Program.cs
using System; using System.Collections.Generic; using System.Windows.Forms; using Palaso.Reporting; using SolidGui.Properties; namespace SolidGui { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(params string[]args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //bring in settings from any previous version if (Settings.Default.NeedUpgrade) { //see http://stackoverflow.com/questions/3498561/net-applicationsettingsbase-should-i-call-upgrade-every-time-i-load Settings.Default.Upgrade(); Settings.Default.NeedUpgrade = false; Settings.Default.Save(); } SetupErrorHandling(); SetupUsageTracking(); MainWindowPM model = new MainWindowPM(); MainWindowView form = new MainWindowView(model); if(args.Length > 0 && args[0].EndsWith(".solid")) { model.OpenDictionary(args[0]); form.OnFileLoaded(args[0]); } Application.Run(form); Settings.Default.Save(); } private static void SetupErrorHandling() { ExceptionHandler.Init(); Logger.Init(); ErrorReport.Init("[email protected]"); } private static void SetupUsageTracking() { if (Settings.Default.Reporting == null) { Settings.Default.Reporting = new ReportingSettings(); Settings.Default.Save(); } UsageReporter.Init(Settings.Default.Reporting, "solid.palaso.org", "UA-22170471-4"); } } }
using System; using System.Collections.Generic; using System.Windows.Forms; using Palaso.Reporting; using SolidGui.Properties; namespace SolidGui { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(params string[]args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (Settings.Default.Reporting == null) Settings.Default.Reporting = new ReportingSettings(); //bring in settings from any previous version if (Settings.Default.NeedUpgrade) { //see http://stackoverflow.com/questions/3498561/net-applicationsettingsbase-should-i-call-upgrade-every-time-i-load Settings.Default.Upgrade(); Settings.Default.NeedUpgrade = false; Settings.Default.Save(); } SetupErrorHandling(); SetupUsageTracking(); MainWindowPM model = new MainWindowPM(); MainWindowView form = new MainWindowView(model); if(args.Length > 0 && args[0].EndsWith(".solid")) { model.OpenDictionary(args[0]); form.OnFileLoaded(args[0]); } Application.Run(form); Settings.Default.Save(); } private static void SetupErrorHandling() { ExceptionHandler.Init(); Logger.Init(); ErrorReport.Init("[email protected]"); } private static void SetupUsageTracking() { if (Settings.Default.Reporting == null) { Settings.Default.Reporting = new ReportingSettings(); Settings.Default.Save(); } UsageReporter.Init(Settings.Default.Reporting, "solid.palaso.org", "UA-22170471-4"); } } }
mit
C#
de57ec946fef38559993c17550b101e47ba535b3
Normalise line endings once again.
stomppah/KAOS-Engine,stomppah/KAOS-Engine,stomppah/KAOS-Engine
KAOS/Utilities/Camera.cs
KAOS/Utilities/Camera.cs
using OpenTK; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KAOS.Utilities { /// <summary> /// Camera: http://neokabuto.blogspot.co.uk/2014/01/opentk-tutorial-5-basic-camera.html (slightly modified) /// </summary> public static class Camera { public static Vector3 Position = Vector3.Zero; public static Vector3 Orientation = new Vector3((float)Math.PI, 0f, 0f); public static float MoveSpeed = 0.2f; public static float MouseSensitivity = 0.01f; public static Matrix4 GetViewMatrix() { Vector3 lookat = new Vector3(); lookat.X = (float)(Math.Sin((float)Orientation.X) * Math.Cos((float)Orientation.Y)); lookat.Y = (float)Math.Sin((float)Orientation.Y); lookat.Z = (float)(Math.Cos((float)Orientation.X) * Math.Cos((float)Orientation.Y)); return Matrix4.LookAt(Position, Position + lookat, Vector3.UnitY); } public static void Move(float x, float y, float z) { Vector3 offset = new Vector3(); Vector3 forward = new Vector3((float)Math.Sin((float)Orientation.X), 0, (float)Math.Cos((float)Orientation.X)); Vector3 right = new Vector3(-forward.Z, 0, forward.X); offset += x * right; offset += y * forward; offset.Y += z; offset.NormalizeFast(); offset = Vector3.Multiply(offset, MoveSpeed); Position += offset; Logger.WriteLine("Camera Position = " + Position); } public static void AddRotation(float x, float y) { x = x * MouseSensitivity; y = y * MouseSensitivity; Orientation.X = (Orientation.X + x) % ((float)Math.PI * 2.0f); Orientation.Y = Math.Max(Math.Min(Orientation.Y + y, (float)Math.PI / 2.0f - 0.1f), (float)-Math.PI / 2.0f + 0.1f); } } }
using OpenTK; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KAOS.Utilities { /// <summary> /// Camera: http://neokabuto.blogspot.co.uk/2014/01/opentk-tutorial-5-basic-camera.html (slightly modified) /// </summary> public static class Camera { public static Vector3 Position = Vector3.Zero; public static Vector3 Orientation = new Vector3((float)Math.PI, 0f, 0f); public static float MoveSpeed = 0.2f; public static float MouseSensitivity = 0.01f; public static Matrix4 GetViewMatrix() { Vector3 lookat = new Vector3(); lookat.X = (float)(Math.Sin((float)Orientation.X) * Math.Cos((float)Orientation.Y)); lookat.Y = (float)Math.Sin((float)Orientation.Y); lookat.Z = (float)(Math.Cos((float)Orientation.X) * Math.Cos((float)Orientation.Y)); return Matrix4.LookAt(Position, Position + lookat, Vector3.UnitY); } public static void Move(float x, float y, float z) { Vector3 offset = new Vector3(); Vector3 forward = new Vector3((float)Math.Sin((float)Orientation.X), 0, (float)Math.Cos((float)Orientation.X)); Vector3 right = new Vector3(-forward.Z, 0, forward.X); offset += x * right; offset += y * forward; offset.Y += z; offset.NormalizeFast(); offset = Vector3.Multiply(offset, MoveSpeed); Position += offset; Logger.WriteLine("Camera Position = " + Position); } public static void AddRotation(float x, float y) { x = x * MouseSensitivity; y = y * MouseSensitivity; Orientation.X = (Orientation.X + x) % ((float)Math.PI * 2.0f); Orientation.Y = Math.Max(Math.Min(Orientation.Y + y, (float)Math.PI / 2.0f - 0.1f), (float)-Math.PI / 2.0f + 0.1f); } } }
mit
C#
019ffe6a68b0f7df97e94bd57a4580f11f568e4c
Remove unnecessary using
Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training
src/AtomicChessPuzzles/DbRepositories/PositionRepository.cs
src/AtomicChessPuzzles/DbRepositories/PositionRepository.cs
using AtomicChessPuzzles.Models; using MongoDB.Driver; using System; using System.Linq; namespace AtomicChessPuzzles.DbRepositories { public class PositionRepository : IPositionRepository { MongoSettings settings; IMongoCollection<TrainingPosition> positionCollection; Random rnd = new Random(); public PositionRepository() { settings = new MongoSettings(); GetCollection(); } private void GetCollection() { MongoClient client = new MongoClient(); positionCollection = client.GetDatabase(settings.Database).GetCollection<TrainingPosition>(settings.PositionCollectionName); } public TrainingPosition GetRandomMateInOne() { double x = rnd.NextDouble(); double y = rnd.NextDouble(); FilterDefinitionBuilder<TrainingPosition> filterBuilder = Builders<TrainingPosition>.Filter; FilterDefinition<TrainingPosition> filter = filterBuilder.Eq("type", "mateInOne") & filterBuilder.Near("location", x, y); var found = positionCollection.Find(filter); if (found == null) return null; else return found.Limit(1).First(); } } }
using AtomicChessPuzzles.Models; using MongoDB.Bson; using MongoDB.Driver; using System; using System.Linq; namespace AtomicChessPuzzles.DbRepositories { public class PositionRepository : IPositionRepository { MongoSettings settings; IMongoCollection<TrainingPosition> positionCollection; Random rnd = new Random(); public PositionRepository() { settings = new MongoSettings(); GetCollection(); } private void GetCollection() { MongoClient client = new MongoClient(); positionCollection = client.GetDatabase(settings.Database).GetCollection<TrainingPosition>(settings.PositionCollectionName); } public TrainingPosition GetRandomMateInOne() { double x = rnd.NextDouble(); double y = rnd.NextDouble(); FilterDefinitionBuilder<TrainingPosition> filterBuilder = Builders<TrainingPosition>.Filter; FilterDefinition<TrainingPosition> filter = filterBuilder.Eq("type", "mateInOne") & filterBuilder.Near("location", x, y); var found = positionCollection.Find(filter); if (found == null) return null; else return found.Limit(1).First(); } } }
agpl-3.0
C#
3aadfb4b5d66ac8ee16d3e61d7f59a03accba130
Update src/Avalonia.Controls/Notifications/INotificationManager.cs
SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,akrisiun/Perspex,jkoritzinsky/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia
src/Avalonia.Controls/Notifications/INotificationManager.cs
src/Avalonia.Controls/Notifications/INotificationManager.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. namespace Avalonia.Controls.Notifications { /// <summary> /// Represents a notification manager that can be used to show notifications in a window or using /// the host operating system. /// </summary> public interface INotificationManager { /// <summary> /// Show a notification. /// </summary> /// <param name="notification">The notification to be displayed.</param> void Show(INotification notification); } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. namespace Avalonia.Controls.Notifications { /// <summary> /// Defines the interfaces for NotificationManagers. /// </summary> public interface INotificationManager { /// <summary> /// Show a notification. /// </summary> /// <param name="notification">The notification to be displayed.</param> void Show(INotification notification); } }
mit
C#
e2dd7df304328f3a2631efa0db4fb234165f858c
Make Cake Bakery resolution case insensitive
DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn
src/OmniSharp.Cake/Services/ScriptGenerationToolResolver.cs
src/OmniSharp.Cake/Services/ScriptGenerationToolResolver.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using OmniSharp.Cake.Configuration; namespace OmniSharp.Cake.Services { internal static class ScriptGenerationToolResolver { public static string GetExecutablePath(string rootPath, ICakeConfiguration configuration) { var toolPath = GetToolPath(rootPath, configuration); if (!Directory.Exists(toolPath)) { return string.Empty; } var bakeryPath = GetLatestBakeryPath(toolPath); if (bakeryPath == null) { return string.Empty; } return Path.Combine(toolPath, bakeryPath, "tools", "Cake.Bakery.exe"); } private static string GetToolPath(string rootPath, ICakeConfiguration configuration) { var toolPath = configuration.GetValue(Constants.Paths.Tools); return Path.Combine(rootPath, !string.IsNullOrWhiteSpace(toolPath) ? toolPath : "tools"); } private static string GetLatestBakeryPath(string toolPath) { var directories = GetBakeryPaths(toolPath); // TODO: Sort by semantic version? return directories.OrderByDescending(x => x).FirstOrDefault(); } private static IEnumerable<string> GetBakeryPaths(string toolPath) { foreach (var directory in Directory.EnumerateDirectories(toolPath)) { var topDirectory = directory.Split(Path.DirectorySeparatorChar).Last(); if (topDirectory.StartsWith("cake.bakery", StringComparison.OrdinalIgnoreCase)) { yield return topDirectory; } } } } }
using System.IO; using System.Linq; using OmniSharp.Cake.Configuration; namespace OmniSharp.Cake.Services { internal static class ScriptGenerationToolResolver { public static string GetExecutablePath(string rootPath, ICakeConfiguration configuration) { var toolPath = GetToolPath(rootPath, configuration); if (!Directory.Exists(toolPath)) { return string.Empty; } var bakeryPath = GetLatestBakeryPath(toolPath); if (bakeryPath == null) { return string.Empty; } return Path.Combine(toolPath, bakeryPath, "tools", "Cake.Bakery.exe"); } private static string GetToolPath(string rootPath, ICakeConfiguration configuration) { var toolPath = configuration.GetValue(Constants.Paths.Tools); return Path.Combine(rootPath, !string.IsNullOrWhiteSpace(toolPath) ? toolPath : "tools"); } private static string GetLatestBakeryPath(string toolPath) { var directories = Directory.GetDirectories(toolPath, "cake.bakery*", SearchOption.TopDirectoryOnly); // TODO: Sort by semantic version? return directories.OrderByDescending(x => x).FirstOrDefault(); } } }
mit
C#
821e13a1a7526b719a2c680e742781b36cfd4b02
Update Hosting to account for DataProtection API changes.
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNet.Hosting/HostingServices.cs
src/Microsoft.AspNet.Hosting/HostingServices.cs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.AspNet.Hosting.Builder; using Microsoft.AspNet.Hosting.Server; using Microsoft.AspNet.Hosting.Startup; using Microsoft.AspNet.Security.DataProtection; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.Logging; namespace Microsoft.AspNet.Hosting { public static class HostingServices { public static IEnumerable<IServiceDescriptor> GetDefaultServices() { return GetDefaultServices(new Configuration()); } public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration) { var describer = new ServiceDescriber(configuration); yield return describer.Transient<IHostingEngine, HostingEngine>(); yield return describer.Transient<IServerManager, ServerManager>(); yield return describer.Transient<IStartupManager, StartupManager>(); yield return describer.Transient<IStartupLoaderProvider, StartupLoaderProvider>(); yield return describer.Transient<IApplicationBuilderFactory, ApplicationBuilderFactory>(); yield return describer.Transient<IHttpContextFactory, HttpContextFactory>(); yield return describer.Singleton<ITypeActivator, TypeActivator>(); yield return describer.Instance<IApplicationLifetime>(new ApplicationLifetime()); // TODO: Do we expect this to be provide by the runtime eventually? yield return describer.Singleton<ILoggerFactory, LoggerFactory>(); yield return describer.Scoped(typeof(IContextAccessor<>), typeof(ContextAccessor<>)); foreach (var service in DataProtectionServices.GetDefaultServices()) { yield return service; } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.AspNet.Hosting.Builder; using Microsoft.AspNet.Hosting.Server; using Microsoft.AspNet.Hosting.Startup; using Microsoft.AspNet.Security.DataProtection; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.Logging; namespace Microsoft.AspNet.Hosting { public static class HostingServices { public static IEnumerable<IServiceDescriptor> GetDefaultServices() { return GetDefaultServices(new Configuration()); } public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration) { var describer = new ServiceDescriber(configuration); yield return describer.Transient<IHostingEngine, HostingEngine>(); yield return describer.Transient<IServerManager, ServerManager>(); yield return describer.Transient<IStartupManager, StartupManager>(); yield return describer.Transient<IStartupLoaderProvider, StartupLoaderProvider>(); yield return describer.Transient<IApplicationBuilderFactory, ApplicationBuilderFactory>(); yield return describer.Transient<IHttpContextFactory, HttpContextFactory>(); yield return describer.Singleton<ITypeActivator, TypeActivator>(); yield return describer.Instance<IApplicationLifetime>(new ApplicationLifetime()); // TODO: Do we expect this to be provide by the runtime eventually? yield return describer.Singleton<ILoggerFactory, LoggerFactory>(); yield return describer.Scoped(typeof(IContextAccessor<>), typeof(ContextAccessor<>)); if (PlatformHelper.IsMono) { #if ASPNET50 yield return describer.Instance<IDataProtectionProvider>(DataProtectionProvider.CreateFromLegacyDpapi()); #endif } else { // The default IDataProtectionProvider is a singleton. // Note: DPAPI isn't usable in IIS where the user profile hasn't been loaded, but loading DPAPI // is deferred until the first call to Protect / Unprotect. It's up to an IIS-based host to // replace this service as part of application initialization. yield return describer.Instance<IDataProtectionProvider>(DataProtectionProvider.CreateFromDpapi()); } } } }
apache-2.0
C#
f9065331ef5789f988acc395e1ad40849bfe5bc4
Fix unit test
dswisher/yaclops
src/Yaclops.Tests/Mocks/MockReflectedCommand.cs
src/Yaclops.Tests/Mocks/MockReflectedCommand.cs
using System; using System.Collections.Generic; using Yaclops.Reflecting; namespace Yaclops.Tests.Mocks { internal class MockReflectedCommand : IReflectedCommand<object> { private static readonly Func<object> _factory = () => new object(); private readonly List<string> _verbs = new List<string>(); private readonly List<ReflectedNamedParameter> _namedParameters = new List<ReflectedNamedParameter>(); private readonly List<ReflectedPositionalParameter> _positionalParameters = new List<ReflectedPositionalParameter>(); public IReadOnlyList<string> Verbs { get { return _verbs; } } public IReadOnlyList<ReflectedNamedParameter> NamedParameters { get { return _namedParameters; } } public IReadOnlyList<ReflectedPositionalParameter> PositionalParameters { get { return _positionalParameters; } } public Func<object> Factory { get { return _factory; } } public void AddVerbs(params string[] verbs) { _verbs.AddRange(verbs); } public static MockReflectedCommand FromVerbs(params string[] verbs) { var mock = new MockReflectedCommand(); mock.AddVerbs(verbs); return mock; } } }
using System; using System.Collections.Generic; using Yaclops.Reflecting; namespace Yaclops.Tests.Mocks { internal class MockReflectedCommand : IReflectedCommand<object> { private static readonly Func<object> _factory = () => new object(); private readonly List<string> _verbs = new List<string>(); private readonly List<ReflectedNamedParameter> _namedParameters = new List<ReflectedNamedParameter>(); public IReadOnlyList<string> Verbs { get { return _verbs; } } public IReadOnlyList<ReflectedNamedParameter> NamedParameters { get { return _namedParameters; } } public IReadOnlyList<ReflectedPositionalParameter> PositionalParameters { get { throw new NotImplementedException(); } } public Func<object> Factory { get { return _factory; } } public void AddVerbs(params string[] verbs) { _verbs.AddRange(verbs); } public static MockReflectedCommand FromVerbs(params string[] verbs) { var mock = new MockReflectedCommand(); mock.AddVerbs(verbs); return mock; } } }
mit
C#
4110758b0c2fb39c1896ea039b623b2c9a2ecbea
Update reset pax method
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Services/VehicleService.cs
Battery-Commander.Web/Services/VehicleService.cs
using BatteryCommander.Web.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Services { public class VehicleService { public static async Task Reset_Drivers(Database db) { foreach (var vehicle in db.Vehicles) { vehicle.DriverId = null; vehicle.A_DriverId = null; foreach (var passenger in vehicle.Passengers.ToList()) { vehicle.Passengers.Remove(passenger); } } await db.SaveChangesAsync(); } public static async Task<IEnumerable<Vehicle>> Filter(Database db, Query query) { IQueryable<Vehicle> vehicles = db .Vehicles .Include(vehicle => vehicle.Unit) .Include(vehicle => vehicle.Driver) .Include(vehicle => vehicle.A_Driver) .Include(vehicle => vehicle.Passengers) .ThenInclude(passenger => passenger.Soldier); if (query.Units?.Any() == true) { vehicles = vehicles.Where(vehicle => query.Units.Contains(vehicle.UnitId)); } else if (query.IncludeIgnoredUnits == false) { vehicles = vehicles.Where(vehicle => !vehicle.Unit.IgnoreForReports); } if (query.Available.HasValue) { vehicles = vehicles.Where(vehicle => vehicle.Available == query.Available); } return await vehicles .OrderBy(vehicle => vehicle.Bumper) .ToListAsync(); } public class Query { public int[] Units { get; set; } public Boolean? IncludeIgnoredUnits { get; set; } = false; public Boolean? Available { get; set; } } } }
using BatteryCommander.Web.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Services { public class VehicleService { public static async Task Reset_Drivers(Database db) { foreach (var vehicle in db.Vehicles) { vehicle.DriverId = null; vehicle.A_DriverId = null; } await db.SaveChangesAsync(); } public static async Task<IEnumerable<Vehicle>> Filter(Database db, Query query) { IQueryable<Vehicle> vehicles = db .Vehicles .Include(vehicle => vehicle.Unit) .Include(vehicle => vehicle.Driver) .Include(vehicle => vehicle.A_Driver) .Include(vehicle => vehicle.Passengers) .ThenInclude(passenger => passenger.Soldier); if (query.Units?.Any() == true) { vehicles = vehicles.Where(vehicle => query.Units.Contains(vehicle.UnitId)); } else if (query.IncludeIgnoredUnits == false) { vehicles = vehicles.Where(vehicle => !vehicle.Unit.IgnoreForReports); } if (query.Available.HasValue) { vehicles = vehicles.Where(vehicle => vehicle.Available == query.Available); } return await vehicles .OrderBy(vehicle => vehicle.Bumper) .ToListAsync(); } public class Query { public int[] Units { get; set; } public Boolean? IncludeIgnoredUnits { get; set; } = false; public Boolean? Available { get; set; } } } }
mit
C#
24cb93d06de92048802d113b02348ff1b5442404
Fix soldier save link
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Views/Soldiers/Edit.cshtml
Battery-Commander.Web/Views/Soldiers/Edit.cshtml
@model Soldier @using (Html.BeginForm("Save", "Soldiers", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.Id) @Html.ValidationSummary() <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Unit) @Html.DropDownListFor(model => model.UnitId, (IEnumerable<SelectListItem>)ViewBag.Units, "-- Select Unit --") </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.LastName) @Html.EditorFor(model => model.LastName) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.FirstName) @Html.EditorFor(model => model.FirstName) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Rank) @Html.DropDownListFor(model => model.Rank, Html.GetEnumSelectList<Rank>()) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.DoDId) @Html.EditorFor(model => model.DoDId) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.MilitaryEmail) @Html.EditorFor(model => model.MilitaryEmail) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.CivilianEmail) @Html.EditorFor(model => model.CivilianEmail) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.DateOfBirth) @Html.EditorFor(model => model.DateOfBirth) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Gender) @Html.DropDownListFor(model => model.Gender, Html.GetEnumSelectList<Gender>()) </div> <button type="submit">Save</button> }
@model Soldier @using (Html.BeginForm("Save", "Soldier", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.Id) @Html.ValidationSummary() <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Unit) @Html.DropDownListFor(model => model.UnitId, (IEnumerable<SelectListItem>)ViewBag.Units, "-- Select Unit --") </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.LastName) @Html.EditorFor(model => model.LastName) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.FirstName) @Html.EditorFor(model => model.FirstName) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Rank) @Html.DropDownListFor(model => model.Rank, Html.GetEnumSelectList<Rank>()) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.DoDId) @Html.EditorFor(model => model.DoDId) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.MilitaryEmail) @Html.EditorFor(model => model.MilitaryEmail) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.CivilianEmail) @Html.EditorFor(model => model.CivilianEmail) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.DateOfBirth) @Html.EditorFor(model => model.DateOfBirth) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Gender) @Html.DropDownListFor(model => model.Gender, Html.GetEnumSelectList<Gender>()) </div> <button type="submit">Save</button> }
mit
C#
f3dace6ce21b9a4c0dd404e883d854774af9c248
Make all IEdges weighted
DasAllFolks/SharpGraphs
Graph/IEdge.cs
Graph/IEdge.cs
using System; namespace Graph { /// <summary> /// Default interface for a graph edge, whether directed or undirected. /// </summary> /// <typeparam name="V"> /// The type used to create vertex (node) labels. /// </typeparam> /// <typeparam name="W"> /// The type used for the edge weight. /// </typeparam> public interface IEdge<V, W> : IEquatable<IEdge<V, W>> where V : struct, IEquatable<V> where W : struct, IEquatable<W>, IComparable<W> { /// <summary> /// The weight of the <see cref="IEdge{V, W}"/>. /// </summary> W Weight { get; set; } } }
using System; namespace Graph { /// <summary> /// Default interface for a graph edge, whether directed or undirected. /// </summary> /// <typeparam name="V"> /// The type used to create vertex (node) labels. /// </typeparam> public interface IEdge<V> : IEquatable<IEdge<V>> where V : struct, IEquatable<V> { } }
apache-2.0
C#
f8d1f7d7552ddf03e7441d5e9ba1f0945b6a0f77
Use one component helper class #2;
KonH/UDBase
Common/Scheme.cs
Common/Scheme.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; using UDBase.Components; namespace UDBase.Common { /* If you want some combination of components you need to inherit from that class * add call AddComponent for required components */ public abstract class Scheme : IScheme { Dictionary<IComponent, ComponentHelperBase> _components = new Dictionary<IComponent, ComponentHelperBase>(); public void AddComponent(ComponentHelperBase helper, params IComponent[] components) { for(int i = 0; i < components.Length; i++) { _components.Add(components[i], helper); } } public void Init() { var iter = _components.GetEnumerator(); while(iter.MoveNext()) { var component = iter.Current.Key; component.Init(); var helper = iter.Current.Value; helper.Attach(component); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using UDBase.Components; namespace UDBase.Common { /* If you want some combination of components you need to inherit from that class * add call AddComponent for required components */ public abstract class Scheme : IScheme { Dictionary<IComponent, ComponentHelperBase> _components = new Dictionary<IComponent, ComponentHelperBase>(); public void AddComponent(ComponentHelperBase helper, IComponent component) { _components.Add(component, helper); } public void AddComponents<T>(CompositeHelper<T> helper, params IComponent[] components) where T:IComponent { for(int i = 0; i < components.Length; i++) { _components.Add(components[i], helper); } } public void Init() { var iter = _components.GetEnumerator(); while(iter.MoveNext()) { var component = iter.Current.Key; component.Init(); var helper = iter.Current.Value; helper.Attach(component); } } } }
mit
C#
dabc692f3cf22ac1250126143c3c925c930f39b0
Implement IsValidDestination for Bishop
ProgramFOX/Chess.NET
ChessDotNet/Pieces/Bishop.cs
ChessDotNet/Pieces/Bishop.cs
namespace ChessDotNet.Pieces { public class Bishop : ChessPiece { public override Player Owner { get; set; } public Bishop(Player owner) { Owner = owner; } public override string GetFenCharacter() { return Owner == Player.White ? "B" : "b"; } public override bool IsValidDestination(Position origin, Position destination, ChessGame game) { Utilities.ThrowIfNull(origin, "origin"); Utilities.ThrowIfNull(destination, "destination"); PositionDistance posDelta = new PositionDistance(origin, destination); if (posDelta.DistanceX != posDelta.DistanceY) return false; bool increasingRank = (int)destination.Rank > (int)origin.Rank; bool increasingFile = (int)destination.File > (int)origin.File; ChessPiece[][] board = game.GetBoardForReadOnlyPurposes(); for (int f = (int)origin.File + (increasingFile ? 1 : -1), r = (int)origin.Rank + (increasingRank ? 1 : -1); increasingFile ? f < (int)destination.File : f > (int)destination.File; f += increasingFile ? 1 : -1, r += increasingRank ? 1 : -1) { if (board[r][f].Owner != Player.None) { return false; } } return true; } } }
namespace ChessDotNet.Pieces { public class Bishop : ChessPiece { public override Player Owner { get; set; } public Bishop(Player owner) { Owner = owner; } public override string GetFenCharacter() { return Owner == Player.White ? "B" : "b"; } } }
mit
C#
bc817eb4f580303ddd8b30dcc98b78aabf2fd510
Update Global.asax.cs
HEDIDIN/LogicAppsExceptionManagementApi,HEDIDIN/LogicAppsExceptionManagementApi,HEDIDIN/LogicAppsExceptionManagementApi
LogManagement/Global.asax.cs
LogManagement/Global.asax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace LogManagement { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); DocumentDbRepository<Models.CrmRequest>.Initialize(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace LogManagement { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
mit
C#
4dfc1250c2294247f096d2bd0399eae6da9208e6
Fix struct parsing when Value == null
Banane9/XmlRpc
XmlRpc/Types/XmlRpcStruct.cs
XmlRpc/Types/XmlRpcStruct.cs
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using XmlRpc.Types.Structs; namespace XmlRpc.Types { /// <summary> /// Represents an XmlRpcType containing a xml rpc struct that is derived from <see cref="XmlRpc.Types.Structs.BaseStruct"/>. /// </summary> /// <typeparam name="TXmlRpcStruct">The Type of the struct. Also the Type of the Value property.</typeparam> public sealed class XmlRpcStruct<TXmlRpcStruct> : XmlRpcType<TXmlRpcStruct> where TXmlRpcStruct : BaseStruct, new() { /// <summary> /// The name of value content elements for this XmlRpc type. /// </summary> public override string ContentElementName { get { return XmlRpcElements.StructElement; } } /// <summary> /// Creates a new instance of the <see cref="XmlRpc.Types.XmlRpcStruct"/> class with Value set to default value for TXmlRpcType. /// </summary> public XmlRpcStruct() : base() { } /// <summary> /// Creates a new instance of the <see cref="XmlRpc.Types.XmlRpcStruct"/> class with the given value. /// </summary> /// <param name="value">The struct encapsulated by this.</param> public XmlRpcStruct(TXmlRpcStruct value) : base(value) { } /// <summary> /// Generates a value-XElement capsuling the struct. /// </summary> /// <returns>The generated Xml.</returns> public override XElement GenerateXml() { return new XElement(XName.Get(XmlRpcElements.ValueElement), Value.GenerateXml()); } /// <summary> /// Sets the Value property with the information contained in the value-XElement. /// </summary> /// <param name="xElement">The element containing the information.</param> /// <returns>Whether it was successful or not.</returns> protected override bool parseXml(XElement xElement) { if (Value == null) Value = new TXmlRpcStruct(); return Value.ParseXml(xElement.Elements().First()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using XmlRpc.Types.Structs; namespace XmlRpc.Types { /// <summary> /// Represents an XmlRpcType containing a xml rpc struct that is derived from <see cref="XmlRpc.Types.Structs.BaseStruct"/>. /// </summary> /// <typeparam name="TXmlRpcStruct">The Type of the struct. Also the Type of the Value property.</typeparam> public sealed class XmlRpcStruct<TXmlRpcStruct> : XmlRpcType<TXmlRpcStruct> where TXmlRpcStruct : BaseStruct, new() { /// <summary> /// The name of value content elements for this XmlRpc type. /// </summary> public override string ContentElementName { get { return XmlRpcElements.StructElement; } } /// <summary> /// Creates a new instance of the <see cref="XmlRpc.Types.XmlRpcStruct"/> class with Value set to default value for TXmlRpcType. /// </summary> public XmlRpcStruct() : base() { } /// <summary> /// Creates a new instance of the <see cref="XmlRpc.Types.XmlRpcStruct"/> class with the given value. /// </summary> /// <param name="value">The struct encapsulated by this.</param> public XmlRpcStruct(TXmlRpcStruct value) : base(value) { } /// <summary> /// Generates a value-XElement capsuling the struct. /// </summary> /// <returns>The generated Xml.</returns> public override XElement GenerateXml() { return new XElement(XName.Get(XmlRpcElements.ValueElement), Value.GenerateXml()); } /// <summary> /// Sets the Value property with the information contained in the value-XElement. /// </summary> /// <param name="xElement">The element containing the information.</param> /// <returns>Whether it was successful or not.</returns> protected override bool parseXml(XElement xElement) { return Value.ParseXml(xElement.Elements().First()); } } }
lgpl-2.1
C#
3c3ee042794be726fe054f0c6c137e6777cd809f
Add Publish() and re-Connect()ing test.
jorik041/mono-reactive,paulcbetts/mono-reactive,atsushieno/mono-reactive
System.Reactive.Tests/System.Reactive.Linq/ObservableConnectableTest.cs
System.Reactive.Tests/System.Reactive.Linq/ObservableConnectableTest.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Threading; using NUnit.Framework; namespace System.Reactive.Linq.Tests { [TestFixture] public class ObservableConnectableTest { [Test] public void Publish () { var source = Observable.Range (2, 3); int result = 1; bool started = false; var published = source.Publish (); var pdis1 = published.Subscribe (i => { started = true; result *= i; }); Assert.IsFalse (started, "#1"); var cdis = published.Connect (); Assert.IsTrue (started, "#2"); Thread.Sleep (100); // should be enough to finish publishing source. Assert.AreEqual (24, result, "#3"); var pdis2 = published.Subscribe (i => { started = true; result *= i; }); Thread.Sleep (50); // should be enough to make some change (if it were to happen). Assert.AreEqual (24, result, "#3"); // but it should not happen. cdis.Dispose (); // disconnect pdis1.Dispose (); pdis2.Dispose (); } [Test] public void PublishConnectTwice () { var source = Observable.Range (2, 3); int result = 1; bool started = false; var published = source.Publish (); var pdis1 = published.Subscribe (i => { started = true; result *= i; }); Assert.IsFalse (started, "#1"); var cdis1 = published.Connect (); var cdis2 = published.Connect (); // no error Assert.AreEqual (cdis1, cdis2, "#2"); cdis1.Dispose (); } [Test] // FIXME: this test is somewhat processing-speed dependent. Sleep() is not enough very often. public void PublishReconnect () { var source = Observable.Interval (TimeSpan.FromMilliseconds (50)); int result = 0; bool started = false; var published = source.Publish (); var pdis1 = published.Subscribe (i => result++); var cdis1 = published.Connect (); Thread.Sleep (200); // should be enough to receive some events Assert.IsTrue (result > 0, "#1"); cdis1.Dispose (); // disconnect int oldResult = result; Thread.Sleep (200); // should be enough to raise interval event if it were active (which should *not*) Assert.AreEqual (oldResult, result, "#2"); var cdis2 = published.Connect (); Thread.Sleep (400); // should be enough to receive some events Assert.IsTrue (result > oldResult, "#3"); cdis2.Dispose (); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Threading; using NUnit.Framework; namespace System.Reactive.Linq.Tests { [TestFixture] public class ObservableConnectableTest { [Test] public void Publish () { var source = Observable.Range (2, 3); int result = 1; bool started = false; var published = source.Publish (); var pdis1 = published.Subscribe (i => { started = true; result *= i; }); Assert.IsFalse (started, "#1"); var cdis = published.Connect (); Assert.IsTrue (started, "#2"); Thread.Sleep (100); // should be enough to finish publishing source. Assert.AreEqual (24, result, "#3"); var pdis2 = published.Subscribe (i => { started = true; result *= i; }); Thread.Sleep (50); // should be enough to make some change (if it were to happen). Assert.AreEqual (24, result, "#3"); // but it should not happen. cdis.Dispose (); // disconnect pdis1.Dispose (); pdis2.Dispose (); } [Test] public void PublishConnectTwice () { var source = Observable.Range (2, 3); int result = 1; bool started = false; var published = source.Publish (); var pdis1 = published.Subscribe (i => { started = true; result *= i; }); Assert.IsFalse (started, "#1"); var cdis1 = published.Connect (); var cdis2 = published.Connect (); // no error Assert.AreEqual (cdis1, cdis2, "#2"); cdis1.Dispose (); } } }
mit
C#
083983ae6b1db8f879146adda6512e5f534bd9a3
Update ExchangeRateRepository.cs
tiksn/TIKSN-Framework
TIKSN.Core/Finance/ForeignExchange/Data/Mongo/ExchangeRateRepository.cs
TIKSN.Core/Finance/ForeignExchange/Data/Mongo/ExchangeRateRepository.cs
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using TIKSN.Data.Mongo; namespace TIKSN.Finance.ForeignExchange.Data.Mongo { public class ExchangeRateRepository : MongoRepository<ExchangeRateEntity, Guid>, IExchangeRateRepository { public ExchangeRateRepository( IMongoClientSessionProvider mongoClientSessionProvider, IMongoDatabaseProvider mongoDatabaseProvider) : base( mongoClientSessionProvider, mongoDatabaseProvider, "ExchangeRates") { } public Task<IReadOnlyCollection<ExchangeRateEntity>> SearchAsync( Guid foreignExchangeID, string baseCurrencyCode, string counterCurrencyCode, DateTime dateFrom, DateTime dateTo, CancellationToken cancellationToken) { var filter = Builders<ExchangeRateEntity>.Filter.And( Builders<ExchangeRateEntity>.Filter.Eq(item => item.ForeignExchangeID, foreignExchangeID), Builders<ExchangeRateEntity>.Filter.Eq(item => item.BaseCurrencyCode, baseCurrencyCode), Builders<ExchangeRateEntity>.Filter.Eq(item => item.CounterCurrencyCode, counterCurrencyCode), Builders<ExchangeRateEntity>.Filter.Gte(item => item.AsOn, dateFrom), Builders<ExchangeRateEntity>.Filter.Lte(item => item.AsOn, dateTo)); return base.SearchAsync(filter, cancellationToken); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MongoDB.Driver; using TIKSN.Data.Mongo; namespace TIKSN.Finance.ForeignExchange.Data.Mongo { public class ExchangeRateRepository : MongoRepository<ExchangeRateEntity, Guid>, IExchangeRateRepository { public ExchangeRateRepository( IMongoClientSessionProvider mongoClientSessionProvider, IMongoDatabaseProvider mongoDatabaseProvider) : base( mongoClientSessionProvider, mongoDatabaseProvider, "ExchangeRates") { } public Task<IReadOnlyCollection<ExchangeRateEntity>> SearchAsync( Guid foreignExchangeID, string baseCurrencyCode, string counterCurrencyCode, DateTimeOffset dateFrom, DateTimeOffset dateTo, CancellationToken cancellationToken) { var filter = Builders<ExchangeRateEntity>.Filter.And( Builders<ExchangeRateEntity>.Filter.Eq(item => item.ForeignExchangeID, foreignExchangeID), Builders<ExchangeRateEntity>.Filter.Eq(item => item.BaseCurrencyCode, baseCurrencyCode), Builders<ExchangeRateEntity>.Filter.Eq(item => item.CounterCurrencyCode, counterCurrencyCode), Builders<ExchangeRateEntity>.Filter.Gte(item => item.AsOn, dateFrom), Builders<ExchangeRateEntity>.Filter.Lte(item => item.AsOn, dateTo)); return base.SearchAsync(filter, cancellationToken); } } }
mit
C#
46622090d8479001a728c23398d0994a45f16417
Fix for annual turnover.
Paymentsense/Dapper.SimpleSave
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Merchant/MerchantDto.cs
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Merchant/MerchantDto.cs
using PS.Mothership.Core.Common.Template.Cust; using PS.Mothership.Core.Common.Template.Gen; using System; using System.Runtime.Serialization; using System.Collections.Generic; using PS.Mothership.Core.Common.Dto.Contact; namespace PS.Mothership.Core.Common.Dto.Merchant { [DataContract] public class MerchantDto { [DataMember] public Guid MerchantGuid { get; set; } [DataMember] public long? V1MerchantId { get; set; } [DataMember] public string LocatorId { get; set; } [DataMember] public long ThompsonCodeKey { get; set; } [DataMember] public long AnnualTurnover { get; set; } [DataMember] public CustNumberEmployeesEnum NumberEmployeesKey { get; set; } [DataMember] public GenBusinessLegalTypeEnum BusinessLegalTypeKey { get; set; } [DataMember] public long CurrentTradingBankKey { get; set; } [DataMember] public GenNoContactReasonEnum CallRestrictedReasonKey { get; set; } [DataMember] public long EmailRestrictedReasonKey { get; set; } [DataMember] public FullAddressDto Address { get; set; } [DataMember] public Guid PhoneGuid { get; set; } [DataMember] public Guid EmailAddressGuid { get; set; } [DataMember] public string WebsiteURL { get; set; } [DataMember] public string CreditPreScreenFlag { get; set; } [DataMember] public string ExperianBusinessURN { get; set; } [DataMember] public string ExperianLocationURN { get; set; } [DataMember] public DateTime? ExperianLastUpdate { get; set; } [DataMember] public Guid UpdateSessionGuid { get; set; } [DataMember] public DateTimeOffset UpdateDate { get; set; } [DataMember] public IList<ContactDto> Contacts { get; set; } public MerchantDto() { this.Contacts = new List<ContactDto>(); } } }
using PS.Mothership.Core.Common.Template.Cust; using PS.Mothership.Core.Common.Template.Gen; using System; using System.Runtime.Serialization; using System.Collections.Generic; using PS.Mothership.Core.Common.Dto.Contact; namespace PS.Mothership.Core.Common.Dto.Merchant { [DataContract] public class MerchantDto { [DataMember] public Guid MerchantGuid { get; set; } [DataMember] public long? V1MerchantId { get; set; } [DataMember] public string LocatorId { get; set; } [DataMember] public long ThompsonCodeKey { get; set; } [DataMember] public CustAnnualTurnoverEnum AnnualTurnover { get; set; } [DataMember] public CustNumberEmployeesEnum NumberEmployeesKey { get; set; } [DataMember] public GenBusinessLegalTypeEnum BusinessLegalTypeKey { get; set; } [DataMember] public long CurrentTradingBankKey { get; set; } [DataMember] public GenNoContactReasonEnum CallRestrictedReasonKey { get; set; } [DataMember] public long EmailRestrictedReasonKey { get; set; } [DataMember] public FullAddressDto Address { get; set; } [DataMember] public Guid PhoneGuid { get; set; } [DataMember] public Guid EmailAddressGuid { get; set; } [DataMember] public string WebsiteURL { get; set; } [DataMember] public string CreditPreScreenFlag { get; set; } [DataMember] public string ExperianBusinessURN { get; set; } [DataMember] public string ExperianLocationURN { get; set; } [DataMember] public DateTime? ExperianLastUpdate { get; set; } [DataMember] public Guid UpdateSessionGuid { get; set; } [DataMember] public DateTimeOffset UpdateDate { get; set; } [DataMember] public IList<ContactDto> Contacts { get; set; } public MerchantDto() { this.Contacts = new List<ContactDto>(); } } }
mit
C#
d3807b6d085b67b64c6de641f53cd4b25336b60f
Update Router.cs
phonicmouse/SharpPaste,phonicmouse/SharpPaste
Routers/Router.cs
Routers/Router.cs
/* * Created by SharpDevelop. * User: Phonic Mouse * Date: 01/08/2016 * Time: 19:36 */ using System; using System.Linq; using System.Text; using LiteDB; using MlkPwgen; using Nancy; using Newtonsoft.Json; namespace SharpPaste { public class Router : NancyModule { public Router() { Get["/"] = _ => View["index"]; Get["/{longId}"] = parameters => { string longId = parameters.longId; using(var db = new LiteDatabase(Config.DBPATH)) { var result = db.GetCollection<Paste>("pastes").FindOne(Query.EQ("LongId", longId)); return View["paste", result]; } }; Get["/{longId}/raw"] = parameters => { string longId = parameters.longId; using(var db = new LiteDatabase(Config.DBPATH)) { var result = db.GetCollection<Paste>("pastes").FindOne(Query.EQ("LongId", longId)); var encodedBytes = Convert.FromBase64String(result.Body); var decodedString = Encoding.UTF8.GetString(encodedBytes); return decodedString; } }; //Get["/list"] = _ => { // using(var db = new LiteDatabase(Config.DBPATH)) // { // var list = db.GetCollection<Paste>("pastes").FindAll().ToArray(); // var jsonList = JsonConvert.SerializeObject(list); // // return jsonList; // } //}; Post["/add"] = _ => { var body = this.Request.Body; int length = (int) body.Length; var data = new byte[length]; body.Read(data, 0, length); var decodedPaste = JsonConvert.DeserializeObject<Paste>(Encoding.Default.GetString(data)); string longId = PasswordGenerator.Generate(Config.TOKENLENGTH); using(var db = new LiteDatabase(Config.DBPATH)) { var pastes = db.GetCollection<Paste>("pastes"); var paste = new Paste { LongId = longId, Title = decodedPaste.Title, Body = decodedPaste.Body, Language = decodedPaste.Language }; pastes.Insert(paste); } return longId; }; Post["/delete"] = _ => { return 0; // WIP }; } } }
/* * Created by SharpDevelop. * User: Phonic Mouse * Date: 01/08/2016 * Time: 19:36 */ using System; using System.Linq; using System.Text; using LiteDB; using MlkPwgen; using Nancy; using Newtonsoft.Json; namespace SharpPaste { public class Router : NancyModule { public Router() { Get["/"] = _ => View["index"]; Get["/paste/{longId}"] = parameters => { string longId = parameters.longId; using(var db = new LiteDatabase(Config.DBPATH)) { var result = db.GetCollection<Paste>("pastes").FindOne(Query.EQ("LongId", longId)); return View["paste", result]; } }; Get["/paste/{longId}/raw"] = parameters => { string longId = parameters.longId; using(var db = new LiteDatabase(Config.DBPATH)) { var result = db.GetCollection<Paste>("pastes").FindOne(Query.EQ("LongId", longId)); var encodedBytes = Convert.FromBase64String(result.Body); var decodedString = Encoding.UTF8.GetString(encodedBytes); return decodedString; } }; //Get["/paste/list"] = _ => { // using(var db = new LiteDatabase(Config.DBPATH)) // { // var list = db.GetCollection<Paste>("pastes").FindAll().ToArray(); // var jsonList = JsonConvert.SerializeObject(list); // // return jsonList; // } //}; Post["/paste/add"] = _ => { var body = this.Request.Body; int length = (int) body.Length; var data = new byte[length]; body.Read(data, 0, length); var decodedPaste = JsonConvert.DeserializeObject<Paste>(Encoding.Default.GetString(data)); string longId = PasswordGenerator.Generate(Config.TOKENLENGTH); using(var db = new LiteDatabase(Config.DBPATH)) { var pastes = db.GetCollection<Paste>("pastes"); var paste = new Paste { LongId = longId, Title = decodedPaste.Title, Body = decodedPaste.Body, Language = decodedPaste.Language }; pastes.Insert(paste); } return longId; }; Post["/paste/delete"] = _ => { return 0; // WIP }; } } }
mit
C#
e49893bf8350cdec9df83286552db59b18edbfaf
Remove the empty implementation of SafeHandleBase.Dispose (overrides SafeHandle.Dispose) from release builds
sushihangover/libgit2sharp,xoofx/libgit2sharp,jorgeamado/libgit2sharp,vorou/libgit2sharp,vivekpradhanC/libgit2sharp,libgit2/libgit2sharp,dlsteuer/libgit2sharp,OidaTiftla/libgit2sharp,Zoxive/libgit2sharp,AArnott/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,ethomson/libgit2sharp,Skybladev2/libgit2sharp,oliver-feng/libgit2sharp,shana/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,GeertvanHorrik/libgit2sharp,jorgeamado/libgit2sharp,AMSadek/libgit2sharp,jeffhostetler/public_libgit2sharp,PKRoma/libgit2sharp,jamill/libgit2sharp,jeffhostetler/public_libgit2sharp,Skybladev2/libgit2sharp,red-gate/libgit2sharp,AArnott/libgit2sharp,nulltoken/libgit2sharp,red-gate/libgit2sharp,dlsteuer/libgit2sharp,xoofx/libgit2sharp,nulltoken/libgit2sharp,github/libgit2sharp,psawey/libgit2sharp,vorou/libgit2sharp,GeertvanHorrik/libgit2sharp,rcorre/libgit2sharp,github/libgit2sharp,shana/libgit2sharp,vivekpradhanC/libgit2sharp,ethomson/libgit2sharp,whoisj/libgit2sharp,psawey/libgit2sharp,sushihangover/libgit2sharp,Zoxive/libgit2sharp,AMSadek/libgit2sharp,mono/libgit2sharp,whoisj/libgit2sharp,oliver-feng/libgit2sharp,rcorre/libgit2sharp,jamill/libgit2sharp,mono/libgit2sharp,OidaTiftla/libgit2sharp
LibGit2Sharp/Core/Handles/SafeHandleBase.cs
LibGit2Sharp/Core/Handles/SafeHandleBase.cs
using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; namespace LibGit2Sharp.Core.Handles { internal abstract class SafeHandleBase : SafeHandle { #if LEAKS private readonly string trace; #endif protected SafeHandleBase() : base(IntPtr.Zero, true) { #if LEAKS trace = new StackTrace(2, true).ToString(); #endif } #if DEBUG protected override void Dispose(bool disposing) { if (!disposing && !IsInvalid) { Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "A {0} handle wrapper has not been properly disposed.", GetType().Name)); #if LEAKS Trace.WriteLine(trace); #endif Trace.WriteLine(""); } base.Dispose(disposing); } #endif public override bool IsInvalid { get { return (handle == IntPtr.Zero); } } protected abstract override bool ReleaseHandle(); } }
using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; namespace LibGit2Sharp.Core.Handles { internal abstract class SafeHandleBase : SafeHandle { #if LEAKS private readonly string trace; #endif protected SafeHandleBase() : base(IntPtr.Zero, true) { #if LEAKS trace = new StackTrace(2, true).ToString(); #endif } protected override void Dispose(bool disposing) { #if DEBUG if (!disposing && !IsInvalid) { Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "A {0} handle wrapper has not been properly disposed.", GetType().Name)); #if LEAKS Trace.WriteLine(trace); #endif Trace.WriteLine(""); } #endif base.Dispose(disposing); } public override bool IsInvalid { get { return (handle == IntPtr.Zero); } } protected abstract override bool ReleaseHandle(); } }
mit
C#
ebd8f28e579922b5c844e66fd681384cf2e311b7
Add checks to GetMediaFileExtraAsync
moljac/Xamarin.Mobile,xamarin/Xamarin.Mobile,orand/Xamarin.Mobile,nexussays/Xamarin.Mobile,xamarin/Xamarin.Mobile,haithemaraissia/Xamarin.Mobile
MonoDroid/Xamarin.Mobile/Media/MediaFile.cs
MonoDroid/Xamarin.Mobile/Media/MediaFile.cs
using System; using System.IO; using System.Threading.Tasks; using Android.Content; using File = System.IO.File; using IOException = System.IO.IOException; namespace Xamarin.Media { public static class MediaFileExtensions { public static Task<MediaFile> GetMediaFileExtraAsync (this Intent self, Context context) { if (self == null) throw new ArgumentNullException ("self"); if (context == null) throw new ArgumentNullException ("context"); var uri = (Android.Net.Uri)self.GetParcelableExtra (MediaFile.ExtraName); if (uri == null) throw new ArgumentException ("Intent was not results from MediaPicker", "self"); bool isPhoto = self.GetBooleanExtra ("isPhoto", false); string action = self.GetStringExtra ("action"); var path = (Android.Net.Uri)self.GetParcelableExtra ("path"); return MediaPickerActivity.GetMediaFileAsync (context, 0, action, isPhoto, ref path, uri) .ContinueWith (t => t.Result.ToTask()).Unwrap(); } } public sealed class MediaFile : IDisposable { internal MediaFile (string path, bool deletePathOnDispose) { this.deletePathOnDispose = deletePathOnDispose; this.path = path; } public string Path { get { if (this.isDisposed) throw new ObjectDisposedException (null); return this.path; } } public Stream GetStream() { if (this.isDisposed) throw new ObjectDisposedException (null); return File.OpenRead (this.path); } public void Dispose() { Dispose (true); GC.SuppressFinalize (this); } private bool isDisposed; private readonly bool deletePathOnDispose; private readonly string path; internal const string ExtraName = "MediaFile"; private void Dispose (bool disposing) { if (this.isDisposed) return; this.isDisposed = true; if (this.deletePathOnDispose) { try { File.Delete (this.path); // We don't really care if this explodes for a normal IO reason. } catch (UnauthorizedAccessException) { } catch (DirectoryNotFoundException) { } catch (IOException) { } } } ~MediaFile() { Dispose (false); } } }
using System; using System.IO; using System.Threading.Tasks; using Android.Content; using File = System.IO.File; using IOException = System.IO.IOException; namespace Xamarin.Media { public static class MediaFileExtensions { public static Task<MediaFile> GetMediaFileExtraAsync (this Intent self, Context context) { var uri = (Android.Net.Uri)self.GetParcelableExtra (MediaFile.ExtraName); bool isPhoto = self.GetBooleanExtra ("isPhoto", false); string action = self.GetStringExtra ("action"); var path = (Android.Net.Uri)self.GetParcelableExtra ("path"); return MediaPickerActivity.GetMediaFileAsync (context, 0, action, isPhoto, ref path, uri) .ContinueWith (t => t.Result.ToTask()).Unwrap(); } } public sealed class MediaFile : IDisposable { internal MediaFile (string path, bool deletePathOnDispose) { this.deletePathOnDispose = deletePathOnDispose; this.path = path; } public string Path { get { if (this.isDisposed) throw new ObjectDisposedException (null); return this.path; } } public Stream GetStream() { if (this.isDisposed) throw new ObjectDisposedException (null); return File.OpenRead (this.path); } public void Dispose() { Dispose (true); GC.SuppressFinalize (this); } private bool isDisposed; private readonly bool deletePathOnDispose; private readonly string path; internal const string ExtraName = "MediaFile"; private void Dispose (bool disposing) { if (this.isDisposed) return; this.isDisposed = true; if (this.deletePathOnDispose) { try { File.Delete (this.path); // We don't really care if this explodes for a normal IO reason. } catch (UnauthorizedAccessException) { } catch (DirectoryNotFoundException) { } catch (IOException) { } } } ~MediaFile() { Dispose (false); } } }
apache-2.0
C#
c5b8aa6d236b6072199acdfe520a486772e4db2d
Move all CDN scripts before bower scripts
croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/website-application
source/CroquetAustralia.Website/Layouts/Shared/AfterRenderBody.cshtml
source/CroquetAustralia.Website/Layouts/Shared/AfterRenderBody.cshtml
@using CroquetAustralia.Website.App.Infrastructure @* ReSharper disable All *@ @{ var model = (IViewModel) PageData["model"]; if (model.ShowSidebar) { @RenderPage("EndColumns.cshtml") } } </div> </div> <script src="//code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script> <script src="//ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"></script> <!-- bower:js --> <script src="/bower_components/angular/angular.js"></script> <script src="/bower_components/bootstrap-submenu/dist/js/bootstrap-submenu.js"></script> <script src="/bower_components/ng-file-upload/ng-file-upload.js"></script> <script src="/bower_components/markdown-editpreview-ng/lib/codemwnci/bootstrap-markdown.js"></script> <script src="/bower_components/markdown-editpreview-ng/lib/codemwnci/markdown-editpreview-ng.js"></script> <script src="/bower_components/markdown-editpreview-ng/lib/codemwnci/Markdown.Converter.js"></script> <script src="/bower_components/markdown-editpreview-ng/lib/codemwnci/Markdown.Sanitizer.js"></script> <script src="/bower_components/Angular.uuid2/dist/angular-uuid2.js"></script> <script src="/bower_components/moment/moment.js"></script> <script src="/bower_components/moment-timezone/builds/moment-timezone-with-data-2010-2020.js"></script> <script src="/bower_components/angular-moment/angular-moment.js"></script> <!-- endbower --> <script src="~/bower_components/bootstrap-submenu/js/bootstrap-submenu.js"></script> <!-- inject:js --> <script src="/app/app.js"></script> <script src="/app/admin/files/FileUpload.Module.js"></script> <script src="/app/admin/files/FileUpload.js"></script> <script src="/app/admin/home/AddNews.Module.js"></script> <script src="/app/admin/home/AddNews.js"></script> <script src="/app/admin/home/AddPage.Module.js"></script> <script src="/app/admin/home/AddPage.js"></script> <script src="/app/tournaments/scripts/DateOfBirthRange.js"></script> <script src="/app/tournaments/scripts/Tournament.js"></script> <script src="/app/tournaments/scripts/TournamentItem.js"></script> <script src="/app/tournaments/scripts/TournamentPlayer.js"></script> <script src="/app/tournaments/scripts/TournamentsController.js"></script> <!-- endinject --> <script> $('.dropdown-submenu > a').submenupicker(); </script>
@using CroquetAustralia.Website.App.Infrastructure @* ReSharper disable All *@ @{ var model = (IViewModel) PageData["model"]; if (model.ShowSidebar) { @RenderPage("EndColumns.cshtml") } } </div> </div> <script src="//code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <!-- bower:js --> <script src="/bower_components/angular/angular.js"></script> <script src="/bower_components/bootstrap-submenu/dist/js/bootstrap-submenu.js"></script> <script src="/bower_components/ng-file-upload/ng-file-upload.js"></script> <script src="/bower_components/markdown-editpreview-ng/lib/codemwnci/bootstrap-markdown.js"></script> <script src="/bower_components/markdown-editpreview-ng/lib/codemwnci/markdown-editpreview-ng.js"></script> <script src="/bower_components/markdown-editpreview-ng/lib/codemwnci/Markdown.Converter.js"></script> <script src="/bower_components/markdown-editpreview-ng/lib/codemwnci/Markdown.Sanitizer.js"></script> <script src="/bower_components/Angular.uuid2/dist/angular-uuid2.js"></script> <script src="/bower_components/moment/moment.js"></script> <script src="/bower_components/moment-timezone/builds/moment-timezone-with-data-2010-2020.js"></script> <script src="/bower_components/angular-moment/angular-moment.js"></script> <!-- endbower --> @* markdown-editpreview-ng.js requires jQuery is be before Angular *@ @*<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js"></script>*@ @*<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>*@ <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script> <script src="//ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"></script> <script src="~/bower_components/bootstrap-submenu/js/bootstrap-submenu.js"></script> <!-- inject:js --> <script src="/app/app.js"></script> <script src="/app/admin/files/FileUpload.Module.js"></script> <script src="/app/admin/files/FileUpload.js"></script> <script src="/app/admin/home/AddNews.Module.js"></script> <script src="/app/admin/home/AddNews.js"></script> <script src="/app/admin/home/AddPage.Module.js"></script> <script src="/app/admin/home/AddPage.js"></script> <script src="/app/tournaments/scripts/DateOfBirthRange.js"></script> <script src="/app/tournaments/scripts/Tournament.js"></script> <script src="/app/tournaments/scripts/TournamentItem.js"></script> <script src="/app/tournaments/scripts/TournamentPlayer.js"></script> <script src="/app/tournaments/scripts/TournamentsController.js"></script> <!-- endinject --> <script> $('.dropdown-submenu > a').submenupicker(); </script>
mit
C#
0aee9152bd7feb5f32a032facc8f19179c4e811b
Make AcceptedCharacters public
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNetCore.Razor.Evolution/Legacy/AcceptedCharacters.cs
src/Microsoft.AspNetCore.Razor.Evolution/Legacy/AcceptedCharacters.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.AspNetCore.Razor.Evolution.Legacy { [Flags] public enum AcceptedCharacters { None = 0, NewLine = 1, WhiteSpace = 2, NonWhiteSpace = 4, AllWhiteSpace = NewLine | WhiteSpace, Any = AllWhiteSpace | NonWhiteSpace, AnyExceptNewline = NonWhiteSpace | WhiteSpace } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.AspNetCore.Razor.Evolution.Legacy { [Flags] internal enum AcceptedCharacters { None = 0, NewLine = 1, WhiteSpace = 2, NonWhiteSpace = 4, AllWhiteSpace = NewLine | WhiteSpace, Any = AllWhiteSpace | NonWhiteSpace, AnyExceptNewline = NonWhiteSpace | WhiteSpace } }
apache-2.0
C#
a4984e1515b2fd641a4c61f1fa339c05de7975a3
Replace nameof() with a string paramenter name to be compatible with VS2013
pveller/Sitecore.FakeDb,sergeyshushlyapin/Sitecore.FakeDb
src/Sitecore.FakeDb/Sites/FakeSiteContextSwitcher.cs
src/Sitecore.FakeDb/Sites/FakeSiteContextSwitcher.cs
using System; using System.Collections.Generic; using System.Linq; namespace Sitecore.FakeDb.Sites { using System.Collections.Specialized; using Sitecore.Sites; using Sitecore.Web; using StringDictionary = Sitecore.Collections.StringDictionary; /// <summary> /// Switches The Site Context and sync context with Factory.Sites /// </summary> public class FakeSiteContextSwitcher: SiteContextSwitcher { private readonly List<SiteInfo> _pocket = new List<SiteInfo>(); public FakeSiteContextSwitcher(SiteContext site) : base(site) { if (site == null) throw new ArgumentNullException("site"); _pocket.AddRange(SiteContextFactory.Sites); //SiteContextFactory stores cashed data in _searchTable so clearing .Sites is not enough SiteContextFactory.Reset(); //Returning back all sites except Context to avoid duplication AddOnlyNew(SiteContextFactory.Sites, _pocket.Where(t => t.Name != site.Name)); SiteContextFactory.Sites.Add(new SiteInfo(new StringDictionary(ToDictionary(site.Properties)))); } private IDictionary<string, string> ToDictionary(NameValueCollection col) { IDictionary<string, string> dict = new Dictionary<string, string>(); foreach (var k in col.AllKeys) { dict.Add(k, col[k]); } return dict; } private void AddOnlyNew(List<SiteInfo> currentSites, IEnumerable<SiteInfo> update) { currentSites.AddRange(update.Where(t => currentSites.All(s => s.Name != t.Name))); } public override void Dispose() { SiteContextFactory.Reset(); AddOnlyNew(SiteContextFactory.Sites, _pocket); base.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Sitecore.FakeDb.Sites { using System.Collections.Specialized; using Sitecore.Sites; using Sitecore.Web; using StringDictionary = Sitecore.Collections.StringDictionary; /// <summary> /// Switches The Site Context and sync context with Factory.Sites /// </summary> public class FakeSiteContextSwitcher: SiteContextSwitcher { private readonly List<SiteInfo> _pocket = new List<SiteInfo>(); public FakeSiteContextSwitcher(SiteContext site) : base(site) { if (site == null) throw new ArgumentNullException(nameof(site)); _pocket.AddRange(SiteContextFactory.Sites); //SiteContextFactory stores cashed data in _searchTable so clearing .Sites is not enough SiteContextFactory.Reset(); //Returning back all sites except Context to avoid duplication AddOnlyNew(SiteContextFactory.Sites, _pocket.Where(t => t.Name != site.Name)); SiteContextFactory.Sites.Add(new SiteInfo(new StringDictionary(ToDictionary(site.Properties)))); } private IDictionary<string, string> ToDictionary(NameValueCollection col) { IDictionary<string, string> dict = new Dictionary<string, string>(); foreach (var k in col.AllKeys) { dict.Add(k, col[k]); } return dict; } private void AddOnlyNew(List<SiteInfo> currentSites, IEnumerable<SiteInfo> update) { currentSites.AddRange(update.Where(t => currentSites.All(s => s.Name != t.Name))); } public override void Dispose() { SiteContextFactory.Reset(); AddOnlyNew(SiteContextFactory.Sites, _pocket); base.Dispose(); } } }
mit
C#
de5a104664812172e72569883bab4a8839e47f04
Fix typo in ICanvasCellViewFrontend
TheBrainTech/xwt,lytico/xwt,hamekoz/xwt,hwthomas/xwt,mono/xwt,antmicro/xwt
Xwt/Xwt.Backends/ICanvasCellViewFrontend.cs
Xwt/Xwt.Backends/ICanvasCellViewFrontend.cs
// // ICanvasCellViewFrontend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2013 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; namespace Xwt.Backends { public interface ICanvasCellViewFrontend: ICellViewFrontend { ApplicationContext ApplicationContext { get; } void Draw (object ctxBackend, Rectangle cellArea); Rectangle GetDrawingAreaForBounds (Rectangle cellBounds); [Obsolete("Use GetRequiredSize (SizeConstraint)")] Size GetRequiredSize (); Size GetRequiredSize (SizeConstraint widthConstraint); } public class CellViewStatus { public Rectangle CellBounds { get; set; } public Rectangle BackgroundBounds { get; set; } public bool Selected { get; set; } public bool HasFocus { get; set; } } }
// // ICanvasCellViewFrontend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2013 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; namespace Xwt.Backends { public interface ICanvasCellViewFrontend: ICellViewFrontend { ApplicationContext ApplicationContext { get; } void Draw (object ctxBackend, Rectangle cellArea); Rectangle GetDrawingAreaForBounds (Rectangle cellBounds); [Obsolete("Use OnGetRequiredSize (SizeConstraint widthConstraint)")] Size GetRequiredSize (); Size GetRequiredSize (SizeConstraint widthConstraint); } public class CellViewStatus { public Rectangle CellBounds { get; set; } public Rectangle BackgroundBounds { get; set; } public bool Selected { get; set; } public bool HasFocus { get; set; } } }
mit
C#
ba1a396186c92aaeb7ea071dab2da2230d9316b2
Remove StructLayout attributes
vazgriz/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary
CSharpGameLibrary/GLFW/structs.cs
CSharpGameLibrary/GLFW/structs.cs
using System; using System.Runtime.InteropServices; namespace CSGL.GLFW { public struct VideoMode { public readonly int width; public readonly int height; public readonly int redBits; public readonly int greenBits; public readonly int blueBits; public readonly int refreshRate; } public unsafe struct NativeGammaRamp { public ushort* red; public ushort* green; public ushort* blue; public uint size; public NativeGammaRamp(ushort* red, ushort* green, ushort* blue, uint size) { this.red = red; this.green = green; this.blue = blue; this.size = size; } } public struct GammaRamp { public ushort[] red; public ushort[] green; public ushort[] blue; public uint size; public GammaRamp(ushort[] red, ushort[] green, ushort[] blue, uint size) { this.red = red; this.green = green; this.blue = blue; this.size = size; } public GammaRamp(NativeGammaRamp ramp) { size = ramp.size; red = new ushort[size]; green = new ushort[size]; blue = new ushort[size]; unsafe { for (int i = 0; i < size; i++) { red[i] = ramp.red[i]; green[i] = ramp.green[i]; blue[i] = ramp.blue[i]; } } } } public unsafe struct NativeImage { public int width; public int height; public byte* data; public NativeImage(int width, int height, byte* data) { this.width = width; this.height = height; this.data = data; } } }
using System; using System.Runtime.InteropServices; namespace CSGL.GLFW { [StructLayout(LayoutKind.Sequential)] public struct VideoMode { public readonly int width; public readonly int height; public readonly int redBits; public readonly int greenBits; public readonly int blueBits; public readonly int refreshRate; } [StructLayout(LayoutKind.Sequential)] public unsafe struct NativeGammaRamp { public ushort* red; public ushort* green; public ushort* blue; public uint size; public NativeGammaRamp(ushort* red, ushort* green, ushort* blue, uint size) { this.red = red; this.green = green; this.blue = blue; this.size = size; } } public struct GammaRamp { public ushort[] red; public ushort[] green; public ushort[] blue; public uint size; public GammaRamp(ushort[] red, ushort[] green, ushort[] blue, uint size) { this.red = red; this.green = green; this.blue = blue; this.size = size; } public GammaRamp(NativeGammaRamp ramp) { size = ramp.size; red = new ushort[size]; green = new ushort[size]; blue = new ushort[size]; unsafe { for (int i = 0; i < size; i++) { red[i] = ramp.red[i]; green[i] = ramp.green[i]; blue[i] = ramp.blue[i]; } } } } [StructLayout(LayoutKind.Sequential)] public unsafe struct NativeImage { public int width; public int height; public byte* data; public NativeImage(int width, int height, byte* data) { this.width = width; this.height = height; this.data = data; } } }
mit
C#
9ea5cfcff985cc0a14c4fb5df57ea40ef954515d
Update the example program
jonathanvdc/Pixie,jonathanvdc/Pixie
Examples/ConsoleDriver/Program.cs
Examples/ConsoleDriver/Program.cs
using System; using Pixie; using Pixie.Terminal; using Pixie.Markup; namespace ConsoleDriver { public static class Program { public static void Main(string[] args) { var log = TerminalLog.Acquire(); log.Log(new LogEntry( Severity.Progress, new Title("Hello world"), new Box( new Text( "This is a hello world example. Wow this is a really long piece of text!!! " + "I wonder if this'll fit on a single line."), WrappingStrategy.Word, 4))); } } }
using System; using Pixie; using Pixie.Terminal; using Pixie.Markup; namespace ConsoleDriver { public static class Program { public static void Main(string[] args) { var log = TerminalLog.Acquire(); log.Log(new LogEntry( Severity.Progress, new Title("Hello world"), new Text("This is a hello world example"))); } } }
mit
C#
58b03281379dc07129e636cf9d076079780f39db
Optimize finding script template
appetizermonster/Unity3D-ActionEngine
Assets/ActionEngine/AEScript/Editor/AEScriptEditor.cs
Assets/ActionEngine/AEScript/Editor/AEScriptEditor.cs
using Microsoft.CSharp; using System; using System.CodeDom.Compiler; using System.Collections; using System.IO; using System.Linq; using System.Reflection; using UnityEditor; using UnityEngine; namespace ActionEngine { [CustomEditor(typeof(AEScriptRunner))] [CanEditMultipleObjects] public class AEScriptRunnerEditor : Editor { [MenuItem("Assets/Create/C# AEScript", false, 94)] private static void CreateAEScriptSource () { var scriptTemplatePath = GetAEScriptTemplatePath(); var createScriptAsset = typeof(ProjectWindowUtil).GetMethod("CreateScriptAsset", BindingFlags.NonPublic | BindingFlags.Static); createScriptAsset.Invoke(null, new object[] { scriptTemplatePath, "New AEX.cs" }); } private static string scriptTemplatePath_ = null; private static string GetAEScriptTemplatePath () { if (scriptTemplatePath_ != null && File.Exists(scriptTemplatePath_)) return scriptTemplatePath_; var templates = AssetDatabase.FindAssets("AEX.Template"); if (templates == null || templates.Length == 0) throw new InvalidOperationException("Can't find a script template"); var template = AssetDatabase.GUIDToAssetPath(templates[0]); scriptTemplatePath_ = Path.GetFullPath(template); return scriptTemplatePath_; } public override void OnInspectorGUI () { base.OnInspectorGUI(); GUILayout.Space(10); GUI.enabled = EditorApplication.isPlaying; GUILayout.BeginHorizontal(); if (GUILayout.Button(new GUIContent("Reload and Play"))) { targets.ToList().ForEach((x) => ReloadAndPlay(x as AEScriptRunner)); } if (GUILayout.Button(new GUIContent("Kill"))) { targets.ToList().ForEach((x) => Kill(x as AEScriptRunner)); } GUILayout.EndHorizontal(); GUI.enabled = true; } private void ReloadAndPlay (AEScriptRunner obj) { obj.Kill(); obj.Play().AddDelay(1f); // Add delay to compensate script loading time } private void Kill (AEScriptRunner obj) { obj.Kill(); } } }
using Microsoft.CSharp; using System; using System.CodeDom.Compiler; using System.Collections; using System.IO; using System.Reflection; using UnityEditor; using UnityEngine; using System.Linq; namespace ActionEngine { [CustomEditor(typeof(AEScriptRunner))] [CanEditMultipleObjects] public class AEScriptRunnerEditor : Editor { [MenuItem("Assets/Create/C# AEScript", false, 94)] private static void CreateAEScriptSource () { var templates = AssetDatabase.FindAssets("AEX.Template"); if (templates == null || templates.Length == 0) throw new InvalidOperationException("Can't find a script template"); var template = AssetDatabase.GUIDToAssetPath(templates[0]); var templatePath = Path.GetFullPath(template); var createScriptAsset = typeof(ProjectWindowUtil).GetMethod("CreateScriptAsset", BindingFlags.NonPublic | BindingFlags.Static); createScriptAsset.Invoke(null, new object[] { templatePath, "New AEX.cs" }); } public override void OnInspectorGUI () { base.OnInspectorGUI(); GUILayout.Space(10); GUI.enabled = EditorApplication.isPlaying; GUILayout.BeginHorizontal(); if (GUILayout.Button(new GUIContent("Reload and Play"))) { targets.ToList().ForEach((x) => ReloadAndPlay(x as AEScriptRunner)); } if (GUILayout.Button(new GUIContent("Kill"))) { targets.ToList().ForEach((x) => Kill(x as AEScriptRunner)); } GUILayout.EndHorizontal(); GUI.enabled = true; } private void ReloadAndPlay (AEScriptRunner obj) { obj.Kill(); obj.Play().AddDelay(1f); // Add delay to compensate script loading time } private void Kill (AEScriptRunner obj) { obj.Kill(); } } }
mit
C#
6ba4e73995855a32d15f150fcfeb451aeb23b178
Remove unnecessary whitespace from OpenConnection
jagrem/msg
Core/Msg.Core/Transport/Connections/OpenConnection.cs
Core/Msg.Core/Transport/Connections/OpenConnection.cs
using System.Threading.Tasks; using Msg.Core.Versioning; using Msg.Core.Transport; namespace Msg.Core.Transport.Connections { public class OpenConnection : IConnection { readonly IConnection connection; internal OpenConnection (IConnection connection) { this.connection = connection; } public Task<byte[]> SendAsync (byte[] message) { return connection.SendAsync (message); } public bool IsConnected { get { return true; } } public bool IsClosed { get { return false; } } public long MaximumFrameSize { get { // Replace with negotiated maximum frame size return connection.MaximumFrameSize; } } public Version Version { get { // Replace with version parameter return connection.Version; } } public System.Collections.Generic.IEnumerable<VersionRange> SupportedVersions { get { return connection.SupportedVersions; } } } }
using System.Threading.Tasks; using Msg.Core.Versioning; using Msg.Core.Transport; namespace Msg.Core.Transport.Connections { public class OpenConnection : IConnection { readonly IConnection connection; internal OpenConnection (IConnection connection) { this.connection = connection; } public Task<byte[]> SendAsync (byte[] message) { return connection.SendAsync (message); } public bool IsConnected { get { return true; } } public bool IsClosed { get { return false; } } public long MaximumFrameSize { get { // Replace with negotiated maximum frame size return connection.MaximumFrameSize; } } public Version Version { get { // Replace with version parameter return connection.Version; } } public System.Collections.Generic.IEnumerable<VersionRange> SupportedVersions { get { return connection.SupportedVersions; } } } }
apache-2.0
C#
09613f4e3e7263904530b4605a93320b522ed3bc
Add jQuery mobile loader widget
xamarin/PortableRazor,MilenPavlov/PortableRazor
Samples/iCongress/PortableCongress/Controllers/PoliticianController.cs
Samples/iCongress/PortableCongress/Controllers/PoliticianController.cs
using System; using PortableRazor; namespace PortableCongress { public class PoliticianController { IHybridWebView webView; IDataAccess dataAccess; public PoliticianController (IHybridWebView webView, IDataAccess dataAccess) { this.webView = webView; this.dataAccess = dataAccess; } public void ShowPoliticianList() { var list = dataAccess.LoadAllPoliticans (); var template = new PoliticianList () { Model = list }; var page = template.GenerateString (); webView.LoadHtmlString (page); } public Politician ShowPoliticianView(int id) { var politician = dataAccess.LoadPolitician (id); var template = new PoliticianView () { Model = politician }; var page = template.GenerateString (); webView.LoadHtmlString (page); return politician; } public async void ShowRecentVotes(int id) { webView.EvaluateJavascript ("$.mobile.loading( 'show', {\n text: 'Loading Recent Votes ...',\n " + "textVisible: 'false',\n theme: 'b',\n textonly: 'false' });"); var votes = await WebAccess.GetRecentVotesAsync (id); var template = new RecentVotesList () { Model = votes }; var page = template.GenerateString (); webView.LoadHtmlString (page); } } }
using System; using PortableRazor; namespace PortableCongress { public class PoliticianController { IHybridWebView webView; IDataAccess dataAccess; public PoliticianController (IHybridWebView webView, IDataAccess dataAccess) { this.webView = webView; this.dataAccess = dataAccess; } public void ShowPoliticianList() { var list = dataAccess.LoadAllPoliticans (); var template = new PoliticianList () { Model = list }; var page = template.GenerateString (); webView.LoadHtmlString (page); } public Politician ShowPoliticianView(int id) { var politician = dataAccess.LoadPolitician (id); var template = new PoliticianView () { Model = politician }; var page = template.GenerateString (); webView.LoadHtmlString (page); return politician; } public async void ShowRecentVotes(int id) { //var votes = dataAccess.LoadRecentVotes (id); var votes = await WebAccess.GetRecentVotesAsync (id); var template = new RecentVotesList () { Model = votes }; var page = template.GenerateString (); webView.LoadHtmlString (page); } } }
mit
C#
616689cf33932c18c950cbbcf14ca96edbc95705
Update BattlePeer.cs
PokemonUnity/PokemonUnity
PokemonUnity.Shared/Monster/BattlePeer.cs
PokemonUnity.Shared/Monster/BattlePeer.cs
using System; using System.Collections.Generic; using PokemonUnity; using PokemonUnity.Inventory; using PokemonUnity.Overworld; using PokemonUnity.Character; namespace PokemonUnity.Monster { public partial class PokeBattle_NullBattlePeer : IPokeBattle_BattlePeer { public void pbOnEnteringBattle(Combat.Battle battle,Monster.Pokemon pokemon) { } public int pbStorePokemon(Player player,Monster.Pokemon pokemon) { if (player.Party.GetCount()<6) { player.Party[player.Party.GetCount()]=pokemon; } return -1; } public string pbGetStorageCreator() { return null; } public int pbCurrentBox() { return -1; } public string pbBoxName(int box) { return ""; } } public partial class PokeBattle_RealBattlePeer { public int pbStorePokemon(Player player,Monster.Pokemon pokemon) { if (player.Party.GetCount()<6) { player.Party[player.Party.GetCount()]=pokemon; return -1; } else { pokemon.Heal(); //int oldcurbox=Game.GameData.PokemonStorage.currentBox; //int storedbox=Game.GameData.PokemonStorage.pbStoreCaught(pokemon); int oldcurbox=Game.GameData.Player.PC.ActiveBox; int? storedbox = Game.GameData.Player.PC.getIndexOfFirstEmpty(); //if (storedbox<0) { if (!storedbox.HasValue) { //Game.UI.pbDisplayPaused(Game._INTL("Can't catch any more...")); return oldcurbox; } else { return storedbox.Value; } } } public string pbGetStorageCreator() { string creator=null; //if (Game.GameData != null && Game.GameData.Global.seenStorageCreator) { if (Game.GameData != null && Game.GameData.Player.IsCreator) { //creator=Game.GameData.PokemonStorage.pbGetStorageCreator(); creator="someone"; //ToDo... } return creator; } public int pbCurrentBox() { //return Game.GameData.PokemonStorage.currentBox; return Game.GameData.Player.PC.ActiveBox; } public string pbBoxName(int box) { //return box<0 ? "" : $PokemonStorage[box].name; return box<0 ? "" : Game.GameData.Player.PC.BoxNames[box]; } } public partial class PokeBattle_BattlePeer { public static PokeBattle_RealBattlePeer create() { return new PokeBattle_RealBattlePeer(); } } public interface IPokeBattle_BattlePeer { string pbBoxName(int box); int pbCurrentBox(); string pbGetStorageCreator(); void pbOnEnteringBattle(Combat.Battle battle, Monster.Pokemon pokemon); int pbStorePokemon(Player player, Monster.Pokemon pokemon); } }
using PokemonUnity; using PokemonUnity.Inventory; using System; using System.Linq; using System.Text; using System.Collections.Generic; using PokemonUnity.Overworld; using PokemonUnity.Character; namespace PokemonUnity.Monster { public partial class PokeBattle_NullBattlePeer : IPokeBattle_BattlePeer { public void pbOnEnteringBattle(Combat.Battle battle,Monster.Pokemon pokemon) { } public int pbStorePokemon(Player player,Monster.Pokemon pokemon) { if (player.Party.Length<6) { player.Party[player.Party.Length]=pokemon; } return -1; } public string pbGetStorageCreator() { return null; } public int pbCurrentBox() { return -1; } public string pbBoxName(int box) { return ""; } } public partial class PokeBattle_RealBattlePeer { public int pbStorePokemon(Player player,Monster.Pokemon pokemon) { if (player.Party.Length<6) { player.Party[player.Party.Length]=pokemon; return -1; } else { pokemon.Heal(); int oldcurbox=Game.GameData.PokemonStorage.currentBox; //int oldcurbox=Game.GameData.Player.PC.ActiveBox; int storedbox=Game.GameData.PokemonStorage.pbStoreCaught(pokemon); //int storedbox=Game.GameData.Player.PC.addPokemon(pokemon); if (storedbox<0) { Game.UI.pbDisplayPaused(Game._INTL("Can't catch any more...")); return oldcurbox; } else { return storedbox; } } } public string pbGetStorageCreator() { string creator=null; if (Game.GameData != null && Game.GameData.Global.seenStorageCreator) { //if (Game.GameData != null && Game.GameData.seenStorageCreator) { //creator=Game.GameData.PokemonStorage.pbGetStorageCreator(); creator=Game.GameData.Player.PC.pbGetStorageCreator(); } return creator; } public int pbCurrentBox() { //return Game.GameData.PokemonStorage.currentBox; return Game.GameData.Player.PC.ActiveBox; } public string pbBoxName(int box) { //return box<0 ? "" : $PokemonStorage[box].name; return box<0 ? "" : Game.GameData.Player.PC.BoxNames[box]; } } public partial class PokeBattle_BattlePeer { public static PokeBattle_RealBattlePeer create() { return new PokeBattle_RealBattlePeer(); } } public interface IPokeBattle_BattlePeer { string pbBoxName(int box); int pbCurrentBox(); string pbGetStorageCreator(); void pbOnEnteringBattle(Combat.Battle battle, Monster.Pokemon pokemon); int pbStorePokemon(Player player, Monster.Pokemon pokemon); } }
bsd-3-clause
C#
06b606100b8cfeee669999462839423677515bf7
add 2do
MartinRL/SlackTurnus,MartinRL/SlackTurnus
SlackTurnus/Controllers/HomeController.cs
SlackTurnus/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Web; using System.Web.Hosting; using System.Web.Mvc; using Newtonsoft.Json; namespace SlackTurnus.Controllers { public class HomeController : Controller { private readonly IGetSlackTurnus _getSlackTurnus; public HomeController(IGetSlackTurnus getSlackTurnus) { _getSlackTurnus = getSlackTurnus; } public ActionResult Index() { return View(_getSlackTurnus.Execute()); } public ActionResult Accept() { throw new NotImplementedException(); } } public interface IGetSlackTurnus { IOrderedDictionary Execute(); } public class GetSlackTurnus : IGetSlackTurnus { public IOrderedDictionary Execute() { string slackersAsJson; // 2do: DI http://stackoverflow.com/questions/6390608/structuremap-is-not-disposing-data-context-when-using-httpcontextscoped using (var streamReader = new StreamReader(HostingEnvironment.MapPath("~/DomainModel/slackTurnus.json"))) { slackersAsJson = streamReader.ReadToEnd(); } return JsonConvert.DeserializeObject<OrderedDictionary>(slackersAsJson); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Web; using System.Web.Hosting; using System.Web.Mvc; using Newtonsoft.Json; namespace SlackTurnus.Controllers { public class HomeController : Controller { private readonly IGetSlackTurnus _getSlackTurnus; public HomeController(IGetSlackTurnus getSlackTurnus) { _getSlackTurnus = getSlackTurnus; } public ActionResult Index() { return View(_getSlackTurnus.Execute()); } public ActionResult Accept() { throw new NotImplementedException(); } } public interface IGetSlackTurnus { IOrderedDictionary Execute(); } public class GetSlackTurnus : IGetSlackTurnus { public IOrderedDictionary Execute() { string slackersAsJson; using (var streamReader = new StreamReader(HostingEnvironment.MapPath("~/DomainModel/slackTurnus.json"))) { slackersAsJson = streamReader.ReadToEnd(); } return JsonConvert.DeserializeObject<OrderedDictionary>(slackersAsJson); } } }
mit
C#
90ef417afc30e542bcef8b43ac2c290217230372
Fix naming of MonoMac vs MonoMac 64-bit platform
l8s/Eto,bbqchickenrobot/Eto-1,l8s/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,PowerOfCode/Eto,l8s/Eto
Source/Eto.Mac/Properties/AssemblyInfo.cs
Source/Eto.Mac/Properties/AssemblyInfo.cs
using System.Reflection; #if XAMMAC2 [assembly: AssemblyTitle("Eto.Forms - Xamarin.Mac v2.0 Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac v2.0")] #elif XAMMAC [assembly: AssemblyTitle("Eto.Forms - Xamarin.Mac Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac")] #elif Mac64 [assembly: AssemblyTitle("Eto.Forms - MonoMac 64-bit Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac with 64-bit mono")] #else [assembly: AssemblyTitle("Eto.Forms - MonoMac Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac")] #endif
using System.Reflection; #if XAMMAC2 [assembly: AssemblyTitle("Eto.Forms - Xamarin.Mac v2.0 Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac v2.0")] #elif XAMMAC [assembly: AssemblyTitle("Eto.Forms - Xamarin.Mac Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac")] #elif Mac64 [assembly: AssemblyTitle("Eto.Forms - MonoMac Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac")] #else [assembly: AssemblyTitle("Eto.Forms - MonoMac 64-bit Platform")] [assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac with 64-bit mono")] #endif
bsd-3-clause
C#
08b3004d7e72aad92e4dc7c6eb07a4c6ac89c7ed
Remove duplicates from sorted list
Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews
LeetCode/remote/remove_duplicates_from_sorted_list.cs
LeetCode/remote/remove_duplicates_from_sorted_list.cs
// https://leetcode.com/submissions/detail/52724586/ // // // Submission Details // 164 / 164 test cases passed. // Status: Accepted // Runtime: 160 ms // // Submitted: 0 minutes ago // /** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode DeleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } head.next = DeleteDuplicates(head.next); return head.val == head.next.val ? head.next : head; } } // https://leetcode.com/submissions/detail/64406454/ // // Submission Details // 164 / 164 test cases passed. // Status: Accepted // Runtime: 168 ms // // Submitted: 0 minutes ago public class Solution { public ListNode DeleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } head.next = DeleteDuplicates(head.next); if (head.val == head.next.val) { return head.next; } return head; } } // // Submission Details // 164 / 164 test cases passed. // Status: Accepted // Runtime: 164 ms // // Submitted: 0 minutes ago // /** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode DeleteDuplicates(ListNode head) { var dummy = new ListNode(int.MaxValue); var it = dummy; while (head != null) { var next = head.next; if (it.val != head.val) { it.next = head; it = it.next; it.next = null; } head = next; } return dummy.next; } }
// https://leetcode.com/submissions/detail/52724586/ // // // Submission Details // 164 / 164 test cases passed. // Status: Accepted // Runtime: 160 ms // // Submitted: 0 minutes ago // /** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode DeleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } head.next = DeleteDuplicates(head.next); return head.val == head.next.val ? head.next : head; } } // // Submission Details // 164 / 164 test cases passed. // Status: Accepted // Runtime: 164 ms // // Submitted: 0 minutes ago // /** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode DeleteDuplicates(ListNode head) { var dummy = new ListNode(int.MaxValue); var it = dummy; while (head != null) { var next = head.next; if (it.val != head.val) { it.next = head; it = it.next; it.next = null; } head = next; } return dummy.next; } }
mit
C#
9326e0a548912653f5a3ac57c0d64779e73f331b
Fix issue of wrong counting characters if a text contains newline
fin-alice/Mystique,azyobuzin/Mystique
Inscribe/Text/TweetTextCounter.cs
Inscribe/Text/TweetTextCounter.cs
using System.Linq; using System.Text.RegularExpressions; namespace Inscribe.Text { public static class TweetTextCounter { public static int Count(string input) { // Input maybe contains CRLF as a new line, but twitter converts CRLF to LF. // It means CRLF should be treat as one charator. string inputCRLFProcessed = input.Replace(System.Environment.NewLine, "\n"); // URL is MAX 20 Chars (if URL has HTTPS scheme, URL is MAX 21 Chars) int prevIndex = 0; int totalCount = 0; foreach (var m in RegularExpressions.UrlRegex.Matches(inputCRLFProcessed).OfType<Match>()) { totalCount += m.Index - prevIndex; prevIndex = m.Index + m.Groups[0].Value.Length; bool isHasHttpsScheme = m.Groups[0].Value.Contains("https"); if (m.Groups[0].Value.Length < TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0)) totalCount += m.Groups[0].Value.Length; else totalCount += TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0); } totalCount += inputCRLFProcessed.Length - prevIndex; return totalCount; } } }
using System.Linq; using System.Text.RegularExpressions; namespace Inscribe.Text { public static class TweetTextCounter { public static int Count(string input) { // URL is MAX 20 Chars (if URL has HTTPS scheme, URL is MAX 21 Chars) int prevIndex = 0; int totalCount = 0; foreach (var m in RegularExpressions.UrlRegex.Matches(input).OfType<Match>()) { totalCount += m.Index - prevIndex; prevIndex = m.Index + m.Groups[0].Value.Length; bool isHasHttpsScheme = m.Groups[0].Value.Contains("https"); if (m.Groups[0].Value.Length < TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0)) totalCount += m.Groups[0].Value.Length; else totalCount += TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0); } totalCount += input.Length - prevIndex; return totalCount; } } }
mit
C#
ec07bc055f293f86d9da265df002af6d49b1ac7b
change user agent
jvalladolid/recurly-client-net,cgerrior/recurly-client-net
Library/Configuration/Settings.cs
Library/Configuration/Settings.cs
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; [assembly: InternalsVisibleTo("Recurly.Test")] namespace Recurly.Configuration { internal class Settings { // non-static, as these change per instance, likely public string ApiKey { get; private set; } public string PrivateKey { get; private set; } public string Subdomain { get; private set; } public int PageSize { get; private set; } protected const string RecurlyServerUri = "https://{0}.recurly.com/v2{1}"; // static, unlikely to change public string UserAgent { get { return "Recurly C# Client v" + Assembly.GetExecutingAssembly().GetName().Version; } } public string AuthorizationHeaderValue { get { if (!ApiKey.IsNullOrEmpty()) return "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(ApiKey)); return string.Empty; } } public string GetServerUri(string givenPath) { if (givenPath.Contains("://")) return givenPath; return string.Format(RecurlyServerUri, Subdomain, givenPath); } private static Settings _instance; public static Settings Instance { get { return _instance ?? (_instance = new Settings()); } } private Settings() { ApiKey = Section.Current.ApiKey; Subdomain = Section.Current.Subdomain; PrivateKey = Section.Current.PrivateKey; PageSize = Section.Current.PageSize; } internal Settings(string apiKey, string subdomain, string privateKey, int pageSize) { ApiKey = apiKey; Subdomain = subdomain; PrivateKey = privateKey; PageSize = pageSize; } } }
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; [assembly: InternalsVisibleTo("Recurly.Test")] namespace Recurly.Configuration { internal class Settings { // non-static, as these change per instance, likely public string ApiKey { get; private set; } public string PrivateKey { get; private set; } public string Subdomain { get; private set; } public int PageSize { get; private set; } protected const string RecurlyServerUri = "https://{0}.recurly.com/v2{1}"; // static, unlikely to change public string UserAgent { get { return "Recurly .NET Client v" + Assembly.GetExecutingAssembly().GetName().Version; } } public string AuthorizationHeaderValue { get { if (!ApiKey.IsNullOrEmpty()) return "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(ApiKey)); return string.Empty; } } public string GetServerUri(string givenPath) { if (givenPath.Contains("://")) return givenPath; return string.Format(RecurlyServerUri, Subdomain, givenPath); } private static Settings _instance; public static Settings Instance { get { return _instance ?? (_instance = new Settings()); } } private Settings() { ApiKey = Section.Current.ApiKey; Subdomain = Section.Current.Subdomain; PrivateKey = Section.Current.PrivateKey; PageSize = Section.Current.PageSize; } internal Settings(string apiKey, string subdomain, string privateKey, int pageSize) { ApiKey = apiKey; Subdomain = subdomain; PrivateKey = privateKey; PageSize = pageSize; } } }
mit
C#
d8a1478200c86e1e60649ac2418cba7c40e4dc9a
Add helpers to SettingsDictionary
NIKASoftwareDevs/Orchard,jtkech/Orchard,sfmskywalker/Orchard,geertdoornbos/Orchard,jchenga/Orchard,aaronamm/Orchard,Cphusion/Orchard,emretiryaki/Orchard,harmony7/Orchard,alejandroaldana/Orchard,vairam-svs/Orchard,bigfont/orchard-continuous-integration-demo,dcinzona/Orchard,Anton-Am/Orchard,grapto/Orchard.CloudBust,JRKelso/Orchard,Inner89/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,huoxudong125/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,stormleoxia/Orchard,gcsuk/Orchard,xiaobudian/Orchard,Fogolan/OrchardForWork,Fogolan/OrchardForWork,yonglehou/Orchard,hhland/Orchard,Anton-Am/Orchard,patricmutwiri/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,openbizgit/Orchard,LaserSrl/Orchard,vairam-svs/Orchard,enspiral-dev-academy/Orchard,ericschultz/outercurve-orchard,LaserSrl/Orchard,SouleDesigns/SouleDesigns.Orchard,jagraz/Orchard,openbizgit/Orchard,Inner89/Orchard,mgrowan/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,patricmutwiri/Orchard,sebastienros/msc,escofieldnaxos/Orchard,dcinzona/Orchard-Harvest-Website,huoxudong125/Orchard,MpDzik/Orchard,Lombiq/Orchard,dburriss/Orchard,emretiryaki/Orchard,vairam-svs/Orchard,DonnotRain/Orchard,mgrowan/Orchard,ehe888/Orchard,openbizgit/Orchard,dozoft/Orchard,dcinzona/Orchard,hannan-azam/Orchard,hannan-azam/Orchard,rtpHarry/Orchard,jagraz/Orchard,Lombiq/Orchard,geertdoornbos/Orchard,tobydodds/folklife,AdvantageCS/Orchard,MetSystem/Orchard,harmony7/Orchard,TalaveraTechnologySolutions/Orchard,vard0/orchard.tan,omidnasri/Orchard,angelapper/Orchard,fassetar/Orchard,OrchardCMS/Orchard-Harvest-Website,jersiovic/Orchard,bigfont/orchard-cms-modules-and-themes,ehe888/Orchard,mgrowan/Orchard,kgacova/Orchard,KeithRaven/Orchard,Dolphinsimon/Orchard,dozoft/Orchard,SouleDesigns/SouleDesigns.Orchard,mvarblow/Orchard,TalaveraTechnologySolutions/Orchard,Morgma/valleyviewknolls,JRKelso/Orchard,phillipsj/Orchard,salarvand/Portal,brownjordaninternational/OrchardCMS,Codinlab/Orchard,m2cms/Orchard,smartnet-developers/Orchard,spraiin/Orchard,rtpHarry/Orchard,luchaoshuai/Orchard,emretiryaki/Orchard,SzymonSel/Orchard,marcoaoteixeira/Orchard,salarvand/orchard,MpDzik/Orchard,MetSystem/Orchard,AEdmunds/beautiful-springtime,ericschultz/outercurve-orchard,salarvand/Portal,dburriss/Orchard,harmony7/Orchard,OrchardCMS/Orchard,hbulzy/Orchard,OrchardCMS/Orchard,Codinlab/Orchard,luchaoshuai/Orchard,dozoft/Orchard,vairam-svs/Orchard,hbulzy/Orchard,sfmskywalker/Orchard,yersans/Orchard,JRKelso/Orchard,Fogolan/OrchardForWork,mvarblow/Orchard,AndreVolksdorf/Orchard,xkproject/Orchard,Ermesx/Orchard,phillipsj/Orchard,Dolphinsimon/Orchard,fassetar/Orchard,salarvand/orchard,alejandroaldana/Orchard,ehe888/Orchard,arminkarimi/Orchard,li0803/Orchard,armanforghani/Orchard,yersans/Orchard,Sylapse/Orchard.HttpAuthSample,luchaoshuai/Orchard,MpDzik/Orchard,stormleoxia/Orchard,yersans/Orchard,Fogolan/OrchardForWork,Inner89/Orchard,kgacova/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,Anton-Am/Orchard,jersiovic/Orchard,salarvand/Portal,fassetar/Orchard,arminkarimi/Orchard,bedegaming-aleksej/Orchard,qt1/Orchard,salarvand/orchard,jimasp/Orchard,sfmskywalker/Orchard,grapto/Orchard.CloudBust,oxwanawxo/Orchard,alejandroaldana/Orchard,escofieldnaxos/Orchard,m2cms/Orchard,andyshao/Orchard,AndreVolksdorf/Orchard,caoxk/orchard,planetClaire/Orchard-LETS,harmony7/Orchard,cryogen/orchard,salarvand/Portal,xkproject/Orchard,RoyalVeterinaryCollege/Orchard,yonglehou/Orchard,neTp9c/Orchard,oxwanawxo/Orchard,Praggie/Orchard,SeyDutch/Airbrush,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,infofromca/Orchard,mgrowan/Orchard,dozoft/Orchard,jtkech/Orchard,dcinzona/Orchard-Harvest-Website,hhland/Orchard,grapto/Orchard.CloudBust,escofieldnaxos/Orchard,dcinzona/Orchard,m2cms/Orchard,xkproject/Orchard,hbulzy/Orchard,Cphusion/Orchard,Dolphinsimon/Orchard,Serlead/Orchard,johnnyqian/Orchard,smartnet-developers/Orchard,gcsuk/Orchard,jimasp/Orchard,AndreVolksdorf/Orchard,alejandroaldana/Orchard,TalaveraTechnologySolutions/Orchard,jimasp/Orchard,brownjordaninternational/OrchardCMS,jchenga/Orchard,SeyDutch/Airbrush,salarvand/Portal,harmony7/Orchard,gcsuk/Orchard,phillipsj/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,LaserSrl/Orchard,cooclsee/Orchard,sfmskywalker/Orchard,cryogen/orchard,mvarblow/Orchard,mgrowan/Orchard,JRKelso/Orchard,IDeliverable/Orchard,abhishekluv/Orchard,TaiAivaras/Orchard,jchenga/Orchard,NIKASoftwareDevs/Orchard,salarvand/orchard,IDeliverable/Orchard,stormleoxia/Orchard,bigfont/orchard-continuous-integration-demo,Dolphinsimon/Orchard,MetSystem/Orchard,jaraco/orchard,bigfont/orchard-continuous-integration-demo,dcinzona/Orchard-Harvest-Website,NIKASoftwareDevs/Orchard,KeithRaven/Orchard,dozoft/Orchard,NIKASoftwareDevs/Orchard,bigfont/orchard-cms-modules-and-themes,aaronamm/Orchard,hannan-azam/Orchard,MpDzik/Orchard,bedegaming-aleksej/Orchard,smartnet-developers/Orchard,omidnasri/Orchard,austinsc/Orchard,andyshao/Orchard,arminkarimi/Orchard,hannan-azam/Orchard,angelapper/Orchard,armanforghani/Orchard,angelapper/Orchard,KeithRaven/Orchard,enspiral-dev-academy/Orchard,asabbott/chicagodevnet-website,neTp9c/Orchard,geertdoornbos/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,johnnyqian/Orchard,austinsc/Orchard,sebastienros/msc,TalaveraTechnologySolutions/Orchard,fortunearterial/Orchard,vard0/orchard.tan,patricmutwiri/Orchard,dburriss/Orchard,omidnasri/Orchard,RoyalVeterinaryCollege/Orchard,infofromca/Orchard,cryogen/orchard,OrchardCMS/Orchard,Ermesx/Orchard,TaiAivaras/Orchard,armanforghani/Orchard,Inner89/Orchard,SzymonSel/Orchard,Ermesx/Orchard,TaiAivaras/Orchard,fortunearterial/Orchard,tobydodds/folklife,bedegaming-aleksej/Orchard,smartnet-developers/Orchard,OrchardCMS/Orchard-Harvest-Website,ericschultz/outercurve-orchard,OrchardCMS/Orchard-Harvest-Website,RoyalVeterinaryCollege/Orchard,xiaobudian/Orchard,hannan-azam/Orchard,DonnotRain/Orchard,kouweizhong/Orchard,cooclsee/Orchard,qt1/orchard4ibn,vard0/orchard.tan,abhishekluv/Orchard,qt1/orchard4ibn,MpDzik/Orchard,caoxk/orchard,dcinzona/Orchard-Harvest-Website,patricmutwiri/Orchard,bigfont/orchard-cms-modules-and-themes,huoxudong125/Orchard,dburriss/Orchard,Morgma/valleyviewknolls,openbizgit/Orchard,xiaobudian/Orchard,andyshao/Orchard,jchenga/Orchard,cooclsee/Orchard,johnnyqian/Orchard,jtkech/Orchard,austinsc/Orchard,arminkarimi/Orchard,AndreVolksdorf/Orchard,qt1/Orchard,rtpHarry/Orchard,OrchardCMS/Orchard-Harvest-Website,grapto/Orchard.CloudBust,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,gcsuk/Orchard,planetClaire/Orchard-LETS,abhishekluv/Orchard,xiaobudian/Orchard,qt1/Orchard,aaronamm/Orchard,SouleDesigns/SouleDesigns.Orchard,kgacova/Orchard,ericschultz/outercurve-orchard,Sylapse/Orchard.HttpAuthSample,Serlead/Orchard,hhland/Orchard,m2cms/Orchard,Dolphinsimon/Orchard,Praggie/Orchard,omidnasri/Orchard,hbulzy/Orchard,tobydodds/folklife,planetClaire/Orchard-LETS,aaronamm/Orchard,geertdoornbos/Orchard,AEdmunds/beautiful-springtime,enspiral-dev-academy/Orchard,Inner89/Orchard,li0803/Orchard,Morgma/valleyviewknolls,Lombiq/Orchard,OrchardCMS/Orchard,jersiovic/Orchard,qt1/orchard4ibn,kgacova/Orchard,DonnotRain/Orchard,LaserSrl/Orchard,SzymonSel/Orchard,Codinlab/Orchard,Fogolan/OrchardForWork,neTp9c/Orchard,emretiryaki/Orchard,omidnasri/Orchard,OrchardCMS/Orchard-Harvest-Website,IDeliverable/Orchard,abhishekluv/Orchard,grapto/Orchard.CloudBust,johnnyqian/Orchard,AdvantageCS/Orchard,austinsc/Orchard,dcinzona/Orchard,stormleoxia/Orchard,MetSystem/Orchard,KeithRaven/Orchard,angelapper/Orchard,spraiin/Orchard,phillipsj/Orchard,abhishekluv/Orchard,cooclsee/Orchard,NIKASoftwareDevs/Orchard,bigfont/orchard-cms-modules-and-themes,tobydodds/folklife,RoyalVeterinaryCollege/Orchard,Serlead/Orchard,OrchardCMS/Orchard,hhland/Orchard,planetClaire/Orchard-LETS,asabbott/chicagodevnet-website,emretiryaki/Orchard,TaiAivaras/Orchard,kgacova/Orchard,TalaveraTechnologySolutions/Orchard,openbizgit/Orchard,SouleDesigns/SouleDesigns.Orchard,Cphusion/Orchard,jerryshi2007/Orchard,vairam-svs/Orchard,AEdmunds/beautiful-springtime,gcsuk/Orchard,oxwanawxo/Orchard,escofieldnaxos/Orchard,andyshao/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,enspiral-dev-academy/Orchard,andyshao/Orchard,Serlead/Orchard,li0803/Orchard,SeyDutch/Airbrush,TalaveraTechnologySolutions/Orchard,enspiral-dev-academy/Orchard,abhishekluv/Orchard,AndreVolksdorf/Orchard,marcoaoteixeira/Orchard,omidnasri/Orchard,fassetar/Orchard,jagraz/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,Morgma/valleyviewknolls,qt1/Orchard,hhland/Orchard,Cphusion/Orchard,Codinlab/Orchard,DonnotRain/Orchard,huoxudong125/Orchard,asabbott/chicagodevnet-website,AdvantageCS/Orchard,SzymonSel/Orchard,angelapper/Orchard,rtpHarry/Orchard,spraiin/Orchard,jersiovic/Orchard,infofromca/Orchard,johnnyqian/Orchard,austinsc/Orchard,TalaveraTechnologySolutions/Orchard,IDeliverable/Orchard,sfmskywalker/Orchard,omidnasri/Orchard,spraiin/Orchard,kouweizhong/Orchard,brownjordaninternational/OrchardCMS,fortunearterial/Orchard,RoyalVeterinaryCollege/Orchard,marcoaoteixeira/Orchard,jerryshi2007/Orchard,Anton-Am/Orchard,TalaveraTechnologySolutions/Orchard,xkproject/Orchard,jaraco/orchard,dmitry-urenev/extended-orchard-cms-v10.1,omidnasri/Orchard,m2cms/Orchard,vard0/orchard.tan,smartnet-developers/Orchard,cryogen/orchard,qt1/Orchard,qt1/orchard4ibn,jerryshi2007/Orchard,SeyDutch/Airbrush,fortunearterial/Orchard,AdvantageCS/Orchard,yersans/Orchard,arminkarimi/Orchard,infofromca/Orchard,spraiin/Orchard,kouweizhong/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,hbulzy/Orchard,dburriss/Orchard,caoxk/orchard,jerryshi2007/Orchard,Praggie/Orchard,SouleDesigns/SouleDesigns.Orchard,patricmutwiri/Orchard,KeithRaven/Orchard,marcoaoteixeira/Orchard,neTp9c/Orchard,sebastienros/msc,sfmskywalker/Orchard,MetSystem/Orchard,qt1/orchard4ibn,Anton-Am/Orchard,qt1/orchard4ibn,Codinlab/Orchard,vard0/orchard.tan,jerryshi2007/Orchard,luchaoshuai/Orchard,AEdmunds/beautiful-springtime,Sylapse/Orchard.HttpAuthSample,li0803/Orchard,fassetar/Orchard,SzymonSel/Orchard,dcinzona/Orchard-Harvest-Website,caoxk/orchard,Cphusion/Orchard,bigfont/orchard-cms-modules-and-themes,mvarblow/Orchard,oxwanawxo/Orchard,asabbott/chicagodevnet-website,grapto/Orchard.CloudBust,jimasp/Orchard,li0803/Orchard,rtpHarry/Orchard,cooclsee/Orchard,dcinzona/Orchard-Harvest-Website,luchaoshuai/Orchard,vard0/orchard.tan,planetClaire/Orchard-LETS,phillipsj/Orchard,bedegaming-aleksej/Orchard,sfmskywalker/Orchard,mvarblow/Orchard,fortunearterial/Orchard,neTp9c/Orchard,IDeliverable/Orchard,Morgma/valleyviewknolls,MpDzik/Orchard,jtkech/Orchard,xiaobudian/Orchard,Sylapse/Orchard.HttpAuthSample,jtkech/Orchard,ehe888/Orchard,Ermesx/Orchard,escofieldnaxos/Orchard,jagraz/Orchard,yonglehou/Orchard,marcoaoteixeira/Orchard,TaiAivaras/Orchard,stormleoxia/Orchard,DonnotRain/Orchard,armanforghani/Orchard,Serlead/Orchard,Ermesx/Orchard,yersans/Orchard,alejandroaldana/Orchard,xkproject/Orchard,kouweizhong/Orchard,Praggie/Orchard,bigfont/orchard-continuous-integration-demo,jersiovic/Orchard,SeyDutch/Airbrush,salarvand/orchard,JRKelso/Orchard,aaronamm/Orchard,omidnasri/Orchard,sebastienros/msc,jagraz/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,Lombiq/Orchard,armanforghani/Orchard,jaraco/orchard,yonglehou/Orchard,jimasp/Orchard,infofromca/Orchard,huoxudong125/Orchard,jchenga/Orchard,Lombiq/Orchard,jaraco/orchard,LaserSrl/Orchard,oxwanawxo/Orchard,yonglehou/Orchard,dcinzona/Orchard,brownjordaninternational/OrchardCMS,bedegaming-aleksej/Orchard,tobydodds/folklife,OrchardCMS/Orchard-Harvest-Website,sfmskywalker/Orchard,Sylapse/Orchard.HttpAuthSample,ehe888/Orchard,kouweizhong/Orchard,tobydodds/folklife,Praggie/Orchard,geertdoornbos/Orchard,AdvantageCS/Orchard,sebastienros/msc,brownjordaninternational/OrchardCMS
src/Orchard/ContentManagement/MetaData/Models/SettingsDictionary.cs
src/Orchard/ContentManagement/MetaData/Models/SettingsDictionary.cs
using System; using System.Collections.Generic; using System.Web.Mvc; namespace Orchard.ContentManagement.MetaData.Models { public class SettingsDictionary : Dictionary<string, string> { public SettingsDictionary() { } public SettingsDictionary(IDictionary<string, string> dictionary) : base(dictionary) { } private T TryGetModel<T>(string key) where T : class { var binder = new DefaultModelBinder(); var controllerContext = new ControllerContext(); var context = new ModelBindingContext { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T)), ModelName = key, ValueProvider = new DictionaryValueProvider<string>(this, null) }; return (T)binder.BindModel(controllerContext, context); } public T GetModel<T>() where T : class, new() { return GetModel<T>(typeof(T).Name); } public T GetModel<T>(string key) where T : class, new() { return TryGetModel<T>(key) ?? new T(); } public bool ContainsModel<T>() where T : class { return TryGetModel<T>(typeof(T).Name) != null; } public bool ContainsModel<T>(string key) where T : class { return TryGetModel<T>(key) != null; } } }
using System.Collections.Generic; using System.Web.Mvc; namespace Orchard.ContentManagement.MetaData.Models { public class SettingsDictionary : Dictionary<string, string> { public SettingsDictionary() { } public SettingsDictionary(IDictionary<string, string> dictionary) : base(dictionary) { } public T GetModel<T>() where T : class, new() { return GetModel<T>(typeof(T).Name); } public T GetModel<T>(string key) where T : class, new() { var binder = new DefaultModelBinder(); var controllerContext = new ControllerContext(); var context = new ModelBindingContext { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T)), ModelName = key, ValueProvider = new DictionaryValueProvider<string>(this, null) }; return (T)binder.BindModel(controllerContext, context) ?? new T(); } } }
bsd-3-clause
C#
abb399c4b695a6c7a2494eac6f8fd3e7c6e773a9
Fix bug by removing duplicate code
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts.Web/Extensions/HtmlHelperExtensions.cs
src/SFA.DAS.EmployerAccounts.Web/Extensions/HtmlHelperExtensions.cs
using SFA.DAS.Authorization; using System; using System.Linq; using System.Web.Mvc; namespace SFA.DAS.EmployerAccounts.Web.Extensions { public static class HtmlHelperExtensions { public static MvcHtmlString CommaSeperatedAddressToHtml(this HtmlHelper htmlHelper, string commaSeperatedAddress) { var htmlAddress = commaSeperatedAddress.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(line => $"{line.Trim()}<br/>") .Aggregate("", (x, y) => x + y); return new MvcHtmlString(htmlAddress); } public static AuthorizationResult GetAuthorizationResult(this HtmlHelper htmlHelper, FeatureType featureType) { var authorisationService = DependencyResolver.Current.GetService<IAuthorizationService>(); var authorizationResult = authorisationService.GetAuthorizationResult(featureType); return authorizationResult; } public static bool ViewExists(this HtmlHelper html, string viewName) { var controllerContext = html.ViewContext.Controller.ControllerContext; var result = ViewEngines.Engines.FindView(controllerContext, viewName, null); return result.View != null; } } }
using SFA.DAS.Authorization; using System; using System.Linq; using System.Linq.Expressions; using System.Web.Mvc; namespace SFA.DAS.EmployerAccounts.Web.Extensions { public static class HtmlHelperExtensions { public static MvcHtmlString CommaSeperatedAddressToHtml(this HtmlHelper htmlHelper, string commaSeperatedAddress) { var htmlAddress = commaSeperatedAddress.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(line => $"{line.Trim()}<br/>") .Aggregate("", (x, y) => x + y); return new MvcHtmlString(htmlAddress); } public static AuthorizationResult GetAuthorizationResult(this HtmlHelper htmlHelper, FeatureType featureType) { var authorisationService = DependencyResolver.Current.GetService<IAuthorizationService>(); var authorizationResult = authorisationService.GetAuthorizationResult(featureType); return authorizationResult; } public static bool IsValid<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) { var partialFieldName = ExpressionHelper.GetExpressionText(expression); var fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(partialFieldName); if (htmlHelper.ViewData.ModelState.ContainsKey(fullHtmlFieldName)) { var modelState = htmlHelper.ViewData.ModelState[fullHtmlFieldName]; var errors = modelState?.Errors; if (errors != null && errors.Any()) { return false; } } return true; } public static bool ViewExists(this HtmlHelper html, string viewName) { var controllerContext = html.ViewContext.Controller.ControllerContext; var result = ViewEngines.Engines.FindView(controllerContext, viewName, null); return result.View != null; } } }
mit
C#
e277df001d8984a46231cdc9086b598c2938764b
Remove blank line
tmat/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,aelij/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,diryboy/roslyn,eriawan/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,wvdd007/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,weltkante/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,aelij/roslyn,sharwell/roslyn,heejaechang/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,jmarolf/roslyn,heejaechang/roslyn,genlu/roslyn,wvdd007/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,tannergooding/roslyn,mavasani/roslyn,gafter/roslyn,physhi/roslyn,AlekseyTs/roslyn,KirillOsenkov/roslyn,davkean/roslyn,brettfo/roslyn,KirillOsenkov/roslyn,physhi/roslyn,physhi/roslyn,genlu/roslyn,davkean/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,davkean/roslyn,CyrusNajmabadi/roslyn,brettfo/roslyn,dotnet/roslyn,brettfo/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,eriawan/roslyn,KevinRansom/roslyn,aelij/roslyn,panopticoncentral/roslyn,genlu/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,tannergooding/roslyn,tannergooding/roslyn,dotnet/roslyn,heejaechang/roslyn,jmarolf/roslyn,weltkante/roslyn,gafter/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,gafter/roslyn,diryboy/roslyn,AmadeusW/roslyn,panopticoncentral/roslyn,diryboy/roslyn,eriawan/roslyn,tmat/roslyn
src/Features/Core/Portable/IncrementalCaches/MetadataInfo.cs
src/Features/Core/Portable/IncrementalCaches/MetadataInfo.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.Collections.Generic; using Microsoft.CodeAnalysis.FindSymbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.IncrementalCaches { internal partial class SymbolTreeInfoIncrementalAnalyzerProvider { private readonly struct MetadataInfo { /// <summary> /// Can't be null. Even if we weren't able to read in metadata, we'll still create an empty /// index. /// </summary> public readonly SymbolTreeInfo SymbolTreeInfo; /// <summary> /// The set of projects that are referencing this metadata-index. When this becomes empty we can dump the /// index from memory. /// <para/> /// Note: the Incremental-Analyzer infrastructure guarantees that it will call all the /// methods on <see cref="SymbolTreeInfoIncrementalAnalyzer"/> in a serial fashion. As that is the only /// type that reads/writes these <see cref="MetadataInfo"/> objects, we don't need to lock this. /// </summary> public readonly HashSet<ProjectId> ReferencingProjects; public MetadataInfo(SymbolTreeInfo info, HashSet<ProjectId> referencingProjects) { Contract.ThrowIfNull(info); SymbolTreeInfo = info; ReferencingProjects = referencingProjects; } } } }
// 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.Collections.Generic; using Microsoft.CodeAnalysis.FindSymbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.IncrementalCaches { internal partial class SymbolTreeInfoIncrementalAnalyzerProvider { private readonly struct MetadataInfo { /// <summary> /// Can't be null. Even if we weren't able to read in metadata, we'll still create an empty /// index. /// </summary> public readonly SymbolTreeInfo SymbolTreeInfo; /// <summary> /// The set of projects that are referencing this metadata-index. When this becomes empty we can dump the /// index from memory. /// <para/> /// Note: the Incremental-Analyzer infrastructure guarantees that it will call all the /// methods on <see cref="SymbolTreeInfoIncrementalAnalyzer"/> in a serial fashion. As that is the only /// type that reads/writes these <see cref="MetadataInfo"/> objects, we don't need to lock this. /// </summary> public readonly HashSet<ProjectId> ReferencingProjects; public MetadataInfo(SymbolTreeInfo info, HashSet<ProjectId> referencingProjects) { Contract.ThrowIfNull(info); SymbolTreeInfo = info; ReferencingProjects = referencingProjects; } } } }
mit
C#
a5a87fb3b65c378c4b20619d071780bdd215238c
Implement Reverse function for CreateConstraintExpression
barser/fluentmigrator,vgrigoriu/fluentmigrator,spaccabit/fluentmigrator,modulexcite/fluentmigrator,tohagan/fluentmigrator,stsrki/fluentmigrator,lahma/fluentmigrator,fluentmigrator/fluentmigrator,FabioNascimento/fluentmigrator,swalters/fluentmigrator,lcharlebois/fluentmigrator,drmohundro/fluentmigrator,daniellee/fluentmigrator,alphamc/fluentmigrator,spaccabit/fluentmigrator,tommarien/fluentmigrator,drmohundro/fluentmigrator,schambers/fluentmigrator,akema-fr/fluentmigrator,mstancombe/fluentmig,daniellee/fluentmigrator,lcharlebois/fluentmigrator,daniellee/fluentmigrator,eloekset/fluentmigrator,IRlyDontKnow/fluentmigrator,igitur/fluentmigrator,lahma/fluentmigrator,mstancombe/fluentmigrator,lahma/fluentmigrator,akema-fr/fluentmigrator,amroel/fluentmigrator,jogibear9988/fluentmigrator,alphamc/fluentmigrator,IRlyDontKnow/fluentmigrator,itn3000/fluentmigrator,KaraokeStu/fluentmigrator,fluentmigrator/fluentmigrator,itn3000/fluentmigrator,KaraokeStu/fluentmigrator,wolfascu/fluentmigrator,stsrki/fluentmigrator,tohagan/fluentmigrator,jogibear9988/fluentmigrator,dealproc/fluentmigrator,MetSystem/fluentmigrator,FabioNascimento/fluentmigrator,igitur/fluentmigrator,eloekset/fluentmigrator,swalters/fluentmigrator,tommarien/fluentmigrator,amroel/fluentmigrator,mstancombe/fluentmig,istaheev/fluentmigrator,schambers/fluentmigrator,barser/fluentmigrator,istaheev/fluentmigrator,mstancombe/fluentmig,bluefalcon/fluentmigrator,wolfascu/fluentmigrator,MetSystem/fluentmigrator,istaheev/fluentmigrator,bluefalcon/fluentmigrator,modulexcite/fluentmigrator,mstancombe/fluentmigrator,dealproc/fluentmigrator,tohagan/fluentmigrator,vgrigoriu/fluentmigrator
src/FluentMigrator/Expressions/CreateConstraintExpression.cs
src/FluentMigrator/Expressions/CreateConstraintExpression.cs
using System.Collections.Generic; using FluentMigrator.Model; namespace FluentMigrator.Expressions { public class CreateConstraintExpression : MigrationExpressionBase { public virtual ConstraintDefinition Constraint { get; set; } /// <summary> /// Initializes a new instance of the <see cref="T:CreateConstraintExpression"/> class. /// </summary> public CreateConstraintExpression(ConstraintType type) { Constraint = new ConstraintDefinition(type); } public override void ExecuteWith(IMigrationProcessor processor) { processor.Process(this); } public override void CollectValidationErrors(ICollection<string> errors) { Constraint.CollectValidationErrors(errors); } public override void ApplyConventions(IMigrationConventions conventions) { Constraint.ApplyConventions(conventions); } public override IMigrationExpression Reverse() { //constraint type is private in ConstraintDefinition return new DeleteConstraintExpression(Constraint.IsPrimaryKeyConstraint ? ConstraintType.PrimaryKey : ConstraintType.Unique) { Constraint = this.Constraint }; } public override string ToString() { return base.ToString() + Constraint.ConstraintName; } } }
using System.Collections.Generic; using FluentMigrator.Model; namespace FluentMigrator.Expressions { public class CreateConstraintExpression : MigrationExpressionBase { public virtual ConstraintDefinition Constraint { get; set; } /// <summary> /// Initializes a new instance of the <see cref="T:CreateConstraintExpression"/> class. /// </summary> public CreateConstraintExpression(ConstraintType type) { Constraint = new ConstraintDefinition(type); } public override void ExecuteWith(IMigrationProcessor processor) { processor.Process(this); } public override void CollectValidationErrors(ICollection<string> errors) { Constraint.CollectValidationErrors(errors); } public override void ApplyConventions(IMigrationConventions conventions) { Constraint.ApplyConventions(conventions); } public override string ToString() { return base.ToString() + Constraint.ConstraintName; } } }
apache-2.0
C#
7c01dac0545e6d682093ddd9587100832ad5cd30
Downgrade ClientVersion (#1782)
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Helpers/Constants.cs
WalletWasabi/Helpers/Constants.cs
using NBitcoin; using NBitcoin.Protocol; using System; using WalletWasabi.Backend.Models.Responses; namespace WalletWasabi.Helpers { public static class Constants { public static readonly Version ClientVersion = new Version(1, 1, 5); public const string BackendMajorVersion = "3"; public static readonly VersionsResponse VersionsResponse = new VersionsResponse { ClientVersion = ClientVersion.ToString(), BackendMajorVersion = BackendMajorVersion }; public const uint ProtocolVersion_WITNESS_VERSION = 70012; public const int MaxPasswordLength = 150; public static readonly NodeRequirement NodeRequirements = new NodeRequirement { RequiredServices = NodeServices.NODE_WITNESS, MinVersion = ProtocolVersion_WITNESS_VERSION, MinProtocolCapabilities = new ProtocolCapabilities { SupportGetBlock = true, SupportWitness = true, SupportMempoolQuery = true } }; public static readonly NodeRequirement LocalNodeRequirements = new NodeRequirement { RequiredServices = NodeServices.NODE_WITNESS, MinVersion = ProtocolVersion_WITNESS_VERSION, MinProtocolCapabilities = new ProtocolCapabilities { SupportGetBlock = true, SupportWitness = true } }; public static readonly NodeRequirement LocalBackendNodeRequirements = new NodeRequirement { RequiredServices = NodeServices.NODE_WITNESS, MinVersion = ProtocolVersion_WITNESS_VERSION, MinProtocolCapabilities = new ProtocolCapabilities { SupportGetBlock = true, SupportWitness = true, SupportMempoolQuery = true, SupportSendHeaders = true, SupportPingPong = true, PeerTooOld = true } }; public const int P2wpkhInputSizeInBytes = 41; public const int P2pkhInputSizeInBytes = 145; public const int OutputSizeInBytes = 33; // https://en.bitcoin.it/wiki/Bitcoin // There are a maximum of 2,099,999,997,690,000 Bitcoin elements (called satoshis), which are currently most commonly measured in units of 100,000,000 known as BTC. Stated another way, no more than 21 million BTC can ever be created. public const long MaximumNumberOfSatoshis = 2099999997690000; private static readonly BitcoinWitPubKeyAddress MainNetCoordinatorAddress = new BitcoinWitPubKeyAddress("bc1qs604c7jv6amk4cxqlnvuxv26hv3e48cds4m0ew", Network.Main); private static readonly BitcoinWitPubKeyAddress TestNetCoordinatorAddress = new BitcoinWitPubKeyAddress("tb1qecaheev3hjzs9a3w9x33wr8n0ptu7txp359exs", Network.TestNet); private static readonly BitcoinWitPubKeyAddress RegTestCoordinatorAddress = new BitcoinWitPubKeyAddress("bcrt1qangxrwyej05x9mnztkakk29s4yfdv4n586gs8l", Network.RegTest); public static BitcoinWitPubKeyAddress GetCoordinatorAddress(Network network) { Guard.NotNull(nameof(network), network); if (network == Network.Main) { return MainNetCoordinatorAddress; } if (network == Network.TestNet) { return TestNetCoordinatorAddress; } // else regtest return RegTestCoordinatorAddress; } public const string ChangeOfSpecialLabelStart = "change of ("; public const string ChangeOfSpecialLabelEnd = ")"; public const int BigFileReadWriteBufferSize = 1 * 1024 * 1024; public const int SevenDaysConfirmationTarget = 1008; } }
using NBitcoin; using NBitcoin.Protocol; using System; using WalletWasabi.Backend.Models.Responses; namespace WalletWasabi.Helpers { public static class Constants { public static readonly Version ClientVersion = new Version(1, 1, 6); public const string BackendMajorVersion = "3"; public static readonly VersionsResponse VersionsResponse = new VersionsResponse { ClientVersion = ClientVersion.ToString(), BackendMajorVersion = BackendMajorVersion }; public const uint ProtocolVersion_WITNESS_VERSION = 70012; public const int MaxPasswordLength = 150; public static readonly NodeRequirement NodeRequirements = new NodeRequirement { RequiredServices = NodeServices.NODE_WITNESS, MinVersion = ProtocolVersion_WITNESS_VERSION, MinProtocolCapabilities = new ProtocolCapabilities { SupportGetBlock = true, SupportWitness = true, SupportMempoolQuery = true } }; public static readonly NodeRequirement LocalNodeRequirements = new NodeRequirement { RequiredServices = NodeServices.NODE_WITNESS, MinVersion = ProtocolVersion_WITNESS_VERSION, MinProtocolCapabilities = new ProtocolCapabilities { SupportGetBlock = true, SupportWitness = true } }; public static readonly NodeRequirement LocalBackendNodeRequirements = new NodeRequirement { RequiredServices = NodeServices.NODE_WITNESS, MinVersion = ProtocolVersion_WITNESS_VERSION, MinProtocolCapabilities = new ProtocolCapabilities { SupportGetBlock = true, SupportWitness = true, SupportMempoolQuery = true, SupportSendHeaders = true, SupportPingPong = true, PeerTooOld = true } }; public const int P2wpkhInputSizeInBytes = 41; public const int P2pkhInputSizeInBytes = 145; public const int OutputSizeInBytes = 33; // https://en.bitcoin.it/wiki/Bitcoin // There are a maximum of 2,099,999,997,690,000 Bitcoin elements (called satoshis), which are currently most commonly measured in units of 100,000,000 known as BTC. Stated another way, no more than 21 million BTC can ever be created. public const long MaximumNumberOfSatoshis = 2099999997690000; private static readonly BitcoinWitPubKeyAddress MainNetCoordinatorAddress = new BitcoinWitPubKeyAddress("bc1qs604c7jv6amk4cxqlnvuxv26hv3e48cds4m0ew", Network.Main); private static readonly BitcoinWitPubKeyAddress TestNetCoordinatorAddress = new BitcoinWitPubKeyAddress("tb1qecaheev3hjzs9a3w9x33wr8n0ptu7txp359exs", Network.TestNet); private static readonly BitcoinWitPubKeyAddress RegTestCoordinatorAddress = new BitcoinWitPubKeyAddress("bcrt1qangxrwyej05x9mnztkakk29s4yfdv4n586gs8l", Network.RegTest); public static BitcoinWitPubKeyAddress GetCoordinatorAddress(Network network) { Guard.NotNull(nameof(network), network); if (network == Network.Main) { return MainNetCoordinatorAddress; } if (network == Network.TestNet) { return TestNetCoordinatorAddress; } // else regtest return RegTestCoordinatorAddress; } public const string ChangeOfSpecialLabelStart = "change of ("; public const string ChangeOfSpecialLabelEnd = ")"; public const int BigFileReadWriteBufferSize = 1 * 1024 * 1024; public const int SevenDaysConfirmationTarget = 1008; } }
mit
C#
b5ba577d049c392060c5b5588390d020d2d18904
update error info
chinaboard/WeeklyRobot
WeeklyRobot.Service/HttpHelper.cs
WeeklyRobot.Service/HttpHelper.cs
using System; using System.IO; using System.Net; using System.Text; namespace WeeklyRobot.Service { public static class HttpHelper { public static string Post(string url, PostBody postBody, int timeout = 5000) { try { Logger.Debug($"Post\t{url}"); var bytes = Encoding.UTF8.GetBytes(postBody.ToString()); var request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.Timeout = timeout; request.ContentLength = bytes.Length; request.ContentType = Config.TryGet(nameof(request.ContentType), "application /x-www-form-urlencoded; charset=UTF-8"); var magicCodeName = string.Empty; if (Config.TryGet("MagicCodeType", out magicCodeName)) { var magicCodeValue = Config.TryGet("MagicCodeValue", ""); var magicCodePath = Config.TryGet("MagicCodePath", "/"); var magicCodeDomain = Config.TryGet("MagicCodeDomain", ".baidu.com"); request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(new Cookie(magicCodeName, magicCodeValue, magicCodePath, magicCodeDomain)); } var proxyAddress = string.Empty; if (Config.TryGet("WebProxy", out proxyAddress)) { request.Proxy = new WebProxy(proxyAddress); } using (var reqstream = request.GetRequestStream()) { reqstream.Write(bytes, 0, bytes.Length); var response = (HttpWebResponse)request.GetResponse(); var stream = response.GetResponseStream(); var reader = new StreamReader(stream); return reader.ReadToEnd(); } } catch (Exception e) { Logger.Error(e.ToString()); return e.Message; } } } }
using System.IO; using System.Net; using System.Text; namespace WeeklyRobot.Service { public static class HttpHelper { public static string Post(string url, PostBody postBody, int timeout = 5000) { Logger.Debug($"Post\t{url}"); var bytes = Encoding.UTF8.GetBytes(postBody.ToString()); var request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.Timeout = timeout; request.ContentLength = bytes.Length; request.ContentType = Config.TryGet(nameof(request.ContentType), "application /x-www-form-urlencoded; charset=UTF-8"); var magicCodeName = string.Empty; if (Config.TryGet("MagicCodeType", out magicCodeName)) { var magicCodeValue = Config.TryGet("MagicCodeValue", ""); var magicCodePath = Config.TryGet("MagicCodePath", "/"); var magicCodeDomain = Config.TryGet("MagicCodeDomain", ".baidu.com"); request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(new Cookie(magicCodeName, magicCodeValue, magicCodePath, magicCodeDomain)); } var proxyAddress = string.Empty; if (Config.TryGet("WebProxy", out proxyAddress)) { request.Proxy = new WebProxy(proxyAddress); } using (var reqstream = request.GetRequestStream()) { reqstream.Write(bytes, 0, bytes.Length); var response = (HttpWebResponse)request.GetResponse(); var stream = response.GetResponseStream(); var reader = new StreamReader(stream); return reader.ReadToEnd(); } } } }
mit
C#
7debca0cfcec7fa397a18354421014aea0cea98c
Update PolyCubicBezierSegmentTests.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
tests/Core2D.UnitTests/Path/Segments/PolyCubicBezierSegmentTests.cs
tests/Core2D.UnitTests/Path/Segments/PolyCubicBezierSegmentTests.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Core2D.Path.Segments; using Core2D.Shapes; using System.Linq; using Xunit; namespace Core2D.UnitTests { public class PolyCubicBezierSegmentTests { [Fact] [Trait("Core2D.Path", "Segments")] public void Points_Not_Null() { var target = new PolyCubicBezierSegment(); Assert.False(target.Points.IsDefault); } [Fact] [Trait("Core2D.Path", "Segments")] public void GetPoints_Should_Return_All_Segment_Points() { var segment = new PolyCubicBezierSegment(); segment.Points = segment.Points.Add(new PointShape()); segment.Points = segment.Points.Add(new PointShape()); segment.Points = segment.Points.Add(new PointShape()); segment.Points = segment.Points.Add(new PointShape()); segment.Points = segment.Points.Add(new PointShape()); var target = segment.GetPoints(); var count = target.Count(); Assert.Equal(5, count); Assert.Equal(segment.Points, target); } [Fact] [Trait("Core2D.Path", "Segments")] public void ToString_Should_Return_Path_Markup() { var target = new PolyCubicBezierSegment(); target.Points = target.Points.Add(new PointShape()); target.Points = target.Points.Add(new PointShape()); target.Points = target.Points.Add(new PointShape()); target.Points = target.Points.Add(new PointShape()); target.Points = target.Points.Add(new PointShape()); var actual = target.ToString(); Assert.Equal("C0,0 0,0 0,0 0,0 0,0", actual); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Core2D.Path.Segments; using Core2D.Shapes; using System.Linq; using Xunit; namespace Core2D.UnitTests { public class PolyCubicBezierSegmentTests { [Fact] [Trait("Core2D.Path", "Segments")] public void Points_Not_Null() { var target = new PolyCubicBezierSegment(); Assert.False(target.Points.IsDefault); } [Fact] [Trait("Core2D.Path", "Segments")] public void GetPoints_Should_Return_All_Segment_Points() { var segment = new PolyCubicBezierSegment(); segment.Points = segment.Points.Add(new PointShape()); segment.Points = segment.Points.Add(new PointShape()); segment.Points = segment.Points.Add(new PointShape()); segment.Points = segment.Points.Add(new PointShape()); segment.Points = segment.Points.Add(new PointShape()); var target = segment.GetPoints(); Assert.Equal(5, target.Count()); Assert.Equal(segment.Points, target); } [Fact] [Trait("Core2D.Path", "Segments")] public void ToString_Should_Return_Path_Markup() { var target = new PolyCubicBezierSegment(); target.Points = target.Points.Add(new PointShape()); target.Points = target.Points.Add(new PointShape()); target.Points = target.Points.Add(new PointShape()); target.Points = target.Points.Add(new PointShape()); target.Points = target.Points.Add(new PointShape()); var actual = target.ToString(); Assert.Equal("C0,0 0,0 0,0 0,0 0,0", actual); } } }
mit
C#
324cc93945992dabdd7a1937fe749778ef020373
Add check of email claim existence.
enarod/enarod-web-api,enarod/enarod-web-api,enarod/enarod-web-api
Infopulse.EDemocracy.Web/Controllers/API/BaseApiController.cs
Infopulse.EDemocracy.Web/Controllers/API/BaseApiController.cs
using Infopulse.EDemocracy.Data.Interfaces; using Infopulse.EDemocracy.Data.Repositories; using System.Linq; using System.Net.Http; using System.Security.Authentication; using System.Security.Claims; using System.ServiceModel.Channels; using System.Web; using System.Web.Http; namespace Infopulse.EDemocracy.Web.Controllers.API { /// <summary> /// The base class for api controllers /// </summary> public abstract class BaseApiController : ApiController { protected IUserDetailRepository userDetailRepository; protected BaseApiController() { this.userDetailRepository = new UserDetailRepository(); } /// <summary> /// Gets UserEmail of signed in user. /// </summary> /// <returns>Signed in user's email.</returns> protected string GetSignedInUserEmail() { var identity = User.Identity as ClaimsIdentity; if (identity != null) { var emailClaim = identity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Email); if (emailClaim == null) { throw new AuthenticationException("Email claim not found"); } var email = emailClaim.Value; return email; } return null; } /// <summary> /// Gets ID of signed in user. /// </summary> /// <returns>User ID.</returns> protected int GetSignedInUserId() { var userEmail = GetSignedInUserEmail(); var userId = userDetailRepository.GetUserId(userEmail); return userId; } protected string GetClientIP(HttpRequestMessage request = null) { request = request ?? Request; var ip = Request.GetOwinContext().Request.RemoteIpAddress; // WebAPI 2.2 feature if (!string.IsNullOrWhiteSpace(ip)) return ip; if (request.Properties.ContainsKey("MS_HttpContext")) { return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress; } else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name)) { RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name]; return prop.Address; } else if (HttpContext.Current != null) { return HttpContext.Current.Request.UserHostAddress; } else { return null; } } } }
using Infopulse.EDemocracy.Data.Interfaces; using Infopulse.EDemocracy.Data.Repositories; using System.Linq; using System.Net.Http; using System.Security.Claims; using System.ServiceModel.Channels; using System.Web; using System.Web.Http; namespace Infopulse.EDemocracy.Web.Controllers.API { /// <summary> /// The base class for api controllers /// </summary> public abstract class BaseApiController : ApiController { protected IUserDetailRepository userDetailRepository; protected BaseApiController() { this.userDetailRepository = new UserDetailRepository(); } /// <summary> /// Gets UserEmail of signed in user. /// </summary> /// <returns>Signed in user's email.</returns> protected string GetSignedInUserEmail() { var identity = User.Identity as ClaimsIdentity; if (identity != null) { var emailClaim = identity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Email); var email = emailClaim.Value; return email; } return null; } /// <summary> /// Gets ID of signed in user. /// </summary> /// <returns>User ID.</returns> protected int GetSignedInUserId() { var userEmail = GetSignedInUserEmail(); var userId = userDetailRepository.GetUserId(userEmail); return userId; } protected string GetClientIP(HttpRequestMessage request = null) { request = request ?? Request; var ip = Request.GetOwinContext().Request.RemoteIpAddress; // WebAPI 2.2 feature if (!string.IsNullOrWhiteSpace(ip)) return ip; if (request.Properties.ContainsKey("MS_HttpContext")) { return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress; } else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name)) { RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name]; return prop.Address; } else if (HttpContext.Current != null) { return HttpContext.Current.Request.UserHostAddress; } else { return null; } } } }
cc0-1.0
C#
f24bb44954d333ed7dd95caa0e5a8a890e4c0d12
Change Tests for Util.DecodeWord Use DecodeWords instead to test more variants Swap from {Expected, Encoded} to {Encoded, Expected} (Different encoded variants can give the same result) Add data for split variants, and also variants that have non encoded data mixed in.
pocky6/S22.Imap,smiley22/S22.Imap,SyncCloud/S22.Imap,d-knauer/S22.Imap
Tests/EncodedWordTest.cs
Tests/EncodedWordTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace S22.Imap.Test { /// <summary> /// Contains unit tests for decoding MIME "encoded-words". /// </summary> [TestClass] public class EncodedWordTest { /// <summary> /// Tests for decoding Q-encoded "encoded-words" strings. /// </summary> [TestMethod] public void DecodeQEncodedWords() { Dictionary<string, string> dict = new Dictionary<string, string>() { { "", "" }, { "Hello World", "Hello World" }, { "=?ISO-8859-1?Q?Feil_p=E5_PowerShot_A70?=", "Feil på PowerShot A70" }, { "=?utf-8?Q?=E5=84=AA:_2013__NEW_PROUDCTS__RD_LED_T?=\r\n" + "\t=?utf-8?Q?V=2C_TABLET_PC_=2C_PORTABLE?=\r\n", "優: 2013 NEW PROUDCTS RD LED TV, TABLET PC , PORTABLE" }, { "Information =?ISO-8859-1?Q?f=F6r?= dig", "Information för dig" }, { "faktura =?ISO-8859-1?Q?F14072-=F6stersund=2Epdf?=", "faktura F14072-östersund.pdf" }, }; foreach (KeyValuePair<string, string> pair in dict) Assert.AreEqual<string>(pair.Value, Util.DecodeWords(pair.Key)); } /// <summary> /// Tests for decoding Base64 "encoded-words" strings. /// </summary> [TestMethod] public void DecodeBase64EncodedWords() { Dictionary<string, string> dict = new Dictionary<string, string>() { { "", "" }, { "=?UTF-8?B?6YeN6KaB6YO15Lu2?=", "重要郵件" }, { "=?shift-jis?B?kZeQTY3Pgt2DgYFbg4s=?=", "送信済みメール" }, { "=?euc-kr?B?xde9usauILv5x8PA1LTPtNku?=", "테스트 샘플입니다." }, { "=?gb2312?B?Y21uZHkua2FuZyi/uvb09s4p?=", "cmndy.kang(亢鲷鑫)" }, { "=?utf-8?B?QmV0YWxuaW5nc2F2aSBhdnNlZW5kZSAuc2UtZG9tw6RubmFt?=\r\n" + "\t=?utf-8?B?bg==?=", "Betalningsavi avseende .se-domännamn" }, }; foreach (KeyValuePair<string, string> pair in dict) Assert.AreEqual<string>(pair.Value, Util.DecodeWords(pair.Key)); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace S22.Imap.Test { /// <summary> /// Contains unit tests for decoding MIME "encoded-words". /// </summary> [TestClass] public class EncodedWordTest { /// <summary> /// Tests for decoding Q-encoded "encoded-word" strings. /// </summary> [TestMethod] public void DecodeQEncodedWord() { Dictionary<string, string> dict = new Dictionary<string, string>() { { "", "" }, { "Hello World", "Hello World" }, { "Feil på PowerShot A70", "=?ISO-8859-1?Q?Feil_p=E5_PowerShot_A70?=" }, }; foreach (KeyValuePair<string, string> pair in dict) Assert.AreEqual<string>(pair.Key, Util.DecodeWord(pair.Value)); } /// <summary> /// Tests for decoding Base64 "encoded-word" strings. /// </summary> [TestMethod] public void DecodeBase64EncodedWord() { Dictionary<string, string> dict = new Dictionary<string, string>() { { "", "" }, { "重要郵件", "=?UTF-8?B?6YeN6KaB6YO15Lu2?=" }, { "送信済みメール", "=?shift-jis?B?kZeQTY3Pgt2DgYFbg4s=?=" }, { "테스트 샘플입니다.", "=?euc-kr?B?xde9usauILv5x8PA1LTPtNku?="} }; foreach (KeyValuePair<string, string> pair in dict) Assert.AreEqual<string>(pair.Key, Util.DecodeWord(pair.Value)); } } }
mit
C#
e14d0509a54675056ac87cdf12050d5da974d33f
tidy master page
codingoutloud/matechtax,codingoutloud/matechtax
MATechTaxWebSite/MATechTaxWebSite/Views/Shared/_Layout.cshtml
MATechTaxWebSite/MATechTaxWebSite/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>@ViewBag.Title - My ASP.NET MVC Application</title> <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width" /> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <header> <div class="content-wrapper"> <div class="float-left"> <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p> </div> <div class="float-right"> <section id="login"> @Html.Partial("_LoginPartial") </section> </div> </div> </header> <div id="body"> @RenderSection("featured", required: false) <section class="content-wrapper main-content clear-fix"> @RenderBody() </section> </div> <footer> <div class="content-wrapper"> <div class="float-left"> <p>&copy; @DateTime.Now.Year - My ASP.NET MVC Application</p> <p><small>Page generated @DateTime.Now.ToLongTimeString() (Local Time)</small></p> </div> </div> </footer> @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>@ViewBag.Title - My ASP.NET MVC Application</title> <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width" /> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <header> <div class="content-wrapper"> <div class="float-left"> <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p> </div> <div class="float-right"> <section id="login"> @Html.Partial("_LoginPartial") </section> <nav> <ul id="menu"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul> </nav> </div> </div> </header> <div id="body"> @RenderSection("featured", required: false) <section class="content-wrapper main-content clear-fix"> @RenderBody() </section> </div> <footer> <div class="content-wrapper"> <div class="float-left"> <p>&copy; @DateTime.Now.Year - My ASP.NET MVC Application</p> </div> </div> </footer> @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) </body> </html>
mit
C#
d427d48b0d2911233228aac182ad4f8e412b5ca7
Fix name violation
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Statement.cs
WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Statement.cs
using NBitcoin.Secp256k1; using System; using System.Collections.Generic; using System.Linq; using WalletWasabi.Helpers; namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation { public class Statement { public Statement(params Equation[] equations) : this(equations as IEnumerable<Equation>) { } public Statement(IEnumerable<Equation> equations) { // The equation matrix should not be jagged Guard.NotNullOrEmpty(nameof(equations), equations); var n = equations.First().Generators.Count(); Guard.True(nameof(equations), equations.All(e => e.Generators.Count() == n)); foreach (var generator in equations.SelectMany(equation => equation.Generators)) { Guard.NotNull(nameof(generator), generator); } Equations = equations; } public IEnumerable<Equation> Equations { get; } public bool CheckVerificationEquation(GroupElementVector publicNonces, Scalar challenge, IEnumerable<ScalarVector> allResponses) { // The responses matrix should match the generators in the equations and // there should be once nonce per equation. Guard.True(nameof(publicNonces), Equations.Count() == publicNonces.Count()); Equations.CheckDimesions(allResponses); return Equations.Zip(publicNonces, allResponses, (equation, r, s) => equation.Verify(r, challenge, s)).All(x => x); } public GroupElementVector SimulatePublicNonces(Scalar challenge, IEnumerable<ScalarVector> allGivenResponses) { // The responses matrix should match the generators in the equations and Equations.CheckDimesions(allGivenResponses); return new GroupElementVector(Enumerable.Zip(Equations, allGivenResponses, (e, r) => e.Simulate(challenge, r))); } } }
using NBitcoin.Secp256k1; using System; using System.Collections.Generic; using System.Linq; using WalletWasabi.Helpers; namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation { public class Statement { public Statement(params Equation[] equations) : this(equations as IEnumerable<Equation>) { } public Statement(IEnumerable<Equation> equations) { // The equation matrix should not be jagged Guard.NotNullOrEmpty(nameof(equations), equations); var n = equations.First().Generators.Count(); Guard.True(nameof(equations), equations.All(e => e.Generators.Count() == n)); foreach (var generator in equations.SelectMany(equation => equation.Generators)) { Guard.NotNull(nameof(generator), generator); } Equations = equations; } public IEnumerable<Equation> Equations { get; } public bool CheckVerificationEquation(GroupElementVector publicNonces, Scalar challenge, IEnumerable<ScalarVector> allResponses) { // The responses matrix should match the generators in the equations and // there should be once nonce per equation. Guard.True(nameof(publicNonces), Equations.Count() == publicNonces.Count()); Equations.CheckDimesions(allResponses); return Equations.Zip(publicNonces, allResponses, (equation, R, s) => equation.Verify(R, challenge, s)).All(x => x); } public GroupElementVector SimulatePublicNonces(Scalar challenge, IEnumerable<ScalarVector> allGivenResponses) { // The responses matrix should match the generators in the equations and Equations.CheckDimesions(allGivenResponses); return new GroupElementVector(Enumerable.Zip(Equations, allGivenResponses, (e, r) => e.Simulate(challenge, r))); } } }
mit
C#
70fe6be8152be381e35beade62aa6dc9311ba4f2
Comment change
bogosoft/Data
Bogosoft.Data/ParameterDirection.cs
Bogosoft.Data/ParameterDirection.cs
namespace Bogosoft.Data { /// <summary> /// Indicates the direction of data flow between this parameter and a data source. These values are /// a direct mapping to those in <see cref="System.Data.ParameterDirection"/>. /// </summary> public enum ParameterDirection { /// <summary> /// The associated parameter passes data to a data source. /// </summary> Input = 1, /// <summary> /// The associated parameter passes data back from a data source. /// </summary> Output = 2, /// <summary> /// The associated parameter passes data to and from a data source. /// </summary> InputOutput = 3, /// <summary> /// The associated parameter passes back the result of a stored procedure /// or function executed against a data source. /// </summary> ReturnValue = 6 } }
namespace Bogosoft.Data { /// <summary> /// Indicates that direction of data flow between this parameter and a data source. These values are /// a direct mapping to those in <see cref="System.Data.ParameterDirection"/>. /// </summary> public enum ParameterDirection { /// <summary> /// The associated parameter passes data to a data source. /// </summary> Input = 1, /// <summary> /// The associated parameter passes data back from a data source. /// </summary> Output = 2, /// <summary> /// The associated parameter passes data to and from a data source. /// </summary> InputOutput = 3, /// <summary> /// The associated parameter passes back the result of a stored procedure /// or function executed against a data source. /// </summary> ReturnValue = 6 } }
mit
C#
a01200a5861fb269ddf3748680e9104823e3761f
Add missing comments
noliar/MoreAuthentication
src/DevZH.AspNet.Authentication.NetEase/NetEaseHelper.cs
src/DevZH.AspNet.Authentication.NetEase/NetEaseHelper.cs
using Microsoft.Framework.Internal; using Newtonsoft.Json.Linq; namespace DevZH.AspNet.Authentication.NetEase { /// <summary> /// Contains static methods that allow to extract user's information from a <see cref="JObject"/> /// instance retrieved from NetEase after a successful authentication process. /// </summary> internal static class NetEaseHelper { /// <summary> /// 获取用户 ID /// </summary> internal static string GetId([NotNull] JObject user) => user.Value<string>("userId"); /// <summary> /// 获取用户 名称 /// </summary> internal static string GetName([NotNull] JObject user) => user.Value<string>("username"); } }
using Microsoft.Framework.Internal; using Newtonsoft.Json.Linq; namespace DevZH.AspNet.Authentication.NetEase { internal static class NetEaseHelper { internal static string GetId([NotNull] JObject user) => user.Value<string>("userId"); internal static string GetName([NotNull] JObject user) => user.Value<string>("username"); } }
apache-2.0
C#
e3153ead0db771080a7b6db96b49b558b1ced33f
Add code documentation for SetStatistics processor
sergeyshushlyapin/Sitecore.FakeDb
src/Sitecore.FakeDb/Pipelines/AddDbItem/SetStatistics.cs
src/Sitecore.FakeDb/Pipelines/AddDbItem/SetStatistics.cs
namespace Sitecore.FakeDb.Pipelines.AddDbItem { using System.Linq; using Sitecore.Data; /// <summary> /// Creates and fulfills item statistics fields for all the item languages. /// The fields included are 'Created', 'CreatedBy', 'Revision', 'Updated' /// and 'UpdatedBy'. /// <para> /// The 'Created' and 'Updated' fields are set to the current date in ISO /// format. The 'CreatedBy' and 'UpdatedBy' fields store the current user /// name. The 'Revision' field is a <see cref="System.Guid"/> generated for /// each of the item languages. /// </para> /// </summary> public class SetStatistics { public virtual void Process(AddDbItemArgs args) { var item = args.DbItem; var date = DateUtil.IsoNow; var user = Context.User.Name; AddStatisticsFields(item, date, user); SetStatisticsForAllLanguages(item, date, user); } private static void AddStatisticsFields(DbItem item, string date, string user) { item.Fields.Add(new DbField("__Created", FieldIDs.Created) { Value = date }); item.Fields.Add(new DbField("__Created by", FieldIDs.CreatedBy) { Value = user }); item.Fields.Add(new DbField("__Revision", FieldIDs.Revision) { Value = ID.NewID.ToString() }); item.Fields.Add(new DbField("__Updated", FieldIDs.Updated) { Value = date }); item.Fields.Add(new DbField("__Updated by", FieldIDs.UpdatedBy) { Value = user }); } private static void SetStatisticsForAllLanguages(DbItem item, string date, string user) { foreach (var lang in item.Fields .SelectMany(field => field.Values) .Select(l => l.Key)) { SetFieldValue(item.Fields[FieldIDs.Created], lang, date); SetFieldValue(item.Fields[FieldIDs.CreatedBy], lang, user); SetFieldValue(item.Fields[FieldIDs.Revision], lang, ID.NewID.ToString()); SetFieldValue(item.Fields[FieldIDs.Updated], lang, date); SetFieldValue(item.Fields[FieldIDs.UpdatedBy], lang, user); } } private static void SetFieldValue(DbField field, string lang, string value) { var valueSet = !string.IsNullOrEmpty( field.GetValue(lang, Version.Latest.Number)); if (!valueSet) { field.SetValue(lang, value); } } } }
namespace Sitecore.FakeDb.Pipelines.AddDbItem { using System.Linq; using Sitecore.Data; public class SetStatistics { public virtual void Process(AddDbItemArgs args) { var item = args.DbItem; var date = DateUtil.IsoNow; var user = Context.User.Name; AddStatisticsFields(item, date, user); SetStatisticsForAllLanguages(item, date, user); } private static void AddStatisticsFields(DbItem item, string date, string user) { item.Fields.Add(new DbField("__Created", FieldIDs.Created) { Value = date }); item.Fields.Add(new DbField("__Created by", FieldIDs.CreatedBy) { Value = user }); item.Fields.Add(new DbField("__Revision", FieldIDs.Revision) { Value = ID.NewID.ToString() }); item.Fields.Add(new DbField("__Updated", FieldIDs.Updated) { Value = date }); item.Fields.Add(new DbField("__Updated by", FieldIDs.UpdatedBy) { Value = user }); } private static void SetStatisticsForAllLanguages(DbItem item, string date, string user) { foreach (var lang in item.Fields .SelectMany(field => field.Values) .Select(l => l.Key)) { SetFieldValue(item.Fields[FieldIDs.Created], lang, date); SetFieldValue(item.Fields[FieldIDs.CreatedBy], lang, user); SetFieldValue(item.Fields[FieldIDs.Revision], lang, ID.NewID.ToString()); SetFieldValue(item.Fields[FieldIDs.Updated], lang, date); SetFieldValue(item.Fields[FieldIDs.UpdatedBy], lang, user); } } private static void SetFieldValue(DbField field, string lang, string value) { var valueSet = !string.IsNullOrEmpty( field.GetValue(lang, Version.Latest.Number)); if (!valueSet) { field.SetValue(lang, value); } } } }
mit
C#
c9ab30e1508b904f4c25a4c7ec4b9cc30951cbff
Enable detailed errors for redis tests (#1962)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/Microsoft.AspNetCore.SignalR.Redis.Tests/Startup.cs
test/Microsoft.AspNetCore.SignalR.Redis.Tests/Startup.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.SignalR.Redis.Tests { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSignalR(options => { options.EnableDetailedErrors = true; }) .AddMessagePackProtocol() .AddRedis(options => { // We start the servers before starting redis so we want to time them out ASAP options.Options.ConnectTimeout = 1; }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseSignalR(options => options.MapHub<EchoHub>("/echo")); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.SignalR.Redis.Tests { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSignalR() .AddMessagePackProtocol() .AddRedis(options => { // We start the servers before starting redis so we want to time them out ASAP options.Options.ConnectTimeout = 1; }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseSignalR(options => options.MapHub<EchoHub>("/echo")); } } }
apache-2.0
C#
e6b67199a9755f1369dbe8c7e99391a1ad7128e1
Fix another ReSharper issue.
ExRam/ExRam.Gremlinq
ExRam.Gremlinq/Gremlin/Steps/DerivedLabelNamesGremlinStep.cs
ExRam.Gremlinq/Gremlin/Steps/DerivedLabelNamesGremlinStep.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace ExRam.Gremlinq { public abstract class DerivedLabelNamesGremlinStep : NonTerminalGremlinStep { protected static readonly ConcurrentDictionary<(IGraphModel model, Type type), ImmutableList<object>> TypeLabelDict = new ConcurrentDictionary<(IGraphModel, Type), ImmutableList<object>>(); } public sealed class DerivedLabelNamesGremlinStep<T> : DerivedLabelNamesGremlinStep { private readonly string _stepName; public DerivedLabelNamesGremlinStep(string stepName) { this._stepName = stepName; } public override IEnumerable<TerminalGremlinStep> Resolve(IGraphModel model) { yield return new TerminalGremlinStep(this._stepName, GetDerivedLabelNames(model)); } private static ImmutableList<object> GetDerivedLabelNames(IGraphModel model) { return TypeLabelDict .GetOrAdd( (model, typeof(T)), tuple => tuple.model.GetDerivedTypes(typeof(T), true) .Select(type => tuple.model.TryGetLabelOfType(type) .IfNone(() => throw new InvalidOperationException())) .OrderBy(x => x) .ToImmutableList<object>()); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace ExRam.Gremlinq { public sealed class DerivedLabelNamesGremlinStep<T> : NonTerminalGremlinStep { private readonly string _stepName; private static readonly ConcurrentDictionary<(IGraphModel model, Type type), ImmutableList<object>> TypeLabelDict = new ConcurrentDictionary<(IGraphModel, Type), ImmutableList<object>>(); public DerivedLabelNamesGremlinStep(string stepName) { this._stepName = stepName; } public override IEnumerable<TerminalGremlinStep> Resolve(IGraphModel model) { yield return new TerminalGremlinStep(this._stepName, GetDerivedLabelNames(model)); } private static ImmutableList<object> GetDerivedLabelNames(IGraphModel model) { return TypeLabelDict .GetOrAdd( (model, typeof(T)), tuple => tuple.model.GetDerivedTypes(typeof(T), true) .Select(type => tuple.model.TryGetLabelOfType(type) .IfNone(() => throw new InvalidOperationException())) .OrderBy(x => x) .ToImmutableList<object>()); } } }
mit
C#
f2811aac860a96966ea50c3697cfc11dd0fd844d
Update EntityQueryRepository.cs
tiksn/TIKSN-Framework
TIKSN.Core/Data/EntityFrameworkCore/EntityQueryRepository.cs
TIKSN.Core/Data/EntityFrameworkCore/EntityQueryRepository.cs
using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace TIKSN.Data.EntityFrameworkCore { public class EntityQueryRepository<TContext, TEntity, TIdentity> : EntityRepository<TContext, TEntity>, IQueryRepository<TEntity, TIdentity> where TContext : DbContext where TEntity : class, IEntity<TIdentity>, new() where TIdentity : IEquatable<TIdentity> { public EntityQueryRepository(TContext dbContext) : base(dbContext) { } protected IQueryable<TEntity> Entities => dbContext.Set<TEntity>().AsNoTracking(); public Task<bool> ExistsAsync(TIdentity id, CancellationToken cancellationToken) { return Entities.AnyAsync(a => a.ID.Equals(id), cancellationToken); } public Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken) { return Entities.SingleAsync(entity => entity.ID.Equals(id), cancellationToken); } public Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken) { return Entities.SingleOrDefaultAsync(entity => entity.ID.Equals(id), cancellationToken); } } }
using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace TIKSN.Data.EntityFrameworkCore { public class EntityQueryRepository<TContext, TEntity, TIdentity> : EntityRepository<TContext, TEntity>, IQueryRepository<TEntity, TIdentity> where TContext : DbContext where TEntity : class, IEntity<TIdentity>, new() where TIdentity : IEquatable<TIdentity> { public EntityQueryRepository(TContext dbContext) : base(dbContext) { } protected IQueryable<TEntity> Entities => dbContext.Set<TEntity>().AsNoTracking(); public Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken) { return Entities.SingleAsync(entity => entity.ID.Equals(id), cancellationToken); } public Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken) { return Entities.SingleOrDefaultAsync(entity => entity.ID.Equals(id), cancellationToken); } } }
mit
C#
7271b8d27dc4996eba6fe7e34d4273323e878d4a
make appveyor build another bunch of packages
vostok/core
Vostok.Core.Tests/Airlock/GenericSerializeDeserializeTest.cs
Vostok.Core.Tests/Airlock/GenericSerializeDeserializeTest.cs
using System; using System.IO; using FluentAssertions; using Vostok.Commons.Binary; namespace Vostok.Airlock { internal static class GenericSerializeDeserializeTest { private class TestAirlockSource : IAirlockSource { public Stream ReadStream => throw new NotImplementedException(); public IBinaryReader Reader { get; set; } } private class TestAirlockSink : IAirlockSink { public Stream WriteStream => throw new NotImplementedException(); public IBinaryWriter Writer { get; set; } } public static void RunTest<T,TSerializer>(T obj) where TSerializer : IAirlockSerializer<T>, IAirlockDeserializer<T>, new() { var serializer = new TSerializer(); var bufferWriter = new BinaryBufferWriter(10000); var airlockSink = new TestAirlockSink { Writer = bufferWriter }; serializer.Serialize(obj, airlockSink); var airlockSource = new TestAirlockSource { Reader = new BinaryBufferReader(bufferWriter.Buffer, 0) }; var deserialized = serializer.Deserialize(airlockSource); deserialized.ShouldBeEquivalentTo(obj); } } }
using System; using System.IO; using FluentAssertions; using Vostok.Commons.Binary; namespace Vostok.Airlock { internal static class GenericSerializeDeserializeTest { private class TestAirlockSource : IAirlockSource { public Stream ReadStream => throw new NotImplementedException(); public IBinaryReader Reader { get; set; } } private class TestAirlockSink : IAirlockSink { public Stream WriteStream => throw new NotImplementedException(); public IBinaryWriter Writer { get; set; } } public static void RunTest<T,TSerializer>(T obj) where TSerializer : IAirlockSerializer<T>, IAirlockDeserializer<T>, new() { var serializer = new TSerializer(); var bufferWriter = new BinaryBufferWriter(10000); var airlockSink = new TestAirlockSink { Writer = bufferWriter }; serializer.Serialize(obj, airlockSink); var airlockSource = new TestAirlockSource { Reader = new BinaryBufferReader(bufferWriter.Buffer, 0) }; var obj2 = serializer.Deserialize(airlockSource); obj2.ShouldBeEquivalentTo(obj); } } }
mit
C#
3e6d842f596e6d417af2802bf72caa439f279f4d
Fix DeepEquals in EnumerableExtensions
OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core
Core/OfficeDevPnP.Core/Extensions/EnumerableExtensions.cs
Core/OfficeDevPnP.Core/Extensions/EnumerableExtensions.cs
using System; using System.Collections.Generic; using System.Linq; namespace OfficeDevPnP.Core.Extensions { /// <summary> /// Extension methods to make working with IEnumerable&lt;T&gt; values easier. /// </summary> public static class EnumerableExtensions { /// <summary> /// Compares to instances of IEnumerable&lt;T&gt; /// </summary> /// <typeparam name="T">The type of the enumerated item</typeparam> /// <param name="source">Source enumeration</param> /// <param name="target">Target enumeration</param> /// <returns>Wether the two enumerations are deep equal</returns> public static Boolean DeepEquals<T>(this IEnumerable<T> source, IEnumerable<T> target) { return ((source.Except(target).Count() == 0) && (target.Except(source).Count() == 0)); } } }
using System; using System.Collections.Generic; using System.Linq; namespace OfficeDevPnP.Core.Extensions { /// <summary> /// Extension methods to make working with IEnumerable&lt;T&gt; values easier. /// </summary> public static class EnumerableExtensions { /// <summary> /// Compares to instances of IEnumerable&lt;T&gt; /// </summary> /// <typeparam name="T">The type of the enumerated item</typeparam> /// <param name="source">Source enumeration</param> /// <param name="target">Target enumeration</param> /// <returns>Wether the two enumerations are deep equal</returns> public static Boolean DeepEquals<T>(this IEnumerable<T> source, IEnumerable<T> target) { return (source.Except(target).Count() == 0); } } }
mit
C#
13372aa27db563872fa053c252ca773e83ec32ee
Add support for duplicate ids.
mntone/SvgForXaml
Mntone.SvgForXaml/Mntone.SvgForXaml.Shared/SvgDocument.cs
Mntone.SvgForXaml/Mntone.SvgForXaml.Shared/SvgDocument.cs
using Mntone.SvgForXaml.Interfaces; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Text; using Windows.Data.Xml.Dom; namespace Mntone.SvgForXaml { public sealed class SvgDocument : INode { private Dictionary<string, SvgElement> _idCache; private SvgDocument() { this._idCache = new Dictionary<string, SvgElement>(); } [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] SvgDocument INode.OwnerDocument => this; [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] INode INode.ParentNode => null; [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] IReadOnlyCollection<SvgElement> INode.ChildNodes => this._ChildNodes; [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] SvgElement INode.FirstChild => this.RootElement; [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] SvgElement INode.LastChild => this.RootElement; [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] private IReadOnlyCollection<SvgElement> _ChildNodes; public INode CloneNode(bool deep = false) { var shallow = (SvgDocument)this.MemberwiseClone(); if (deep) { throw new NotImplementedException(); } return shallow; } public SvgSvgElement RootElement { get; private set; } internal void AddIdCache(string id, SvgElement element) { if (this._idCache.ContainsKey(id)) return; this._idCache.Add(id, element); } public SvgElement GetElementById(string id) { if (!this._idCache.ContainsKey(id)) return null; return this._idCache[id]; } public static SvgDocument Parse(byte[] document) => Parse(Encoding.UTF8.GetString(document, 0, document.Length)); public static SvgDocument Parse(byte[] document, Encoding encoding) => Parse(encoding.GetString(document, 0, document.Length)); public static SvgDocument Parse(string document) { var xml = new XmlDocument(); xml.LoadXml(document, new XmlLoadSettings { ProhibitDtd = false }); return Parse(xml); } public static SvgDocument Parse(XmlDocument document) { var svgDocument = new SvgDocument(); var rootElement = new SvgSvgElement(svgDocument, document.DocumentElement); var childNodes = new Collection<SvgElement>(); childNodes.Add(rootElement); svgDocument._ChildNodes = childNodes; svgDocument.RootElement = rootElement; return svgDocument; } } }
using Mntone.SvgForXaml.Interfaces; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Text; using Windows.Data.Xml.Dom; namespace Mntone.SvgForXaml { public sealed class SvgDocument : INode { private Dictionary<string, SvgElement> _idCache; private SvgDocument() { this._idCache = new Dictionary<string, SvgElement>(); } [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] SvgDocument INode.OwnerDocument => this; [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] INode INode.ParentNode => null; [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] IReadOnlyCollection<SvgElement> INode.ChildNodes => this._ChildNodes; [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] SvgElement INode.FirstChild => this.RootElement; [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] SvgElement INode.LastChild => this.RootElement; [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] private IReadOnlyCollection<SvgElement> _ChildNodes; public INode CloneNode(bool deep = false) { var shallow = (SvgDocument)this.MemberwiseClone(); if (deep) { throw new NotImplementedException(); } return shallow; } public SvgSvgElement RootElement { get; private set; } internal void AddIdCache(string id, SvgElement element) { this._idCache.Add(id, element); } public SvgElement GetElementById(string id) { if (!this._idCache.ContainsKey(id)) return null; return this._idCache[id]; } public static SvgDocument Parse(byte[] document) => Parse(Encoding.UTF8.GetString(document, 0, document.Length)); public static SvgDocument Parse(byte[] document, Encoding encoding) => Parse(encoding.GetString(document, 0, document.Length)); public static SvgDocument Parse(string document) { var xml = new XmlDocument(); xml.LoadXml(document, new XmlLoadSettings { ProhibitDtd = false }); return Parse(xml); } public static SvgDocument Parse(XmlDocument document) { var svgDocument = new SvgDocument(); var rootElement = new SvgSvgElement(svgDocument, document.DocumentElement); var childNodes = new Collection<SvgElement>(); childNodes.Add(rootElement); svgDocument._ChildNodes = childNodes; svgDocument.RootElement = rootElement; return svgDocument; } } }
mit
C#