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
3a654c5df76ef0cb2c8f9b57bea0a42cf0f39d6d
Rework the client class.
0x2aff/WoWCore
Common/Network/Client.cs
Common/Network/Client.cs
/* MIT License * * Copyright (c) 2019 Stanislaw Schlosser <https://github.com/0x2aff> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ using System; using System.Net; using System.Net.Sockets; namespace WoWCore.Common.Network { public class Client : IDisposable { /// <summary> /// Instantiates the <see cref="Client" /> class. /// </summary> /// <param name="tcpClient">Client connection for the TCP network service.</param> public Client(TcpClient tcpClient) { if (tcpClient == null) throw new ArgumentNullException(nameof(tcpClient)); Ip = ((IPEndPoint) tcpClient.Client.RemoteEndPoint).Address.ToString(); Port = ((IPEndPoint) tcpClient.Client.RemoteEndPoint).Port; TcpClient = tcpClient; } /// <summary> /// IP address of the client. /// </summary> public string Ip { get; } /// <summary> /// Port of the client. /// </summary> public int Port { get; } /// <summary> /// Client connection for the TCP network service. /// </summary> public TcpClient TcpClient { get; } /// <inheritdoc /> /// <summary> /// Releases the managed and unmanaged resources used by the <see cref="T:WoWCore.Common.Network.Client" />. /// </summary> public void Dispose() { TcpClient?.Dispose(); } } }
/* MIT License * * Copyright (c) 2019 Stanislaw Schlosser <https://github.com/0x2aff> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ using System; using System.Net; using System.Net.Sockets; namespace WoWCore.Common.Network { public class Client { public string Ip { get; set; } public int Port { get; set; } public TcpClient TcpClient { get; set; } public Client(TcpClient tcpClient) { if (tcpClient == null) throw new ArgumentNullException(nameof(tcpClient)); Ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString(); Port = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port; TcpClient = tcpClient; } } }
mit
C#
8d010cfb5d9c38263cfb676071674b57d3277ebf
make the log noisy
darvell/Coremero
Coremero/Coremero/Log.cs
Coremero/Coremero/Log.cs
using System; using NLog; namespace Coremero { public static class Log { private static ILogger _logger; private static ILogger Logger { get { if (_logger == null) { _logger = LogManager.GetLogger("Coremero"); } return _logger; } } public static void Trace(string message) { Logger.Trace(message); } public static void Debug(string message) { Logger.Debug(message); } public static void Info(string message) { Logger.Info(message); } public static void Warn(string message) { Logger.Warn(message); } public static void Exception(Exception e, string message = null) { Logger.Error(message + e.Message + e.StackTrace); } public static void Error(string message) { Logger.Error(message); } public static void Fatal(string message) { Logger.Fatal(message); } public static void FatalException(Exception e, string message = null) { Logger.Fatal(e, message); } } }
using System; using NLog; namespace Coremero { public static class Log { private static ILogger _logger; private static ILogger Logger { get { if (_logger == null) { _logger = LogManager.GetLogger("Coremero"); } return _logger; } } public static void Trace(string message) { Logger.Trace(message); } public static void Debug(string message) { Logger.Debug(message); } public static void Info(string message) { Logger.Info(message); } public static void Warn(string message) { Logger.Warn(message); } public static void Exception(Exception e, string message = null) { Logger.Error(e, message); } public static void Error(string message) { Logger.Error(message); } public static void Fatal(string message) { Logger.Fatal(message); } public static void FatalException(Exception e, string message = null) { Logger.Fatal(e, message); } } }
mit
C#
0ecd9d87190852ac7f9b3807887cd176844573d9
Handle empty MONO_PATH
0install/monopath-emulator
monopath-emulator.cs
monopath-emulator.cs
using System; using System.IO; using System.Reflection; using System.Windows.Forms; static class MonoPathEmulator { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static int Main(string[] args) { if (args.LongLength == 0) throw new ArgumentException("Missing target"); string targetPath = args[0]; var targetArgs = new string[args.LongLength - 1]; Array.Copy(args, 1, targetArgs, 0, args.LongLength - 1); AppDomain domain = AppDomain.CreateDomain("target"); domain.AssemblyResolve += OnAssemblyResolve; try { return domain.ExecuteAssembly(targetPath, null, targetArgs); } catch (TypeInitializationException ex) { throw ex.InnerException; } } private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs e) { var assembly = new AssemblyName(e.Name); string[] prefixCandidates = (assembly.CultureInfo == null) ? new[] { assembly.Name, Path.Combine(assembly.Name, assembly.Name) } : new[] { assembly.Name, Path.Combine(assembly.Name, assembly.Name), Path.Combine(assembly.CultureInfo.TwoLetterISOLanguageName, assembly.Name), Path.Combine(assembly.CultureInfo.TwoLetterISOLanguageName, Path.Combine(assembly.Name, assembly.Name)) }; string monoPath = Environment.GetEnvironmentVariable("MONO_PATH"); if (string.IsNullOrEmpty(monoPath)) return null; foreach (string directory in monoPath.Split(Path.PathSeparator)) { foreach (string prefix in prefixCandidates) { string assemblyPath = Path.Combine(directory, prefix + ".dll"); if (File.Exists(assemblyPath)) return Assembly.LoadFile(assemblyPath); } foreach (string prefix in prefixCandidates) { string assemblyPath = Path.Combine(directory, prefix + ".exe"); if (File.Exists(assemblyPath)) return Assembly.LoadFile(assemblyPath); } } return null; } }
using System; using System.IO; using System.Reflection; using System.Windows.Forms; static class MonoPathEmulator { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static int Main(string[] args) { if (args.LongLength == 0) throw new ArgumentException("Missing target"); string targetPath = args[0]; var targetArgs = new string[args.LongLength - 1]; Array.Copy(args, 1, targetArgs, 0, args.LongLength - 1); AppDomain domain = AppDomain.CreateDomain("target"); domain.AssemblyResolve += OnAssemblyResolve; try { return domain.ExecuteAssembly(targetPath, null, targetArgs); } catch (TypeInitializationException ex) { throw ex.InnerException; } } private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs e) { var assembly = new AssemblyName(e.Name); string[] prefixCandidates = (assembly.CultureInfo == null) ? new[] { assembly.Name, Path.Combine(assembly.Name, assembly.Name) } : new[] { assembly.Name, Path.Combine(assembly.Name, assembly.Name), Path.Combine(assembly.CultureInfo.TwoLetterISOLanguageName, assembly.Name), Path.Combine(assembly.CultureInfo.TwoLetterISOLanguageName, Path.Combine(assembly.Name, assembly.Name)) }; string[] directories = (Environment.GetEnvironmentVariable("MONO_PATH") ?? "").Split(Path.PathSeparator); foreach (string directory in directories) { foreach (string prefix in prefixCandidates) { string assemblyPath = Path.Combine(directory, prefix + ".dll"); if (File.Exists(assemblyPath)) return Assembly.LoadFile(assemblyPath); } foreach (string prefix in prefixCandidates) { string assemblyPath = Path.Combine(directory, prefix + ".exe"); if (File.Exists(assemblyPath)) return Assembly.LoadFile(assemblyPath); } } return null; } }
mit
C#
6370179e661a095c62f829eb2417c493329f6cc0
Mark Case.Duration and Case.Output as internal.
Duohong/fixie,fixie/fixie,KevM/fixie,bardoloi/fixie,EliotJones/fixie,bardoloi/fixie,JakeGinnivan/fixie
src/Fixie/Case.cs
src/Fixie/Case.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Fixie.Discovery; using Fixie.Execution; namespace Fixie { public class Case : BehaviorContext { readonly List<Exception> exceptions; public Case(MethodInfo caseMethod, params object[] parameters) { Parameters = parameters != null && parameters.Length == 0 ? null : parameters; Class = caseMethod.ReflectedType; Method = caseMethod.IsGenericMethodDefinition ? caseMethod.MakeGenericMethod(GenericArgumentResolver.ResolveTypeArguments(caseMethod, parameters)) : caseMethod; Name = GetName(); exceptions = new List<Exception>(); } string GetName() { var name = Class.FullName + "." + Method.Name; if (Method.IsGenericMethod) name = string.Format("{0}<{1}>", name, string.Join(", ", Method.GetGenericArguments().Select(x => x.FullName))); if (Parameters != null && Parameters.Length > 0) name = string.Format("{0}({1})", name, string.Join(", ", Parameters.Select(x => x.ToDisplayString()))); return name; } public string Name { get; private set; } public Type Class { get; private set; } public MethodInfo Method { get; private set; } public object[] Parameters { get; private set; } public IReadOnlyList<Exception> Exceptions { get { return exceptions; } } public void Fail(Exception reason) { var wrapped = reason as PreservedException; if (wrapped != null) exceptions.Add(wrapped.OriginalException); else exceptions.Add(reason); } public void ClearExceptions() { exceptions.Clear(); } public Fixture Fixture { get; internal set; } internal TimeSpan Duration { get; set; } internal string Output { get; set; } public object ReturnValue { get; internal set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Fixie.Discovery; using Fixie.Execution; namespace Fixie { public class Case : BehaviorContext { readonly List<Exception> exceptions; public Case(MethodInfo caseMethod, params object[] parameters) { Parameters = parameters != null && parameters.Length == 0 ? null : parameters; Class = caseMethod.ReflectedType; Method = caseMethod.IsGenericMethodDefinition ? caseMethod.MakeGenericMethod(GenericArgumentResolver.ResolveTypeArguments(caseMethod, parameters)) : caseMethod; Name = GetName(); exceptions = new List<Exception>(); } string GetName() { var name = Class.FullName + "." + Method.Name; if (Method.IsGenericMethod) name = string.Format("{0}<{1}>", name, string.Join(", ", Method.GetGenericArguments().Select(x => x.FullName))); if (Parameters != null && Parameters.Length > 0) name = string.Format("{0}({1})", name, string.Join(", ", Parameters.Select(x => x.ToDisplayString()))); return name; } public string Name { get; private set; } public Type Class { get; private set; } public MethodInfo Method { get; private set; } public object[] Parameters { get; private set; } public IReadOnlyList<Exception> Exceptions { get { return exceptions; } } public void Fail(Exception reason) { var wrapped = reason as PreservedException; if (wrapped != null) exceptions.Add(wrapped.OriginalException); else exceptions.Add(reason); } public void ClearExceptions() { exceptions.Clear(); } public Fixture Fixture { get; internal set; } public TimeSpan Duration { get; internal set; } public string Output { get; internal set; } public object ReturnValue { get; internal set; } } }
mit
C#
e4d8c3cec2387a953c77b35ff73374bfcb3e9075
Update Program.cs
proguerammer/SyncBot
SyncBotCLI/Program.cs
SyncBotCLI/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SyncBot.Core; namespace SyncBotCLI { class Program { static string user; static string password; static string workspace; static string server; static string path; static void Main(string[] args) { ProcessArguments(args); if(user == null || password == null || workspace == null || server == null || path == null) { Console.WriteLine("Incorrect usage: SyncBotCLI -u <user> -p <password> -w <workspace> -s <server> //path/to/sync"); return; } var worker = new SyncWorker(); worker.Gathered += OnGathered; worker.Syncing += OnSyncing; worker.Error += OnError; worker.InitializePerforce(user, password, workspace, server); try { Task task = worker.Sync(path); task.Wait(); } catch (AggregateException ae) { Console.WriteLine(ae.InnerException.Message); } Console.WriteLine("Finished."); } static void ProcessArguments(string[] args) { for(int i = 0; i < args.Length; ++i) { if(args[i] == "-u") { i++; user = args[i]; } else if(args[i] == "-p") { i++; password = args[i]; } else if(args[i] == "-w") { i++; workspace = args[i]; } else if(args[i] == "-s") { i++; server = args[i]; } else if(args[i].StartsWith("//")) { path = args[i]; } } } static void OnGathered(object sender, GatherEventArgs e) { Console.WriteLine("Syncing {0} files for a total of {1} bytes", e.TotalFileCount, e.TotalFileSize); } static void OnSyncing(object sender, SyncEventArgs e) { Console.WriteLine("{0:D2}: {1}", e.Id, e.Name); } static void OnError(object sender, ErrorEventArgs e) { Console.WriteLine("ERROR: {0}", e.Error); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SyncBot.Core; namespace SyncBotCLI { class Program { static string user; static string password; static string workspace; static string server; static string path; static void Main(string[] args) { ProcessArguments(args); if(user == null || password == null || workspace == null || server == null || path == null) { Console.WriteLine("Incorrect usage: SyncBotCLI -u <user> -p <password> -w <workspace> -s <server> //path/to/sync"); return; } var worker = new SyncWorker(); worker.Gathered += OnGathered; worker.Syncing += OnSyncing; worker.Error += OnError; worker.InitializePerforce(user, password, workspace, server); Task task = worker.Sync(path); task.Wait(); Console.WriteLine("Finished."); } static void ProcessArguments(string[] args) { for(int i = 0; i < args.Length; ++i) { if(args[i] == "-u") { i++; user = args[i]; } else if(args[i] == "-p") { i++; password = args[i]; } else if(args[i] == "-w") { i++; workspace = args[i]; } else if(args[i] == "-s") { i++; server = args[i]; } else if(args[i].StartsWith("//")) { path = args[i]; } } } static void OnGathered(object sender, GatherEventArgs e) { Console.WriteLine("Syncing {0} files for a total of {1} bytes", e.TotalFileCount, e.TotalFileSize); } static void OnSyncing(object sender, SyncEventArgs e) { Console.WriteLine("{0:D2}: {1}", e.Id, e.Name); } static void OnError(object sender, ErrorEventArgs e) { Console.WriteLine("ERROR: {0}", e.Error); } } }
mit
C#
40d1d58bfd2ef9720d3cb3ee021d282220413c52
Update AlainAssaf.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/AlainAssaf.cs
src/Firehose.Web/Authors/AlainAssaf.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class AlainAssaf : IAmACommunityMember { public string FirstName => "Alain"; public string LastName => "Alain"; public string ShortBioOrTagLine => "EUC Engineer/Architect | Citrix CTA | CCE-V Certified | CUGC Leader | PowerShell Fanatic"; public string StateOrRegion => "North Carolina, USA"; public string EmailAddress => ""; public string TwitterHandle => "alainassaf"; public string GitHubHandle => "alainassaf"; public string GravatarHash => "55e3ac1ac8ca9129cc9e138a158b07bb"; public GeoPosition Position => new GeoPosition(35.7795900, -78.6381790); public Uri WebSite => new Uri("https://alainassaf.com/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://alainassaf.com/feed.xml"); } } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class AlainAssaf : IAmACommunityMember { public string FirstName => "Alain"; public string LastName => "Alain"; public string ShortBioOrTagLine => "Citrix Specialist at SECU - Citrix Technology Advocate - Feedspot Top 50 PowerShell Blogs on the web"; public string StateOrRegion => "North Carolina, USA"; public string EmailAddress => ""; public string TwitterHandle => "alainassaf"; public string GitHubHandle => "alainassaf"; public string GravatarHash => "55e3ac1ac8ca9129cc9e138a158b07bb"; public GeoPosition Position => new GeoPosition(35.7795900, -78.6381790); public Uri WebSite => new Uri("https://alainassaf.github.io/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://alainassaf.github.io/feed.xml"); } } public string FeedLanguageCode => "en"; } }
mit
C#
06bde4b9ab37e335970be5459ba6789687632ae8
Update GoneMobile.cs (#179)
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/GoneMobile.cs
src/Firehose.Web/Authors/GoneMobile.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class GoneMobile : IAmACommunityMember { public string FirstName => "Gone"; public string LastName => "Mobile"; public string StateOrRegion => "Internet"; public string EmailAddress => "gonemobilecast@gmail.com"; public string ShortBioOrTagLine => "is a development podcast focused on mobile development hosted by Jon Dick and Greg Shackles."; public Uri WebSite => new Uri("http://gonemobile.io"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://gonemobile.io/podcast.rss"); } } public string TwitterHandle => "gonemobilecast"; public GeoPosition Position => new GeoPosition(51.2537750, -85.3232140); public string GravatarHash => "cb611c5ecd9a53b2af53a9d50d83c3c5"; public string GitHubHandle => string.Empty; } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class GoneMobile : IAmACommunityMember { public string FirstName => "Gone"; public string LastName => "Mobile"; public string StateOrRegion => "Internet"; public string EmailAddress => "gonemobilecast@gmail.com"; public string ShortBioOrTagLine => "is a development podcast focused on mobile development hosted by Jon Dick and Greg Shackles."; public Uri WebSite => new Uri("http://gonemobile.io"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://feed.gonemobile.io"); } } public string TwitterHandle => "gonemobilecast"; public GeoPosition Position => new GeoPosition(51.2537750, -85.3232140); public string GravatarHash => "cb611c5ecd9a53b2af53a9d50d83c3c5"; public string GitHubHandle => string.Empty; } }
mit
C#
f80156f134b6992699ffa19386babbbea1fb43c2
修改 Index View (新增Genere下拉選單).
NemoChenTW/MvcMovie,NemoChenTW/MvcMovie,NemoChenTW/MvcMovie
src/MvcMovie/Views/Movies/Index.cshtml
src/MvcMovie/Views/Movies/Index.cshtml
@model IEnumerable<MvcMovie.Models.Movie> @{ ViewData["Title"] = "Index"; } <h2>Index</h2> <p> <a asp-action="Create">Create New</a> </p> <form asp-controller="Movies" asp-action="Index" method="get"> <p> Genre: @Html.DropDownList("movieGenre", "All") Title: <input type="text" name="SearchString"> <input type="submit" value="Filter" /> </p> </form> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Genre) </th> <th> @Html.DisplayNameFor(model => model.Price) </th> <th> @Html.DisplayNameFor(model => model.ReleaseDate) </th> <th> @Html.DisplayNameFor(model => model.Title) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Genre) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.DisplayFor(modelItem => item.ReleaseDate) </td> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> | <a asp-action="Details" asp-route-id="@item.ID">Details</a> | <a asp-action="Delete" asp-route-id="@item.ID">Delete</a> </td> </tr> } </table>
@model IEnumerable<MvcMovie.Models.Movie> @{ ViewData["Title"] = "Index"; } <h2>Index</h2> <p> <a asp-action="Create">Create New</a> </p> <form asp-controller="Movies" asp-action="Index" method="get"> <p> Title: <input type="text" name="SearchString"> <input type="submit" value="Filter" /> </p> </form> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Genre) </th> <th> @Html.DisplayNameFor(model => model.Price) </th> <th> @Html.DisplayNameFor(model => model.ReleaseDate) </th> <th> @Html.DisplayNameFor(model => model.Title) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Genre) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.DisplayFor(modelItem => item.ReleaseDate) </td> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> | <a asp-action="Details" asp-route-id="@item.ID">Details</a> | <a asp-action="Delete" asp-route-id="@item.ID">Delete</a> </td> </tr> } </table>
apache-2.0
C#
30918c049db00a72ea309c2b5a1d6e8b98a76d7f
make static ScrapeHandler
phnx47/Prometheus.Client
src/Prometheus.Client/ScrapeHandler.cs
src/Prometheus.Client/ScrapeHandler.cs
using System.IO; using System.Linq; using Prometheus.Client.Collectors.Abstractions; namespace Prometheus.Client { public static class ScrapeHandler { public static void Process(ICollectorRegistry registry, Stream outputStream) { var collected = registry.CollectAll(); TextFormatter.Format(outputStream, collected.ToArray()); } public static MemoryStream Process(ICollectorRegistry registry) { // leave open var stream = new MemoryStream(); var collected = registry.CollectAll(); TextFormatter.Format(stream, collected.ToArray()); stream.Position = 0; return stream; } } }
using System.IO; using System.Linq; using Prometheus.Client.Collectors.Abstractions; namespace Prometheus.Client { public class ScrapeHandler { public static void Process(ICollectorRegistry registry, Stream outputStream) { var collected = registry.CollectAll(); TextFormatter.Format(outputStream, collected.ToArray()); } public static MemoryStream Process(ICollectorRegistry registry) { // leave open var stream = new MemoryStream(); var collected = registry.CollectAll(); TextFormatter.Format(stream, collected.ToArray()); stream.Position = 0; return stream; } } }
mit
C#
45fa2da43337c14a5f6b655b24e4bd3869dd1828
use regex to normalize line endings
mavasani/roslyn-analyzers,dotnet/roslyn-analyzers,dotnet/roslyn-analyzers,mavasani/roslyn-analyzers
src/Test.Utilities/StringExtensions.cs
src/Test.Utilities/StringExtensions.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Text.RegularExpressions; namespace Test.Utilities { public static class StringExtensions { public static string NormalizeLineEndings(this string input) => Regex.Replace(input, "(?<!\r)\n", "\r\n"); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Test.Utilities { public static class StringExtensions { public static string NormalizeLineEndings(this string input) { if (input.Contains("\n") && !input.Contains("\r\n")) { input = input.Replace("\n", "\r\n"); } return input; } } }
mit
C#
341c0a84b87cfa804cd8ee73c89af708446962a8
Fix build, this is not allwoed on the method itself
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
bindings/src/Object.cs
bindings/src/Object.cs
// // Urho's Object C# sugar // // Authors: // Miguel de Icaza (miguel@xamarin.com) // // Copyrigh 2015 Xamarin INc // using System; using System.Runtime.InteropServices; namespace Urho { public partial class UrhoObject : RefCounted { // Invoked by the subscribe methods static void ObjectCallback (IntPtr data, int stringHash, IntPtr variantMap) { GCHandle gch = GCHandle.FromIntPtr(data); Action<IntPtr> a = (Action<IntPtr>) gch.Target; a (variantMap); } } }
// // Urho's Object C# sugar // // Authors: // Miguel de Icaza (miguel@xamarin.com) // // Copyrigh 2015 Xamarin INc // using System; using System.Runtime.InteropServices; namespace Urho { public partial class UrhoObject : RefCounted { // Invoked by the subscribe methods [UnmanagedFunctionPointer(CallingConvention.Cdecl)] static void ObjectCallback (IntPtr data, int stringHash, IntPtr variantMap) { GCHandle gch = GCHandle.FromIntPtr(data); Action<IntPtr> a = (Action<IntPtr>) gch.Target; a (variantMap); } } }
mit
C#
2d1aa7397b9f7ec4865295c7262af0ba71cc7cc9
add GetUniqueIndexString()
yasokada/unity-160820-Inventory-UI
Assets/DataBaseManager.cs
Assets/DataBaseManager.cs
using UnityEngine; //using System.Collections; using System.IO; using System.Collections.Generic; using System.Linq; using NS_MyStringUtil; /* * - add GetUniqueIndexString() * v0.5 2016 Aug. 25 * - rename [kIndex_caseNo] to [kIndex_shelfNo] * v0.4 2016 Aug. 25 * - fix typo > [Resouce] to [Resource] * v0.3 2016 Aug. 24 * - GetString() takes [itemName] arg * v0.2 2016 Aug. 24 * - update getString() to use getElementWithLikeSearch() * - add getElementWithLikeSearch() * - add dictionary [m_dic] * - add [kIndex_checkDate] * - add [kIndex_XXX] such as kIndex_row * v0.1 2016 Aug. 23 * - add LoadCsvResouce() */ namespace NS_DataBaseManager { public class DataBaseManager { Dictionary <string, string> m_dic; public const int kIndex_shelfNo = 0; public const int kIndex_row = 1; public const int kIndex_column = 2; public const int kIndex_name = 3; public const int kIndex_about = 4; public const int kIndex_url = 5; public const int kIndex_checkDate = 6; public void LoadCsvResource() { if (m_dic == null) { m_dic = new Dictionary<string, string>(); } TextAsset csv = Resources.Load ("inventory") as TextAsset; StringReader reader = new StringReader (csv.text); string line = ""; string itmnm; while (reader.Peek () != -1) { line = reader.ReadLine (); itmnm = MyStringUtil.ExtractCsvColumn (line, kIndex_name); m_dic.Add (itmnm, line); } } public string GetUniqueIndexString(int shelfNo, int row, int column) { string res; res = string.Format ("{0:0000}", shelfNo); res = res + string.Format ("{0:00}", row); res = res + string.Format ("{0:00}", column); return res; } public string GetString(string itemName) { string res = getElementWithLikeSearch (m_dic, itemName); return res; } private static string getElementWithLikeSearch(Dictionary<string, string> myDic, string searchKey) { //Dictionaryの規定値は「null, null」なので、空文字を返したい場合はnull判定を入れる return myDic.Where(n => n.Key.Contains(searchKey)).FirstOrDefault().Value; } } }
using UnityEngine; //using System.Collections; using System.IO; using System.Collections.Generic; using System.Linq; using NS_MyStringUtil; /* * - rename [kIndex_caseNo] to [kIndex_shelfNo] * v0.4 2016 Aug. 25 * - fix typo > [Resouce] to [Resource] * v0.3 2016 Aug. 24 * - GetString() takes [itemName] arg * v0.2 2016 Aug. 24 * - update getString() to use getElementWithLikeSearch() * - add getElementWithLikeSearch() * - add dictionary [m_dic] * - add [kIndex_checkDate] * - add [kIndex_XXX] such as kIndex_row * v0.1 2016 Aug. 23 * - add LoadCsvResouce() */ namespace NS_DataBaseManager { public class DataBaseManager { Dictionary <string, string> m_dic; public const int kIndex_shelfNo = 0; public const int kIndex_row = 1; public const int kIndex_column = 2; public const int kIndex_name = 3; public const int kIndex_about = 4; public const int kIndex_url = 5; public const int kIndex_checkDate = 6; public void LoadCsvResource() { if (m_dic == null) { m_dic = new Dictionary<string, string>(); } TextAsset csv = Resources.Load ("inventory") as TextAsset; StringReader reader = new StringReader (csv.text); string line = ""; string itmnm; while (reader.Peek () != -1) { line = reader.ReadLine (); itmnm = MyStringUtil.ExtractCsvColumn (line, kIndex_name); m_dic.Add (itmnm, line); } } public string GetString(string itemName) { string res = getElementWithLikeSearch (m_dic, itemName); return res; } private static string getElementWithLikeSearch(Dictionary<string, string> myDic, string searchKey) { //Dictionaryの規定値は「null, null」なので、空文字を返したい場合はnull判定を入れる return myDic.Where(n => n.Key.Contains(searchKey)).FirstOrDefault().Value; } } }
mit
C#
a71fd7238a2952737b32ea8080214fff6c87a3fd
Add ToString for ChessPiece
ProgramFOX/Chess.NET
ChessDotNet/ChessPiece.cs
ChessDotNet/ChessPiece.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChessDotNet { public class ChessPiece { public Pieces Piece { get; private set; } public Players Player { get; private set; } public static ChessPiece None { get { return new ChessPiece(Pieces.None, Players.None); } } public ChessPiece(Pieces piece, Players player) { Piece = piece; Player = player; } public override bool Equals(object obj) { ChessPiece c1 = this; ChessPiece c2 = (ChessPiece)obj; return c1.Piece == c2.Piece && c1.Player == c2.Player; } public override int GetHashCode() { return new { Piece, Player }.GetHashCode(); } public static bool operator ==(ChessPiece c1, ChessPiece c2) { return c1.Equals(c2); } public static bool operator !=(ChessPiece c1, ChessPiece c2) { return !c1.Equals(c2); } public override string ToString() { return String.Format("ChessPiece: {0}, {1}", Piece, Player); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChessDotNet { public class ChessPiece { public Pieces Piece { get; private set; } public Players Player { get; private set; } public static ChessPiece None { get { return new ChessPiece(Pieces.None, Players.None); } } public ChessPiece(Pieces piece, Players player) { Piece = piece; Player = player; } public override bool Equals(object obj) { ChessPiece c1 = this; ChessPiece c2 = (ChessPiece)obj; return c1.Piece == c2.Piece && c1.Player == c2.Player; } public override int GetHashCode() { return new { Piece, Player }.GetHashCode(); } public static bool operator ==(ChessPiece c1, ChessPiece c2) { return c1.Equals(c2); } public static bool operator !=(ChessPiece c1, ChessPiece c2) { return !c1.Equals(c2); } } }
mit
C#
1f897473b7f4ee3532837f6d3c543bd8cf91a4d9
Bump version to 1.0.0.0-rc1
github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity
common/SolutionInfo.cs
common/SolutionInfo.cs
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.VersionForAssembly)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.VersionForAssembly)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { // this is for the AssemblyVersion and AssemblyVersion attributes, which can't handle alphanumerics internal const string VersionForAssembly = "0.99.0"; // Actual real version internal const string Version = "1.0.0.0-rc1"; } }
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.VersionForAssembly)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.VersionForAssembly)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { // this is for the AssemblyVersion and AssemblyVersion attributes, which can't handle alphanumerics internal const string VersionForAssembly = "0.99.0"; // Actual real version internal const string Version = "1.0.0.0-rc"; } }
mit
C#
58956a7053e6c6803ef648df062b928236b96342
bump revision
FacturAPI/facturapi-net
facturapi-net/Router/Router.cs
facturapi-net/Router/Router.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; namespace Facturapi { internal static partial class Router { private static string UriWithQuery(string path, Dictionary<string, object> query = null) { var url = path; if (query != null) { return $"{path}?{DictionaryToQueryString(query)}"; } else { return path; } } private static string DictionaryToQueryString(Dictionary<string, object> dict) { return String.Join("&", dict.Select(x => String.Format("{0}={1}", Uri.EscapeDataString(x.Key), Uri.EscapeDataString(x.Value.ToString())))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; namespace Facturapi { internal static partial class Router { private static string UriWithQuery(string path, Dictionary<string, object> query = null) { var url = path; if (query != null) { return $"{path}{DictionaryToQueryString(query)}"; } else { return path; } } private static string DictionaryToQueryString(Dictionary<string, object> dict) { return String.Join("&", dict.Select(x => String.Format("{0}={1}", Uri.EscapeDataString(x.Key), Uri.EscapeDataString(x.Value.ToString())))); } } }
mit
C#
d1b1f048ed57a39510c5a809f2b8a3610e014dac
Use the new reflection API on .NET 4.5 and .NET Core
Thilas/commandline,anthonylangsworth/commandline,anthonylangsworth/commandline,Thilas/commandline
src/CommandLine/Core/Verb.cs
src/CommandLine/Core/Verb.cs
// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information. using System; using System.Collections.Generic; using System.Linq; #if !NET40 using System.Reflection; #endif namespace CommandLine.Core { sealed class Verb { private readonly string name; private readonly string helpText; public Verb(string name, string helpText) { if (name == null) throw new ArgumentNullException("name"); if (helpText == null) throw new ArgumentNullException("helpText"); this.name = name; this.helpText = helpText; } public string Name { get { return name; } } public string HelpText { get { return helpText; } } public static Verb FromAttribute(VerbAttribute attribute) { return new Verb( attribute.Name, attribute.HelpText ); } public static IEnumerable<Tuple<Verb, Type>> SelectFromTypes(IEnumerable<Type> types) { return from type in types let attrs = type.GetTypeInfo().GetCustomAttributes(typeof(VerbAttribute), true).ToArray() where attrs.Length == 1 select Tuple.Create( FromAttribute((VerbAttribute)attrs.Single()), type); } } }
// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information. using System; using System.Collections.Generic; using System.Linq; #if PLATFORM_DOTNET using System.Reflection; #endif namespace CommandLine.Core { sealed class Verb { private readonly string name; private readonly string helpText; public Verb(string name, string helpText) { if (name == null) throw new ArgumentNullException("name"); if (helpText == null) throw new ArgumentNullException("helpText"); this.name = name; this.helpText = helpText; } public string Name { get { return name; } } public string HelpText { get { return helpText; } } public static Verb FromAttribute(VerbAttribute attribute) { return new Verb( attribute.Name, attribute.HelpText ); } public static IEnumerable<Tuple<Verb, Type>> SelectFromTypes(IEnumerable<Type> types) { return from type in types let attrs = type.GetTypeInfo().GetCustomAttributes(typeof(VerbAttribute), true).ToArray() where attrs.Length == 1 select Tuple.Create( FromAttribute((VerbAttribute)attrs.Single()), type); } } }
mit
C#
b603bbb894f0e4edd7a4b42c9e9a0dd2c8cfa9a2
Add skeleton code to main program
Lc5/CurrencyRates,Lc5/CurrencyRates,Lc5/CurrencyRates
src/CurrencyRates/Program.cs
src/CurrencyRates/Program.cs
using System; namespace CurrencyRates { class Program { enum Actions { Fetch, Show }; static void Main(string[] args) { try { var action = Actions.Fetch; if (args.Length > 0) { action = (Actions)Enum.Parse(typeof(Actions), args[0], true); } switch (action) { case Actions.Fetch: //@todo implement Fetch action break; case Actions.Show: //@todo implement Show action break; default: break; } } catch (Exception e) { Console.WriteLine("An error occured: " + e.Message); } } } }
using CurrencyRates.Entity; using System; namespace CurrencyRates { class Program { static void Main(string[] args) { } } }
mit
C#
32bbb6ebe9eb4600ce8154903517e3760bb86f04
update Remove method to execute the request on its own
smartfile/client-csharp
SmartFile/SmartFile.cs
SmartFile/SmartFile.cs
using System; using System.Collections; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Web; using RestSharp; using RestSharp.Extensions; namespace SmartFile { public class Client : RestClient { // Constructor public Client(string baseUrl) : base(baseUrl) { } public static RestRequest GetUploadRequest(string filename) { var request = new RestRequest("/path/data/", Method.POST); request.AddFile("file", filename); return request; } public static IRestResponse Upload(RestClient client, string filename) { var request = GetUploadRequest(filename); return client.Execute(request); } public static RestRequest GetDownloadRequest(string downloadName) { var request = new RestRequest("/path/data/" + downloadName, Method.GET); return request; } public static IRestResponse Download(RestClient client, string downloadName, string downloadLocation) { var request = GetDownloadRequest(downloadName); client.DownloadData(request).SaveAs(downloadLocation); return client.Execute(request); } public static RestRequest GetMoveRequest(string sourceFile, string destinationFolder) { var request = new RestRequest("/path/oper/move/", Method.POST); request.AddParameter("src", sourceFile); request.AddParameter("dst", destinationFolder); return request; } public static IRestResponse Move(RestClient client, string sourceFile, string destinationFolder) { var request = GetMoveRequest(sourceFile, destinationFolder); return client.Execute(request); } public static RestRequest GetRemoveRequest(string FileToBeDeleted) { var request = new RestRequest("/path/oper/remove/", Method.POST); request.AddParameter("path", FileToBeDeleted); return request; } public static IRestResponse Remove(RestClient client, string FileToBeDeleted) { var request = GetRemoveRequest(FileToBeDeleted); return client.Execute(request); } } }
using System; using System.Collections; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Web; using RestSharp; using RestSharp.Extensions; namespace SmartFile { public class Client : RestClient { // Constructor public Client(string baseUrl) : base(baseUrl) { } public static RestRequest GetUploadRequest(string filename) { var request = new RestRequest("/path/data/", Method.POST); request.AddFile("file", filename); return request; } public static IRestResponse Upload(RestClient client, string filename) { var request = GetUploadRequest(filename); return client.Execute(request); } public static RestRequest GetDownloadRequest(string downloadName) { var request = new RestRequest("/path/data/" + downloadName, Method.GET); return request; } public static IRestResponse Download(RestClient client, string downloadName, string downloadLocation) { var request = GetDownloadRequest(downloadName); client.DownloadData(request).SaveAs(downloadLocation); return client.Execute(request); } public static RestRequest GetMoveRequest(string sourceFile, string destinationFolder) { var request = new RestRequest("/path/oper/move/", Method.POST); request.AddParameter("src", sourceFile); request.AddParameter("dst", destinationFolder); return request; } public static IRestResponse Move(RestClient client, string sourceFile, string destinationFolder) { var request = GetMoveRequest(sourceFile, destinationFolder); return client.Execute(request); } public static RestRequest Remove(string FileToBeDeleted) { var request = new RestRequest("/path/oper/remove/", Method.POST); request.AddParameter("path", FileToBeDeleted); return request; } } }
bsd-3-clause
C#
3bf9c42b9472960e6aa93a4ef8fe64a0d38a516c
add generic access to IServiceContext
volak/Aggregates.NET,volak/Aggregates.NET
src/Aggregates.NET/ContextExtensions.cs
src/Aggregates.NET/ContextExtensions.cs
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Aggregates.Contracts; namespace Aggregates { [ExcludeFromCodeCoverage] public static class ContextExtensions { public static TUnitOfWork App<TUnitOfWork>(this IServiceContext context) where TUnitOfWork : class, UnitOfWork.IApplication { return context.App as TUnitOfWork; } /// <summary> /// Easier access to uow if user implements IGeneric /// </summary> public static UnitOfWork.IGeneric App(this IServiceContext context) { return context.App as UnitOfWork.IGeneric; } public static Task<TResponse> Service<TService, TResponse>(this IServiceContext context, TService service) where TService : class, IService<TResponse> { var container = context.Container; var processor = container.Resolve<IProcessor>(); return processor.Process<TService, TResponse>(service, container); } public static Task<TResponse> Service<TService, TResponse>(this IServiceContext context, Action<TService> service) where TService : class, IService<TResponse> { var container = context.Container; var processor = container.Resolve<IProcessor>(); var factory = container.Resolve<IEventFactory>(); return processor.Process<TService, TResponse>(factory.Create(service), container); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Aggregates.Contracts; namespace Aggregates { public static class ContextExtensions { public static TUnitOfWork App<TUnitOfWork>(this IServiceContext context) where TUnitOfWork : class, UnitOfWork.IApplication { return context.App as TUnitOfWork; } public static Task<TResponse> Service<TService, TResponse>(this IServiceContext context, TService service) where TService : class, IService<TResponse> { var container = context.Container; var processor = container.Resolve<IProcessor>(); return processor.Process<TService, TResponse>(service, container); } public static Task<TResponse> Service<TService, TResponse>(this IServiceContext context, Action<TService> service) where TService : class, IService<TResponse> { var container = context.Container; var processor = container.Resolve<IProcessor>(); var factory = container.Resolve<IEventFactory>(); return processor.Process<TService, TResponse>(factory.Create(service), container); } } }
mit
C#
708d12bfd2d551af9053fac0a9fd63950dab57bc
update to dist location
ucdavis/Namster,ucdavis/Namster,ucdavis/Namster
src/Namster/Views/Shared/_Layout.cshtml
src/Namster/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - Namster</title> <link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-blue.min.css" /> <!--<script src="https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js"></script>--> <link href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&amp;lang=en" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <environment names="Development"> <link rel="stylesheet" href="~/css/dist/site.css" /> </environment> <environment names="Staging,Production"> <link rel="stylesheet" href="~/css/dist/site.min.css" asp-append-version="true"/> </environment> <script src="~/js/dist/vendor.bundle.js"></script> </head> <body> @RenderBody() <!--<footer class="mdl-mini-footer"> <div class="mdl-mini-footer--left-section"> <p>&copy; 2015 - Namster</p> </div> </footer>--> </div> <environment names="Development"> <script src="http://localhost:8080/webpack-dev-server.js"></script> </environment> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js" asp-fallback-src="~/lib/jquery/dist/jquery.min.js" asp-fallback-test="window.jQuery"> </script> @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - Namster</title> <link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-blue.min.css" /> <!--<script src="https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js"></script>--> <link href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&amp;lang=en" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <environment names="Development"> <link rel="stylesheet" href="~/css/site.css" /> </environment> <environment names="Staging,Production"> <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true"/> </environment> <script src="~/js/dist/vendor.bundle.js"></script> </head> <body> @RenderBody() <!--<footer class="mdl-mini-footer"> <div class="mdl-mini-footer--left-section"> <p>&copy; 2015 - Namster</p> </div> </footer>--> </div> <environment names="Development"> <script src="http://localhost:8080/webpack-dev-server.js"></script> </environment> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js" asp-fallback-src="~/lib/jquery/dist/jquery.min.js" asp-fallback-test="window.jQuery"> </script> @RenderSection("scripts", required: false) </body> </html>
mit
C#
a597d2d90c9eb44ca22a7c4fb55e636d043037bc
Bump version number to 0.11.1
Deadpikle/NetSparkle,Deadpikle/NetSparkle
AssemblyInfo.cs
AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NetSparkle")] [assembly: AssemblyDescription("NetSparkle is an auto update framework for .NET developers")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NetSparkle")] [assembly: AssemblyCopyright("Portions Copyright © Dirk Eisenberg 2010, Deadpikle 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("279448fc-5103-475e-b209-68f3268df7b5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.11.1")] [assembly: AssemblyFileVersion("0.11.1")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NetSparkle")] [assembly: AssemblyDescription("NetSparkle is an auto update framework for .NET developers")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NetSparkle")] [assembly: AssemblyCopyright("Portions Copyright © Dirk Eisenberg 2010, Deadpikle 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("279448fc-5103-475e-b209-68f3268df7b5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.10.0")] [assembly: AssemblyFileVersion("0.10.0")]
mit
C#
d40005b360385ae83eab0956422496bf32707509
Add remove method for cache
Mozu/mozu-dotnet,sanjaymandadi/mozu-dotnet,rocky0904/mozu-dotnet,ezekielthao/mozu-dotnet
SDK/Mozu.Api/Cache/CacheManager.cs
SDK/Mozu.Api/Cache/CacheManager.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Text; using System.Threading.Tasks; namespace Mozu.Api.Cache { public class CacheManager { private readonly ObjectCache _cache; private static readonly object _lockObj = new Object(); private static volatile CacheManager instance; private CacheManager() { _cache = MemoryCache.Default; } public static CacheManager Instance { get { if (instance == null) { lock (_lockObj) { if (instance == null) instance = new CacheManager(); } } return instance; } } public T Get<T>(string id) { return (T)_cache[id]; } public void Add<T>(T obj, string id) { if (!MozuConfig.EnableCache) return; if (_cache.Contains(id)) _cache.Remove(id); var policy = new CacheItemPolicy(); policy.SlidingExpiration = new TimeSpan(1, 0, 0); _cache.Set(id, obj, policy); } public void Update<T>(T obj, string id) { if (!MozuConfig.EnableCache) return; _cache.Remove(id); Add(obj, id); } public void Remove(string id) { if (!MozuConfig.EnableCache) return; _cache.Remove(id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Text; using System.Threading.Tasks; namespace Mozu.Api.Cache { public class CacheManager { private readonly ObjectCache _cache; private static readonly object _lockObj = new Object(); private static volatile CacheManager instance; private CacheManager() { _cache = MemoryCache.Default; } public static CacheManager Instance { get { if (instance == null) { lock (_lockObj) { if (instance == null) instance = new CacheManager(); } } return instance; } } public T Get<T>(string id) { return (T)_cache[id]; } public void Add<T>(T obj, string id) { if (!MozuConfig.EnableCache) return; if (_cache.Contains(id)) _cache.Remove(id); var policy = new CacheItemPolicy(); policy.SlidingExpiration = new TimeSpan(1, 0, 0); _cache.Set(id, obj, policy); } public void Update<T>(T obj, string id) { if (!MozuConfig.EnableCache) return; _cache.Remove(id); Add(obj, id); } } }
mit
C#
b6f6d0691537674ddc12fd2c207ed1470076cf2c
make test locale independent
wallymathieu/XmlUnit,wallymathieu/XmlUnit,wallymathieu/XmlUnit,wallymathieu/XmlUnit,wallymathieu/XmlUnit
xmlunit/tests/csharp/ValidatorTests.cs
xmlunit/tests/csharp/ValidatorTests.cs
namespace XmlUnit.Tests { using System; using System.IO; using System.Xml; using System.Xml.Schema; using NUnit.Framework; using XmlUnit; [TestFixture] public class ValidatorTests { public static readonly string VALID_FILE = ".\\..\\tests\\etc\\BookXsdGenerated.xml"; public static readonly string INVALID_FILE = ".\\..\\tests\\etc\\invalidBook.xml"; [Test] public void XsdValidFileIsValid() { PerformAssertion(VALID_FILE, true); } private Validator PerformAssertion(string file, bool expected) { FileStream input = File.Open(file, FileMode.Open, FileAccess.Read); try { Validator validator = new Validator(new XmlInput(new StreamReader(input))); Assert.AreEqual(expected, validator.IsValid); return validator; } finally { input.Close(); } } [Test] public void XsdInvalidFileIsNotValid() { Validator validator = PerformAssertion(INVALID_FILE, false); Assert.IsFalse(validator.IsValid); Assert.IsTrue(validator.ValidationMessage .IndexOf("http://www.publishing.org") > -1, validator.ValidationMessage); Assert.IsTrue(validator.ValidationMessage.IndexOf("Book") > -1, validator.ValidationMessage); } } }
namespace XmlUnit.Tests { using System; using System.IO; using System.Xml; using System.Xml.Schema; using NUnit.Framework; using XmlUnit; [TestFixture] public class ValidatorTests { public static readonly string VALID_FILE = ".\\..\\tests\\etc\\BookXsdGenerated.xml"; public static readonly string INVALID_FILE = ".\\..\\tests\\etc\\invalidBook.xml"; [Test] public void XsdValidFileIsValid() { PerformAssertion(VALID_FILE, true); } private Validator PerformAssertion(string file, bool expected) { FileStream input = File.Open(file, FileMode.Open, FileAccess.Read); try { Validator validator = new Validator(new XmlInput(new StreamReader(input))); Assert.AreEqual(expected, validator.IsValid); return validator; } finally { input.Close(); } } [Test] public void XsdInvalidFileIsNotValid() { Validator validator = PerformAssertion(INVALID_FILE, false); string expected = "The element 'http://www.publishing.org:Book' has incomplete content"; Assert.AreEqual(true, validator.ValidationMessage.StartsWith(expected)); } } }
bsd-3-clause
C#
46a4ce33dcbe94ef90d08f850833732c2344ffe8
Update Asset.cs
coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk,coinapi/coinapi-sdk
data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Asset.cs
data-api/csharp-rest/CoinAPI.REST.V1/DataModels/Asset.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoinAPI.REST.V1 { public class Asset { public string asset_id { get; set; } public string name { get; set; } public bool type_is_crypto { get; set; } public DateTime? data_start { get; set; } public DateTime? data_end { get; set; } public DateTime? data_quote_start { get; set; } public DateTime? data_quote_end { get; set; } public DateTime? data_orderbook_start { get; set; } public DateTime? data_orderbook_end { get; set; } public DateTime? data_trade_start { get; set; } public DateTime? data_trade_end { get; set; } public long? data_quote_count { get; set; } public long? data_trade_count { get; set; } public long? data_symbols_count { get; set; } public decimal? volume_1hrs_usd { get; set; } public decimal? volume_1day_usd { get; set; } public decimal? volume_1mth_usd { get; set; } public decimal? price_usd { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoinAPI.REST.V1 { public class Asset { public string asset_id { get; set; } public string name { get; set; } public bool type_is_crypto { get; set; } public DateTime? data_quote_start { get; set; } public DateTime? data_quote_end { get; set; } public DateTime? data_orderbook_start { get; set; } public DateTime? data_orderbook_end { get; set; } public DateTime? data_trade_start { get; set; } public DateTime? data_trade_end { get; set; } public long? data_quote_count { get; set; } public long? data_trade_count { get; set; } public long? data_symbols_count { get; set; } public decimal? volume_1hrs_usd { get; set; } public decimal? volume_1day_usd { get; set; } public decimal? volume_1mth_usd { get; set; } public decimal? price_usd { get; set; } } }
mit
C#
0c36ff608221f613213d06e98bb406423f73f8a5
Fix ansi filename decoded as gibberish in zip file
majorsilence/sharpcompress,Gert-Jan/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress,KOLANICH/sharpcompress,adamhathcock/sharpcompress,sepehr1014/sharpcompress,Icenium/sharpcompress,weltkante/sharpcompress,RainsSoft/sharpcompress,ycaihua/sharpcompress,catester/sharpcompress,Wagnerp/sharpcompress,tablesmit/sharpcompress
SharpCompress/Common/ArchiveEncoding.cs
SharpCompress/Common/ArchiveEncoding.cs
using System.Globalization; using System.Text; namespace SharpCompress.Common { public class ArchiveEncoding { /// <summary> /// Default encoding to use when archive format doesn't specify one. /// </summary> public static Encoding Default; /// <summary> /// Encoding used by encryption schemes which don't comply with RFC 2898. /// </summary> public static Encoding Password; static ArchiveEncoding() { #if PORTABLE || NETFX_CORE Default = Encoding.UTF8; Password = Encoding.UTF8; #else Default = Encoding.Default; Password = Encoding.Default; #endif } } }
using System.Globalization; using System.Text; namespace SharpCompress.Common { public class ArchiveEncoding { /// <summary> /// Default encoding to use when archive format doesn't specify one. /// </summary> public static Encoding Default; /// <summary> /// Encoding used by encryption schemes which don't comply with RFC 2898. /// </summary> public static Encoding Password; static ArchiveEncoding() { #if PORTABLE || NETFX_CORE Default = Encoding.UTF8; Password = Encoding.UTF8; #else Default = Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.OEMCodePage); Password = Encoding.Default; #endif } } }
mit
C#
1d5d62cb40b46583454c76d2d8cd2aae8e68c03f
Move Feed widget "Feed" categories to "General"
danielchalmers/DesktopWidgets
DesktopWidgets/Widgets/RSSFeed/Settings.cs
DesktopWidgets/Widgets/RSSFeed/Settings.cs
using System; using System.Collections.Generic; using System.ComponentModel; using DesktopWidgets.Classes; using DesktopWidgets.WidgetBase.Settings; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Widgets.RSSFeed { public class Settings : WidgetSettingsBase { public Settings() { Style.FontSettings.FontSize = 16; } [Category("Style")] [DisplayName("Max Headlines")] public int MaxHeadlines { get; set; } = 5; [Category("General")] [DisplayName("Refresh Interval")] public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromHours(1); [PropertyOrder(0)] [Category("General")] [DisplayName("URL")] public string RssFeedUrl { get; set; } [PropertyOrder(1)] [Category("General")] [DisplayName("Title Whitelist")] public List<string> TitleWhitelist { get; set; } = new List<string>(); [PropertyOrder(2)] [Category("General")] [DisplayName("Title Blacklist")] public List<string> TitleBlacklist { get; set; } = new List<string>(); [PropertyOrder(3)] [Category("General")] [DisplayName("Category Whitelist")] public List<string> CategoryWhitelist { get; set; } = new List<string>(); [Category("Style")] [DisplayName("Show Publish Date")] public bool ShowPublishDate { get; set; } [Category("Style")] [DisplayName("Publish Date Font Settings")] public FontSettings PublishDateFontSettings { get; set; } = new FontSettings { FontSize = 11 }; [Category("Style")] [DisplayName("Publish Date Format")] public string PublishDateFormat { get; set; } = ""; [Category("Style")] [DisplayName("Publish Date Time Offset")] public TimeSpan PublishDateTimeOffset { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using DesktopWidgets.Classes; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.RSSFeed { public class Settings : WidgetSettingsBase { public Settings() { Style.FontSettings.FontSize = 16; } [Category("Style")] [DisplayName("Max Headlines")] public int MaxHeadlines { get; set; } = 5; [Category("General")] [DisplayName("Refresh Interval")] public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromHours(1); [Category("Feed")] [DisplayName("URL")] public string RssFeedUrl { get; set; } [Category("Feed (Filter)")] [DisplayName("Title Whitelist")] public List<string> TitleWhitelist { get; set; } = new List<string>(); [Category("Feed (Filter)")] [DisplayName("Title Blacklist")] public List<string> TitleBlacklist { get; set; } = new List<string>(); [Category("Feed (Filter)")] [DisplayName("Category Whitelist")] public List<string> CategoryWhitelist { get; set; } = new List<string>(); [Category("Style")] [DisplayName("Show Publish Date")] public bool ShowPublishDate { get; set; } [Category("Style")] [DisplayName("Publish Date Font Settings")] public FontSettings PublishDateFontSettings { get; set; } = new FontSettings { FontSize = 11 }; [Category("Style")] [DisplayName("Publish Date Format")] public string PublishDateFormat { get; set; } = ""; [Category("Style")] [DisplayName("Publish Date Time Offset")] public TimeSpan PublishDateTimeOffset { get; set; } } }
apache-2.0
C#
d57fd401d850c197201a8576a0de7a43f3a214ce
remove magic numbers
rmterra/NesZord
src/NesZord.Core/Extensions/ByteExtension.cs
src/NesZord.Core/Extensions/ByteExtension.cs
using System; namespace NesZord.Core.Extensions { public static class ByteExtension { public const int HALF_BYTE = 4; public const int BCD_MAXIMUM_VALUE = 9; public static bool GetBitAt(this byte value, int index) { return (value & (1 << index)) != 0; } public static byte ConvertToBcd(this byte value) { var tenColumn = value >> HALF_BYTE; if (tenColumn > BCD_MAXIMUM_VALUE) { throw new InvalidOperationException("Ten column overflow BCD maximum value"); } var unitColumn = (tenColumn << HALF_BYTE) ^ value; if (unitColumn > BCD_MAXIMUM_VALUE) { throw new InvalidOperationException("Unit column overflow BCD maximum value"); } tenColumn *= 10; return (byte)(tenColumn + unitColumn); } } }
using System; namespace NesZord.Core.Extensions { public static class ByteExtension { public static bool GetBitAt(this byte value, int index) { return (value & (1 << index)) != 0; } public static byte ConvertToBcd(this byte value) { var tenColumn = value >> 4; if (tenColumn > 9) { throw new InvalidOperationException("Ten column overflow BCD maximum value"); } var unitColumn = (tenColumn << 4) ^ value; if (unitColumn > 9) { throw new InvalidOperationException("Unit column overflow BCD maximum value"); } return (byte)((tenColumn * 10) + unitColumn); } } }
apache-2.0
C#
81a9ad997618bd32369244ca50d7f6061a733cea
微调卡牌概率。
Ivony/TableGames
Ivony.TableGame.SimpleGames/SimpleGame.cs
Ivony.TableGame.SimpleGames/SimpleGame.cs
using Ivony.TableGame.Basics; using Ivony.TableGame.SimpleGames.Rules; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ivony.TableGame.SimpleGames { public class SimpleGame : BasicGame<SimpleGamePlayer, SimpleGameCard> { public SimpleGame( IGameHost gameHost ) : base( gameHost ) { } protected override CardDealer CreateCardDealer() { var specialDealer = new UnlimitedCardDealer() .Register( () => new OverturnCard(), 1 ) .Register( () => new AngelCard(), 2 ) .Register( () => new DevilCard(), 5 ) .Register( () => new ClearCard(), 10 ) .Register( () => new PurifyCard(), 5 ) .Register( () => new ReboundCard(), 3 ) .Register( () => new ShieldCard(), 10 ) .Register( () => new PeepCard(), 8 ); var normalDealer = new UnlimitedCardDealer() .Register( () => new AttackCard( 1 ), 30 ) .Register( () => new AttackCard( 2 ), 40 ) .Register( () => new AttackCard( 3 ), 50 ) .Register( () => new AttackCard( 4 ), 25 ) .Register( () => new AttackCard( 5 ), 20 ) .Register( () => new AttackCard( 6 ), 15 ) .Register( () => new AttackCard( 7 ), 10 ) .Register( () => new AttackCard( 8 ), 7 ) .Register( () => new AttackCard( 9 ), 5 ) .Register( () => new AttackCard( 10 ), 3 ); return new UnlimitedCardDealer() .Register( () => specialDealer.DealCard(), 3 ) .Register( () => normalDealer.DealCard(), 7 ); } protected override GamePlayer TryJoinGameCore( IGameHost gameHost, IPlayerHost playerHost ) { lock ( SyncRoot ) { if ( PlayerCollection.Count == 3 ) return null; var player = new SimpleGamePlayer( gameHost, playerHost ); PlayerCollection.Add( player ); if ( PlayerCollection.Count == 3 ) gameHost.Run(); return player; } } } }
using Ivony.TableGame.Basics; using Ivony.TableGame.SimpleGames.Rules; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ivony.TableGame.SimpleGames { public class SimpleGame : BasicGame<SimpleGamePlayer, SimpleGameCard> { public SimpleGame( IGameHost gameHost ) : base( gameHost ) { } protected override CardDealer CreateCardDealer() { var specialDealer = new UnlimitedCardDealer() .Register( () => new OverturnCard(), 1 ) .Register( () => new AngelCard(), 2 ) .Register( () => new DevilCard(), 5 ) .Register( () => new ClearCard(), 10 ) .Register( () => new PurifyCard(), 5 ) .Register( () => new ReboundCard(), 3 ) .Register( () => new ShieldCard(), 10 ) .Register( () => new PeepCard(), 8 ); var normalDealer = new UnlimitedCardDealer() .Register( () => new AttackCard( 1 ), 30 ) .Register( () => new AttackCard( 2 ), 40 ) .Register( () => new AttackCard( 3 ), 50 ) .Register( () => new AttackCard( 4 ), 25 ) .Register( () => new AttackCard( 5 ), 20 ) .Register( () => new AttackCard( 6 ), 15 ) .Register( () => new AttackCard( 7 ), 10 ) .Register( () => new AttackCard( 8 ), 7 ) .Register( () => new AttackCard( 9 ), 5 ) .Register( () => new AttackCard( 10 ), 3 ); return new UnlimitedCardDealer() .Register( () => specialDealer.DealCard(), 4 ) .Register( () => normalDealer.DealCard(), 6 ); } protected override GamePlayer TryJoinGameCore( IGameHost gameHost, IPlayerHost playerHost ) { lock ( SyncRoot ) { if ( PlayerCollection.Count == 3 ) return null; var player = new SimpleGamePlayer( gameHost, playerHost ); PlayerCollection.Add( player ); if ( PlayerCollection.Count == 3 ) gameHost.Run(); return player; } } } }
apache-2.0
C#
9d5e4e966660819efb182f17ac69c9ed523266f0
Make LambdaEqualityHelper.Equals symmetric when exactly one argument is null
sushihangover/libgit2sharp,libgit2/libgit2sharp,jamill/libgit2sharp,rcorre/libgit2sharp,nulltoken/libgit2sharp,whoisj/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,AMSadek/libgit2sharp,nulltoken/libgit2sharp,jamill/libgit2sharp,jeffhostetler/public_libgit2sharp,shana/libgit2sharp,ethomson/libgit2sharp,OidaTiftla/libgit2sharp,xoofx/libgit2sharp,Skybladev2/libgit2sharp,psawey/libgit2sharp,GeertvanHorrik/libgit2sharp,jorgeamado/libgit2sharp,Zoxive/libgit2sharp,red-gate/libgit2sharp,shana/libgit2sharp,dlsteuer/libgit2sharp,mono/libgit2sharp,github/libgit2sharp,mono/libgit2sharp,whoisj/libgit2sharp,OidaTiftla/libgit2sharp,jorgeamado/libgit2sharp,vivekpradhanC/libgit2sharp,PKRoma/libgit2sharp,xoofx/libgit2sharp,GeertvanHorrik/libgit2sharp,sushihangover/libgit2sharp,vivekpradhanC/libgit2sharp,vorou/libgit2sharp,jeffhostetler/public_libgit2sharp,red-gate/libgit2sharp,github/libgit2sharp,rcorre/libgit2sharp,ethomson/libgit2sharp,Skybladev2/libgit2sharp,Zoxive/libgit2sharp,AArnott/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,oliver-feng/libgit2sharp,oliver-feng/libgit2sharp,AArnott/libgit2sharp,vorou/libgit2sharp,dlsteuer/libgit2sharp,AMSadek/libgit2sharp,psawey/libgit2sharp
LibGit2Sharp/Core/LambdaEqualityHelper.cs
LibGit2Sharp/Core/LambdaEqualityHelper.cs
using System; namespace LibGit2Sharp.Core { internal class LambdaEqualityHelper<T> { private readonly Func<T, object>[] equalityContributorAccessors; public LambdaEqualityHelper(params Func<T, object>[] equalityContributorAccessors) { this.equalityContributorAccessors = equalityContributorAccessors; } public bool Equals(T instance, T other) { if (ReferenceEquals(null, instance) || ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(instance, other)) { return true; } if (instance.GetType() != other.GetType()) { return false; } foreach (Func<T, object> accessor in equalityContributorAccessors) { if (!Equals(accessor(instance), accessor(other))) { return false; } } return true; } public int GetHashCode(T instance) { int hashCode = GetType().GetHashCode(); unchecked { foreach (Func<T, object> accessor in equalityContributorAccessors) { hashCode = (hashCode*397) ^ accessor(instance).GetHashCode(); } } return hashCode; } } }
using System; namespace LibGit2Sharp.Core { internal class LambdaEqualityHelper<T> { private readonly Func<T, object>[] equalityContributorAccessors; public LambdaEqualityHelper(params Func<T, object>[] equalityContributorAccessors) { this.equalityContributorAccessors = equalityContributorAccessors; } public bool Equals(T instance, T other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(instance, other)) { return true; } if (instance.GetType() != other.GetType()) { return false; } foreach (Func<T, object> accessor in equalityContributorAccessors) { if (!Equals(accessor(instance), accessor(other))) { return false; } } return true; } public int GetHashCode(T instance) { int hashCode = GetType().GetHashCode(); unchecked { foreach (Func<T, object> accessor in equalityContributorAccessors) { hashCode = (hashCode*397) ^ accessor(instance).GetHashCode(); } } return hashCode; } } }
mit
C#
f71af96528eadf8cb20488d56f78f7f4fb823137
Check the path (#364)
AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,AnthonySteele/NuKeeper,AnthonySteele/NuKeeper,skolima/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper,skolima/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper
NuKeeper/Commands/LocalNuKeeperCommand.cs
NuKeeper/Commands/LocalNuKeeperCommand.cs
using McMaster.Extensions.CommandLineUtils; using NuKeeper.Configuration; using NuKeeper.Inspection.Logging; using System.IO; namespace NuKeeper.Commands { internal abstract class LocalNuKeeperCommand : CommandBase { [Argument(0, Description = "The path to a .sln or .csproj file, or to a directory containing a .NET Core solution/project. " + "If none is specified, the current directory will be used.")] // ReSharper disable once UnassignedGetOnlyAutoProperty // ReSharper disable once MemberCanBePrivate.Global protected string Path { get; } protected LocalNuKeeperCommand(IConfigureLogLevel logger) : base(logger) { } protected override ValidationResult PopulateSettings(SettingsContainer settings) { var baseResult = base.PopulateSettings(settings); if (!baseResult.IsSuccess) { return baseResult; } if (! string.IsNullOrWhiteSpace(Path) && ! Directory.Exists(Path)) { return ValidationResult.Failure($"Path '{Path}' was not found"); } settings.UserSettings.Directory = Path; return ValidationResult.Success; } } }
using McMaster.Extensions.CommandLineUtils; using NuKeeper.Configuration; using NuKeeper.Inspection.Logging; namespace NuKeeper.Commands { internal abstract class LocalNuKeeperCommand : CommandBase { [Argument(0, Description = "The path to a .sln or .csproj file, or to a directory containing a .NET Core solution/project. " + "If none is specified, the current directory will be used.")] // ReSharper disable once UnassignedGetOnlyAutoProperty // ReSharper disable once MemberCanBePrivate.Global protected string Path { get; } protected LocalNuKeeperCommand(IConfigureLogLevel logger) : base(logger) { } protected override ValidationResult PopulateSettings(SettingsContainer settings) { var baseResult = base.PopulateSettings(settings); if (!baseResult.IsSuccess) { return baseResult; } settings.UserSettings.Directory = Path; return ValidationResult.Success; } } }
apache-2.0
C#
a7356e59ee935ff356b012b30de1c8a55ae26736
Update IUserConfirmation.cs
tiksn/TIKSN-Framework
TIKSN.Core/Progress/IUserConfirmation.cs
TIKSN.Core/Progress/IUserConfirmation.cs
namespace TIKSN.Progress { public interface IUserConfirmation { bool ShouldContinue(string query, string caption); bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll); bool ShouldProcess(string target); bool ShouldProcess(string target, string action); bool ShouldProcess(string verboseDescription, string verboseWarning, string caption); } }
namespace TIKSN.Progress { public interface IUserConfirmation { bool ShouldContinue(string query, string caption); bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll); bool ShouldProcess(string target); bool ShouldProcess(string target, string action); bool ShouldProcess(string verboseDescription, string verboseWarning, string caption); } }
mit
C#
d4ec21640839b4bf9aaf8b3123e354f8e900ca7d
Add default behavior for delimited layout
forcewake/FlatFile
src/FlatFile.Delimited/Implementation/DelimitedLayout.cs
src/FlatFile.Delimited/Implementation/DelimitedLayout.cs
namespace FlatFile.Delimited.Implementation { using System; using System.Linq.Expressions; using FlatFile.Core; using FlatFile.Core.Base; public class DelimitedLayout<TTarget> : LayoutBase<TTarget, DelimitedFieldSettings, IDelimitedFieldSettingsConstructor, IDelimitedLayout<TTarget>>, IDelimitedLayout<TTarget> { private string _delimiter = ","; private string _quotes = string.Empty; public DelimitedLayout() : this( new DelimitedFieldSettingsFactory(), new DelimitedFieldSettingsBuilder(), new FieldsContainer<DelimitedFieldSettings>()) { } public DelimitedLayout( IFieldSettingsFactory<DelimitedFieldSettings, IDelimitedFieldSettingsConstructor> fieldSettingsFactory, IFieldSettingsBuilder<DelimitedFieldSettings, IDelimitedFieldSettingsConstructor> builder, IFieldsContainer<DelimitedFieldSettings> fieldsContainer) : base(fieldSettingsFactory, builder, fieldsContainer) { } public string Delimiter { get { return _delimiter; } } public string Quotes { get { return _quotes; } } public IDelimitedLayout<TTarget, IDelimitedLayout<TTarget>> WithQuote(string quote) { _quotes = quote; return this; } public IDelimitedLayout<TTarget, IDelimitedLayout<TTarget>> WithDelimiter(string delimiter) { _delimiter = delimiter; return this; } public override IDelimitedLayout<TTarget> WithMember<TProperty>(Expression<Func<TTarget, TProperty>> expression, Action<IDelimitedFieldSettingsConstructor> settings = null) { ProcessProperty(expression, settings); return this; } } }
namespace FlatFile.Delimited.Implementation { using System; using System.Linq.Expressions; using FlatFile.Core; using FlatFile.Core.Base; public class DelimitedLayout<TTarget> : LayoutBase<TTarget, DelimitedFieldSettings, IDelimitedFieldSettingsConstructor, IDelimitedLayout<TTarget>>, IDelimitedLayout<TTarget> { private string _delimiter; private string _quotes; public DelimitedLayout() : this( new DelimitedFieldSettingsFactory(), new DelimitedFieldSettingsBuilder(), new FieldsContainer<DelimitedFieldSettings>()) { } public DelimitedLayout( IFieldSettingsFactory<DelimitedFieldSettings, IDelimitedFieldSettingsConstructor> fieldSettingsFactory, IFieldSettingsBuilder<DelimitedFieldSettings, IDelimitedFieldSettingsConstructor> builder, IFieldsContainer<DelimitedFieldSettings> fieldsContainer) : base(fieldSettingsFactory, builder, fieldsContainer) { } public string Delimiter { get { return _delimiter; } } public string Quotes { get { return _quotes; } } public IDelimitedLayout<TTarget, IDelimitedLayout<TTarget>> WithQuote(string quote) { _quotes = quote; return this; } public IDelimitedLayout<TTarget, IDelimitedLayout<TTarget>> WithDelimiter(string delimiter) { _delimiter = delimiter; return this; } public override IDelimitedLayout<TTarget> WithMember<TProperty>(Expression<Func<TTarget, TProperty>> expression, Action<IDelimitedFieldSettingsConstructor> settings = null) { ProcessProperty(expression, settings); return this; } } }
mit
C#
adef81632231c29a392cce98cfd0e291d251aa36
Fix get worker filename
henrikstengaard/hstwb-installer,henrikstengaard/hstwb-installer,henrikstengaard/hstwb-installer,henrikstengaard/hstwb-installer,henrikstengaard/hstwb-installer,henrikstengaard/hstwb-installer
src/HstWbInstaller.Imager.GuiApp/Helpers/WorkerHelper.cs
src/HstWbInstaller.Imager.GuiApp/Helpers/WorkerHelper.cs
namespace HstWbInstaller.Imager.GuiApp.Helpers { using System.IO; using Core.Helpers; public static class WorkerHelper { public static string GetWorkerFileName() { var executingFile = ApplicationDataHelper.GetExecutingFile(); return Path.GetExtension(executingFile) switch { ".dll" => $"{Path.GetFileNameWithoutExtension(executingFile)}.exe", _ => Path.GetFileName(executingFile) }; } } }
namespace HstWbInstaller.Imager.GuiApp.Helpers { using System.IO; using Core.Helpers; public static class WorkerHelper { public static string GetWorkerFileName() { var executingFile = ApplicationDataHelper.GetExecutingFile(); return $"{Path.GetFileNameWithoutExtension(executingFile)}.exe"; } } }
mit
C#
c5546c803e5ae56af672f6f937eb745a3fce4847
Update to use UTC instead of local time
Shuttle/shuttle-core-infrastructure,Shuttle/Shuttle.Core.Infrastructure
Shuttle.Core.Infrastructure/ThreadSleep.cs
Shuttle.Core.Infrastructure/ThreadSleep.cs
using System; using System.Threading; namespace Shuttle.Core.Infrastructure { public static class ThreadSleep { public const int MaxStepSize = 1000; public static void While(int ms, IThreadState state) { // step size should be as large as possible, // max step size by default While(ms, state, MaxStepSize); } public static void While(int ms, IThreadState state, int step) { // don't sleep less than zero if (ms < 0) return; // step size must be positive and less than max step size if (step < 0 || step > MaxStepSize) step = MaxStepSize; // end time var end = DateTime.UtcNow.AddMilliseconds(ms); // sleep time should be // 1) as large as possible to reduce burden on the os and improve accuracy // 2) less than the max step size to keep the thread responsive to thread state var remaining = (int)(end - DateTime.UtcNow).TotalMilliseconds; while (state.Active && remaining > 0) { var sleep = remaining < step ? remaining : step; Thread.Sleep(sleep); remaining = (int)(end - DateTime.UtcNow).TotalMilliseconds; } } } }
using System; using System.Threading; namespace Shuttle.Core.Infrastructure { public static class ThreadSleep { public const int MaxStepSize = 1000; public static void While(int ms, IThreadState state) { // step size should be as large as possible, // max step size by default While(ms, state, MaxStepSize); } public static void While(int ms, IThreadState state, int step) { // don't sleep less than zero if (ms < 0) return; // step size must be positive and less than max step size if (step < 0 || step > MaxStepSize) step = MaxStepSize; // end time var end = DateTime.Now.AddMilliseconds(ms); // sleep time should be // 1) as large as possible to reduce burden on the os and improve accuracy // 2) less than the max step size to keep the thread responsive to thread state var remaining = (int)(end - DateTime.Now).TotalMilliseconds; while (state.Active && remaining > 0) { var sleep = remaining < step ? remaining : step; Thread.Sleep(sleep); remaining = (int)(end - DateTime.Now).TotalMilliseconds; } } } }
bsd-3-clause
C#
3d66527eec00b99774184cf0090056560f78503f
更新 DomTree 演示项目
yonglehou/Jumony,zpzgone/Jumony,yonglehou/Jumony,zpzgone/Jumony,wukaixian/Jumony,wukaixian/Jumony
WebSite/DomTree/App_Code/CacheProvider.cs
WebSite/DomTree/App_Code/CacheProvider.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using Ivony.Html.Web; using Ivony.Html.Web.Mvc; class CacheProvider : IMvcCachePolicyProvider { public CachePolicy CreateCachePolicy( ControllerContext context, ActionDescriptor action, IDictionary<string, object> parameters ) { var cacheToken = CacheToken.FromVirtualPath( context.HttpContext ) + CacheToken.FromQueryString( context.HttpContext ); return new MyCachePolicy( context.HttpContext, cacheToken, this ); } public CachePolicy CreateCachePolicy( HttpContextBase context ) { throw new NotSupportedException(); } private class MyCachePolicy : StandardCachePolicy { public MyCachePolicy( HttpContextBase context, CacheToken cacheToken, ICachePolicyProvider provider ) : base( context, cacheToken, provider, TimeSpan.FromDays( 1 ), true, "~/StaticCaches", true ) { } public override void ApplyClientCachePolicy() { base.ApplyClientCachePolicy(); HttpContext.GetClientCachePolicy().SetCacheability( HttpCacheability.Private ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using Ivony.Html.Web; using Ivony.Html.Web.Mvc; class CacheProvider : IMvcCachePolicyProvider { public CachePolicy CreateCachePolicy( ControllerContext context, ActionDescriptor action, IDictionary<string, object> parameters ) { return null; var cacheToken = CacheToken.FromVirtualPath( context.HttpContext ) + CacheToken.FromQueryString( context.HttpContext ); return new MyCachePolicy( context.HttpContext, cacheToken, this ); } public CachePolicy CreateCachePolicy( HttpContextBase context ) { throw new NotSupportedException(); } private class MyCachePolicy : StandardCachePolicy { public MyCachePolicy( HttpContextBase context, CacheToken cacheToken, ICachePolicyProvider provider ) : base( context, cacheToken, provider, TimeSpan.FromDays( 1 ), true, "~/StaticCaches", true ) { } public override void ApplyClientCachePolicy() { base.ApplyClientCachePolicy(); HttpContext.GetClientCachePolicy().SetCacheability( HttpCacheability.Private ); } } }
apache-2.0
C#
8dc8727bc307ea3aa610637f91e434598d443f35
Fix instructions screen back button
Nigh7Sh4de/shatterfall,Nigh7Sh4de/shatterfall
shatterfall/Assets/Scripts/selector.cs
shatterfall/Assets/Scripts/selector.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class selector : MonoBehaviour { public static int option; public List<GameObject> uiChoices; private float ready = 0; private float READY_DELAY = 0.2f; public bool selectable; public GameObject howToPlay; public AudioClip selectSound; private AudioSource source; private float TOGGLE_THRESHOLD = 0.6f; // Use this for initialization void Start () { source = GetComponent<AudioSource>(); option = 0; transform.localScale = uiChoices [0].transform.localScale * 9f; selectable = true; howToPlay.SetActive (false); ready = 0; } void toggleInstructions() { if (!howToPlay.activeSelf) { selectable = false; howToPlay.SetActive(true); } else { howToPlay.SetActive(false); selectable = true; } } IEnumerator loadMainScene() { selectable = false; float fadeTime = GameObject.Find ("Fader").GetComponent<Fading> ().BeginFade (1); yield return new WaitForSeconds (fadeTime); Application.LoadLevel ("main"); } // Update is called once per frame void Update () { if (ready > 0) ready -= Time.deltaTime; if ((Input.GetKey (KeyCode.UpArrow) || (Input.GetAxis ("MoveVertical") > TOGGLE_THRESHOLD)) && ready <= 0 && selectable) { source.PlayOneShot (selectSound, 1F); ready = READY_DELAY; if (option == 0) { option = uiChoices.Count - 1; } else { option--; } } if ((Input.GetKey(KeyCode.DownArrow) || (Input.GetAxis("MoveVertical") < -TOGGLE_THRESHOLD)) && ready <= 0 && selectable) { source.PlayOneShot (selectSound, 1F); ready = READY_DELAY; if (option == uiChoices.Count - 1) { option = 0; } else { option++; } } transform.position = uiChoices [option].transform.position + new Vector3 (-uiChoices [option].transform.localScale.x * 0.55f, uiChoices [option].transform.localScale.x * 0.2f, 0); if ((Input.GetKeyDown (KeyCode.Space) || Input.GetAxis ("Submit") > 0) && ready <= 0) { ready = READY_DELAY * 1000; if (option < 3 && selectable) { source.PlayOneShot (selectSound, 1F); StartCoroutine(loadMainScene()); } else { source.PlayOneShot (selectSound, 1F); ready = READY_DELAY * 3; toggleInstructions (); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class selector : MonoBehaviour { public static int option; public List<GameObject> uiChoices; private float ready = 0; private float READY_DELAY = 0.2f; public bool selectable; public GameObject howToPlay; public AudioClip selectSound; private AudioSource source; private float TOGGLE_THRESHOLD = 0.6f; // Use this for initialization void Start () { source = GetComponent<AudioSource>(); option = 0; transform.localScale = uiChoices [0].transform.localScale * 9f; selectable = true; howToPlay.SetActive (false); ready = 0; } void toggleInstructions() { if (!howToPlay.activeSelf) { selectable = false; howToPlay.SetActive(true); } else { howToPlay.SetActive(false); selectable = true; } } IEnumerator loadMainScene() { selectable = false; float fadeTime = GameObject.Find ("Fader").GetComponent<Fading> ().BeginFade (1); yield return new WaitForSeconds (fadeTime); Application.LoadLevel ("main"); } // Update is called once per frame void Update () { if (ready > 0) ready -= Time.deltaTime; if ((Input.GetKey (KeyCode.UpArrow) || (Input.GetAxis ("MoveVertical") > TOGGLE_THRESHOLD)) && ready <= 0 && selectable) { source.PlayOneShot (selectSound, 1F); ready = READY_DELAY; if (option == 0) { option = uiChoices.Count - 1; } else { option--; } } if ((Input.GetKey(KeyCode.DownArrow) || (Input.GetAxis("MoveVertical") < -TOGGLE_THRESHOLD)) && ready <= 0 && selectable) { source.PlayOneShot (selectSound, 1F); ready = READY_DELAY; if (option == uiChoices.Count - 1) { option = 0; } else { option++; } } transform.position = uiChoices [option].transform.position + new Vector3 (-uiChoices [option].transform.localScale.x * 0.55f, uiChoices [option].transform.localScale.x * 0.2f, 0); if ((Input.GetKeyDown (KeyCode.Space) || Input.GetAxis ("Submit") > 0) && ready <= 0) { ready = READY_DELAY * 1000; if (option < 3 && selectable) { source.PlayOneShot (selectSound, 1F); StartCoroutine(loadMainScene()); } else { source.PlayOneShot (selectSound, 1F); toggleInstructions (); } } } }
mit
C#
e31b6300eb3fe7c3306379800a7943cb4dbba52c
Rename variable
appharbor/appharbor-cli
src/AppHarbor/CompressionExtensions.cs
src/AppHarbor/CompressionExtensions.cs
using System.Collections.Generic; using System.IO; using System.Linq; using ICSharpCode.SharpZipLib.Tar; namespace AppHarbor { public static class CompressionExtensions { public static void ToTar(this DirectoryInfo sourceDirectory, Stream output, string[] excludedDirectoryNames) { var archive = TarArchive.CreateOutputTarArchive(output); archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/'); var entries = GetFiles(sourceDirectory, excludedDirectoryNames) .Select(x => TarEntry.CreateEntryFromFile(x.FullName)) .ToList(); var entriesCount = entries.Count(); var progressBar = new MegaByteProgressBar(); for (var i = 0; i < entriesCount; i++) { archive.WriteEntry(entries[i], true); progressBar.Update("Packing files", entries.Take(i + 1).Sum(x => x.Size), entries.Sum(x => x.Size)); } archive.Close(); } private static IEnumerable<FileInfo> GetFiles(DirectoryInfo directory, string[] excludedDirectories) { return directory.GetFiles("*", SearchOption.TopDirectoryOnly) .Concat(directory.GetDirectories() .Where(x => !excludedDirectories.Contains(x.Name)) .SelectMany(x => GetFiles(x, excludedDirectories))); } } }
using System.Collections.Generic; using System.IO; using System.Linq; using ICSharpCode.SharpZipLib.Tar; namespace AppHarbor { public static class CompressionExtensions { public static void ToTar(this DirectoryInfo sourceDirectory, Stream output, string[] excludedDirectoryNames) { var archive = TarArchive.CreateOutputTarArchive(output); archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/'); var entries = GetFiles(sourceDirectory, excludedDirectoryNames) .Select(x => TarEntry.CreateEntryFromFile(x.FullName)) .ToList(); var entriesCount = entries.Count(); var consoleProgressBar = new MegaByteProgressBar(); for (var i = 0; i < entriesCount; i++) { archive.WriteEntry(entries[i], true); consoleProgressBar.Update("Packing files", entries.Take(i + 1).Sum(x => x.Size), entries.Sum(x => x.Size)); } archive.Close(); } private static IEnumerable<FileInfo> GetFiles(DirectoryInfo directory, string[] excludedDirectories) { return directory.GetFiles("*", SearchOption.TopDirectoryOnly) .Concat(directory.GetDirectories() .Where(x => !excludedDirectories.Contains(x.Name)) .SelectMany(x => GetFiles(x, excludedDirectories))); } } }
mit
C#
580faf26a1041028a8a8585b74cc4a00ddda1a9e
Add bio and github handle for John Miller (#173)
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/JohnMiller.cs
src/Firehose.Web/Authors/JohnMiller.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web { public class JohnMiller : IWorkAtXamarinOrMicrosoft { public string FirstName => "John"; public string LastName => "Miller"; public string StateOrRegion => "Pennsylvania, USA"; public string EmailAddress => ""; public string ShortBioOrTagLine => "Senior Support Engineer at Microsoft"; public Uri WebSite => new Uri("http://jmillerdev.net"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://jmillerdev.net/rss"); } } public string TwitterHandle => "jmillerdev"; public string GravatarHash => "116669ac5e3589d5a5d404e47c32aa72"; public string GitHubHandle => "therealjohn"; public GeoPosition Position => new GeoPosition(41.2033220, -77.1945250); } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web { public class JohnMiller : IWorkAtXamarinOrMicrosoft { public string FirstName => "John"; public string LastName => "Miller"; public string StateOrRegion => "Pennsylvania, USA"; public string EmailAddress => ""; public string ShortBioOrTagLine => string.Empty; public Uri WebSite => new Uri("http://jmillerdev.net"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://jmillerdev.net/rss"); } } public string TwitterHandle => "jmillerdev"; public string GravatarHash => "116669ac5e3589d5a5d404e47c32aa72"; public string GitHubHandle => string.Empty; public GeoPosition Position => new GeoPosition(41.2033220, -77.1945250); } }
mit
C#
94b95041453e636c5d127adc7084348fa157b222
Fix iOS app entry for raw keyboard input (#4780)
peppy/osu,johnneijzen/osu,NeoAdonis/osu,peppy/osu,2yangk23/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,ZLima12/osu,peppy/osu,EVAST9919/osu,peppy/osu-new,ZLima12/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu
osu.iOS/Application.cs
osu.iOS/Application.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using UIKit; namespace osu.iOS { public class Application { public static void Main(string[] args) { UIApplication.Main(args, "GameUIApplication", "AppDelegate"); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using UIKit; namespace osu.iOS { public class Application { public static void Main(string[] args) { UIApplication.Main(args, null, "AppDelegate"); } } }
mit
C#
e9bb78175b804f655d4dafdb3c0f79295fefcebf
load jquery before everything else, not after
ribombee/mothman-dad-city,ribombee/mothman-dad-city,ribombee/mothman-dad-city,ribombee/mothman-dad-city
VLN2-H27/VLN2-H27/Views/Shared/_Layout.cshtml
VLN2-H27/VLN2-H27/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - My ASP.NET Application</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") @Scripts.Render("~/bundles/jquery") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("Collabor.io", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("Editor", "editor", "Editor")</li> <li>@Html.ActionLink("Projects", "projects", "Editor")</li> </ul> @Html.Partial("_LoginPartial") </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p> </footer> </div> @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - My ASP.NET Application</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("Collabor.io", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("Editor", "editor", "Editor")</li> <li>@Html.ActionLink("Projects", "projects", "Editor")</li> </ul> @Html.Partial("_LoginPartial") </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
mit
C#
0f94acffbe812a6916e5c9102e0d4a28e04789f9
Change formatting to match C# style
versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla
VersionOne.ServiceHost.Core/Logging/Logger.cs
VersionOne.ServiceHost.Core/Logging/Logger.cs
using System; using System.Xml; using VersionOne.ServiceHost.Core.Configuration; using VersionOne.ServiceHost.Eventing; namespace VersionOne.ServiceHost.Core.Logging { public class Logger : ILogger { private readonly IEventManager eventManager; public Logger(IEventManager eventManager) { this.eventManager = eventManager; } public void Log(string message) { Log(LogMessage.SeverityType.Info, message, null); } public void Log(string message, Exception exception) { Log(LogMessage.SeverityType.Error, message, exception); } public void Log(LogMessage.SeverityType severity, string message) { Log(severity, message, null); } public void Log(LogMessage.SeverityType severity, string message, Exception exception) { eventManager.Publish(new LogMessage(severity, message, exception)); } public void LogVersionOneConfiguration(LogMessage.SeverityType severity, XmlElement config) { try { var entity = VersionOneSettings.FromXmlElement(config); Log(severity, " VersionOne URL: " + entity.Url); Log(severity, string.Format(" Using proxy server: {0}, Authentication Type: {1}", entity.ProxySettings != null && entity.ProxySettings.Enabled, entity.AuthenticationType)); } catch (Exception ex) { Log(LogMessage.SeverityType.Warning, "Failed to log VersionOne configuration data.", ex); } } public void LogVersionOneConnectionInformation(LogMessage.SeverityType severity, string metaVersion, string memberOid, string defaultMemberRole) { Log(severity, " VersionOne Meta version: " + metaVersion); Log(severity, " VersionOne Member OID: " + memberOid); Log(severity, " VersionOne Member default role: " + defaultMemberRole); } } }
using System; using System.Xml; using VersionOne.ServiceHost.Core.Configuration; using VersionOne.ServiceHost.Eventing; namespace VersionOne.ServiceHost.Core.Logging { public class Logger : ILogger { private readonly IEventManager eventManager; public Logger(IEventManager eventManager) { this.eventManager = eventManager; } public void Log(string message) { Log(LogMessage.SeverityType.Info, message, null); } public void Log(string message, Exception exception) { Log(LogMessage.SeverityType.Error, message, exception); } public void Log(LogMessage.SeverityType severity, string message) { Log(severity, message, null); } public void Log(LogMessage.SeverityType severity, string message, Exception exception) { eventManager.Publish(new LogMessage(severity, message, exception)); } public void LogVersionOneConfiguration(LogMessage.SeverityType severity, XmlElement config) { try { var entity = VersionOneSettings.FromXmlElement(config); Log(severity, " VersionOne URL: " + entity.Url); Log(severity, string.Format(" Using proxy server: {0}, Authentication Type: {1}", entity.ProxySettings != null && entity.ProxySettings.Enabled, entity.AuthenticationType)); } catch(Exception ex) { Log(LogMessage.SeverityType.Warning, "Failed to log VersionOne configuration data.", ex); } } public void LogVersionOneConnectionInformation(LogMessage.SeverityType severity, string metaVersion, string memberOid, string defaultMemberRole) { Log(severity, " VersionOne Meta version: " + metaVersion); Log(severity, " VersionOne Member OID: " + memberOid); Log(severity, " VersionOne Member default role: " + defaultMemberRole); } } }
bsd-3-clause
C#
0db35ba4466ceb223a8478bc9b1d4f7a2df11b42
support detect lower case web.config
303248153/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb
ZKWeb/ZKWeb.Hosting.AspNetCore/StartupBase.cs
ZKWeb/ZKWeb.Hosting.AspNetCore/StartupBase.cs
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.PlatformAbstractions; using System; using System.IO; using System.Threading; using System.Threading.Tasks; using ZKWebStandard.Ioc; namespace ZKWeb.Hosting.AspNetCore { /// <summary> /// Base startup class for Asp.Net Core /// </summary> public abstract class StartupBase { /// <summary> /// Get website root directory /// </summary> /// <returns></returns> public virtual string GetWebsiteRootDirectory() { var path = PlatformServices.Default.Application.ApplicationBasePath; while (!(File.Exists(Path.Combine(path, "Web.config")) || File.Exists(Path.Combine(path, "web.config")))) { path = Path.GetDirectoryName(path); if (string.IsNullOrEmpty(path)) { throw new DirectoryNotFoundException("Website root directory not found"); } } return path; } /// <summary> /// Allow child class to configure middlewares /// </summary> protected virtual void ConfigureMiddlewares(IApplicationBuilder app) { } /// <summary> /// Configure application /// </summary> public virtual void Configure(IApplicationBuilder app, IApplicationLifetime lifetime) { try { // Initialize application Application.Ioc.RegisterMany<CoreWebsiteStopper>(ReuseType.Singleton); Application.Initialize(GetWebsiteRootDirectory()); Application.Ioc.RegisterInstance(lifetime); // Configure middlewares ConfigureMiddlewares(app); } catch { // Stop application after error reported var thread = new Thread(() => { Thread.Sleep(3000); lifetime.StopApplication(); }); thread.IsBackground = true; thread.Start(); throw; } // Set request handler, it will running in thread pool // It can't throw any exception otherwise application will get killed app.Run(coreContext => Task.Run(() => { var context = new CoreHttpContextWrapper(coreContext); try { // Handle request Application.OnRequest(context); } catch (CoreHttpResponseEndException) { // Success } catch (Exception ex) { // Error try { Application.OnError(context, ex); } catch (CoreHttpResponseEndException) { // Handle error success } catch (Exception) { // Handle error failed } } })); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.PlatformAbstractions; using System; using System.IO; using System.Threading; using System.Threading.Tasks; using ZKWebStandard.Ioc; namespace ZKWeb.Hosting.AspNetCore { /// <summary> /// Base startup class for Asp.Net Core /// </summary> public abstract class StartupBase { /// <summary> /// Get website root directory /// </summary> /// <returns></returns> public virtual string GetWebsiteRootDirectory() { var path = PlatformServices.Default.Application.ApplicationBasePath; while (!File.Exists(Path.Combine(path, "Web.config"))) { path = Path.GetDirectoryName(path); if (string.IsNullOrEmpty(path)) { throw new DirectoryNotFoundException("Website root directory not found"); } } return path; } /// <summary> /// Allow child class to configure middlewares /// </summary> protected virtual void ConfigureMiddlewares(IApplicationBuilder app) { } /// <summary> /// Configure application /// </summary> public virtual void Configure(IApplicationBuilder app, IApplicationLifetime lifetime) { try { // Initialize application Application.Ioc.RegisterMany<CoreWebsiteStopper>(ReuseType.Singleton); Application.Initialize(GetWebsiteRootDirectory()); Application.Ioc.RegisterInstance(lifetime); // Configure middlewares ConfigureMiddlewares(app); } catch { // Stop application after error reported var thread = new Thread(() => { Thread.Sleep(3000); lifetime.StopApplication(); }); thread.IsBackground = true; thread.Start(); throw; } // Set request handler, it will running in thread pool // It can't throw any exception otherwise application will get killed app.Run(coreContext => Task.Run(() => { var context = new CoreHttpContextWrapper(coreContext); try { // Handle request Application.OnRequest(context); } catch (CoreHttpResponseEndException) { // Success } catch (Exception ex) { // Error try { Application.OnError(context, ex); } catch (CoreHttpResponseEndException) { // Handle error success } catch (Exception) { // Handle error failed } } })); } } }
mit
C#
05d5dfa18a30a0dabe49dc254dffef1e467c533f
Return 0xFF for an undefined cartridge read rather than 0x00
eightlittlebits/elbgb
elbgb_core/Memory/NullCartridge.cs
elbgb_core/Memory/NullCartridge.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace elbgb_core.Memory { class NullCartridge : Cartridge { public NullCartridge(CartridgeHeader header, byte[] romData) : base(header, romData) { } public override byte ReadByte(ushort address) { return 0xFF; } public override void WriteByte(ushort address, byte value) { return; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace elbgb_core.Memory { class NullCartridge : Cartridge { public NullCartridge(CartridgeHeader header, byte[] romData) : base(header, romData) { } public override byte ReadByte(ushort address) { return 0; } public override void WriteByte(ushort address, byte value) { return; } } }
mit
C#
547b0fac6ffbe8fc3168e3776b932e81b2a995c6
Use GtkWorkarounds to set a link handler
iainx/xwt,mminns/xwt,directhex/xwt,mono/xwt,lytico/xwt,mminns/xwt,residuum/xwt,TheBrainTech/xwt,antmicro/xwt,sevoku/xwt,cra0zy/xwt,hwthomas/xwt,steffenWi/xwt,akrisiun/xwt,hamekoz/xwt
Xwt.Gtk/Xwt.GtkBackend/LinkLabelBackend.cs
Xwt.Gtk/Xwt.GtkBackend/LinkLabelBackend.cs
// // LinkLabelBackend.cs // // Author: // Jérémie Laval <jeremie.laval@xamarin.com> // // Copyright (c) 2012 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt; using Xwt.Backends; namespace Xwt.GtkBackend { class LinkLabelBackend : LabelBackend, ILinkLabelBackend { Uri uri; public LinkLabelBackend () { Label.UseMarkup = true; Label.SetLinkHandler (OpenLink); } public Uri Uri { get { return uri; } set { uri = value; var text = Label.Text; string url = string.Format ("<a href=\"{1}\">{0}</a>", text, uri.ToString ()); Label.Markup = url; } } internal static void OpenLink (string link) { System.Diagnostics.Process.Start (link); } } }
// // LinkLabelBackend.cs // // Author: // Jérémie Laval <jeremie.laval@xamarin.com> // // Copyright (c) 2012 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt; using Xwt.Backends; namespace Xwt.GtkBackend { class LinkLabelBackend : LabelBackend, ILinkLabelBackend { Uri uri; public LinkLabelBackend () { Label.UseMarkup = true; } public Uri Uri { get { return uri; } set { uri = value; var text = Label.Text; string url = string.Format ("<a href=\"{1}\">{0}</a>", text, uri.ToString ()); Label.Markup = url; } } } }
mit
C#
1f1f1ecc042f8129416dca96be5d0aad7b046f6f
Change version to v1.1.3
darkautism/KautismSFOEditor
kautismSFOEditor/Properties/AssemblyInfo.cs
kautismSFOEditor/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 組件的一般資訊是由下列的屬性集控制。 // 變更這些屬性的值即可修改組件的相關 // 資訊。 [assembly: AssemblyTitle("kautismSFOEditor")] [assembly: AssemblyDescription("SFO Editor")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("http://darkautism.blogspot.tw/")] [assembly: AssemblyProduct("kautismSFOEditor")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 將 ComVisible 設定為 false 會使得這個組件中的型別 // 對 COM 元件而言為不可見。如果您需要從 COM 存取這個組件中 // 的型別,請在該型別上將 ComVisible 屬性設定為 true。 [assembly: ComVisible(false)] // 下列 GUID 為專案公開 (Expose) 至 COM 時所要使用的 typelib ID [assembly: Guid("5a3b3973-7e2d-4853-99a6-6792ad4566f5")] // 組件的版本資訊是由下列四項值構成: // // 主要版本 // 次要版本 // 組建編號 // 修訂編號 // // 您可以指定所有的值,也可以依照以下的方式,使用 '*' 將組建和修訂編號 // 指定為預設值: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.3.*")] [assembly: AssemblyFileVersion("1.1.3.0")] [assembly: NeutralResourcesLanguage("en-US")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 組件的一般資訊是由下列的屬性集控制。 // 變更這些屬性的值即可修改組件的相關 // 資訊。 [assembly: AssemblyTitle("kautismSFOEditor")] [assembly: AssemblyDescription("SFO Editor")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("http://darkautism.blogspot.tw/")] [assembly: AssemblyProduct("kautismSFOEditor")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 將 ComVisible 設定為 false 會使得這個組件中的型別 // 對 COM 元件而言為不可見。如果您需要從 COM 存取這個組件中 // 的型別,請在該型別上將 ComVisible 屬性設定為 true。 [assembly: ComVisible(false)] // 下列 GUID 為專案公開 (Expose) 至 COM 時所要使用的 typelib ID [assembly: Guid("5a3b3973-7e2d-4853-99a6-6792ad4566f5")] // 組件的版本資訊是由下列四項值構成: // // 主要版本 // 次要版本 // 組建編號 // 修訂編號 // // 您可以指定所有的值,也可以依照以下的方式,使用 '*' 將組建和修訂編號 // 指定為預設值: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.1.*")] [assembly: AssemblyFileVersion("1.1.1.0")] [assembly: NeutralResourcesLanguage("en-US")]
mit
C#
6eb35ed750ba3981a55ec8021e4650221bb11859
Change priority of StrokeWatcherScheduler to Highest.
rubyu/CreviceApp,rubyu/CreviceApp
CreviceApp/GM.GestureMachine.cs
CreviceApp/GM.GestureMachine.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Crevice.GestureMachine { using System.Threading; using System.Drawing; using Crevice.Core.FSM; using Crevice.Core.Events; using Crevice.Threading; public class GestureMachine : GestureMachine<GestureMachineConfig, ContextManager, EvaluationContext, ExecutionContext> { public GestureMachine( GestureMachineConfig gestureMachineConfig, CallbackManager callbackManager) : base(gestureMachineConfig, callbackManager, new ContextManager()) { } private readonly LowLatencyScheduler _strokeWatcherScheduler = new LowLatencyScheduler("StrokeWatcherTaskScheduler", ThreadPriority.Highest, 1); protected override TaskFactory StrokeWatcherTaskFactory => new TaskFactory(_strokeWatcherScheduler); public override bool Input(IPhysicalEvent evnt, Point? point) { lock (lockObject) { if (point.HasValue) { ContextManager.CursorPosition = point.Value; } return base.Input(evnt, point); } } protected override void Dispose(bool disposing) { if (disposing) { ContextManager.Dispose(); _strokeWatcherScheduler.Dispose(); } base.Dispose(disposing); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Crevice.GestureMachine { using System.Threading; using System.Drawing; using Crevice.Core.FSM; using Crevice.Core.Events; using Crevice.Threading; public class GestureMachine : GestureMachine<GestureMachineConfig, ContextManager, EvaluationContext, ExecutionContext> { public GestureMachine( GestureMachineConfig gestureMachineConfig, CallbackManager callbackManager) : base(gestureMachineConfig, callbackManager, new ContextManager()) { } private readonly LowLatencyScheduler _strokeWatcherScheduler = new LowLatencyScheduler( "StrokeWatcherTaskScheduler", ThreadPriority.AboveNormal, 1); protected override TaskFactory StrokeWatcherTaskFactory => new TaskFactory(_strokeWatcherScheduler); public override bool Input(IPhysicalEvent evnt, Point? point) { lock (lockObject) { if (point.HasValue) { ContextManager.CursorPosition = point.Value; } return base.Input(evnt, point); } } protected override void Dispose(bool disposing) { if (disposing) { ContextManager.Dispose(); _strokeWatcherScheduler.Dispose(); } base.Dispose(disposing); } } }
mit
C#
dbef076684fc3f34ab550a7ec7b35c38dd1cb545
add UpdateDate to DateEntity.
SorenZ/Alamut
src/Alamut.Data/Entity/IDateEntity.cs
src/Alamut.Data/Entity/IDateEntity.cs
using System; namespace Alamut.Data.Entity { public interface IDateEntity { DateTime CreateDate { get; set; } DateTime UpdateDate { get; set; } } /// <summary> /// just for use in mongo query builder /// mondo builder can't get serilization information of an interface /// </summary> public class DateEntity : IDateEntity { public DateTime CreateDate { get; set; } public DateTime UpdateDate { get; set; } } }
using System; namespace Alamut.Data.Entity { public interface IDateEntity { DateTime CreateDate { get; set; } } /// <summary> /// just for use in mongo query builder /// mondo builder can't get serilization information of an interface /// </summary> public class DateEntity : IDateEntity { public DateTime CreateDate { get; set; } } }
mit
C#
c8ac0ed0e8a958a8cca3752c8b47a82f9c383328
update for sqlite benchmarks
jmrnilsson/efpad,jmrnilsson/efpad,jmrnilsson/efpad,jmrnilsson/efpad
02-sqlite/Program.cs
02-sqlite/Program.cs
using System; using System.Linq; using System.Collections.Generic; using Microsoft.Data.Entity; namespace ConsoleApp { public class Program { public static void Main() { using (var db = new BloggingContext()) { db.Blogs.RemoveRange(db.Blogs); db.Posts.RemoveRange(db.Posts); db.SaveChanges(); var start = DateTime.UtcNow; foreach (var index in Enumerable.Range(0, 100)) { var blog = new Blog(); blog.Url = Guid.NewGuid().ToString(); blog.Posts = new List<Post>(); foreach (var indexPost in Enumerable.Range(0, index % 20)) { var post = new Post(); post.Title = Guid.NewGuid().ToString(); post.Content = Guid.NewGuid().ToString(); blog.Posts.Add(post); } db.Blogs.Add(blog); } var count = db.SaveChanges(); var duration = (DateTime.UtcNow - start).TotalMilliseconds; Console.WriteLine("{0} records saved to database in {1} at {2} ms per record", count, duration, duration/count); } } } }
using System; using System.Linq; namespace ConsoleApp { public class Program { public static void Main() { var random = new Random(); using (var db = new BloggingContext()) { new string[] { "http://blogs.msdn.com/adonet", "http://microsoft.com", "https://github.com/dotnet/coreclr", "https://github.com/aspnet/" }.ToList().ForEach(url => db.Blogs.Add(new Blog { Url = url, Posts = Enumerable.Range(1, random.Next(1, 4)).Select(r => new Post { Title = "Title" + random.Next(0, 999), Content = "Content" + random.Next(0, 999) }).ToList() })); var count = db.SaveChanges(); Console.WriteLine("{0} records saved to database", count); Console.WriteLine("All blogs in database:"); var blogs = from b in db.Blogs where b.Posts.Any() select new {b.Url, b.Posts.First().Title}; foreach (var blog in blogs) { Console.WriteLine(string.Format("{0} - {1}", blog.Url, blog.Title)); } } } } }
mit
C#
8e9ac4d674d7edcdd4b9c32b7d12ae9cc9db4ace
Add null/empty check (#5)
Fredi/NetIRC
src/NetIRC/Messages/RplNamReplyMessage.cs
src/NetIRC/Messages/RplNamReplyMessage.cs
using System.Collections.Generic; using System.Linq; namespace NetIRC.Messages { public class RplNamReplyMessage : IRCMessage, IServerMessage { public string Channel { get; } public Dictionary<string, string> Nicks { get; } private static char[] userStatuses = new[] { '@', '+' }; public RplNamReplyMessage(ParsedIRCMessage parsedMessage) { Nicks = new Dictionary<string, string>(); Channel = parsedMessage.Parameters[2]; var nicks = parsedMessage.Trailing.Split(' '); foreach (var nick in nicks) { if (!string.IsNullOrWhiteSpace(nick) && userStatuses.Contains(nick[0])) { Nicks.Add(nick.Substring(1), nick.Substring(0, 1)); } else { Nicks.Add(nick, string.Empty); } } } public void TriggerEvent(EventHub eventHub) { eventHub.OnRplNamReply(new IRCMessageEventArgs<RplNamReplyMessage>(this)); } } }
using System.Collections.Generic; using System.Linq; namespace NetIRC.Messages { public class RplNamReplyMessage : IRCMessage, IServerMessage { public string Channel { get; } public Dictionary<string, string> Nicks { get; } private static char[] userStatuses = new[] { '@', '+' }; public RplNamReplyMessage(ParsedIRCMessage parsedMessage) { Nicks = new Dictionary<string, string>(); Channel = parsedMessage.Parameters[2]; var nicks = parsedMessage.Trailing.Split(' '); foreach (var nick in nicks) { if (userStatuses.Contains(nick[0])) { Nicks.Add(nick.Substring(1), nick.Substring(0, 1)); } else { Nicks.Add(nick, string.Empty); } } } public void TriggerEvent(EventHub eventHub) { eventHub.OnRplNamReply(new IRCMessageEventArgs<RplNamReplyMessage>(this)); } } }
mit
C#
e7c7917bf841ecd9c86139262b98ee76b0e24a77
Update svn properties.
cdbean/CySim,justinccdev/opensim,justinccdev/opensim,ft-/arribasim-dev-extras,AlexRa/opensim-mods-Alex,ft-/opensim-optimizations-wip-tests,AlexRa/opensim-mods-Alex,TechplexEngineer/Aurora-Sim,TomDataworks/opensim,N3X15/VoxelSim,rryk/omp-server,bravelittlescientist/opensim-performance,AlexRa/opensim-mods-Alex,RavenB/opensim,ft-/opensim-optimizations-wip,ft-/arribasim-dev-extras,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip-tests,N3X15/VoxelSim,AlphaStaxLLC/taiga,zekizeki/agentservice,allquixotic/opensim-autobackup,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,N3X15/VoxelSim,bravelittlescientist/opensim-performance,QuillLittlefeather/opensim-1,RavenB/opensim,zekizeki/agentservice,ft-/opensim-optimizations-wip,rryk/omp-server,intari/OpenSimMirror,OpenSimian/opensimulator,RavenB/opensim,ft-/opensim-optimizations-wip-extras,justinccdev/opensim,AlphaStaxLLC/taiga,bravelittlescientist/opensim-performance,QuillLittlefeather/opensim-1,cdbean/CySim,rryk/omp-server,AlexRa/opensim-mods-Alex,BogusCurry/arribasim-dev,bravelittlescientist/opensim-performance,Michelle-Argus/ArribasimExtract,allquixotic/opensim-autobackup,OpenSimian/opensimulator,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TechplexEngineer/Aurora-Sim,RavenB/opensim,ft-/opensim-optimizations-wip-extras,OpenSimian/opensimulator,AlexRa/opensim-mods-Alex,intari/OpenSimMirror,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/arribasim-dev-tests,AlphaStaxLLC/taiga,OpenSimian/opensimulator,Michelle-Argus/ArribasimExtract,BogusCurry/arribasim-dev,N3X15/VoxelSim,M-O-S-E-S/opensim,QuillLittlefeather/opensim-1,cdbean/CySim,TomDataworks/opensim,QuillLittlefeather/opensim-1,OpenSimian/opensimulator,ft-/opensim-optimizations-wip-tests,N3X15/VoxelSim,ft-/opensim-optimizations-wip-extras,N3X15/VoxelSim,zekizeki/agentservice,allquixotic/opensim-autobackup,QuillLittlefeather/opensim-1,rryk/omp-server,ft-/arribasim-dev-extras,AlphaStaxLLC/taiga,justinccdev/opensim,AlphaStaxLLC/taiga,ft-/arribasim-dev-tests,Michelle-Argus/ArribasimExtract,M-O-S-E-S/opensim,RavenB/opensim,N3X15/VoxelSim,OpenSimian/opensimulator,TechplexEngineer/Aurora-Sim,M-O-S-E-S/opensim,allquixotic/opensim-autobackup,cdbean/CySim,TomDataworks/opensim,ft-/arribasim-dev-tests,ft-/opensim-optimizations-wip-tests,M-O-S-E-S/opensim,zekizeki/agentservice,ft-/arribasim-dev-tests,allquixotic/opensim-autobackup,TechplexEngineer/Aurora-Sim,BogusCurry/arribasim-dev,rryk/omp-server,AlexRa/opensim-mods-Alex,intari/OpenSimMirror,ft-/opensim-optimizations-wip,ft-/arribasim-dev-tests,Michelle-Argus/ArribasimExtract,M-O-S-E-S/opensim,intari/OpenSimMirror,TomDataworks/opensim,ft-/arribasim-dev-extras,Michelle-Argus/ArribasimExtract,cdbean/CySim,AlphaStaxLLC/taiga,ft-/arribasim-dev-extras,AlphaStaxLLC/taiga,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,intari/OpenSimMirror,QuillLittlefeather/opensim-1,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/arribasim-dev-tests,BogusCurry/arribasim-dev,justinccdev/opensim,ft-/opensim-optimizations-wip-tests,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip,Michelle-Argus/ArribasimExtract,TomDataworks/opensim,RavenB/opensim,cdbean/CySim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,AlphaStaxLLC/taiga,N3X15/VoxelSim,BogusCurry/arribasim-dev,zekizeki/agentservice,ft-/opensim-optimizations-wip-extras,ft-/arribasim-dev-extras,allquixotic/opensim-autobackup,M-O-S-E-S/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,zekizeki/agentservice,justinccdev/opensim,bravelittlescientist/opensim-performance,BogusCurry/arribasim-dev,intari/OpenSimMirror,M-O-S-E-S/opensim,rryk/omp-server,TomDataworks/opensim,OpenSimian/opensimulator,ft-/opensim-optimizations-wip-extras
OpenSim/Framework/ConfigBase.cs
OpenSim/Framework/ConfigBase.cs
using System; using System.Collections.Generic; using System.Text; namespace OpenSim.Framework { public abstract class ConfigBase { protected ConfigurationMember m_configMember; } }
using System; using System.Collections.Generic; using System.Text; namespace OpenSim.Framework { public abstract class ConfigBase { protected ConfigurationMember m_configMember; } }
bsd-3-clause
C#
7fdffb6605b4952eb009cffca2f7f5ef1f50f822
Define private method Game#LetterIsCorrect
12joan/hangman
game.cs
game.cs
using System; using System.Collections.Generic; namespace Hangman { public class Game { public string Word; private List<char> GuessedLetters; public Game(string word) { Word = word; GuessedLetters = new List<char>(); } public string ShownWord() { return Word; } private bool LetterWasGuessed(char letter) { return GuessedLetters.Contains(letter); } private bool LetterIsCorrect(char letter) { return Word.Contains(letter); } } }
using System; using System.Collections.Generic; namespace Hangman { public class Game { public string Word; private List<char> GuessedLetters; public Game(string word) { Word = word; GuessedLetters = new List<char>(); } public string ShownWord() { return Word; } private bool LetterWasGuessed(char letter) { return GuessedLetters.Contains(letter); } } }
unlicense
C#
8af6a2e74478907a08bcd3aa71cb053061496baa
Make sure the OWIN sample runs
khellang/nancy-bootstrapper-prototype
samples/OwinApp/Program.cs
samples/OwinApp/Program.cs
namespace OwinApp { using System; using Microsoft.Owin.Hosting; using Nancy.Bootstrappers.Autofac; using Owin; using Nancy.Owin; public class Program { public static void Main(string[] args) { const string url = "http://localhost:5000"; using (WebApp.Start(url, Configuration)) { Console.WriteLine($"Listening at {url}..."); Console.ReadLine(); } } private static void Configuration(IAppBuilder app) { app.UseNancy(new AutofacBootstrapper()); } } }
namespace OwinApp { using System; using Microsoft.Owin.Hosting; using Owin; using Nancy.Owin; public class Program { public static void Main(string[] args) { const string url = "http://localhost:5000"; using (WebApp.Start(url, Configuration)) { Console.WriteLine($"Listening at {url}..."); Console.ReadLine(); } } private static void Configuration(IAppBuilder app) { app.UseNancy(); } } }
apache-2.0
C#
5e81b0d0111bea2a38604e04a1c7ebad0f2e5aa5
Mark the GInterface registration delegates CDECL.
sillsdev/gtk-sharp,sillsdev/gtk-sharp,sillsdev/gtk-sharp,sillsdev/gtk-sharp,sillsdev/gtk-sharp
glib/GInterfaceAdapter.cs
glib/GInterfaceAdapter.cs
// GInterfaceAdapter.cs // // Author: Mike Kestner <mkestner@novell.com> // // Copyright (c) 2007 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the Lesser GNU General // Public License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace GLib { using System; using System.Runtime.InteropServices; [CDeclCallback] public delegate void GInterfaceInitHandler (IntPtr iface_ptr, IntPtr data); [CDeclCallback] internal delegate void GInterfaceFinalizeHandler (IntPtr iface_ptr, IntPtr data); internal struct GInterfaceInfo { internal GInterfaceInitHandler InitHandler; internal GInterfaceFinalizeHandler FinalizeHandler; internal IntPtr Data; } public abstract class GInterfaceAdapter { GInterfaceInfo info; protected GInterfaceAdapter () { } protected GInterfaceInitHandler InitHandler { set { info.InitHandler = value; } } public abstract GType GType { get; } public abstract IntPtr Handle { get; } internal GInterfaceInfo Info { get { if (info.Data == IntPtr.Zero) info.Data = (IntPtr) GCHandle.Alloc (this); return info; } } } }
// GInterfaceAdapter.cs // // Author: Mike Kestner <mkestner@novell.com> // // Copyright (c) 2007 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the Lesser GNU General // Public License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace GLib { using System; using System.Runtime.InteropServices; public delegate void GInterfaceInitHandler (IntPtr iface_ptr, IntPtr data); internal delegate void GInterfaceFinalizeHandler (IntPtr iface_ptr, IntPtr data); internal struct GInterfaceInfo { internal GInterfaceInitHandler InitHandler; internal GInterfaceFinalizeHandler FinalizeHandler; internal IntPtr Data; } public abstract class GInterfaceAdapter { GInterfaceInfo info; protected GInterfaceAdapter () { } protected GInterfaceInitHandler InitHandler { set { info.InitHandler = value; } } public abstract GType GType { get; } public abstract IntPtr Handle { get; } internal GInterfaceInfo Info { get { if (info.Data == IntPtr.Zero) info.Data = (IntPtr) GCHandle.Alloc (this); return info; } } } }
lgpl-2.1
C#
5f1584c4f18267e52424d774b6ec74bb5c6641b2
Add interval_count to the args and make trial_period_days explicit
xamarin/XamarinStripe,haithemaraissia/XamarinStripe
XamarinStripe/StripePlanInfo.cs
XamarinStripe/StripePlanInfo.cs
/* * Copyright 2011 Joe Dluzen * * Author(s): * Joe Dluzen (jdluzen@gmail.com) * * 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.Text; using System.Web; namespace Xamarin.Payments.Stripe { public class StripePlanInfo : IUrlEncoderInfo { public string ID { get; set; } public int Amount { get; set; } public string Currency { get; set; } public StripePlanInterval Interval { get; set; } public int? IntervalCount { get; set; } public string Name { get; set; } public int? TrialPeriod { get; set; } #region IUrlEncoderInfo Members public virtual void UrlEncode (StringBuilder sb) { sb.AppendFormat ("id={0}&amount={1}&currency={2}&interval={3}&name={4}&", HttpUtility.UrlEncode (ID), Amount, HttpUtility.UrlEncode (Currency ?? "usd"), HttpUtility.UrlEncode (Interval.ToString().ToLower ()), HttpUtility.UrlEncode (Name)); if (IntervalCount.HasValue) sb.AppendFormat ("interval_count={0}&", IntervalCount.Value); if (TrialPeriod.HasValue) sb.AppendFormat ("trial_period_days={0}&", TrialPeriod.Value); } #endregion } }
/* * Copyright 2011 Joe Dluzen * * Author(s): * Joe Dluzen (jdluzen@gmail.com) * * 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.Text; using System.Web; namespace Xamarin.Payments.Stripe { public class StripePlanInfo : IUrlEncoderInfo { public string ID { get; set; } public int Amount { get; set; } public string Currency { get; set; } public StripePlanInterval Interval { get; set; } public string Name { get; set; } public int TrialPeriod { get; set; } #region IUrlEncoderInfo Members public virtual void UrlEncode (StringBuilder sb) { sb.AppendFormat ("id={0}&amount={1}&currency={2}&interval={3}&name={4}&", HttpUtility.UrlEncode (ID), Amount, HttpUtility.UrlEncode (Currency ?? "usd"), HttpUtility.UrlEncode (Interval.ToString().ToLower ()), HttpUtility.UrlEncode (Name)); if (TrialPeriod > 0) sb.AppendFormat ("trial_period_days={0}&", TrialPeriod); } #endregion } }
apache-2.0
C#
17041a0f490036d3ba2681cff63d8004c3a49ce0
Initialize LoginCommand with an AccessTokenFetcher rather than AppHarborApi
appharbor/appharbor-cli
src/AppHarbor/Commands/LoginCommand.cs
src/AppHarbor/Commands/LoginCommand.cs
using System; namespace AppHarbor.Commands { public class LoginCommand : ICommand { private readonly AccessTokenFetcher _accessTokenFetcher; private readonly EnvironmentVariableConfiguration _environmentVariableConfiguration; public LoginCommand(AccessTokenFetcher accessTokenFetcher, EnvironmentVariableConfiguration environmentVariableConfiguration) { _accessTokenFetcher = accessTokenFetcher; _environmentVariableConfiguration = environmentVariableConfiguration; } public void Execute(string[] arguments) { if (_environmentVariableConfiguration.Get("AppHarborToken", EnvironmentVariableTarget.User) != null) { throw new CommandException("You're already logged in"); } Console.WriteLine("Username:"); var username = Console.ReadLine(); Console.WriteLine("Password:"); var password = Console.ReadLine(); } } }
using System; namespace AppHarbor.Commands { public class LoginCommand : ICommand { private readonly AppHarborApi _appHarborApi; private readonly EnvironmentVariableConfiguration _environmentVariableConfiguration; public LoginCommand(AppHarborApi appHarborApi, EnvironmentVariableConfiguration environmentVariableConfiguration) { _appHarborApi = appHarborApi; _environmentVariableConfiguration = environmentVariableConfiguration; } public void Execute(string[] arguments) { if (_environmentVariableConfiguration.Get("AppHarborToken", EnvironmentVariableTarget.User) != null) { throw new CommandException("You're already logged in"); } Console.WriteLine("Username:"); var username = Console.ReadLine(); Console.WriteLine("Password:"); var password = Console.ReadLine(); } } }
mit
C#
cb66e7474e0a35b2e625ab266645fdbe875ed1e7
Use count from event stream. Same fix applied in b860265961b414b3840bae8bdea0445015febe42
ericgreenmix/marten,ericgreenmix/marten,ericgreenmix/marten,ericgreenmix/marten
src/Marten/Events/EventStore.Append.cs
src/Marten/Events/EventStore.Append.cs
using System; using System.Collections.Generic; using System.Linq; #nullable enable namespace Marten.Events { internal partial class EventStore { public StreamAction Append(Guid stream, IEnumerable<object> events) { //TODO NRT: We're ignoring null here as to not unintentionally change any downstream behaviour - Replace with null guards in the future. return Append(stream, events?.ToArray()!); } public StreamAction Append(Guid stream, params object[] events) { return _store.Events.Append(_session, stream, events); } public StreamAction Append(string stream, IEnumerable<object> events) { return Append(stream, events?.ToArray()!); } public StreamAction Append(string stream, params object[] events) { return _store.Events.Append(_session, stream, events); } public StreamAction Append(Guid stream, long expectedVersion, IEnumerable<object> events) { return Append(stream, expectedVersion, events?.ToArray()!); } public StreamAction Append(Guid stream, long expectedVersion, params object[] events) { var eventStream = Append(stream, events); eventStream.ExpectedVersionOnServer = expectedVersion - eventStream.Events.Count; return eventStream; } public StreamAction Append(string stream, long expectedVersion, IEnumerable<object> events) { return Append(stream, expectedVersion, events?.ToArray()!); } public StreamAction Append(string stream, long expectedVersion, params object[] events) { var eventStream = Append(stream, events); eventStream.ExpectedVersionOnServer = expectedVersion - eventStream.Events.Count; return eventStream; } } }
using System; using System.Collections.Generic; using System.Linq; #nullable enable namespace Marten.Events { internal partial class EventStore { public StreamAction Append(Guid stream, IEnumerable<object> events) { //TODO NRT: We're ignoring null here as to not unintentionally change any downstream behaviour - Replace with null guards in the future. return Append(stream, events?.ToArray()!); } public StreamAction Append(Guid stream, params object[] events) { return _store.Events.Append(_session, stream, events); } public StreamAction Append(string stream, IEnumerable<object> events) { return Append(stream, events?.ToArray()!); } public StreamAction Append(string stream, params object[] events) { return _store.Events.Append(_session, stream, events); } public StreamAction Append(Guid stream, long expectedVersion, IEnumerable<object> events) { return Append(stream, expectedVersion, events?.ToArray()!); } public StreamAction Append(Guid stream, long expectedVersion, params object[] events) { var eventStream = Append(stream, events); eventStream.ExpectedVersionOnServer = expectedVersion - eventStream.Events.Count; return eventStream; } public StreamAction Append(string stream, long expectedVersion, IEnumerable<object> events) { return Append(stream, expectedVersion, events?.ToArray()!); } public StreamAction Append(string stream, long expectedVersion, params object[] events) { var eventStream = Append(stream, events); eventStream.ExpectedVersionOnServer = expectedVersion - events.Length; return eventStream; } } }
mit
C#
aea75be169ed001ce1c0ec4c0701c40f63a58e63
Use received function parameter rather than closure
moq/moq.proxy
src/Moq.Proxy.Tests/ManualProxyTest.cs
src/Moq.Proxy.Tests/ManualProxyTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Moq.Proxy.Tests { public class ManualProxyTest { } public interface ICalculator { int Add (int x, int y); } public class CalculatorProxy : ICalculator, IProxy { BehaviorPipeline pipeline; ICalculator target; public CalculatorProxy () { pipeline = new BehaviorPipeline (); } public CalculatorProxy (ICalculator calculator) : this() { target = calculator; } public IList<IProxyBehavior> Behaviors => pipeline.Behaviors; public int Add (int x, int y) { var returns = pipeline.Invoke( new MethodInvocation(this, MethodBase.GetCurrentMethod(), x, y), (input, next) => { try { // Four possible scenarios here: // - call base implementation // - call wrapped instance // - generate a dummy return value (like AutoFixture) // - return default value for return type. var returnValue = target?.Add(x, y); return input.CreateValueReturn(returnValue, x, y); } catch (Exception ex) { return input.CreateExceptionReturn(ex); } } ); var exception = returns.Exception; if (exception != null) throw exception; return ((int?)returns.ReturnValue).GetValueOrDefault(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Moq.Proxy.Tests { public class ManualProxyTest { } public interface ICalculator { int Add (int x, int y); } public class CalculatorProxy : ICalculator, IProxy { BehaviorPipeline pipeline; ICalculator target; public CalculatorProxy () { pipeline = new BehaviorPipeline (); } public CalculatorProxy (ICalculator calculator) : this() { target = calculator; } public IList<IProxyBehavior> Behaviors => pipeline.Behaviors; public int Add (int x, int y) { var input = new MethodInvocation(this, MethodBase.GetCurrentMethod(), x, y); var returns = pipeline.Invoke(input, (i, next) => { try { // Four possible scenarios here: // - call base implementation // - call wrapped instance // - generate a dummy return value (like AutoFixture) // - return default value for return type. var returnValue = target?.Add(x, y); return input.CreateValueReturn(returnValue, x, y); } catch (Exception ex) { return input.CreateExceptionReturn(ex); } }); var exception = returns.Exception; if (exception != null) throw exception; return (int)returns.ReturnValue; } } }
mit
C#
39b002a5127e7294d6c02d64a29d31c8eebe2f22
Add code documentation to the IPalmValue
haefele/PalmDB
src/PalmDB/Serialization/IPalmValue.cs
src/PalmDB/Serialization/IPalmValue.cs
using System.IO; using System.Threading.Tasks; namespace PalmDB.Serialization { /// <summary> /// Handles reading and writing of the specified <typeparamref name="T"/> in a palm database file. /// </summary> /// <typeparam name="T">The type of value this class can read and write.</typeparam> internal interface IPalmValue<T> { /// <summary> /// Reads the <typeparamref name="T"/> using the specified <paramref name="reader"/>. /// </summary> /// <param name="reader">The reader.</param> Task<T> ReadValueAsync(AsyncBinaryReader reader); /// <summary> /// Writes the specified <paramref name="value"/> using the specified <paramref name="writer"/>. /// </summary> /// <param name="writer">The writer.</param> /// <param name="value">The value.</param> Task WriteValueAsync(AsyncBinaryWriter writer, T value); } }
using System.IO; using System.Threading.Tasks; namespace PalmDB.Serialization { internal interface IPalmValue<T> { Task<T> ReadValueAsync(AsyncBinaryReader reader); Task WriteValueAsync(AsyncBinaryWriter writer, T value); } }
mit
C#
bdffd7d8ecf87e8573d81a0082aea940dab95096
Change placement of anchors to left
gep13/gep13,gep13/gep13,gep13/gep13,gep13/gep13
input/_Scripts.cshtml
input/_Scripts.cshtml
<script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'gep13'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function () { var s = document.createElement('script'); s.async = true; s.type = 'text/javascript'; s.src = '//' + disqus_shortname + '.disqus.com/count.js'; (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s); }()); // Google Analytics (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-20926037-1', 'auto'); ga('send', 'pageview'); </script> <script type="text/javascript" src="/assets/js/anchor.min.js"></script> <script type="text/javascript" src="/assets/js/clipboard.min.js"></script> <script type="text/javascript"> anchors.options.placement = 'left'; anchors.add(); new Clipboard('code'); </script>
<script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'gep13'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function () { var s = document.createElement('script'); s.async = true; s.type = 'text/javascript'; s.src = '//' + disqus_shortname + '.disqus.com/count.js'; (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s); }()); // Google Analytics (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-20926037-1', 'auto'); ga('send', 'pageview'); </script> <script type="text/javascript" src="/assets/js/anchor.min.js"></script> <script type="text/javascript" src="/assets/js/clipboard.min.js"></script> <script type="text/javascript"> anchors.add(); new Clipboard('code'); </script>
mit
C#
4a50207b8df0ac9d03d9c464e276835eecbe2b53
Change camera controller
tino113/TowerDefence
Assets/Scripts/Camera/CameraController.cs
Assets/Scripts/Camera/CameraController.cs
using UnityEngine; using System.Collections; public class CameraController : MonoBehaviour { public float startX; public float startZ; public float zoomSpeed = 40f; private float zoomDamping = 6f; private float moveSpeed = 2f; private float moveDamping = 20f; private float minY = 5f; private float maxY = 50f; private float minFoV = 40f; private float maxFoV = 60f; private float minR = 12f; private float maxR = 80f; private float zoom; private float targetX; private float targetY; private float targetZ; private float targetR; private float targetFoV; private Vector3 targetMouse; public void Start () { zoom = 30f; targetX = startX; targetY = FactorZoom(minY, maxY); targetZ = startZ; targetR = FactorZoom(minR, maxR); targetFoV = FactorZoom(minFoV, maxFoV); UpdateCamera (); } public void Update () { targetX += Input.GetAxis("Horizontal") * FactorZoom(moveSpeed/2, moveSpeed); targetZ += Input.GetAxis("Vertical") * FactorZoom(moveSpeed/2, moveSpeed); targetX = Lerp (transform.position.x, targetX, moveDamping); targetY = Lerp (transform.position.y, FactorZoom(minY, maxY), zoomDamping); targetZ = Lerp (transform.position.z, targetZ, moveDamping); targetR = Lerp (transform.localRotation.eulerAngles.x, FactorZoom(minR, maxR), zoomDamping); targetFoV = Lerp (camera.fieldOfView, FactorZoom(minFoV, maxFoV), zoomDamping); float scrollAmount = Input.GetAxis ("Mouse ScrollWheel") * zoomSpeed; if (scrollAmount != 0) { if (scrollAmount > 0) { // move towards point only when zooming in, not out Ray ray = camera.ScreenPointToRay(Input.mousePosition); RaycastHit hitData; bool hit = Physics.Raycast (ray.origin, ray.direction, out hitData); targetMouse = hit ? hitData.point : targetMouse; targetX = Lerp(targetX, targetMouse.x, moveDamping); targetZ = Lerp(targetZ, targetMouse.z, moveDamping); } zoom += scrollAmount; zoom = Mathf.Clamp (zoom, 0, 100); } UpdateCamera (); } private float Lerp (float from, float to, float damping) { return Mathf.Lerp (from, to, Time.deltaTime * damping); } private float FactorZoom (float min, float max) { return (((max - min) / 100) * (100 - zoom)) + min; } private void UpdateCamera () { transform.localRotation = Quaternion.Euler(targetR, 0, 0); transform.position = new Vector3 (targetX, targetY, targetZ); camera.fieldOfView = targetFoV; } }
using UnityEngine; using System.Collections; public class CameraController : MonoBehaviour { public float startX; public float startZ; public float zoomSpeed = 40f; private float zoomDamping = 6f; private float moveSpeed = 2f; private float moveDamping = 20f; private float minY = 5f; private float maxY = 50f; private float minFoV = 40f; private float maxFoV = 60f; private float minR = 12f; private float maxR = 80f; private float zoom; private float targetX; private float targetY; private float targetZ; private float targetR; private float targetFoV; private Vector3 targetMouse; public void Start () { zoom = 30f; targetX = startX; targetY = FactorZoom(minY, maxY); targetZ = startZ; targetR = FactorZoom(minR, maxR); targetFoV = FactorZoom(minFoV, maxFoV); UpdateCamera (); } public void Update () { UpdateInput (); targetX = Lerp (transform.position.x, targetX, moveDamping); targetY = Lerp (transform.position.y, FactorZoom(minY, maxY), zoomDamping); targetZ = Lerp (transform.position.z, targetZ, moveDamping); targetR = Lerp (transform.localRotation.eulerAngles.x, FactorZoom(minR, maxR), zoomDamping); targetFoV = Lerp (camera.fieldOfView, FactorZoom(minFoV, maxFoV), zoomDamping); UpdateCamera (); } private float Lerp (float from, float to, float damping) { return Mathf.Lerp (from, to, Time.deltaTime * damping); } private float FactorZoom (float min, float max) { return (((max - min) / 100) * (100 - zoom)) + min; } private void UpdateCamera () { transform.localRotation = Quaternion.Euler(targetR, 0, 0); transform.position = new Vector3 (targetX, targetY, targetZ); camera.fieldOfView = targetFoV; } private void UpdateInput () { targetX += Input.GetAxis("Horizontal") * FactorZoom(moveSpeed/2, moveSpeed); targetZ += Input.GetAxis("Vertical") * FactorZoom(moveSpeed/2, moveSpeed); float scrollAmount = Input.GetAxis ("Mouse ScrollWheel") * zoomSpeed; if (scrollAmount != 0) { if (scrollAmount > 0) { // move towards point only when zooming in, not out Ray ray = camera.ScreenPointToRay(Input.mousePosition); RaycastHit hitData; bool hit = Physics.Raycast (ray.origin, ray.direction, out hitData); targetMouse = hit ? hitData.point : targetMouse; targetX = Lerp(targetX, hitData.point.x, moveDamping); targetZ = Lerp(targetZ, hitData.point.z, moveDamping); } zoom += scrollAmount; zoom = Mathf.Clamp (zoom, 0, 100); } } }
apache-2.0
C#
780cda0faae0142ba86b1f665f928261ce1dc242
Fix minor bug for mix mode.
shenchi/MiniWar
Assets/Scripts/Phases/GP_ResourcePhase.cs
Assets/Scripts/Phases/GP_ResourcePhase.cs
using UnityEngine; using System.Collections; public class GP_ResourcePhase : Phase { /* public override void OnEnter() { base.OnEnter(); var hexes = TowerManager.Instance.GetHexagonsInRange(CurrentPlayer, TowerType.ResourceTower); var vision = RangeUtils.GetPlayerVisionServer(CurrentPlayer); hexes.IntersectWith(vision); TowerManager.Instance.RemoveHexagonsOccupied(hexes); CurrentPlayer.AddResource(hexes.Count); } */ public override void OnEnter() { base.OnEnter(); CurrentPlayer.AddResource(CurrentPlayer.Production); CurrentPlayer.RpcAddLog("Your resource is increased by " + CurrentPlayer.Production + "."); } }
using UnityEngine; using System.Collections; public class GP_ResourcePhase : Phase { public override void OnEnter() { base.OnEnter(); var hexes = TowerManager.Instance.GetHexagonsInRange(CurrentPlayer, TowerType.ResourceTower); var vision = RangeUtils.GetPlayerVisionServer(CurrentPlayer); hexes.IntersectWith(vision); TowerManager.Instance.RemoveHexagonsOccupied(hexes); CurrentPlayer.AddResource(hexes.Count); } }
mit
C#
f0fc2b0a5fd795dcf5fa7cab4a6dada5b7c5c33e
Initialize ApplicationConfiguration with an IFileSystem
appharbor/appharbor-cli
src/AppHarbor/ApplicationConfiguration.cs
src/AppHarbor/ApplicationConfiguration.cs
namespace AppHarbor { public class ApplicationConfiguration { private readonly IFileSystem _fileSystem; public ApplicationConfiguration(IFileSystem fileSystem) { _fileSystem = fileSystem; } } }
namespace AppHarbor { public class ApplicationConfiguration { } }
mit
C#
0861ee0c8e985bb413681037ab54ea00f1910d82
Make Icon rotate when clicking ShowRepliesButton
smoogipoo/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,ppy/osu,smoogipooo/osu,ppy/osu,peppy/osu-new,peppy/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu
osu.Game/Overlays/Comments/Buttons/ShowRepliesButton.cs
osu.Game/Overlays/Comments/Buttons/ShowRepliesButton.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using Humanizer; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Input.Events; using osuTK; namespace osu.Game.Overlays.Comments.Buttons { public class ShowRepliesButton : CommentRepliesButton { public readonly BindableBool Expanded = new BindableBool(true); private readonly int count; public ShowRepliesButton(int count) { this.count = count; } protected override void LoadComplete() { base.LoadComplete(); Expanded.BindValueChanged(onExpandedChanged, true); } private void onExpandedChanged(ValueChangedEvent<bool> expanded) { Icon.ScaleTo(new Vector2(1, expanded.NewValue ? -1 : 1)); } protected override bool OnClick(ClickEvent e) { Expanded.Toggle(); return base.OnClick(e); } protected override string GetText() => "reply".ToQuantity(count); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using Humanizer; namespace osu.Game.Overlays.Comments.Buttons { public class ShowRepliesButton : CommentRepliesButton { private readonly int count; public ShowRepliesButton(int count) { this.count = count; } protected override string GetText() => "reply".ToQuantity(count); } }
mit
C#
09fb4ad84c563228ef940fd0a072b6dfa593277a
Fix climbing on destroyed blocks
BrianShiau/TeamVelociraptor2
Assets/Scripts/Player.cs
Assets/Scripts/Player.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public class Player : MonoBehaviour { public float speed = 10.0f; public float climbSpeed = 10f; public bool grounded = false; public bool climbing = false; public bool onCorner = false; public Rigidbody2D rb; public Collider2D playerBounds; public HashSet<Collider2D> WallCollisions; public void Awake() { WallCollisions = new HashSet<Collider2D>(); } // Use this for initialization void Start () { rb = gameObject.GetComponent<Rigidbody2D>(); playerBounds = gameObject.GetComponent<Collider2D>(); } void Update () { //Jump is placed in Update for responsiveness if (grounded && Input.GetKey("up")) { grounded = false; rb.AddForce(new Vector2(0, 500)); } //For climbing if (climbing && Input.GetKey("up")) { transform.Translate(0, climbSpeed * Time.deltaTime, 0); } if (climbing && Input.GetKey("down")) { transform.Translate(0, -climbSpeed * Time.deltaTime, 0); } //Disable gravity for climbing if (climbing) rb.gravityScale = 0; else rb.gravityScale = 3; } void FixedUpdate() { //Horizontal Movement float move = Input.GetAxis("Horizontal2") * speed * Time.deltaTime; transform.Translate(move, 0, 0); CheckWallCollisions(); } protected void CheckWallCollisions() { WallCollisions.RemoveWhere(d => !d.enabled); if (!WallCollisions.Any())climbing = false; } void OnCollisionStay2D(Collision2D c) { //Used for jumping if (playerBounds.bounds.min.y >= c.collider.bounds.max.y - .1f && !onCorner) { // - .1f is for some error grounded = true; } //Climbing the wall if (c.gameObject.CompareTag("Wall") && playerBounds.bounds.min.y > c.collider.bounds.min.y - .1f) { if (!WallCollisions.Contains(c.collider)) WallCollisions.Add(c.collider); rb.velocity = new Vector2(0,0); climbing = true; } } void OnCollisionExit2D(Collision2D c) { WallCollisions.Remove(c.collider); grounded = false; climbing = false; } }
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { public float speed = 10.0f; public float climbSpeed = 10f; public bool grounded = false; public bool climbing = false; public bool onCorner = false; public Rigidbody2D rb; public Collider2D playerBounds; // Use this for initialization void Start () { rb = gameObject.GetComponent<Rigidbody2D>(); playerBounds = gameObject.GetComponent<Collider2D>(); } void Update () { //Jump is placed in Update for responsiveness if (grounded && Input.GetKey("up")) { grounded = false; rb.AddForce(new Vector2(0, 500)); } //For climbing if (climbing && Input.GetKey("up")) { transform.Translate(0, climbSpeed * Time.deltaTime, 0); } if (climbing && Input.GetKey("down")) { transform.Translate(0, -climbSpeed * Time.deltaTime, 0); } //Disable gravity for climbing if (climbing) rb.gravityScale = 0; else rb.gravityScale = 3; } void FixedUpdate() { //Horizontal Movement float move = Input.GetAxis("Horizontal2") * speed * Time.deltaTime; transform.Translate(move, 0, 0); } void OnCollisionStay2D(Collision2D c) { //Used for jumping if (playerBounds.bounds.min.y >= c.collider.bounds.max.y - .1f && !onCorner) { // - .1f is for some error grounded = true; } //Climbing the wall if (c.gameObject.CompareTag("Wall") && playerBounds.bounds.min.y > c.collider.bounds.min.y - .1f) { rb.velocity = new Vector2(0,0); climbing = true; } } void OnCollisionExit2D(Collision2D c) { grounded = false; climbing = false; } }
mit
C#
3ef8b625064c776e65d463a065fee5191ac1959f
Update Program.cs
chemadvisor/chemapi_csharp_example
ConsoleClient/Program.cs
ConsoleClient/Program.cs
/* * Copyright (c) 2017 ChemADVISOR, Inc. All rights reserved. * Licensed under The MIT License (MIT) * https://opensource.org/licenses/MIT */ using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace ConsoleClient { internal class Program { public static void Main(string[] args) => MainAsync().GetAwaiter().GetResult(); private static async Task MainAsync() { // set base address var baseAddress = "https://sandbox.chemadvisor.io/chem/rest/v2/"; // set user_key header var userKey = "your_user_key"; // set accept header: "application/xml", "application/json" var acceptHeader = "application/json"; // set api var resource = "regulatory_lists"; // set query parameters: q, limit, offset var q = Uri.EscapeUriString("{\"tags.tag.name\":\"Government Inventory Lists\"}"); var limit = 10; var offset = 0; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseAddress); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); client.DefaultRequestHeaders.Add("user_key", userKey); var response = await client.GetAsync(string.Format("{0}?q={1}&limit={2}&offset={3}", resource, q, limit, offset)); if (response.IsSuccessStatusCode) { Console.WriteLine(await response.Content.ReadAsStringAsync()); } else { Console.WriteLine(response.StatusCode); } Console.ReadLine(); } } }
/* * Copyright (c) 2017 ChemADVISOR, Inc. All rights reserved. * Licensed under The MIT License (MIT) * https://opensource.org/licenses/MIT */ using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace ConsoleClient { internal class Program { public static void Main(string[] args) => MainAsync().GetAwaiter().GetResult(); private static async Task MainAsync() { // set base address var baseAddress = "https://sandbox.chemadvisor.io/chem/rest/v2/"; // set user_key header var userKey = "your_user_key"; // set accept header: "application/xml", "application/json" var acceptHeader = "application/json"; // set api var resource = "lists"; // set query parameters: q, limit, offset var q = Uri.EscapeUriString("{\"tags.tag.name\":\"Government Inventory Lists\"}"); var limit = 10; var offset = 0; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseAddress); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); client.DefaultRequestHeaders.Add("user_key", userKey); var response = await client.GetAsync(string.Format("{0}?q={1}&limit={2}&offset={3}", resource, q, limit, offset)); if (response.IsSuccessStatusCode) { Console.WriteLine(await response.Content.ReadAsStringAsync()); } else { Console.WriteLine(response.StatusCode); } Console.ReadLine(); } } }
mit
C#
f16efd65135891534e83010031cc27f8e15fa926
fix version
Fody/Obsolete
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Obsolete")] [assembly: AssemblyProduct("Obsolete")] [assembly: AssemblyVersion("4.2.4")] [assembly: AssemblyFileVersion("4.2.4")]
using System.Reflection; [assembly: AssemblyTitle("Obsolete")] [assembly: AssemblyProduct("Obsolete")] [assembly: AssemblyVersion("4.2.3")] [assembly: AssemblyFileVersion("4.2.3")]
mit
C#
479d463a4a21836c5cdcf9180e1de86a0e943d1b
Update Exception message to feature app ID, instead of API Key.
telerik/platform-friends-windowsphone
ConnectionSettings.cs
ConnectionSettings.cs
using System; namespace Telerik.Windows.Controls.Cloud.Sample { /// <summary> /// Contains properties used to initialize the Backend Services and Analytics connections. /// </summary> public static class ConnectionSettings { /// <summary>  /// Input your Backend Services App ID below to connect to your own app.  /// </summary>  public static string TelerikAppId = "your-app-id-here"; /// <summary> /// The Telerik Analytics project identifier. /// </summary> public static string AnalyticsProjectKey = "your-analytics-project-key-here"; /// <summary>  /// Specified whether to use HTTPS when communicating with Backend Services.  /// </summary>  public static bool EverliveUseHttps = false; public static void ThrowError() { throw new ArgumentException("Please enter your Backend Services project app ID"); } } }
using System; namespace Telerik.Windows.Controls.Cloud.Sample { /// <summary> /// Contains properties used to initialize the Backend Services and Analytics connections. /// </summary> public static class ConnectionSettings { /// <summary>  /// Input your Backend Services App ID below to connect to your own app.  /// </summary>  public static string TelerikAppId = "your-app-id-here"; /// <summary> /// The Telerik Analytics project identifier. /// </summary> public static string AnalyticsProjectKey = "your-analytics-project-key-here"; /// <summary>  /// Specified whether to use HTTPS when communicating with Backend Services.  /// </summary>  public static bool EverliveUseHttps = false; public static void ThrowError() { throw new ArgumentException("Please enter your Backend Services project API key"); } } }
bsd-2-clause
C#
9f71e18a835a0d333d6aac0d9f73c4da24b9ee6a
Send keystrokes to the console main window
awaescher/RepoZ,awaescher/RepoZ
Grr/ConsoleExtensions.cs
Grr/ConsoleExtensions.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Grr { public static class ConsoleExtensions { [DllImport("User32.dll")] static extern int SetForegroundWindow(IntPtr point); public static void WriteConsoleInput(Process target, string value) { SetForegroundWindow(target.MainWindowHandle); SendKeys.SendWait(value); SendKeys.SendWait("{Enter}"); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Grr { public static class ConsoleExtensions { [DllImport("User32.dll")] static extern int SetForegroundWindow(IntPtr point); public static void WriteConsoleInput(Process target, string value) { SetForegroundWindow((IntPtr)target.Id); SendKeys.SendWait(value); SendKeys.SendWait("{Enter}"); } } }
mit
C#
7c5541efc058b3a1375611307aaebf5d897c74e5
Update PageDocumentDock.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/ViewModels/Docking/Docks/PageDocumentDock.cs
src/Core2D/ViewModels/Docking/Docks/PageDocumentDock.cs
using Core2D.ViewModels.Docking.Documents; using Dock.Model.ReactiveUI.Controls; using ReactiveUI; namespace Core2D.ViewModels.Docking.Docks { public class PageDocumentDock : DocumentDock { public PageDocumentDock() { CreateDocument = ReactiveCommand.Create(CreatePage); } private void CreatePage() { if (!CanCreateDocument) { return; } var page = new PageViewModel() { Id = "PageDocument", Title = "Page" }; Factory?.AddDockable(this, page); Factory?.SetActiveDockable(page); Factory?.SetFocusedDockable(this, page); } } }
using Core2D.ViewModels.Docking.Documents; using Dock.Model.ReactiveUI.Controls; using ReactiveUI; namespace Core2D.ViewModels.Docking.Docks { public class PageDocumentDock : DocumentDock { public PageDocumentDock() { CreateDocument = ReactiveCommand.Create(CreatePage); } private void CreatePage() { if (!CanCreateDocument) { return; } var page = new PageViewModel() { Title = "Page" }; Factory?.AddDockable(this, page); Factory?.SetActiveDockable(page); Factory?.SetFocusedDockable(this, page); } } }
mit
C#
cbbaf8596c2e08393fdbca0e9c881cf60976f535
Update TransferRequestDto.cs
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts/Dtos/TransferRequestDto.cs
src/SFA.DAS.EmployerAccounts/Dtos/TransferRequestDto.cs
using SFA.DAS.CommitmentsV2.Types; using System; using SFA.DAS.EmployerAccounts.Models.TransferConnections; namespace SFA.DAS.EmployerAccounts.Dtos { public class TransferRequestDto { public DateTime CreatedDate { get; set; } public AccountDto ReceiverAccount { get; set; } public AccountDto SenderAccount { get; set; } public TransferApprovalStatus Status { get; set; } public TransferConnectionType Type { get; set; } public decimal TransferCost { get; set; } public string TransferRequestHashedId { get; set; } } }
using SFA.DAS.CommitmentsV2.Types; using System; namespace SFA.DAS.EmployerAccounts.Dtos { public class TransferRequestDto { public DateTime CreatedDate { get; set; } public AccountDto ReceiverAccount { get; set; } public AccountDto SenderAccount { get; set; } public TransferApprovalStatus Status { get; set; } public decimal TransferCost { get; set; } public string TransferRequestHashedId { get; set; } } }
mit
C#
5fefccd21f38401305b9215aab6c5d441523f388
update test data for profiler test
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
test/WeihanLi.Common.Test/ProfilerTest.cs
test/WeihanLi.Common.Test/ProfilerTest.cs
using System.Threading; using Xunit; namespace WeihanLi.Common.Test { public class ProfilerTest { [Theory] [InlineData(500)] [InlineData(1000)] [InlineData(2000)] public void StopWatchProfileTest(int delay) { var profiler = new StopwatchProfiler(); profiler.Start(); Thread.Sleep(delay * 2); profiler.Stop(); Assert.True(profiler.Elapsed.TotalMilliseconds >= delay); profiler.Restart(); Thread.Sleep(delay / 2); profiler.Stop(); Assert.True(profiler.Elapsed.TotalMilliseconds < delay); } } }
using System.Threading; using Xunit; namespace WeihanLi.Common.Test { public class ProfilerTest { [Theory] [InlineData(200)] [InlineData(500)] [InlineData(1000)] public void StopWatchProfileTest(int delay) { var profiler = new StopwatchProfiler(); profiler.Start(); Thread.Sleep(delay * 2); profiler.Stop(); Assert.True(profiler.Elapsed.TotalMilliseconds >= delay); profiler.Restart(); Thread.Sleep(delay / 2); profiler.Stop(); Assert.True(profiler.Elapsed.TotalMilliseconds < delay); } } }
mit
C#
b8378647ff2a1f8d6f14aedbf8c0e77251bc9a9b
change Unit.ToString result
acple/ParsecSharp
ParsecSharp/Core/Unit.cs
ParsecSharp/Core/Unit.cs
using System; namespace ParsecSharp { public readonly struct Unit : IComparable<Unit>, IEquatable<Unit> { public static Unit Instance => default; public int CompareTo(Unit other) => 0; public bool Equals(Unit other) => true; public override bool Equals(object obj) => obj is Unit; public override int GetHashCode() => 0; public override string ToString() => $"<{nameof(Unit)}>"; public static bool operator ==(Unit _, Unit __) => true; public static bool operator !=(Unit _, Unit __) => false; } }
using System; namespace ParsecSharp { public readonly struct Unit : IComparable<Unit>, IEquatable<Unit> { public static Unit Instance => default; public int CompareTo(Unit other) => 0; public bool Equals(Unit other) => true; public override bool Equals(object obj) => obj is Unit; public override int GetHashCode() => 0; public override string ToString() => nameof(Unit); public static bool operator ==(Unit _, Unit __) => true; public static bool operator !=(Unit _, Unit __) => false; } }
mit
C#
010f7021ba0dff937d6dd92c5bfd851636f1c868
Correct names of test methods
danielwertheim/myinfluxdbclient
src/tests/MyInfluxDbClient.UnitTests/ShowSeriesTests.cs
src/tests/MyInfluxDbClient.UnitTests/ShowSeriesTests.cs
using FluentAssertions; using NUnit.Framework; namespace MyInfluxDbClient.UnitTests { public class ShowSeriesTests : UnitTestsOf<ShowSeries> { [Test] public void Generate_Should_return_show_series_When_constructed_empty() { SUT = new ShowSeries(); SUT.Generate().Should().Be("show series"); } [Test] public void Generate_Should_return_show_series_with_measurement_When_from_is_specified() { SUT = new ShowSeries().FromMeasurement("orderCreated"); SUT.Generate().Should().Be("show series from \"orderCreated\""); } [Test] public void Generate_Should_return_show_series_with_where_When_where_is_specified() { SUT = new ShowSeries().WhereTags("merchant='foo'"); SUT.Generate().Should().Be("show series where merchant='foo'"); } [Test] public void Generate_Should_return_show_series_with_from_and_where_When_from_and_where_are_specified() { SUT = new ShowSeries().FromMeasurement("orderCreated").WhereTags("merchant='foo'"); SUT.Generate().Should().Be("show series from \"orderCreated\" where merchant='foo'"); } } }
using FluentAssertions; using NUnit.Framework; namespace MyInfluxDbClient.UnitTests { public class ShowSeriesTests : UnitTestsOf<ShowSeries> { [Test] public void Generate_Should_return_drop_series_When_constructed_empty() { SUT = new ShowSeries(); SUT.Generate().Should().Be("show series"); } [Test] public void Generate_Should_return_drop_series_with_measurement_When_from_is_specified() { SUT = new ShowSeries().FromMeasurement("orderCreated"); SUT.Generate().Should().Be("show series from \"orderCreated\""); } [Test] public void Generate_Should_return_drop_series_with_where_When_where_is_specified() { SUT = new ShowSeries().WhereTags("merchant='foo'"); SUT.Generate().Should().Be("show series where merchant='foo'"); } [Test] public void Generate_Should_return_drop_series_with_from_and_where_When_from_and_where_are_specified() { SUT = new ShowSeries().FromMeasurement("orderCreated").WhereTags("merchant='foo'"); SUT.Generate().Should().Be("show series from \"orderCreated\" where merchant='foo'"); } } }
mit
C#
9ef0e7ff02793c7c795bada42a00859e237d12fc
Fix wrong zone assignment.
Lombiq/Helpful-Extensions,Lombiq/Helpful-Extensions
Extensions/Flows/Drivers/AdditionalStylingPartDisplay.cs
Extensions/Flows/Drivers/AdditionalStylingPartDisplay.cs
using Lombiq.HelpfulExtensions.Extensions.Flows.Models; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display.ContentDisplay; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Views; using System.Threading.Tasks; namespace Lombiq.HelpfulExtensions.Extensions.Flows.Drivers; public class AdditionalStylingPartDisplay : ContentDisplayDriver { public override IDisplayResult Edit(ContentItem model, IUpdateModel updater) => Initialize<AdditionalStylingPart>( $"{nameof(AdditionalStylingPart)}_Edit", viewModel => PopulateViewModel(model, viewModel)) .PlaceInZone("Footer", 3); public override async Task<IDisplayResult> UpdateAsync(ContentItem model, IUpdateModel updater) { var additionalStylingPart = model.As<AdditionalStylingPart>(); if (additionalStylingPart == null) { return null; } await model.AlterAsync<AdditionalStylingPart>(model => updater.TryUpdateModelAsync(model, Prefix)); return await EditAsync(model, updater); } private static void PopulateViewModel(ContentItem model, AdditionalStylingPart viewModel) { var additionalStylingPart = model.As<AdditionalStylingPart>(); if (additionalStylingPart != null) { viewModel.CustomClasses = additionalStylingPart.CustomClasses; viewModel.RemoveGridExtensionClasses = additionalStylingPart.RemoveGridExtensionClasses; } } }
using Lombiq.HelpfulExtensions.Extensions.Flows.Models; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display.ContentDisplay; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Views; using System.Threading.Tasks; namespace Lombiq.HelpfulExtensions.Extensions.Flows.Drivers; public class AdditionalStylingPartDisplay : ContentDisplayDriver { public override IDisplayResult Edit(ContentItem model, IUpdateModel updater) => Initialize<AdditionalStylingPart>( $"{nameof(AdditionalStylingPart)}_Edit", viewModel => PopulateViewModel(model, viewModel)) .PlaceInContent(3); public override async Task<IDisplayResult> UpdateAsync(ContentItem model, IUpdateModel updater) { var additionalStylingPart = model.As<AdditionalStylingPart>(); if (additionalStylingPart == null) { return null; } await model.AlterAsync<AdditionalStylingPart>(model => updater.TryUpdateModelAsync(model, Prefix)); return await EditAsync(model, updater); } private static void PopulateViewModel(ContentItem model, AdditionalStylingPart viewModel) { var additionalStylingPart = model.As<AdditionalStylingPart>(); if (additionalStylingPart != null) { viewModel.CustomClasses = additionalStylingPart.CustomClasses; viewModel.RemoveGridExtensionClasses = additionalStylingPart.RemoveGridExtensionClasses; } } }
bsd-3-clause
C#
76e6196534f3d41643b074e22650996eeb4617ec
clean code
vostok/core
Vostok.Core.Tests/RetriableCall/ExceptionFinder_Tests.cs
Vostok.Core.Tests/RetriableCall/ExceptionFinder_Tests.cs
using System; using System.Collections.Generic; using System.IO; using NUnit.Framework; namespace Vostok.RetriableCall { public class ExceptionFinder_Tests { private static IEnumerable<object[]> GenerateTestCases() { var invalidDataException = new InvalidDataException("invdata"); var invalidOperationException = new InvalidOperationException("invop"); var aggregateException = new AggregateException("agg", invalidOperationException, invalidDataException); yield return new object[] { "rootEx", aggregateException, (Func<Exception, bool>) (ex => ex is AggregateException), aggregateException }; yield return new object[] { "abscentEx", aggregateException, (Func<Exception, bool>) (ex => ex is OutOfMemoryException), null }; yield return new object[] { "condition", aggregateException, (Func<Exception, bool>) (ex => ex.Message == "invdata"), invalidDataException }; yield return new object[] { "wrongCondition", aggregateException, (Func<Exception, bool>) (ex => ex.Message == "sdfkjdhslkj"), null }; var invalidOperationException2 = new InvalidOperationException("op2"); var aggregateException2 = new AggregateException("agg2", aggregateException, invalidOperationException2); var complexEx = new ArgumentException("arg", aggregateException2); yield return new object[] { "nestedEx", complexEx, (Func<Exception, bool>) (ex => ex is InvalidOperationException), invalidOperationException }; yield return new object[] { "nestedEx", complexEx, (Func<Exception, bool>) (ex => ex is AggregateException), aggregateException2 }; } [TestCaseSource(nameof(GenerateTestCases))] public void FindFirstTests(string testCase, Exception ex, Func<Exception,bool> condition, Exception result) { var firstException = ex.FindFirstException(condition); Assert.AreEqual(result, firstException); } } }
using System; using System.Collections.Generic; using System.IO; using NUnit.Framework; namespace Vostok.RetriableCall { public class ExceptionFinder_Tests { private static IEnumerable<object[]> GenerateTestCases() { var invalidDataException = new InvalidDataException("invdata"); var invalidOperationException = new InvalidOperationException("invop"); var aggregateException = new AggregateException("agg", invalidOperationException, invalidDataException); yield return new object[] { "rootEx", aggregateException, (Func<Exception, bool>) (ex => ex is AggregateException), aggregateException }; yield return new object[] { "abscentEx", aggregateException, (Func<Exception, bool>) (ex => ex is OutOfMemoryException), null }; yield return new object[] { "condition", aggregateException, (Func<Exception, bool>) (ex => ex.Message == "invdata"), invalidDataException }; yield return new object[] { "wrongCondition", aggregateException, (Func<Exception, bool>) (ex => ex.Message == "sdfkjdhslkj"), null }; var invalidOperationException2 = new InvalidOperationException("op2"); var aggregateException2 = new AggregateException("agg2", aggregateException, invalidOperationException2); var complexEx = new ArgumentException("arg", aggregateException2); yield return new object[] { "nestedEx", complexEx, (Func<Exception, bool>) (ex => ex is InvalidOperationException), invalidOperationException }; yield return new object[] { "nestedEx", complexEx, (Func<Exception, bool>) (ex => ex is AggregateException), aggregateException2 }; } [Test, TestCaseSource(nameof(GenerateTestCases))] public void FindFirstTests(string testCase, Exception ex, Func<Exception,bool> condition, Exception result) { var firstException = ex.FindFirstException(condition); Assert.AreEqual(result, firstException); } } }
mit
C#
2cf248b139e1cf036a9888d6fb6d2ba819f68d39
Add proptotyping changes to file userAuth.cpl.cs
ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate
userAuth.cpl/userAuth.cpl/userAuth.cpl.cs
userAuth.cpl/userAuth.cpl/userAuth.cpl.cs
using System; using Xamarin.Forms; namespace userAuth.cpl { public class App : Application { public App () { // The root page of your application MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { XAlign = TextAlignment.Center, Text = "Welcome to Xamarin Forms!" } } } }; } protected override void OnStart () { // Handle when your app starts } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } protected void OnClick () { // Handle click send to your app } public class StackOrientationMod : Element.Constraint/|\(InputPr) { // Modify the stack orient command } public class ClickRef : IViewController { public ClickRef () { IVisualElementController = Element.ContentPage() { Attribute.ReferenceEquals}:(bool){ object OnClick(); object OnRelease(); } } Setter. StackOrientation from object(values.ascending, value) }
using System; using Xamarin.Forms; namespace userAuth.cpl { public class App : Application { public App () { // The root page of your application MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { XAlign = TextAlignment.Center, Text = "Welcome to Xamarin Forms!" } } } }; } protected override void OnStart () { // Handle when your app starts } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } protected void OnClick () { // Handle click send to your app } public class ClickRef : IViewController { public ClickRef () { IVisualElementController = Element.ContentPage() { Attribute.ReferenceEquals}:(bool){ object OnClick(); object OnRelease(); } } }
mit
C#
c5986bc8bf0b814e3c046b74b4b8c62d77806408
Create health value field
bartlomiejwolk/Health
HealthComponent/Health.cs
HealthComponent/Health.cs
using UnityEngine; using System.Collections; namespace HealthEx.HealthComponent { public sealed class Health : MonoBehaviour { #region CONSTANTS public const string Version = "v0.1.0"; public const string Extension = "Health"; #endregion #region DELEGATES #endregion #region EVENTS #endregion #region FIELDS #pragma warning disable 0414 /// <summary> /// Allows identify component in the scene file when reading it with /// text editor. /// </summary> [SerializeField] private string componentName = "Health"; #pragma warning restore0414 #endregion #region INSPECTOR FIELDS [SerializeField] private string description = "Description"; [SerializeField] private int healthValue = 100; #endregion #region PROPERTIES /// <summary> /// Optional text to describe purpose of this instance of the component. /// </summary> public string Description { get { return description; } set { description = value; } } /// <summary> /// Health value. /// </summary> public int HealthValue { get { return healthValue; } set { healthValue = value; } } #endregion #region UNITY MESSAGES private void Awake() { } private void FixedUpdate() { } private void LateUpdate() { } private void OnEnable() { } private void Reset() { } private void Start() { } private void Update() { } private void OnValidate() { } #endregion #region EVENT INVOCATORS #endregion #region EVENT HANDLERS #endregion #region METHODS #endregion } }
using UnityEngine; using System.Collections; namespace HealthEx.HealthComponent { public sealed class Health : MonoBehaviour { #region CONSTANTS public const string Version = "v0.1.0"; public const string Extension = "Health"; #endregion #region DELEGATES #endregion #region EVENTS #endregion #region FIELDS #pragma warning disable 0414 /// <summary> /// Allows identify component in the scene file when reading it with /// text editor. /// </summary> [SerializeField] private string componentName = "Health"; #pragma warning restore0414 #endregion #region INSPECTOR FIELDS [SerializeField] private string description = "Description"; #endregion #region PROPERTIES /// <summary> /// Optional text to describe purpose of this instance of the component. /// </summary> public string Description { get { return description; } set { description = value; } } #endregion #region UNITY MESSAGES private void Awake() { } private void FixedUpdate() { } private void LateUpdate() { } private void OnEnable() { } private void Reset() { } private void Start() { } private void Update() { } private void OnValidate() { } #endregion #region EVENT INVOCATORS #endregion #region EVENT HANDLERS #endregion #region METHODS #endregion } }
mit
C#
ac585cec26a9c55864e091f941256a5e6e3cfda9
Fix attemp for the Flags Issue inside the CountryListBox.
moorehojer/YAFNET,YAFNET/YAFNET,mexxanit/YAFNET,mexxanit/YAFNET,Pathfinder-Fr/YAFNET,moorehojer/YAFNET,moorehojer/YAFNET,Pathfinder-Fr/YAFNET,mexxanit/YAFNET,YAFNET/YAFNET,YAFNET/YAFNET,Pathfinder-Fr/YAFNET,YAFNET/YAFNET
yafsrc/YAF.Controls/CountryListBox.cs
yafsrc/YAF.Controls/CountryListBox.cs
/* Yet Another Forum.NET * Copyright (C) 2006-2011 Jaben Cargman * http://www.yetanotherforum.net/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ namespace YAF.Controls { #region Using using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; using YAF.Utils; #endregion /// <summary> /// Custom DropDown List Controls with Images /// </summary> public class CountryListBox : DropDownList { #region Methods /// <summary> /// Add Flag Images to Items /// </summary> /// <param name="writer"> /// The writer. /// </param> protected override void Render(HtmlTextWriter writer) { foreach (ListItem item in this.Items.Cast<ListItem>().Where(item => item.Value.IsSet())) { item.Attributes.Add( "title", "{1}resources/images/flags/{0}.png".FormatWith(item.Value, YafForumInfo.ForumClientFileRoot)); } base.Render(writer); } #endregion } }
/* Yet Another Forum.NET * Copyright (C) 2006-2011 Jaben Cargman * http://www.yetanotherforum.net/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ namespace YAF.Controls { #region Using using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; using YAF.Utils; #endregion /// <summary> /// Custom DropDown List Controls with Images /// </summary> public class CountryListBox : DropDownList { #region Methods /// <summary> /// Add Flag Images to Items /// </summary> /// <param name="writer"> /// The writer. /// </param> protected override void Render(HtmlTextWriter writer) { foreach (ListItem item in this.Items.Cast<ListItem>().Where(item => item.Value.IsSet())) { item.Attributes.Add("title", YafForumInfo.GetURLToResource("flags/{0}.png".FormatWith(item.Value))); } base.Render(writer); } #endregion } }
apache-2.0
C#
dc78c68f129ed1413d72f15b7145fd8232fb45bc
Change starting line in script processor to 1 instead of 0 for easier debugging
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
Resources/ScriptLoader.cs
Resources/ScriptLoader.cs
using System; using System.IO; using System.Text; using System.Windows.Forms; using CefSharp; using CefSharp.WinForms; namespace TweetDck.Resources{ static class ScriptLoader{ private const string UrlPrefix = "td:"; public static string LoadResource(string name){ try{ return File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,name),Encoding.UTF8); }catch(Exception ex){ MessageBox.Show("Unfortunately, "+Program.BrandName+" could not load the "+name+" file. The program will continue running with limited functionality.\r\n\r\n"+ex.Message,Program.BrandName+" Has Failed :(",MessageBoxButtons.OK,MessageBoxIcon.Error); return null; } } public static void ExecuteFile(ChromiumWebBrowser browser, string file){ ExecuteScript(browser,LoadResource(file),"root:"+Path.GetFileNameWithoutExtension(file)); } public static void ExecuteFile(IFrame frame, string file){ ExecuteScript(frame,LoadResource(file),"root:"+Path.GetFileNameWithoutExtension(file)); } public static void ExecuteScript(ChromiumWebBrowser browser, string script, string identifier){ if (script == null)return; using(IFrame frame = browser.GetMainFrame()){ frame.ExecuteJavaScriptAsync(script,UrlPrefix+identifier,1); } } public static void ExecuteScript(IFrame frame, string script, string identifier){ if (script == null)return; frame.ExecuteJavaScriptAsync(script,UrlPrefix+identifier,1); } } }
using System; using System.IO; using System.Text; using System.Windows.Forms; using CefSharp; using CefSharp.WinForms; namespace TweetDck.Resources{ static class ScriptLoader{ private const string UrlPrefix = "td:"; public static string LoadResource(string name){ try{ return File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,name),Encoding.UTF8); }catch(Exception ex){ MessageBox.Show("Unfortunately, "+Program.BrandName+" could not load the "+name+" file. The program will continue running with limited functionality.\r\n\r\n"+ex.Message,Program.BrandName+" Has Failed :(",MessageBoxButtons.OK,MessageBoxIcon.Error); return null; } } public static void ExecuteFile(ChromiumWebBrowser browser, string file){ ExecuteScript(browser,LoadResource(file),"root:"+Path.GetFileNameWithoutExtension(file)); } public static void ExecuteFile(IFrame frame, string file){ ExecuteScript(frame,LoadResource(file),"root:"+Path.GetFileNameWithoutExtension(file)); } public static void ExecuteScript(ChromiumWebBrowser browser, string script, string identifier){ if (script == null)return; using(IFrame frame = browser.GetMainFrame()){ frame.ExecuteJavaScriptAsync(script,UrlPrefix+identifier); } } public static void ExecuteScript(IFrame frame, string script, string identifier){ if (script == null)return; frame.ExecuteJavaScriptAsync(script,UrlPrefix+identifier); } } }
mit
C#
3e03a6c98b673c3622e31339ab3d3f9c00ea9489
Fix for segfault on end of Qt test
TobiasKappe/Selene,TobiasKappe/Selene
Selene.Testing/Harness.cs
Selene.Testing/Harness.cs
using System; using NUnit.Framework; using Gtk; using Qyoto; namespace Selene.Testing { [TestFixture] public partial class Harness { [TestFixtureSetUp] public void Setup() { #if GTK string[] Dummy = new string[] { }; Init.Check(ref Dummy); #endif #if QYOTO new QApplication(new string[] { } ); #endif } [TestFixtureTearDown] public void Teardown() { QApplication.Exec(); } } }
using System; using NUnit.Framework; using Gtk; using Qyoto; namespace Selene.Testing { [TestFixture] public partial class Harness { [TestFixtureSetUp] public void Setup() { #if GTK string[] Dummy = new string[] { }; Init.Check(ref Dummy); #endif #if QYOTO new QApplication(new string[] { } ); #endif } } }
mit
C#
68911c571c585aeec48ec5074c2bab081571a5d3
Create a hysteresis observable transform.
s-soltys/PoolVR
Assets/PoolVR/Util/GeneratedSignals.cs
Assets/PoolVR/Util/GeneratedSignals.cs
using System; using System.Collections; using System.Collections.Generic; using UniRx; using UnityEngine; public static class GeneratedSignals { public static IObservable<float> CreateTriangleSignal(float period) { return Observable.IntervalFrame(1, FrameCountType.Update) .Scan(0f, (c, _) => c + Time.deltaTime) .Select(t => (period - Mathf.Abs(t % (2 * period) - period)) / period); } public static IObservable<bool> Hysteresis<T>(this IObservable<T> obs, Func<T, T, float> compare, T enter, T exit, bool initialState = false) { return obs.Scan(initialState, (state, value) => { var switchState = (state && compare(value, exit) < 0) || (!state && compare(value, enter) > 0); return switchState ? !state : state; }) .DistinctUntilChanged(); } }
using System.Collections; using System.Collections.Generic; using UniRx; using UnityEngine; public class GeneratedSignals { public static IObservable<float> CreateTriangleSignal(float period) { return Observable.IntervalFrame(1, FrameCountType.Update) .Scan(0f, (c, _) => c + Time.deltaTime) .Select(t => (period - Mathf.Abs(t % (2 * period) - period)) / period); } }
mit
C#
aba6968c961e24f0bb1935ed3534502b343a411e
Fix media player allocation error
danielchalmers/DesktopWidgets
DesktopWidgets/Classes/MediaPlayerStore.cs
DesktopWidgets/Classes/MediaPlayerStore.cs
using System.Collections.Generic; using System.IO; using System.Threading; using DesktopWidgets.Properties; using WMPLib; namespace DesktopWidgets.Classes { public static class MediaPlayerStore { private static readonly List<WindowsMediaPlayer> MediaPlayers = new List<WindowsMediaPlayer> { new WindowsMediaPlayer() }; private static WindowsMediaPlayer GetAvailablePlayer() { try { for (var i = 0; i < Settings.Default.MaxConcurrentMediaPlayers; i++) { if (MediaPlayers.Count - 1 >= i && MediaPlayers[i] == null) MediaPlayers.RemoveAt(i); if (MediaPlayers.Count - 1 < i) MediaPlayers.Add(new WindowsMediaPlayer()); if (MediaPlayers[i].playState != WMPPlayState.wmppsPlaying) return MediaPlayers[i]; } } catch { // ignored } return MediaPlayers[0]; } public static void PlaySoundAsync(string path, double volume = 1) { new Thread(delegate() { Play(path, volume); }).Start(); } public static void Play(string path, double volume = 1) { if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) return; var player = GetAvailablePlayer(); player.settings.volume = (int) (volume*100); player.URL = path; } } }
using System.Collections.Generic; using System.IO; using System.Threading; using DesktopWidgets.Properties; using WMPLib; namespace DesktopWidgets.Classes { public static class MediaPlayerStore { private static readonly List<WindowsMediaPlayer> _mediaPlayerList = new List<WindowsMediaPlayer>(); private static WindowsMediaPlayer GetAvailablePlayer() { try { for (var i = 0; i < Settings.Default.MaxConcurrentMediaPlayers; i++) { if (_mediaPlayerList.Count - 1 < i) _mediaPlayerList.Add(new WindowsMediaPlayer()); if (_mediaPlayerList[i].playState != WMPPlayState.wmppsPlaying) return _mediaPlayerList[i]; } } catch { // ignored } return _mediaPlayerList[0]; } public static void PlaySoundAsync(string path, double volume = 1) { new Thread(delegate() { Play(path, volume); }).Start(); } public static void Play(string path, double volume = 1) { var player = GetAvailablePlayer(); if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) return; player.settings.volume = (int) (volume*100); player.URL = path; } } }
apache-2.0
C#
781556b927ec887aaf2738f557ba4876e25d611d
Archive build task fix Process.Start
hatton/libpalaso,ddaspit/libpalaso,gmartin7/libpalaso,hatton/libpalaso,JohnThomson/libpalaso,JohnThomson/libpalaso,andrew-polk/libpalaso,ddaspit/libpalaso,tombogle/libpalaso,tombogle/libpalaso,marksvc/libpalaso,ermshiperete/libpalaso,ermshiperete/libpalaso,gmartin7/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso,gtryus/libpalaso,hatton/libpalaso,darcywong00/libpalaso,glasseyes/libpalaso,ermshiperete/libpalaso,hatton/libpalaso,chrisvire/libpalaso,ddaspit/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,darcywong00/libpalaso,chrisvire/libpalaso,glasseyes/libpalaso,ddaspit/libpalaso,sillsdev/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,andrew-polk/libpalaso,marksvc/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,mccarthyrb/libpalaso,darcywong00/libpalaso,JohnThomson/libpalaso,mccarthyrb/libpalaso,tombogle/libpalaso,chrisvire/libpalaso,ermshiperete/libpalaso,sillsdev/libpalaso,gtryus/libpalaso,marksvc/libpalaso,sillsdev/libpalaso,gtryus/libpalaso,glasseyes/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,JohnThomson/libpalaso,chrisvire/libpalaso
Palaso.MSBuildTasks/Archive/Archive.cs
Palaso.MSBuildTasks/Archive/Archive.cs
using System; using System.Diagnostics; using System.IO; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Palaso.BuildTasks.Archive { public class Archive : Task { [Required] public ITaskItem[] InputFilePaths { get; set; } [Required] public string Command { get; set; } [Required] public string OutputFileName { get; set; } public string BasePath { get; set; } public string WorkingDir { get; set; } public override bool Execute() { string filePathString = FlattenFilePaths(InputFilePaths, ' ', false); var startInfo = new ProcessStartInfo(ExecutableName()); startInfo.Arguments = Arguments() + " " + filePathString; startInfo.WorkingDirectory = String.IsNullOrEmpty(WorkingDir) ? BasePath : WorkingDir; Process.Start(startInfo); return true; } internal string ExecutableName() { switch (Command) { case "Tar": return "tar"; } return String.Empty; } internal string Arguments() { switch (Command) { case "Tar": return "-cvzf " + OutputFileName; } return String.Empty; } internal string TrimBaseFromFilePath(string filePath) { string result = filePath; if (result.StartsWith(BasePath)) { result = filePath.Substring(BasePath.Length); if (result.StartsWith("/") || result.StartsWith("\\")) result = result.TrimStart(new[] {'/', '\\'}); } return result; } internal string FlattenFilePaths(ITaskItem[] items, char delimeter, bool withQuotes) { var sb = new StringBuilder(); bool haveStarted = false; foreach (var item in items) { if (haveStarted) { sb.Append(delimeter); } string filePath = TrimBaseFromFilePath(item.ItemSpec); if (filePath.Contains(" ") || withQuotes) { sb.Append('"'); sb.Append(filePath); sb.Append('"'); } else { sb.Append(filePath); } haveStarted = true; } return sb.ToString(); } private void SafeLog(string msg, params object[] args) { try { Debug.WriteLine(string.Format(msg,args)); Log.LogMessage(msg,args); } catch (Exception) { //swallow... logging fails in the unit test environment, where the log isn't really set up } } } }
using System; using System.Diagnostics; using System.IO; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Palaso.BuildTasks.Archive { public class Archive : Task { [Required] public ITaskItem[] InputFilePaths { get; set; } [Required] public string Command { get; set; } [Required] public string OutputFileName { get; set; } public string BasePath { get; set; } public string WorkingDir { get; set; } public override bool Execute() { string filePathString = FlattenFilePaths(InputFilePaths, ' ', false); var startInfo = new ProcessStartInfo(ExecutableName()); startInfo.Arguments = Arguments() + " " + filePathString; startInfo.WorkingDirectory = String.IsNullOrEmpty(WorkingDir) ? BasePath : WorkingDir; Process.Start(ExecutableName(), Arguments() + " " + filePathString); return true; } internal string ExecutableName() { switch (Command) { case "Tar": return "tar"; } return String.Empty; } internal string Arguments() { switch (Command) { case "Tar": return "-cvzf " + OutputFileName; } return String.Empty; } internal string TrimBaseFromFilePath(string filePath) { string result = filePath; if (result.StartsWith(BasePath)) { result = filePath.Substring(BasePath.Length); if (result.StartsWith("/") || result.StartsWith("\\")) result = result.TrimStart(new[] {'/', '\\'}); } return result; } internal string FlattenFilePaths(ITaskItem[] items, char delimeter, bool withQuotes) { var sb = new StringBuilder(); bool haveStarted = false; foreach (var item in items) { if (haveStarted) { sb.Append(delimeter); } string filePath = TrimBaseFromFilePath(item.ItemSpec); if (filePath.Contains(" ") || withQuotes) { sb.Append('"'); sb.Append(filePath); sb.Append('"'); } else { sb.Append(filePath); } haveStarted = true; } return sb.ToString(); } private void SafeLog(string msg, params object[] args) { try { Debug.WriteLine(string.Format(msg,args)); Log.LogMessage(msg,args); } catch (Exception) { //swallow... logging fails in the unit test environment, where the log isn't really set up } } } }
mit
C#
a074aa86869b77500b3e574967e903f102e21cec
Allow broken Organization->Parent link
ucdavis/Purchasing,ucdavis/Purchasing,ucdavis/Purchasing
Purchasing.Core/Domain/Organization.cs
Purchasing.Core/Domain/Organization.cs
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using FluentNHibernate.Mapping; using UCDArch.Core.DomainModel; namespace Purchasing.Core.Domain { public class Organization : DomainObjectWithTypedId<string> { public Organization() { Accounts = new List<Account>(); ConditionalApprovals = new List<ConditionalApproval>(); Workgroups = new List<Workgroup>(); CustomFields = new List<CustomField>(); } [Required] [StringLength(50)] public virtual string Name { get; set; } [Required] [StringLength(1)] public virtual string TypeCode { get; set; } [Required] [StringLength(50)] public virtual string TypeName { get; set; } public virtual bool IsActive { get; set; } public virtual Organization Parent { get; set; } public virtual IList<Account> Accounts { get; set; } public virtual IList<ConditionalApproval> ConditionalApprovals { get; set; } public virtual IList<Workgroup> Workgroups { get; set; } public virtual IList<CustomField> CustomFields { get; set; } } public class OrganizationMap : ClassMap<Organization> { public OrganizationMap() { ReadOnly(); Table("vOrganizations"); Id(x => x.Id).GeneratedBy.Assigned(); //ID is 4 characters Map(x => x.Name); Map(x => x.TypeCode); Map(x => x.TypeName); Map(x => x.IsActive); References(x => x.Parent).Column("ParentId").NotFound.Ignore(); HasMany(a => a.Accounts); HasMany(a => a.ConditionalApprovals).Inverse().ExtraLazyLoad().Cascade.AllDeleteOrphan(); HasManyToMany(x => x.Workgroups).Table("WorkgroupsXOrganizations").ParentKeyColumn("OrganizationId"). ChildKeyColumn("WorkgroupId").ExtraLazyLoad(); HasMany(x => x.CustomFields).Inverse().ExtraLazyLoad(); } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using FluentNHibernate.Mapping; using UCDArch.Core.DomainModel; namespace Purchasing.Core.Domain { public class Organization : DomainObjectWithTypedId<string> { public Organization() { Accounts = new List<Account>(); ConditionalApprovals = new List<ConditionalApproval>(); Workgroups = new List<Workgroup>(); CustomFields = new List<CustomField>(); } [Required] [StringLength(50)] public virtual string Name { get; set; } [Required] [StringLength(1)] public virtual string TypeCode { get; set; } [Required] [StringLength(50)] public virtual string TypeName { get; set; } public virtual bool IsActive { get; set; } public virtual Organization Parent { get; set; } public virtual IList<Account> Accounts { get; set; } public virtual IList<ConditionalApproval> ConditionalApprovals { get; set; } public virtual IList<Workgroup> Workgroups { get; set; } public virtual IList<CustomField> CustomFields { get; set; } } public class OrganizationMap : ClassMap<Organization> { public OrganizationMap() { ReadOnly(); Table("vOrganizations"); Id(x => x.Id).GeneratedBy.Assigned(); //ID is 4 characters Map(x => x.Name); Map(x => x.TypeCode); Map(x => x.TypeName); Map(x => x.IsActive); References(x => x.Parent).Column("ParentId"); HasMany(a => a.Accounts); HasMany(a => a.ConditionalApprovals).Inverse().ExtraLazyLoad().Cascade.AllDeleteOrphan(); HasManyToMany(x => x.Workgroups).Table("WorkgroupsXOrganizations").ParentKeyColumn("OrganizationId"). ChildKeyColumn("WorkgroupId").ExtraLazyLoad(); HasMany(x => x.CustomFields).Inverse().ExtraLazyLoad(); } } }
mit
C#
6f2cf2d9a55d80f5e42cfabdd8ffd5fa1749cebe
handle paths with non-BMP characters
milleniumbug/Taxonomy
TaxonomyWpf/NativeExplorerInterface.cs
TaxonomyWpf/NativeExplorerInterface.cs
using System; using System.Drawing; using System.Runtime.InteropServices; namespace TaxonomyWpf { public static class NativeExplorerInterface { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct SHFILEINFO { public IntPtr hIcon; public int iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; }; private const uint SHGFI_ICON = 0x100; private const uint SHGFI_LARGEICON = 0x0; // 'Large icon private const uint SHGFI_SMALLICON = 0x1; // 'Small icon [DllImport("shell32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr SHGetFileInfo( string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); [DllImport("user32.dll")] private static extern bool DestroyIcon(IntPtr handle); public sealed class HIcon : IDisposable { public IntPtr IconHandle { get; private set; } public void Dispose() { DestroyIcon(IconHandle); IconHandle = IntPtr.Zero; } public HIcon(IntPtr iconHandle) { IconHandle = iconHandle; } } public static void OpenContextMenuForFile(string path) { } public static HIcon GetHIconForFile(string path) { IntPtr hImg; string fName = path; SHFILEINFO shinfo = new SHFILEINFO(); hImg = SHGetFileInfo( fName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON); // TODO: "You should call this function from a background thread. Failure to do so could cause the UI to stop responding." return new HIcon(shinfo.hIcon); } } }
using System; using System.Drawing; using System.Runtime.InteropServices; namespace TaxonomyWpf { public static class NativeExplorerInterface { [StructLayout(LayoutKind.Sequential)] private struct SHFILEINFO { public IntPtr hIcon; public int iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; }; private const uint SHGFI_ICON = 0x100; private const uint SHGFI_LARGEICON = 0x0; // 'Large icon private const uint SHGFI_SMALLICON = 0x1; // 'Small icon [DllImport("shell32.dll")] private static extern IntPtr SHGetFileInfo( string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); [DllImport("user32.dll")] private static extern bool DestroyIcon(IntPtr handle); public sealed class HIcon : IDisposable { public IntPtr IconHandle { get; private set; } public void Dispose() { DestroyIcon(IconHandle); IconHandle = IntPtr.Zero; } public HIcon(IntPtr iconHandle) { IconHandle = iconHandle; } } public static void OpenContextMenuForFile(string path) { } public static HIcon GetHIconForFile(string path) { IntPtr hImg; string fName = path; SHFILEINFO shinfo = new SHFILEINFO(); hImg = SHGetFileInfo( fName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON); // TODO: "You should call this function from a background thread. Failure to do so could cause the UI to stop responding." return new HIcon(shinfo.hIcon); } } }
mit
C#
b67372a10c2e8362d010d23c7aa901858f5c0db4
Add ability to specify xml root without decorating the target class.
bfriesen/Rock.Messaging,peteraritchie/Rock.Messaging,RockFramework/Rock.Messaging
Rock.Messaging/Routing/XmlMessageParser.cs
Rock.Messaging/Routing/XmlMessageParser.cs
using System; using System.Collections.Concurrent; using System.IO; using System.Text.RegularExpressions; using System.Xml.Serialization; namespace Rock.Messaging.Routing { public class XmlMessageParser : IMessageParser { private readonly ConcurrentDictionary<Type, XmlRootAttribute> _xmlRootAttributes = new ConcurrentDictionary<Type, XmlRootAttribute>(); public void RegisterXmlRoot(Type messageType, string xmlRootElementName) { if (string.IsNullOrWhiteSpace(xmlRootElementName)) { XmlRootAttribute dummy; _xmlRootAttributes.TryRemove(messageType, out dummy); } else { _xmlRootAttributes.AddOrUpdate( messageType, t => new XmlRootAttribute(xmlRootElementName), (t, a) => new XmlRootAttribute(xmlRootElementName)); } } public string GetTypeName(Type messageType) { XmlRootAttribute xmlRootAttribute; if (!_xmlRootAttributes.TryGetValue(messageType, out xmlRootAttribute)) { xmlRootAttribute = Attribute.GetCustomAttribute(messageType, typeof(XmlRootAttribute)) as XmlRootAttribute; } return xmlRootAttribute != null && !string.IsNullOrWhiteSpace(xmlRootAttribute.ElementName) ? xmlRootAttribute.ElementName : messageType.Name; } public string GetTypeName(string rawMessage) { var match = Regex.Match(rawMessage, @"<([a-zA-Z_][a-zA-Z0-9]*)[ >/]"); if (!match.Success) { throw new ArgumentException("Unable to find root xml element.", "rawMessage"); } return match.Groups[1].Value; } public object DeserializeMessage(string rawMessage, Type messageType) { using (var reader = new StringReader(rawMessage)) { return GetXmlSerializer(messageType).Deserialize(reader); } } private XmlSerializer GetXmlSerializer(Type messageType) { XmlRootAttribute xmlRootAttribute; return _xmlRootAttributes.TryGetValue(messageType, out xmlRootAttribute) ? new XmlSerializer(messageType, xmlRootAttribute) : new XmlSerializer(messageType); } } }
using System; using System.IO; using System.Text.RegularExpressions; using System.Xml.Serialization; namespace Rock.Messaging.Routing { public class XmlMessageParser : IMessageParser { public string GetTypeName(Type type) { var xmlRootAttribute = Attribute.GetCustomAttribute(type, typeof(XmlRootAttribute)) as XmlRootAttribute; return xmlRootAttribute != null && !string.IsNullOrWhiteSpace(xmlRootAttribute.ElementName) ? xmlRootAttribute.ElementName : type.Name; } public string GetTypeName(string rawMessage) { var match = Regex.Match(rawMessage, @"<([a-zA-Z_][a-zA-Z0-9]*)[ >/]"); if (!match.Success) { throw new ArgumentException("Unable to find root xml element.", "rawMessage"); } return match.Groups[1].Value; } public object DeserializeMessage(string rawMessage, Type messageType) { var serializer = new XmlSerializer(messageType); using (var reader = new StringReader(rawMessage)) { return serializer.Deserialize(reader); } } } }
mit
C#
c09560332bff3d7343832a199e8957a4472aa551
allow to specify return type for ctor delegate
rolembergfilho/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,linpiero/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,volkanceylan/Serenity,linpiero/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,linpiero/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,linpiero/Serenity,linpiero/Serenity,dfaruque/Serenity
Serenity.Core/Reflection/FastReflection.cs
Serenity.Core/Reflection/FastReflection.cs
using System; using System.Reflection.Emit; namespace Serenity.Reflection { public static class FastReflection { public static Func<object> DelegateForConstructor(Type type) { return DelegateForConstructor<object>(type); } public static Func<TReturn> DelegateForConstructor<TReturn>(Type type) { var ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) throw new MissingMethodException(String.Format( "There is no parameterless constructor for type {0}", type)); var dm = new DynamicMethod("ctor0", type, Type.EmptyTypes); ILGenerator il = dm.GetILGenerator(); il.DeclareLocal(type); il.Emit(OpCodes.Newobj, ctor); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ret); return (Func<TReturn>)dm.CreateDelegate(typeof(Func<TReturn>)); } } }
using System; using System.Reflection.Emit; namespace Serenity.Reflection { public static class FastReflection { public static Func<object> DelegateForConstructor(Type type) { var ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) throw new MissingMethodException(String.Format( "There is no parameterless constructor for type {0}", type)); var dm = new DynamicMethod("ctor0", type, Type.EmptyTypes); ILGenerator il = dm.GetILGenerator(); il.DeclareLocal(type); il.Emit(OpCodes.Newobj, ctor); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ret); return (Func<object>)dm.CreateDelegate(typeof(Func<object>)); } } }
mit
C#
d4b22936af9d406351ce6c54eb16ab333d367bcf
fix net 35
adamhathcock/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress,weltkante/sharpcompress
SharpCompress/Writer/IWriter.Extensions.cs
SharpCompress/Writer/IWriter.Extensions.cs
using System; using System.IO; namespace SharpCompress.Writer { public static class IWriterExtensions { public static void Write(this IWriter writer, string entryPath, Stream source) { writer.Write(entryPath, source, null); } #if !DOTNET51 public static void Write(this IWriter writer, string entryPath, FileInfo source) { if (!source.Exists) { throw new ArgumentException("Source does not exist: " + source.FullName); } using (var stream = source.OpenRead()) { writer.Write(entryPath, stream, source.LastWriteTime); } } public static void Write(this IWriter writer, string entryPath, string source) { writer.Write(entryPath, new FileInfo(source)); } public static void WriteAll(this IWriter writer, string directory, string searchPattern = "*", SearchOption option = SearchOption.TopDirectoryOnly) { if (!Directory.Exists(directory)) { throw new ArgumentException("Directory does not exist: " + directory); } #if NET35 foreach (var file in Directory.GetDirectories(directory, searchPattern, option)) #else foreach (var file in Directory.EnumerateFiles(directory, searchPattern, option)) #endif { writer.Write(file.Substring(directory.Length), file); } } #endif } }
using System; using System.IO; namespace SharpCompress.Writer { public static class IWriterExtensions { public static void Write(this IWriter writer, string entryPath, Stream source) { writer.Write(entryPath, source, null); } #if !DOTNET51 public static void Write(this IWriter writer, string entryPath, FileInfo source) { if (!source.Exists) { throw new ArgumentException("Source does not exist: " + source.FullName); } using (var stream = source.OpenRead()) { writer.Write(entryPath, stream, source.LastWriteTime); } } public static void Write(this IWriter writer, string entryPath, string source) { writer.Write(entryPath, new FileInfo(source)); } public static void WriteAll(this IWriter writer, string directory, string searchPattern = "*", SearchOption option = SearchOption.TopDirectoryOnly) { if (!Directory.Exists(directory)) { throw new ArgumentException("Directory does not exist: " + directory); } foreach (var file in Directory.EnumerateFiles(directory, searchPattern, option)) { writer.Write(file.Substring(directory.Length), file); } } #endif } }
mit
C#
324bd7b8af72589156b237ec8e8948af131d0f67
remove sc from soracoins aliases bcs its also soundcloud
Daniele122898/SoraBot-v2,Daniele122898/SoraBot-v2
SoraBot-v2/SoraBot-v2/Module/CoinModule.cs
SoraBot-v2/SoraBot-v2/Module/CoinModule.cs
using System; using System.Threading.Tasks; using Discord.Commands; using Discord.WebSocket; using Humanizer; using Humanizer.Localisation; using SoraBot_v2.Data; using SoraBot_v2.Services; namespace SoraBot_v2.Module { public class CoinModule : ModuleBase<SocketCommandContext> { private CoinService _coinService; public CoinModule(CoinService coinService) { _coinService = coinService; } // Gain coins [Command("daily"), Alias("earn", "dailies"), Summary("Gives you a daily reward of Sora Coins")] public async Task GetDaily() { await _coinService.DoDaily(Context); } // give coins [Command("send"), Alias("transfer", "sctransfer", "sendcoins", "sendsc", "give"), Summary("Sends specified amount of sc to specified user")] public async Task SendCoins(int amount, ulong userId) { await _coinService.SendMoney(Context, amount, userId); } [Command("send"), Alias("transfer", "sctransfer", "sendcoins", "sendsc", "give"), Summary("Sends specified amount of sc to specified user")] public async Task SendCoins(int amount, SocketUser user) { await _coinService.SendMoney(Context, amount, user.Id); } // check coins [Command("coins"), Alias("soracoins"), Summary("Check how many Sora coins you have")] public async Task GetCoins() { int amount = _coinService.GetAmount(Context.User.Id); await ReplyAsync("", embed: Utility.ResultFeedback( Utility.BlueInfoEmbed, Utility.SuccessLevelEmoji[4], $"💰 You have {amount.ToString()} Sora Coins." )); } } }
using System; using System.Threading.Tasks; using Discord.Commands; using Discord.WebSocket; using Humanizer; using Humanizer.Localisation; using SoraBot_v2.Data; using SoraBot_v2.Services; namespace SoraBot_v2.Module { public class CoinModule : ModuleBase<SocketCommandContext> { private CoinService _coinService; public CoinModule(CoinService coinService) { _coinService = coinService; } // Gain coins [Command("daily"), Alias("earn", "dailies"), Summary("Gives you a daily reward of Sora Coins")] public async Task GetDaily() { await _coinService.DoDaily(Context); } // give coins [Command("send"), Alias("transfer", "sctransfer", "sendcoins", "sendsc", "give"), Summary("Sends specified amount of sc to specified user")] public async Task SendCoins(int amount, ulong userId) { await _coinService.SendMoney(Context, amount, userId); } [Command("send"), Alias("transfer", "sctransfer", "sendcoins", "sendsc", "give"), Summary("Sends specified amount of sc to specified user")] public async Task SendCoins(int amount, SocketUser user) { await _coinService.SendMoney(Context, amount, user.Id); } // check coins [Command("coins"), Alias("sc", "soracoins"), Summary("Check how many Sora coins you have")] public async Task GetCoins() { int amount = _coinService.GetAmount(Context.User.Id); await ReplyAsync("", embed: Utility.ResultFeedback( Utility.BlueInfoEmbed, Utility.SuccessLevelEmoji[4], $"💰 You have {amount} Sora Coins." )); } } }
agpl-3.0
C#
2c1d60f22eb45fd8abc0519fe7e414e2c8bce8c8
debug lines and code clean
ivrToolkit/ivrToolkit
ivrToolkit.Core/Util/TenantSingleton.cs
ivrToolkit.Core/Util/TenantSingleton.cs
using System; using System.IO; using NLog; namespace ivrToolkit.Core.Util { public class TenantSingleton { private static TenantSingleton _instance; private readonly string _tenantDirectory; private readonly string _tenant = ""; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private TenantSingleton() { Logger.Debug("Starting TenantSingleton"); String[] args = Environment.GetCommandLineArgs(); Logger.Debug($"There are {args.Length} args"); foreach (string s in args) { if (s.StartsWith("-t")) { _tenant = s.Substring(2); Logger.Debug($"Tenant name is {_tenant}"); } } var location = System.Reflection.Assembly.GetExecutingAssembly().Location; location = Path.GetDirectoryName(location); if (location == null) throw new Exception("Executable path not found"); if ((_tenant == null) || (_tenant.Trim().Equals(""))) { _tenantDirectory = location; } else { _tenantDirectory = Path.Combine(location, _tenant); } Logger.Debug($"Tenant directory = {_tenantDirectory}"); } public static TenantSingleton Instance { get { if (_instance == null) { _instance = new TenantSingleton(); } return _instance; } } public string TenantDirectory { get { return _tenantDirectory; } } public string Tenant { get { return _tenant; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace ivrToolkit.Core.Util { public class TenantSingleton { private static TenantSingleton instance; private string _tenantDirectory; private string _tenant = ""; private TenantSingleton() { String[] args = Environment.GetCommandLineArgs(); foreach (string s in args) { if (s.StartsWith("-t")) { _tenant = s.Substring(2); } } var location = System.Reflection.Assembly.GetExecutingAssembly().Location; location = Path.GetDirectoryName(location); if (location == null) throw new Exception("Executable path not found"); if ((_tenant == null) || (_tenant.Trim().Equals(""))) { _tenantDirectory = location; } else { _tenantDirectory = Path.Combine(location, _tenant); } } public static TenantSingleton Instance { get { if (instance == null) { instance = new TenantSingleton(); } return instance; } } public string TenantDirectory { get { return _tenantDirectory; } } public string Tenant { get { return _tenant; } } } }
apache-2.0
C#
080351e7c47ba8b979b3daacd4ec4310b6e7c5d2
Tidy up indent. EF7 sucks, so I'm putting this project on hold until they get their shit together and implement complex types.
tintoy/version-management-v2,tintoy/version-management-v2
src/version-management/DataAccess/Models/VersionRange.cs
src/version-management/DataAccess/Models/VersionRange.cs
using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace DD.Cloud.VersionManagement.DataAccess.Models { public class VersionRange { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] [DefaultValue(VersionComponent.Build)] public VersionComponent IncrementBy { get; set; } = VersionComponent.Build; [Required] public int StartVersionMajor { get; set; } [Required] public int StartVersionMinor { get; set; } [Required] public int StartVersionBuild { get; set; } [Required] public int StartVersionRevision { get; set; } [Required] public int EndVersionMajor { get; set; } [Required] public int EndVersionMinor { get; set; } [Required] public int EndVersionBuild { get; set; } [Required] public int EndVersionRevision { get; set; } public ICollection<Release> Releases { get; set; } } }
using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace DD.Cloud.VersionManagement.DataAccess.Models { public class VersionRange { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] [DefaultValue(VersionComponent.Build)] public VersionComponent IncrementBy { get; set; } = VersionComponent.Build; [Required] public int StartVersionMajor { get; set; } [Required] public int StartVersionMinor { get; set; } [Required] public int StartVersionBuild { get; set; } [Required] public int StartVersionRevision { get; set; } [Required] public int EndVersionMajor { get; set; } [Required] public int EndVersionMinor { get; set; } [Required] public int EndVersionBuild { get; set; } [Required] public int EndVersionRevision { get; set; } public ICollection<Release> Releases { get; set; } } }
mit
C#
0ffc7ace851eda3a1ff02e79e7215815418fe6ba
update version
PxAndy/WpfMultiStyle
WpfMultiStyle/Properties/AssemblyInfo.cs
WpfMultiStyle/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("WpfMultiStyle")] [assembly: AssemblyDescription("Apply multiple styles to one element for WPF.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Px_Andy")] [assembly: AssemblyProduct("WpfMultiStyle")] [assembly: AssemblyCopyright("Copyright © Px_Andy 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("862053ed-9901-4fe5-8ab1-887057d0461a")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("WpfMultiStyle")] [assembly: AssemblyDescription("Apply multiple styles to one element for WPF.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Px_Andy")] [assembly: AssemblyProduct("WpfMultiStyle")] [assembly: AssemblyCopyright("Copyright © Px_Andy 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("862053ed-9901-4fe5-8ab1-887057d0461a")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
25dc603712ef0580061d8ced0f0ef7340eafd0a7
Use GraphicsPath.Clone to get clone
mono/xwt,hamekoz/xwt,TheBrainTech/xwt,sevoku/xwt,akrisiun/xwt,steffenWi/xwt,mminns/xwt,hwthomas/xwt,residuum/xwt,lytico/xwt,iainx/xwt,antmicro/xwt,directhex/xwt,mminns/xwt,cra0zy/xwt
Xwt.WPF/Xwt.WPFBackend/DrawingContext.cs
Xwt.WPF/Xwt.WPFBackend/DrawingContext.cs
// // DrawingContext.cs // // Author: // Eric Maupin <ermau@xamarin.com> // // Copyright (c) 2012 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; namespace Xwt.WPFBackend { internal class DrawingContext { internal DrawingContext (Graphics graphics) { if (graphics == null) throw new ArgumentNullException ("graphics"); Graphics = graphics; } internal DrawingContext (DrawingContext context) { Graphics = context.Graphics; var f = context.Font; Font = new Font (f.FontFamily, f.Size, f.Style, f.Unit, f.GdiCharSet, f.GdiVerticalFont); Pen = new Pen (context.Pen.Brush, context.Pen.Width); Brush = (Brush)context.Brush.Clone (); Path = (GraphicsPath) context.Path.Clone(); CurrentX = context.CurrentX; CurrentY = context.CurrentY; } internal readonly Graphics Graphics; internal Font Font = new Font (FontFamily.GenericSansSerif, 12); internal Pen Pen = new Pen (Color.Black, 1); internal Brush Brush = new SolidBrush (Color.Black); internal float CurrentX; internal float CurrentY; internal GraphicsPath Path = new GraphicsPath(); internal void SetColor (Color color) { Pen.Color = color; Brush = new SolidBrush (color); } internal void Save() { if (this.contexts == null) this.contexts = new Stack<DrawingContext> (); this.contexts.Push (new DrawingContext (this)); } internal void Restore() { if (this.contexts == null || this.contexts.Count == 0) throw new InvalidOperationException(); var dc = this.contexts.Pop (); Font = dc.Font; Pen = dc.Pen; Brush = dc.Brush; Path = dc.Path; CurrentX = dc.CurrentX; CurrentY = dc.CurrentY; } private Stack<DrawingContext> contexts; } }
// // DrawingContext.cs // // Author: // Eric Maupin <ermau@xamarin.com> // // Copyright (c) 2012 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; namespace Xwt.WPFBackend { internal class DrawingContext { internal DrawingContext (Graphics graphics) { if (graphics == null) throw new ArgumentNullException ("graphics"); Graphics = graphics; } internal DrawingContext (DrawingContext context) { Graphics = context.Graphics; var f = context.Font; Font = new Font (f.FontFamily, f.Size, f.Style, f.Unit, f.GdiCharSet, f.GdiVerticalFont); Pen = new Pen (context.Pen.Brush, context.Pen.Width); Brush = (Brush)context.Brush.Clone (); Path = new GraphicsPath (context.Path.PathPoints, context.Path.PathTypes, context.Path.FillMode); CurrentX = context.CurrentX; CurrentY = context.CurrentY; } internal readonly Graphics Graphics; internal Font Font = new Font (FontFamily.GenericSansSerif, 12); internal Pen Pen = new Pen (Color.Black, 1); internal Brush Brush = new SolidBrush (Color.Black); internal float CurrentX; internal float CurrentY; internal GraphicsPath Path = new GraphicsPath(); internal void SetColor (Color color) { Pen.Color = color; Brush = new SolidBrush (color); } internal void Save() { if (this.contexts == null) this.contexts = new Stack<DrawingContext> (); this.contexts.Push (new DrawingContext (this)); } internal void Restore() { if (this.contexts == null || this.contexts.Count == 0) throw new InvalidOperationException(); var dc = this.contexts.Pop (); Font = dc.Font; Pen = dc.Pen; Brush = dc.Brush; Path = dc.Path; CurrentX = dc.CurrentX; CurrentY = dc.CurrentY; } private Stack<DrawingContext> contexts; } }
mit
C#
255b63592057d634656b74add7636a454247ad6f
Update GlobalAssemblyInfo.cs
joelhulen/Polly,michael-wolfenden/Polly
src/GlobalAssemblyInfo.cs
src/GlobalAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyProduct("Polly")] [assembly: AssemblyCompany("App vNext")] [assembly: AssemblyDescription("Polly is a library that allows developers to express transient exception handling policies such as Retry, Retry Forever, Wait and Retry or Circuit Breaker in a fluent manner.")] [assembly: AssemblyCopyright("Copyright (c) 2015, App vNext")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif
using System.Reflection; [assembly: AssemblyProduct("Polly")] [assembly: AssemblyCompany("Michael Wolfenden")] [assembly: AssemblyDescription("Polly is a library that allows developers to express transient exception handling policies such as Retry, Retry Forever, Wait and Retry or Circuit Breaker in a fluent manner.")] [assembly: AssemblyCopyright("Copyright (c) 2015, Michael Wolfenden")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif
bsd-3-clause
C#
67b4886ee2c9cdf959fd6cf03d5ac479fe4bc021
Throw exceptions if calling AsXml or Save on the OrphanProject
den-mentiei/omnisharp-vim,nosami/omnisharp-vim,OmniSharp/omnisharp-vim,OmniSharp/omnisharp-vim,AndBicScadMedia/omnisharp-vim,OmniSharp/omnisharp-vim,anurse/omnisharp-vim
server/OmniSharp/Solution/OrphanProject.cs
server/OmniSharp/Solution/OrphanProject.cs
using System; using System.Collections.Generic; using System.Xml.Linq; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.TypeSystem; namespace OmniSharp.Solution { /// <summary> /// Placeholder that can be used for files that don't belong to a project. /// </summary> public class OrphanProject : IProject { public string Title { get; private set; } public List<CSharpFile> Files { get; private set; } public List<IAssemblyReference> References { get; set; } public IProjectContent ProjectContent { get; set; } public string FileName { get; private set; } private CSharpFile _file; public OrphanProject(ISolution solution) { Title = "Orphan Project"; _file = new CSharpFile(this, "dummy_file", ""); Files = new List<CSharpFile>(); Files.Add(_file); string mscorlib = CSharpProject.FindAssembly(CSharpProject.AssemblySearchPaths, "mscorlib"); ProjectContent = new CSharpProjectContent() .SetAssemblyName("OrphanProject") .AddAssemblyReferences(CSharpProject.LoadAssembly(mscorlib)); } public CSharpFile GetFile(string fileName) { return _file; } public CSharpParser CreateParser() { return new CSharpParser(); } public XDocument AsXml() { throw new NotImplementedException(); } public void Save(XDocument project) { throw new NotImplementedException(); } } }
using System.Collections.Generic; using System.Xml.Linq; using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.TypeSystem; namespace OmniSharp.Solution { /// <summary> /// Placeholder that can be used for files that don't belong to a project. /// </summary> public class OrphanProject : IProject { public string Title { get; private set; } public List<CSharpFile> Files { get; private set; } public List<IAssemblyReference> References { get; set; } public IProjectContent ProjectContent { get; set; } public string FileName { get; private set; } private CSharpFile _file; public OrphanProject(ISolution solution) { Title = "Orphan Project"; _file = new CSharpFile(this, "dummy_file", ""); Files = new List<CSharpFile>(); Files.Add(_file); string mscorlib = CSharpProject.FindAssembly(CSharpProject.AssemblySearchPaths, "mscorlib"); ProjectContent = new CSharpProjectContent() .SetAssemblyName("OrphanProject") .AddAssemblyReferences(CSharpProject.LoadAssembly(mscorlib)); } public CSharpFile GetFile(string fileName) { return _file; } public CSharpParser CreateParser() { return new CSharpParser(); } public XDocument AsXml() { return XDocument.Load(FileName); } public void Save(XDocument project) { project.Save(FileName); } } }
mit
C#
c6a32bea8f4fc4388f0601af3027c37e9f7feddd
fix to normalize virtual paths to match format stored in precompiled lookups
RazorGenerator/RazorGenerator,wizzardmr42/RazorGenerator,RazorGenerator/RazorGenerator
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System; using System.Reflection; [assembly: AssemblyVersion("2.0.0")] [assembly: AssemblyProduct("RazorGenerator")] [assembly: AssemblyCompany("RazorGenerator contributors")] [assembly: AssemblyInformationalVersion("2.3.5")]
using System; using System.Reflection; [assembly: AssemblyVersion("2.0.0")] [assembly: AssemblyProduct("RazorGenerator")] [assembly: AssemblyCompany("RazorGenerator contributors")] [assembly: AssemblyInformationalVersion("2.3.4")]
apache-2.0
C#
bd3a8d8653ee60b07d31859e00cf61ff128a89ae
Use pure in-memory db in development environment
lanfeust69/LanfeustBridge,lanfeust69/LanfeustBridge,lanfeust69/LanfeustBridge,lanfeust69/LanfeustBridge,lanfeust69/LanfeustBridge
Services/DbService.cs
Services/DbService.cs
using LiteDB; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace LanfeustBridge.Services { public class DbService { public DbService(DirectoryService directoryService, IHostingEnvironment hostingEnvironment) { if (hostingEnvironment.IsDevelopment()) { Db = new LiteDatabase(new MemoryStream()); } else { var dataFile = Path.Combine(directoryService.DataDirectory, "lanfeust.db"); Db = new LiteDatabase(dataFile); } } public LiteDatabase Db { get; } } }
using LiteDB; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace LanfeustBridge.Services { public class DbService { public DbService(DirectoryService directoryService) { var dataFile = Path.Combine(directoryService.DataDirectory, "lanfeust.db"); Db = new LiteDatabase(dataFile); } public LiteDatabase Db { get; } } }
mit
C#
d0ae60c3313e35ea84dd8d13d9da9bdd1ebf4eb3
Update ScienceSubject.cs
Anatid/XML-Documentation-for-the-KSP-API
src/ScienceSubject.cs
src/ScienceSubject.cs
using System; /// <summary> /// Class containing information on a specific science result, data stored in the persistent file under the R&D node. /// </summary> [Serializable] public class ScienceSubject : IConfigNode { /// <summary> /// Multiply science value by this dataScale value to determine data amount in mits. /// </summary> public float dataScale; /// <summary> /// Subject ID in Experimentname@CelestialbodyExperimentalsituationBiome format /// </summary> public string id; /// <summary> /// Amount of science already earned from this subject, not updated until after transmission/recovery. /// </summary> public float science; /// <summary> /// Total science allowable for this subject, based on subjectValue. /// </summary> public float scienceCap; /// <summary> /// Diminishing value multiplier for decreasing the science value returned from repeated experiments. /// </summary> public float scientificValue; /// <summary> /// Multiplier for specific Celestial Body/Experiment Situation combination. /// </summary> public float subjectValue; /// <summary> /// Title of science subject, displayed in science archives. /// </summary> public string title; /// <summary> /// Return a Science Subject from Research and Development node in the persistent file. /// </summary> /// <param name="node"></param> public ScienceSubject(ConfigNode node); /// <summary> /// Generate new Science Subject. /// </summary> /// <param name="exp">Science Experiment from ScienceDefs file and ModuleScienceExperiment</param> /// <param name="sit">Current experimantal situation, based on VesselSituation</param> /// <param name="body">Current Celestial Body</param> /// <param name="biome">Current biome if applicable, empty string if not</param> public ScienceSubject(ScienceExperiment exp, ExperimentSituations sit, CelestialBody body, string biome = ""); public ScienceSubject(string id, string title, float dataScale, float subjectValue, float scienceCap); public ScienceSubject(ScienceExperiment exp, ExperimentSituations sit, string sourceUid, string sourceTitle, CelestialBody body, string biome = ""); public void Load(ConfigNode node); public void Save(ConfigNode node); }
#region Assembly Assembly-CSharp.dll, v2.0.50727 // C:\Users\David\Documents\Visual Studio 2010\Projects\KSP Science\KSP DEV\Kerbal Space Program\KSP_Data\Managed\Assembly-CSharp.dll #endregion using System; /// <summary> /// Class containing information on a specific science result, data stored in the persistent file under the R&D node. /// </summary> [Serializable] public class ScienceSubject : IConfigNode { /// <summary> /// Multiply science value by this dataScale value to determine data amount in mits. /// </summary> public float dataScale; /// <summary> /// Subject ID in Experimentname@CelestialbodyExperimentalsituationBiome format /// </summary> public string id; /// <summary> /// Amount of science already earned from this subject, not updated until after transmission/recovery. /// </summary> public float science; /// <summary> /// Total science allowable for this subject, based on subjectValue. /// </summary> public float scienceCap; /// <summary> /// Diminishing value multiplier for decreasing the science value returned from repeated experiments. /// </summary> public float scientificValue; /// <summary> /// Multiplier for specific Celestial Body/Experiment Situation combination. /// </summary> public float subjectValue; /// <summary> /// Title of science subject, displayed in science archives. /// </summary> public string title; /// <summary> /// Return a Science Subject from Research and Development node in the persistent file. /// </summary> /// <param name="node"></param> public ScienceSubject(ConfigNode node); /// <summary> /// Generate new Science Subject. /// </summary> /// <param name="exp">Science Experiment from ScienceDefs file and ModuleScienceExperiment</param> /// <param name="sit">Current experimantal situation, based on VesselSituation</param> /// <param name="body">Current Celestial Body</param> /// <param name="biome">Current biome if applicable, empty string if not</param> public ScienceSubject(ScienceExperiment exp, ExperimentSituations sit, CelestialBody body, string biome = ""); public ScienceSubject(string id, string title, float dataScale, float subjectValue, float scienceCap); public ScienceSubject(ScienceExperiment exp, ExperimentSituations sit, string sourceUid, string sourceTitle, CelestialBody body, string biome = ""); public void Load(ConfigNode node); public void Save(ConfigNode node); }
unlicense
C#
98bbd57fd8abe621b4ca8839e110c9728d9d2b4b
refactor imports
DarthAffe/CUE.NET
Devices/Keyboard/ColorBrushes/IBrush.cs
Devices/Keyboard/ColorBrushes/IBrush.cs
using System.Drawing; namespace CUE.NET.Devices.Keyboard.ColorBrushes { public interface IBrush { Color getColorAtPoint(Point point); } }
using System.Drawing.Color; using System.Drawing.Point; namespace CUE.NET.Devices.Keyboard.ColorBrushes { public interface IBrush { public Color getColorAtPoint(Point point); } }
lgpl-2.1
C#
df63e7d63f0a1b478916d4028fd3d643e1b698fa
Fix version number string
HelloFax/hellosign-dotnet-sdk
HelloSign/Properties/AssemblyInfo.cs
HelloSign/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HelloSign")] [assembly: AssemblyDescription("Client library for using the HelloSign API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HelloSign")] [assembly: AssemblyProduct("HelloSign")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("HelloSign")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c36ca08c-9b2a-4b52-a8ae-03d364d69267")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HelloSign")] [assembly: AssemblyDescription("Client library for using the HelloSign API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HelloSign")] [assembly: AssemblyProduct("HelloSign")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("HelloSign")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c36ca08c-9b2a-4b52-a8ae-03d364d69267")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] //[assembly: AssemblyFileVersion("0.0.0.0")]
mit
C#