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
6526b5596a0dfdffaa0b758f9bf48694935a4e8b
Update IChangeTrackable.cs
joelweiss/ChangeTracking
Source/ChangeTracking/IChangeTrackable.cs
Source/ChangeTracking/IChangeTrackable.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Text; namespace ChangeTracking { public interface IChangeTrackable<T> : IChangeTrackable, IRevertibleChangeTracking { /// <summary> /// Gets the original value of a given property. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="selector">The selector.</param> /// <returns></returns> /// <exception cref="System.ArgumentException"> /// A property selector expression has an incorrect format /// or /// A selected member is not a property /// </exception> TResult GetOriginalValue<TResult>(Expression<Func<T, TResult>> selector); /// <summary> /// Gets the original value of a given property. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="propertyName">Name of the property.</param> /// <returns></returns> TResult GetOriginalValue<TResult>(string propertyName); /// <summary> /// Gets the original value of a given property. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns></returns> object GetOriginalValue(string propertyName); /// <summary> /// Gets the original. /// </summary> /// <returns></returns> /// <exception cref="System.MissingMethodException">The type that is specified for T does not have a parameterless constructor.</exception> T GetOriginal(); } public interface IChangeTrackable : INotifyPropertyChanged { event EventHandler StatusChanged; ChangeStatus ChangeTrackingStatus { get; } } internal interface IChangeTrackableInternal { object GetOriginal(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace ChangeTracking { public interface IChangeTrackable<T> : IChangeTrackable, System.ComponentModel.IRevertibleChangeTracking { /// <summary> /// Gets the original value of a given property. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="selector">The selector.</param> /// <returns></returns> /// <exception cref="System.ArgumentException"> /// A property selector expression has an incorrect format /// or /// A selected member is not a property /// </exception> TResult GetOriginalValue<TResult>(Expression<Func<T, TResult>> selector); /// <summary> /// Gets the original value of a given property. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="propertyName">Name of the property.</param> /// <returns></returns> TResult GetOriginalValue<TResult>(string propertyName); /// <summary> /// Gets the original value of a given property. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns></returns> object GetOriginalValue(string propertyName); /// <summary> /// Gets the original. /// </summary> /// <returns></returns> /// <exception cref="System.MissingMethodException">The type that is specified for T does not have a parameterless constructor.</exception> T GetOriginal(); } public interface IChangeTrackable { event EventHandler StatusChanged; ChangeStatus ChangeTrackingStatus { get; } } public interface IChangeTrackableInternal { object GetOriginal(); } }
mit
C#
dde7f41b98595688011742cbaba01475fea5ad6e
fix StackOverflowTest breaks Live Unit Testing (Enterprise!)
acple/ParsecSharp
UnitTest.ParsecSharp/StackOverflowTest.cs
UnitTest.ParsecSharp/StackOverflowTest.cs
#if !DEBUG using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using static ParsecSharp.Parser; namespace UnitTest.ParsecSharp { [TestClass] [TestCategory("SkipWhenLiveUnitTesting")] public class StackOverflowTest { [TestMethod] public void StackOverflowTest1() { var parser = SkipMany(Any<int>()); var source = new int[1000000]; parser.Parse(source); } [TestMethod] public void StackOverflowTest2() { var parser = Many(Any<(int, int, int)>()); var source = Enumerable.Range(0, 1000000).Select(x => (x, x, x)); parser.Parse(source); } [TestMethod] public void StackOverflowTest3() { var parser = Many(Any<Tuple<int, int, int>>()); var source = Enumerable.Range(0, 1000000).Select(x => Tuple.Create(x, x, x)); parser.Parse(source); } } } #endif
#if !DEBUG using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using static ParsecSharp.Parser; namespace UnitTest.ParsecSharp { [TestClass] public class StackOverflowTest { [TestMethod] public void StackOverflowTest1() { var parser = SkipMany(Any<int>()); var source = new int[1000000]; parser.Parse(source); } [TestMethod] public void StackOverflowTest2() { var parser = Many(Any<(int, int, int)>()); var source = Enumerable.Range(0, 1000000).Select(x => (x, x, x)); parser.Parse(source); } [TestMethod] public void StackOverflowTest3() { var parser = Many(Any<Tuple<int, int, int>>()); var source = Enumerable.Range(0, 1000000).Select(x => Tuple.Create(x, x, x)); parser.Parse(source); } } } #endif
mit
C#
2498846740a77e5e131a319590309d258834c20c
enable stats in debug only
rustamserg/mogate
mogate.Shared/Services/Statistics.cs
mogate.Shared/Services/Statistics.cs
using System; using System.Collections.Generic; using System.IO; namespace mogate { public interface IStatistics { void EntityAdded(string entity); void EntityRemoved(string entity); void BehaviorRegistered(string entity, string behavior); void BehaviorFetched (string entity, string behavior); void Dump(); } #if DEBUG public class Statistics : IStatistics { private object m_lock = new object(); private Dictionary<string, int> m_behaviorRegistered = new Dictionary<string, int>(); private Dictionary<string, int> m_behaviorFetched = new Dictionary<string, int>(); public void EntityAdded(string entity) { } public void EntityRemoved(string entity) { } public void BehaviorRegistered(string entity, string behavior) { lock (m_lock) { if (!m_behaviorRegistered.ContainsKey(behavior)) { m_behaviorRegistered.Add (behavior, 0); } m_behaviorRegistered [behavior] = m_behaviorRegistered [behavior] + 1; } } public void BehaviorFetched (string entity, string behavior) { lock (m_lock) { if (!m_behaviorFetched.ContainsKey(behavior)) { m_behaviorFetched.Add (behavior, 0); } m_behaviorFetched [behavior] = m_behaviorFetched [behavior] + 1; } } public void Dump() { lock (m_lock) { using (StreamWriter sw = File.CreateText("/Users/rustam/Documents/behavior_registered.txt")) { foreach (var beh in m_behaviorRegistered.Keys) { sw.WriteLine ("{0}, {1}", beh, m_behaviorRegistered [beh]); } } using (StreamWriter sw = File.CreateText("/Users/rustam/Documents/behavior_fetched.txt")) { foreach (var beh in m_behaviorFetched.Keys) { sw.WriteLine ("{0}, {1}", beh, m_behaviorFetched [beh]); } } } } } #else public class Statistics : IStatistics { public void EntityAdded(string entity) {} public void EntityRemoved(string entity) {} public void BehaviorRegistered(string entity, string behavior) {} public void BehaviorFetched (string entity, string behavior) {} public void Dump() {} } #endif }
using System; using System.Collections.Generic; using System.IO; namespace mogate { public interface IStatistics { void EntityAdded(string entity); void EntityRemoved(string entity); void BehaviorRegistered(string entity, string behavior); void BehaviorFetched (string entity, string behavior); void Dump(); } public class Statistics : IStatistics { private object m_lock = new object(); private Dictionary<string, int> m_behaviorRegistered = new Dictionary<string, int>(); private Dictionary<string, int> m_behaviorFetched = new Dictionary<string, int>(); public void EntityAdded(string entity) { } public void EntityRemoved(string entity) { } public void BehaviorRegistered(string entity, string behavior) { lock (m_lock) { if (!m_behaviorRegistered.ContainsKey(behavior)) { m_behaviorRegistered.Add (behavior, 0); } m_behaviorRegistered [behavior] = m_behaviorRegistered [behavior] + 1; } } public void BehaviorFetched (string entity, string behavior) { lock (m_lock) { if (!m_behaviorFetched.ContainsKey(behavior)) { m_behaviorFetched.Add (behavior, 0); } m_behaviorFetched [behavior] = m_behaviorFetched [behavior] + 1; } } public void Dump() { lock (m_lock) { using (StreamWriter sw = File.CreateText("/Users/rustam/Documents/behavior_registered.txt")) { foreach (var beh in m_behaviorRegistered.Keys) { sw.WriteLine ("{0}, {1}", beh, m_behaviorRegistered [beh]); } } using (StreamWriter sw = File.CreateText("/Users/rustam/Documents/behavior_fetched.txt")) { foreach (var beh in m_behaviorFetched.Keys) { sw.WriteLine ("{0}, {1}", beh, m_behaviorFetched [beh]); } } } } } }
mit
C#
d75ba2b6f700047328bf9128debfed6ff0d2eafd
Fix MSBuild tests on macOS/Linux
DustinCampbell/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn
tests/TestUtility/StringExtensions.cs
tests/TestUtility/StringExtensions.cs
using System.IO; namespace TestUtility { public static class StringExtensions { /// <summary> /// Given a file or directory path, return a path where all directory separators /// are replaced with a forward slash (/) character. /// </summary> public static string EnsureForwardSlashes(this string path) => path.Replace('\\', '/'); } }
using System.IO; namespace TestUtility { public static class StringExtensions { /// <summary> /// Given a file or directory path, return a path where all directory separators /// are replaced with a forward slash (/) character. /// </summary> public static string EnsureForwardSlashes(this string path) => path.Replace(Path.DirectorySeparatorChar, '/'); } }
mit
C#
08e5ab7e31ab6cf6fb2f210a5a23f2363a385555
Update JSON cache to use camel case property names
stvnhrlnd/SH,stvnhrlnd/SH,stvnhrlnd/SH
SH.Site/Controllers/JsonCacheController.cs
SH.Site/Controllers/JsonCacheController.cs
using AutoMapper; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using SH.Site.Models; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Web; using System.Web.Http; using Umbraco.Core.Logging; using Umbraco.Web.WebApi; namespace SH.Site.Controllers { public class JsonCacheController : UmbracoAuthorizedApiController { [HttpGet] public HttpResponseMessage Refresh() { try { // Serialise Umbraco content tree to JSON var content = Umbraco.TypedContentAtRoot(); var contentModels = Mapper.Map<IEnumerable<JsonCacheContentModel>>(content); var json = JsonConvert.SerializeObject(contentModels, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); // Write JSON to file var physicalPath = HttpContext.Current.Server.MapPath(Constants.JsonCachePath); File.WriteAllText(physicalPath, json, Encoding.UTF8); // Compute and store MD5 hash of JSON file using (var stream = File.OpenRead(physicalPath)) { using (var md5 = MD5.Create()) { var hash = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower(); File.WriteAllText(HttpContext.Current.Server.MapPath(Constants.JsonCacheMd5Path), hash); } } return Request.CreateResponse(HttpStatusCode.OK); } catch (Exception exception) { Logger.Error<JsonCacheController>("Failed to refresh JSON cache.", exception); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exception); } } } }
using AutoMapper; using Newtonsoft.Json; using SH.Site.Models; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Web; using System.Web.Http; using Umbraco.Core.Logging; using Umbraco.Web.WebApi; namespace SH.Site.Controllers { public class JsonCacheController : UmbracoAuthorizedApiController { [HttpGet] public HttpResponseMessage Refresh() { try { // Serialise Umbraco content tree to JSON var content = Umbraco.TypedContentAtRoot(); var contentModels = Mapper.Map<IEnumerable<JsonCacheContentModel>>(content); var json = JsonConvert.SerializeObject(contentModels); // Write JSON to file var physicalPath = HttpContext.Current.Server.MapPath(Constants.JsonCachePath); File.WriteAllText(physicalPath, json, Encoding.UTF8); // Compute and store MD5 hash of JSON file using (var stream = File.OpenRead(physicalPath)) { using (var md5 = MD5.Create()) { var hash = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower(); File.WriteAllText(HttpContext.Current.Server.MapPath(Constants.JsonCacheMd5Path), hash); } } return Request.CreateResponse(HttpStatusCode.OK); } catch (Exception exception) { Logger.Error<JsonCacheController>("Failed to refresh JSON cache.", exception); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exception); } } } }
mit
C#
57a8b93e891f9aa1f6fdc6379f8257746152e8e5
Add tests for SA1024 in tuple expressions
DotNetAnalyzers/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/SpacingRules/SA1024CSharp7UnitTests.cs
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/SpacingRules/SA1024CSharp7UnitTests.cs
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.CSharp7.SpacingRules { using System; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using StyleCop.Analyzers.Test.SpacingRules; using TestHelper; using Xunit; public class SA1024CSharp7UnitTests : SA1024UnitTests { /// <summary> /// Verifies spacing around a <c>:</c> character in tuple expressions. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task TestSpacingAroundColonInTupleExpressionsAsync() { const string testCode = @"using System; public class Foo { public void TestMethod() { var values = (x :3, y :4); } }"; const string fixedCode = @"using System; public class Foo { public void TestMethod() { var values = (x: 3, y: 4); } }"; DiagnosticResult[] expected = { this.CSharpDiagnostic().WithLocation(7, 25).WithArguments(" not", "preceded", string.Empty), this.CSharpDiagnostic().WithLocation(7, 25).WithArguments(string.Empty, "followed", string.Empty), this.CSharpDiagnostic().WithLocation(7, 31).WithArguments(" not", "preceded", string.Empty), this.CSharpDiagnostic().WithLocation(7, 31).WithArguments(string.Empty, "followed", string.Empty), }; await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false); await this.VerifyCSharpDiagnosticAsync(fixedCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); await this.VerifyCSharpFixAsync(testCode, fixedCode, cancellationToken: CancellationToken.None).ConfigureAwait(false); } protected override Solution CreateSolution(ProjectId projectId, string language) { Solution solution = base.CreateSolution(projectId, language); Assembly systemRuntime = AppDomain.CurrentDomain.GetAssemblies().Single(x => x.GetName().Name == "System.Runtime"); return solution .AddMetadataReference(projectId, MetadataReference.CreateFromFile(systemRuntime.Location)) .AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(ValueTuple).Assembly.Location)); } } }
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.CSharp7.SpacingRules { using Test.SpacingRules; public class SA1024CSharp7UnitTests : SA1024UnitTests { } }
mit
C#
b29114df97ab2565dfad6c83d3b4918be056f112
Remove unused directives
projectkudu/SimpleWAWS,projectkudu/TryAppService,projectkudu/TryAppService,projectkudu/SimpleWAWS,projectkudu/TryAppService,projectkudu/TryAppService,projectkudu/SimpleWAWS,projectkudu/SimpleWAWS
SimpleWAWS/Authentication/AuthUtilities.cs
SimpleWAWS/Authentication/AuthUtilities.cs
using System.IO; using System.Net; namespace SimpleWAWS.Authentication { public static class AuthUtilities { public static string GetContentFromUrl(string url) { var request = (HttpWebRequest)WebRequest.Create(url); using (var response = request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } public static string GetContentFromGitHubUrl(string url, string method = "GET", bool jsonAccept = false, bool addGitHubHeaders = false, string AuthorizationHeader = "") { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.UserAgent = "x-ms-try-appservice"; if (jsonAccept) { request.Accept = "application/json"; } if (addGitHubHeaders) { request.Accept = "application/vnd.github.v3+json"; } if (!String.IsNullOrEmpty(AuthorizationHeader)) { request.Headers.Add("Authorization", AuthorizationHeader); } using (var response = request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } } }
using System; using System.IO; using System.Net; namespace SimpleWAWS.Authentication { public static class AuthUtilities { public static string GetContentFromUrl(string url) { var request = (HttpWebRequest)WebRequest.Create(url); using (var response = request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } public static string GetContentFromGitHubUrl(string url, string method = "GET", bool jsonAccept = false, bool addGitHubHeaders = false, string AuthorizationHeader = "") { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.UserAgent = "x-ms-try-appservice"; if (jsonAccept) { request.Accept = "application/json"; } if (addGitHubHeaders) { request.Accept = "application/vnd.github.v3+json"; } if (!String.IsNullOrEmpty(AuthorizationHeader)) { request.Headers.Add("Authorization", AuthorizationHeader); } using (var response = request.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } } }
apache-2.0
C#
e1b98091650ac894dfefc858fce95e0b94201469
Update Index.cshtml
Bloyteg/RWXViewer,Bloyteg/RWXViewer,Bloyteg/RWXViewer,Bloyteg/RWXViewer
RWXViewer/Views/Home/Index.cshtml
RWXViewer/Views/Home/Index.cshtml
@{ ViewBag.Title = "RWX Viewer by Byte"; } @section scripts { <script src="@Url.Content("~/Scripts/gl-matrix.js")"></script> <script src="@Url.Content("~/Scripts/knockout-3.1.0.js")"></script> <script src="@Url.Content("~/Scripts/require.js")" data-main="/Scripts/RWXViewer"></script> <script src="@Url.Content("~/Scripts/config.js")"></script> } <div id="header"> <div id="headerContent"> <h1>RWX Viewer by Byte</h1> </div> </div> <div id="content"> <div id="modelSelector" class="infoBar"> <label for="selectWorld">World:</label> <select class="uiSelect" id="selectWorld" disabled data-bind="options: worlds, optionsText: 'Name', optionsCaption: '(None)', value: selectedWorld"></select> <label for="selectModel">Object:</label> <select class="uiSelect" id="selectModel" disabled data-bind="options: models, optionsText: 'Name', optionsCaption: '(None)', value: selectedModel, enable: selectedWorld"></select> </div> <canvas id="viewport" width="960" height="540"> Your browser does not support the HTML 5 Canvas element. </canvas> <div class="infoBar"> Left Mouse: Rotate<br /> Right Mouse: Pan<br /> Mouse Wheel: Zoom </div> </div>
@{ ViewBag.Title = "RWX Viewer by Byte"; } @section scripts { <script src="@Url.Content("~/Scripts/gl-matrix.js")"></script> <script src="@Url.Content("~/Scripts/knockout-3.1.0.js")"></script> <script src="@Url.Content("~/Scripts/require.js")" data-main="/Scripts/RWXViewer"></script> <script src="@Url.Content("~/Scripts/config.js")"></script> } <div id="header"> <div id="headerContent"> <h1>RWX Viewer by Byte</h1> </div> </div> <div id="content"> <div id="modelSelector" class="infoBar"> <label for="selectWorld">World:</label> <select id="selectWorld" data-bind="options: worlds, optionsText: 'Name', optionsCaption: '(None)', value: selectedWorld"></select> <label for="selectModel">Object:</label> <select id="selectModel" data-bind="options: models, optionsText: 'Name', optionsCaption: '(None)', value: selectedModel, enable: selectedWorld"></select> </div> <canvas id="viewport" width="960" height="540"> Your browser does not support the HTML 5 Canvas element. </canvas> <div class="infoBar"> Left Mouse: Rotate<br /> Right Mouse: Pan<br /> Mouse Wheel: Zoom </div> </div>
apache-2.0
C#
7e4e680cad8c7e9c5d194c3b34f0d90629c31e5a
Update MainScript.cs
proyecto26/RestClient
demo/Assets/MainScript.cs
demo/Assets/MainScript.cs
using UnityEngine; using UnityEditor; using Models; using Proyecto26; using System.Collections.Generic; public class MainScript : MonoBehaviour { private readonly string basePath = "https://jsonplaceholder.typicode.com"; public void Get(){ // We can add default request headers for all requests RestClient.DefaultRequestHeaders["Authorization"] = "Bearer ..."; RequestHelper requestOptions; RestClient.GetArray<Post>(basePath + "/posts").Then(res => { EditorUtility.DisplayDialog ("Posts", JsonHelper.ArrayToJsonString<Post>(res, true), "Ok"); return RestClient.GetArray<Todo>(basePath + "/todos"); }).Then(res => { EditorUtility.DisplayDialog ("Todos", JsonHelper.ArrayToJsonString<Todo>(res, true), "Ok"); return RestClient.GetArray<User>(basePath + "/users"); }).Then(res => { EditorUtility.DisplayDialog ("Users", JsonHelper.ArrayToJsonString<User>(res, true), "Ok"); // We can add specific options and override default headers for a request requestOptions = new RequestHelper { url = basePath + "/photos", headers = new Dictionary<string, string> { { "Authorization", "Other token..." } } }; return RestClient.GetArray<Photo>(requestOptions); }).Then(res => { EditorUtility.DisplayDialog("Header", requestOptions.GetHeader("Authorization"), "Ok"); // And later we can clean the default headers for all requests RestClient.CleanDefaultHeaders(); }).Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok")); } public void Post(){ RestClient.Post<Models.Post>(basePath + "/posts", new { title = "foo", body = "bar", userId = 1 }) .Then(res => EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(res, true), "Ok")) .Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok")); } public void Put(){ RestClient.Put<Post>(basePath + "/posts/1", new { title = "foo", body = "bar", userId = 1 }, (err, res, body) => { if(err != null){ EditorUtility.DisplayDialog ("Error", err.Message, "Ok"); } else{ EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(body, true), "Ok"); } }); } public void Delete(){ RestClient.Delete(basePath + "/posts/1", (err, res) => { if(err != null){ EditorUtility.DisplayDialog ("Error", err.Message, "Ok"); } else{ EditorUtility.DisplayDialog ("Success", "Status: " + res.statusCode.ToString(), "Ok"); } }); } }
using UnityEngine; using UnityEditor; using Models; using Proyecto26; using System.Collections.Generic; public class MainScript : MonoBehaviour { private readonly string basePath = "https://jsonplaceholder.typicode.com"; public void Get(){ // We can add default request headers for all requests RestClient.DefaultRequestHeaders["Authorization"] = "Bearer ..."; RequestHelper requestOptions = null; RestClient.GetArray<Post>(new RequestHelper{ url = basePath + "/posts" }).Then(res => { EditorUtility.DisplayDialog ("Posts", JsonHelper.ArrayToJsonString<Post>(res, true), "Ok"); return RestClient.GetArray<Todo>(basePath + "/todos"); }).Then(res => { EditorUtility.DisplayDialog ("Todos", JsonHelper.ArrayToJsonString<Todo>(res, true), "Ok"); return RestClient.GetArray<User>(basePath + "/users"); }).Then(res => { EditorUtility.DisplayDialog ("Users", JsonHelper.ArrayToJsonString<User>(res, true), "Ok"); // We can add specific options and override default headers for a request requestOptions = new RequestHelper { url = basePath + "/photos", headers = new Dictionary<string, string> { { "Authorization", "Other token..." } } }; return RestClient.GetArray<Photo>(requestOptions); }).Then(res => { EditorUtility.DisplayDialog("Header", requestOptions.GetHeader("Authorization"), "Ok"); // And later we can clean the default headers for all requests RestClient.CleanDefaultHeaders(); }).Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok")); } public void Post(){ RestClient.Post<Models.Post>(basePath + "/posts", new { title = "foo", body = "bar", userId = 1 }) .Then(res => EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(res, true), "Ok")) .Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok")); } public void Put(){ RestClient.Put<Post>(basePath + "/posts/1", new { title = "foo", body = "bar", userId = 1 }, (err, res, body) => { if(err != null){ EditorUtility.DisplayDialog ("Error", err.Message, "Ok"); } else{ EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(body, true), "Ok"); } }); } public void Delete(){ RestClient.Delete(basePath + "/posts/1", (err, res) => { if(err != null){ EditorUtility.DisplayDialog ("Error", err.Message, "Ok"); } else{ EditorUtility.DisplayDialog ("Success", "Status: " + res.statusCode.ToString(), "Ok"); } }); } }
mit
C#
35f4eba40cfcc5e092aad75a78d65603c6132f67
Clean up unit test.
ClosedXML/ClosedXML,jongleur1983/ClosedXML,clinchergt/ClosedXML,JavierJJJ/ClosedXML,igitur/ClosedXML,b0bi79/ClosedXML
ClosedXML_Tests/Excel/Styles/NumberFormatTests.cs
ClosedXML_Tests/Excel/Styles/NumberFormatTests.cs
using ClosedXML.Excel; using NUnit.Framework; using System; using System.Data; using System.Linq; namespace ClosedXML_Tests.Excel { public class NumberFormatTests { [Test] public void PreserveCellFormat() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet1"); ws.Column(1).Style.NumberFormat.Format = "yy-MM-dd"; var table = new DataTable(); table.Columns.Add("Date", typeof(DateTime)); for (int i = 0; i < 10; i++) { table.Rows.Add(new DateTime(2017, 1, 1).AddMonths(i)); } ws.Cell("A1").InsertData(table.AsEnumerable()); Assert.AreEqual("yy-MM-dd", ws.Cell("A5").Style.DateFormat.Format); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using ClosedXML.Excel; using System.Data; namespace ClosedXML_Tests.Excel { public class NumberFormatTests { [Test] public void PreserveCellFormat() { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet("Sheet1"); ws.Column(1).Style.NumberFormat.Format = "yy-MM-dd"; var table = new DataTable(); table.Columns.Add("Date", typeof(DateTime)); for (int i = 0; i <10; i++) { table.Rows.Add(new DateTime(2017, 1, 1).AddMonths(i)); } ws.Cell("B1").Value = table.Columns[0].DataType; ws.Cell("A1").InsertData(table.AsEnumerable()); Assert.AreEqual("yy-MM-dd", ws.Cell("A5").Style.DateFormat.Format); } } } }
mit
C#
4e7df57d543b5efda15807e996a90077eb623bfc
Insert tag logic
tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web
src/Tugberk.Web.OldBlogMigrator/Program.cs
src/Tugberk.Web.OldBlogMigrator/Program.cs
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using Bloggy.Domain.Entities; using Raven.Client; using Raven.Client.Document; namespace Tugberk.Web.OldBlogMigrator { class Program { private class TagEquality : IEqualityComparer<Tag> { public bool Equals(Tag x, Tag y) => x.Name.Equals(y.Name); public int GetHashCode(Tag obj) => obj.Name.GetHashCode(); } static void Main(string[] args) { var connStr = args[0]; using (IDocumentStore store = RetrieveDocumentStore()) using (IDocumentSession ses = store.OpenSession()) using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); ses.Advanced.MaxNumberOfRequestsPerSession = int.MaxValue; var userId = Guid.NewGuid().ToString(); var allPosts = ses.Query<BlogPost>().Take(Int32.MaxValue).Where(x => x.IsApproved).ToList(); var allTags = allPosts.SelectMany(x => x.Tags).Distinct(new TagEquality()); foreach (var tag in allTags) { InsertTag(conn, tag, userId); } foreach (var blogPost in allPosts) { Console.WriteLine($"Found '{blogPost.Title}' post, written @ {blogPost.CreatedOn}"); } } } private static void InsertTag(SqlConnection conn, Tag tag, string userId) { using (var cmd = new SqlCommand(@"INSERT INTO [dbo].[Tags] ([Name] ,[CreatedById] ,[CreatedOnUtc] ,[CreationIpAddress] ,[Slug]) VALUES(@Name, @CreatedById, @CreatedOnUtc, @CreationIpAddress, @Slug)", conn)) { cmd.Parameters.AddWithValue("Name", tag.Name); cmd.Parameters.AddWithValue("CreatedById", userId); cmd.Parameters.AddWithValue("CreatedOnUtc", DateTime.UtcNow); cmd.Parameters.AddWithValue("CreationIpAddress", "127.0.0.1"); cmd.Parameters.AddWithValue("Slug", tag.Slug); } } private static IDocumentStore RetrieveDocumentStore() { IDocumentStore store = new DocumentStore { Url = "http://localhost:8080/", DefaultDatabase = "Bloggy" }.Initialize(); return store; } } }
using System; using System.Linq; using Bloggy.Domain.Entities; using Raven.Client; using Raven.Client.Document; namespace Tugberk.Web.OldBlogMigrator { class Program { static void Main(string[] args) { using (IDocumentStore store = RetrieveDocumentStore()) using (IDocumentSession ses = store.OpenSession()) { ses.Advanced.MaxNumberOfRequestsPerSession = int.MaxValue; var posts = ses.Query<BlogPost>().Take(Int32.MaxValue).Where(x => x.IsApproved).ToList(); foreach (var blogPost in posts) { Console.WriteLine($"Found '{blogPost.Title}' post, written @ {blogPost.CreatedOn}"); } } } private static IDocumentStore RetrieveDocumentStore() { IDocumentStore store = new DocumentStore { Url = "http://localhost:8080/", DefaultDatabase = "Bloggy" }.Initialize(); return store; } } }
agpl-3.0
C#
aa1915ddf8fd6bb71607a677d075bbbfb2de21df
Add back arrow in levelselection, to return to mainMenu
danielholst/Froggy
frogJumper/Assets/scripts/levelSelection.cs
frogJumper/Assets/scripts/levelSelection.cs
using UnityEngine; using System.Collections; /** * Class to handle selection of level in the level selection scene **/ public class levelSelection : MonoBehaviour { private Texture2D button; void OnGUI () { GUI.backgroundColor = Color.clear; if (GUI.Button (new Rect (40, 80, 200, 100), button)) { print ("load level 1"); Application.LoadLevel(2); } if (GUI.Button (new Rect (300, 80, 200, 100), button)) { print ("load level 2"); Application.LoadLevel(3); } if (GUI.Button (new Rect (590, 80, 200, 100), button)) { print ("load level 3"); Application.LoadLevel(4); } if (GUI.Button (new Rect (850, 80, 200, 100), button)) { print ("load level 4"); Application.LoadLevel(5); } if (GUI.Button (new Rect (40, 300, 200, 100), button)) { print ("load level 5"); Application.LoadLevel(6); } if (GUI.Button (new Rect (300, 300, 200, 100), button)) { print ("load level 6"); Application.LoadLevel(7); } if (GUI.Button (new Rect (590, 300, 200, 100), button)) { print ("load level 7"); Application.LoadLevel(8); } if (GUI.Button (new Rect (850, 300, 200, 100), button)) { print ("load level 8"); Application.LoadLevel(9); } if (GUI.Button (new Rect (300, 500, 200, 100), button)) { print ("load level 9"); Application.LoadLevel(10); } if (GUI.Button (new Rect (590, 500, 200, 100), button)) { print ("load level 10"); Application.LoadLevel(11); } //button to return to main menu if (GUI.Button (new Rect (0, 570, 230, 130), button)) { print ("load level 10"); Application.LoadLevel(0); } } }
using UnityEngine; using System.Collections; /** * Class to handle selection of level in the level selection scene **/ //TODO public class levelSelection : MonoBehaviour { private Texture2D button; // Use this for initialization void Start () { } // Update is called once per frame void OnGUI () { GUI.backgroundColor = Color.clear; if (GUI.Button (new Rect (40, 80, 200, 100), button)) { print ("load level 1"); Application.LoadLevel(2); } if (GUI.Button (new Rect (300, 80, 200, 100), button)) { print ("load level 2"); Application.LoadLevel(3); } if (GUI.Button (new Rect (590, 80, 200, 100), button)) { print ("load level 3"); Application.LoadLevel(4); } if (GUI.Button (new Rect (850, 80, 200, 100), button)) { print ("load level 4"); Application.LoadLevel(5); } if (GUI.Button (new Rect (40, 300, 200, 100), button)) { print ("load level 5"); Application.LoadLevel(6); } if (GUI.Button (new Rect (300, 300, 200, 100), button)) { print ("load level 6"); Application.LoadLevel(7); } if (GUI.Button (new Rect (590, 300, 200, 100), button)) { print ("load level 7"); Application.LoadLevel(8); } if (GUI.Button (new Rect (850, 300, 200, 100), button)) { print ("load level 8"); Application.LoadLevel(9); } if (GUI.Button (new Rect (300, 500, 200, 100), button)) { print ("load level 9"); Application.LoadLevel(10); } if (GUI.Button (new Rect (590, 500, 200, 100), button)) { print ("load level 10"); Application.LoadLevel(11); } } }
mit
C#
d205edc294cb626b4dcb34da1132498159b0a821
call Path.Combine on $HOME
GNOME/f-spot,dkoeb/f-spot,GNOME/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,mono/f-spot,dkoeb/f-spot,Yetangitu/f-spot,GNOME/f-spot,GNOME/f-spot,mono/f-spot,mono/f-spot,mono/f-spot,NguyenMatthieu/f-spot,mans0954/f-spot,Yetangitu/f-spot,dkoeb/f-spot,mans0954/f-spot,mans0954/f-spot,NguyenMatthieu/f-spot,mans0954/f-spot,mono/f-spot,dkoeb/f-spot,dkoeb/f-spot,mans0954/f-spot,mans0954/f-spot,Sanva/f-spot,Yetangitu/f-spot,nathansamson/F-Spot-Album-Exporter,GNOME/f-spot,dkoeb/f-spot,NguyenMatthieu/f-spot,Yetangitu/f-spot,Sanva/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,mono/f-spot,Yetangitu/f-spot,nathansamson/F-Spot-Album-Exporter,NguyenMatthieu/f-spot,Sanva/f-spot,NguyenMatthieu/f-spot
src/Global.cs
src/Global.cs
namespace FSpot { public class Global { public static string HomeDirectory { get { return System.IO.Path.Combine (System.Environment.GetEnvironmentVariable ("HOME"), ""); } } public static string BaseDirectory { get { return System.IO.Path.Combine (HomeDirectory, System.IO.Path.Combine (".gnome2", "f-spot")); } } public static void ModifyColors (Gtk.Widget widget) { #if false Gdk.Color color = widget.Style.Background (Gtk.StateType.Normal); color.Red = (ushort) (color.Red / 2); color.Blue = (ushort) (color.Blue / 2); color.Green = (ushort) (color.Green / 2); widget.ModifyBg (Gtk.StateType.Normal, color); #else try { widget.ModifyFg (Gtk.StateType.Normal, widget.Style.TextColors [(int)Gtk.StateType.Normal]); widget.ModifyBg (Gtk.StateType.Normal, widget.Style.BaseColors [(int)Gtk.StateType.Normal]); } catch { widget.ModifyFg (Gtk.StateType.Normal, widget.Style.Black); widget.ModifyBg (Gtk.StateType.Normal, widget.Style.White); } #endif } #if false private Cms.Profile display_profile; public Cms.Profile DisplayProfile { get { return Cms.Profile.CreateSRgb (); } } private System.Collections.Hashtable profile_cache; public Cms.Transform DisplayTranform (Cms.Profile image_profile) { if (image_profile == null && display_profile == null) return null; } #endif } }
namespace FSpot { public class Global { public static string HomeDirectory { get { return System.Environment.GetEnvironmentVariable ("HOME"); } } public static string BaseDirectory { get { return System.IO.Path.Combine (HomeDirectory, System.IO.Path.Combine (".gnome2", "f-spot")); } } public static void ModifyColors (Gtk.Widget widget) { #if false Gdk.Color color = widget.Style.Background (Gtk.StateType.Normal); color.Red = (ushort) (color.Red / 2); color.Blue = (ushort) (color.Blue / 2); color.Green = (ushort) (color.Green / 2); widget.ModifyBg (Gtk.StateType.Normal, color); #else try { widget.ModifyFg (Gtk.StateType.Normal, widget.Style.TextColors [(int)Gtk.StateType.Normal]); widget.ModifyBg (Gtk.StateType.Normal, widget.Style.BaseColors [(int)Gtk.StateType.Normal]); } catch { widget.ModifyFg (Gtk.StateType.Normal, widget.Style.Black); widget.ModifyBg (Gtk.StateType.Normal, widget.Style.White); } #endif } #if false private Cms.Profile display_profile; public Cms.Profile DisplayProfile { get { return Cms.Profile.CreateSRgb (); } } private System.Collections.Hashtable profile_cache; public Cms.Transform DisplayTranform (Cms.Profile image_profile) { if (image_profile == null && display_profile == null) return null; } #endif } }
mit
C#
3bcf0e73e2061af5aff5c72e994cd0aa14cf0413
fix gotodefinition for windows
syl20bnr/omnisharp-server,mispencer/OmniSharpServer,OmniSharp/omnisharp-server,x335/omnisharp-server,corngood/omnisharp-server,syl20bnr/omnisharp-server,x335/omnisharp-server,svermeulen/omnisharp-server,corngood/omnisharp-server
OmniSharp/GotoDefinition/GotoDefinitionHandler.cs
OmniSharp/GotoDefinition/GotoDefinitionHandler.cs
using ICSharpCode.NRefactory; using ICSharpCode.NRefactory.CSharp.Resolver; using ICSharpCode.NRefactory.Semantics; using OmniSharp.Parser; using OmniSharp.Solution; namespace OmniSharp.GotoDefinition { public class GotoDefinitionHandler { private readonly BufferParser _bufferParser; public GotoDefinitionHandler(BufferParser bufferParser) { _bufferParser = bufferParser; } public GotoDefinitionResponse GetGotoDefinitionResponse(GotoDefinitionRequest request) { var res = _bufferParser.ParsedContent(request.Buffer, request.FileName); var loc = new TextLocation(request.Line, request.Column); ResolveResult resolveResult = ResolveAtLocation.Resolve(res.Compilation, res.UnresolvedFile, res.SyntaxTree, loc); var response = new GotoDefinitionResponse(); if (resolveResult != null) { var region = resolveResult.GetDefinitionRegion(); response.FileName = region.FileName.LowerCaseDriveLetter(); response.Line = region.BeginLine; response.Column = region.BeginColumn; } return response; } } }
using ICSharpCode.NRefactory; using ICSharpCode.NRefactory.CSharp.Resolver; using ICSharpCode.NRefactory.Semantics; using OmniSharp.Parser; namespace OmniSharp.GotoDefinition { public class GotoDefinitionHandler { private readonly BufferParser _bufferParser; public GotoDefinitionHandler(BufferParser bufferParser) { _bufferParser = bufferParser; } public GotoDefinitionResponse GetGotoDefinitionResponse(GotoDefinitionRequest request) { var res = _bufferParser.ParsedContent(request.Buffer, request.FileName); var loc = new TextLocation(request.Line, request.Column); ResolveResult resolveResult = ResolveAtLocation.Resolve(res.Compilation, res.UnresolvedFile, res.SyntaxTree, loc); var response = new GotoDefinitionResponse(); if (resolveResult != null) { var region = resolveResult.GetDefinitionRegion(); response.FileName = region.FileName; response.Line = region.BeginLine; response.Column = region.BeginColumn; } return response; } } }
mit
C#
b95f2733a676318153f506c40cc1cc9a99ad6179
Fix names and spelling in comments
KentorIT/PU-Adapter,KentorIT/PU-Adapter
VersionInfo.cs
VersionInfo.cs
using System.Reflection; [assembly: AssemblyCompany("Kentor")] [assembly: AssemblyCopyright("Copyright Kentor and contributors 2015")] // Kentor.PU-Adapter uses semantic versioning in three parts // // Major Version // Minor Version // Patch Number // // An odd patch number is a development version, an even patch number is // a released version. [assembly: AssemblyVersion("0.0.31")] [assembly: AssemblyFileVersion("0.0.31")] [assembly: AssemblyInformationalVersion("0.0.31")]
using System.Reflection; [assembly: AssemblyCompany("Kentor")] [assembly: AssemblyCopyright("Copyright Kentor and contributors 2015")] // Kentor.AuthServices uses semantic versioning in three parts // // Major Version // Minor Version // Patch Number // // An odd patch number is a development version, an even patch number is // a relased version. [assembly: AssemblyVersion("0.0.31")] [assembly: AssemblyFileVersion("0.0.31")] [assembly: AssemblyInformationalVersion("0.0.31")]
mit
C#
9e43b2d599d9337bdf4ae64e7196c267f1ebb99e
Add CssReference constructor
Carbon/Css
src/Carbon.Css/Ast/Values/CssReference.cs
src/Carbon.Css/Ast/Values/CssReference.cs
namespace Carbon.Css { using Parser; public sealed class CssReference : CssValue { public CssReference(string name) : base(NodeKind.Reference) { Name = name; } public CssReference(CssToken name) : base(NodeKind.Reference) { Name = name.Text; } public CssReference(string name, CssSequence value) : base(NodeKind.Reference) { Name = name; Value = value; } public string Name { get; } public CssSequence Value { get; set; } } }
namespace Carbon.Css { using Parser; public sealed class CssReference : CssValue { public CssReference(string name) : base(NodeKind.Reference) { Name = name; } public CssReference(CssToken name) : base(NodeKind.Reference) { Name = name.Text; } public string Name { get; } public CssSequence Value { get; set; } } }
mit
C#
550b985f4bd47c2c7a1752142ce0b97b9db00eef
Update ArgumentMapBinder.cs
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
Rest/NakedObjects.Rest/Model/ArgumentMapBinder.cs
Rest/NakedObjects.Rest/Model/ArgumentMapBinder.cs
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace NakedObjects.Rest.Model { public class ArgumentMapBinder : IModelBinder { #region IModelBinder Members public Task BindModelAsync(ModelBindingContext bindingContext) { return bindingContext.HttpContext.Request.IsGet() ? BindFromQuery(bindingContext) : BindFromBody(bindingContext); } #endregion private static Task BindFromBody(ModelBindingContext bindingContext) { return ModelBinderUtils.BindModelOnSuccessOrFail(bindingContext, async () => ModelBinderUtils.CreateArgumentMap(await ModelBinderUtils.DeserializeJsonContent(bindingContext), true), ModelBinderUtils.CreateMalformedArguments<ArgumentMap>); } private static Task BindFromQuery(ModelBindingContext bindingContext) { return ModelBinderUtils.BindModelOnSuccessOrFail(bindingContext, async () => ModelBinderUtils.CreateSimpleArgumentMap(bindingContext.HttpContext.Request.QueryString.ToString()) ?? ModelBinderUtils.CreateArgumentMap(await ModelBinderUtils.DeserializeQueryString(bindingContext), true), ModelBinderUtils.CreateMalformedArguments<ArgumentMap>); } } }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace NakedObjects.Rest.Model { public class ArgumentMapBinder : IModelBinder { #region IModelBinder Members public Task BindModelAsync(ModelBindingContext bindingContext) { return bindingContext.HttpContext.Request.IsGet() ? BindFromQuery(bindingContext) : BindFromBody(bindingContext); } #endregion private static Task BindFromBody(ModelBindingContext bindingContext) { return ModelBinderUtils.BindModelOnSuccessOrFail(bindingContext, async () => ModelBinderUtils.CreateArgumentMap(await ModelBinderUtils.DeserializeJsonContent(bindingContext), true), ModelBinderUtils.CreateMalformedArguments<ArgumentMap>); } private static Task BindFromQuery(ModelBindingContext bindingContext) { return ModelBinderUtils.BindModelOnSuccessOrFail(bindingContext, async () => ModelBinderUtils.CreateSimpleArgumentMap(bindingContext.HttpContext.Request.QueryString.ToString()) ?? ModelBinderUtils.CreateArgumentMap(await ModelBinderUtils.DeserializeQueryString(bindingContext), false), ModelBinderUtils.CreateMalformedArguments<ArgumentMap>); } } }
apache-2.0
C#
0d7226a8fae5948ae5c48861c054d9476588ff75
Fix AppVeyor message limit by printing a warning for the 501st report message
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/CI/AppVeyor/AppVeyorOutputSink.cs
source/Nuke.Common/CI/AppVeyor/AppVeyorOutputSink.cs
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using JetBrains.Annotations; using Nuke.Common.OutputSinks; namespace Nuke.Common.CI.AppVeyor { [UsedImplicitly] [ExcludeFromCodeCoverage] internal class AppVeyorOutputSink : AnsiColorOutputSink { private readonly AppVeyor _appVeyor; private int _messageCount; internal AppVeyorOutputSink(AppVeyor appVeyor) { _appVeyor = appVeyor; } protected override string TraceCode => "90"; protected override string InformationCode => "36;1"; protected override string WarningCode => "33;1"; protected override string ErrorCode => "31;1"; protected override string SuccessCode => "32;1"; protected override void ReportWarning(string text, string details = null) { IncreaseAndCheckMessageCount(); _appVeyor.WriteWarning(text, details); } protected override void ReportError(string text, string details = null) { IncreaseAndCheckMessageCount(); _appVeyor.WriteError(text, details); } private void IncreaseAndCheckMessageCount() { _messageCount++; if (_messageCount == 501) { base.WriteWarning("AppVeyor has a default limit of 500 messages. " + "If you're getting an exception from 'appveyor.exe' after this message, " + "contact https://appveyor.com/support to resolve this issue for your account."); } } } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using JetBrains.Annotations; using Nuke.Common.OutputSinks; namespace Nuke.Common.CI.AppVeyor { [UsedImplicitly] [ExcludeFromCodeCoverage] internal class AppVeyorOutputSink : AnsiColorOutputSink { private readonly AppVeyor _appVeyor; internal AppVeyorOutputSink(AppVeyor appVeyor) { _appVeyor = appVeyor; } protected override string TraceCode => "90"; protected override string InformationCode => "36;1"; protected override string WarningCode => "33;1"; protected override string ErrorCode => "31;1"; protected override string SuccessCode => "32;1"; protected override void ReportWarning(string text, string details = null) { _appVeyor.WriteWarning(text, details); } protected override void ReportError(string text, string details = null) { _appVeyor.WriteError(text, details); } } }
mit
C#
006d5c8fd07517b323159b2ae5c76fcc2c46378d
Switch to using NSWindow instead of presenter
loqu8/pina
Pina.Mac/AppDelegate.cs
Pina.Mac/AppDelegate.cs
using MonoMac.Foundation; using MonoMac.AppKit; using Cirrious.CrossCore; using Cirrious.MvvmCross.Mac.Platform; using Cirrious.MvvmCross.Mac.Views.Presenters; using Cirrious.MvvmCross.ViewModels; using System.Drawing; namespace Pina.Mac { public partial class AppDelegate : MvxApplicationDelegate { MainWindowController mainWindowController; public AppDelegate() { } public override void FinishedLaunching (NSObject notification) { mainWindowController = new MainWindowController (); var setup = new Setup (this, mainWindowController.Window); setup.Initialize (); var startup = Mvx.Resolve<IMvxAppStart> (); startup.Start (); mainWindowController.Window.MakeKeyAndOrderFront (this); return; } } }
using MonoMac.Foundation; using MonoMac.AppKit; using Cirrious.CrossCore; using Cirrious.MvvmCross.Mac.Platform; using Cirrious.MvvmCross.Mac.Views.Presenters; using Cirrious.MvvmCross.ViewModels; using System.Drawing; namespace Pina.Mac { public partial class AppDelegate : MvxApplicationDelegate { MainWindowController mainWindowController; public AppDelegate() { } public override void FinishedLaunching (NSObject notification) { mainWindowController = new MainWindowController (); var presenter = new MvxMacViewPresenter (this, mainWindowController.Window); var setup = new Setup (this, presenter); setup.Initialize (); var startup = Mvx.Resolve<IMvxAppStart> (); startup.Start (); mainWindowController.Window.MakeKeyAndOrderFront (this); return; } } }
mit
C#
cd4b7679aed8a10745b736541926638f21a20159
remove default text
samaritanevent/Samaritans,samaritanevent/Samaritans
Samaritans/Samaritans/Views/Shared/_Layout.cshtml
Samaritans/Samaritans/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") </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("Do Gooders", "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("About", "About", "Home")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul> @Html.Partial("_LoginPartial") </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @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("Do Gooders", "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("About", "About", "Home")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</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#
9eb4600bdad96d5f201b1d934533a32728546325
Use sorting interpreter during pagination
joukevandermaas/saule,laurence79/saule,bjornharrtell/saule,goo32/saule,sergey-litvinov-work/saule,IntertechInc/saule
Saule/Queries/Pagination/PaginationInterpreter.cs
Saule/Queries/Pagination/PaginationInterpreter.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Saule.Queries.Sorting; namespace Saule.Queries.Pagination { internal class PaginationInterpreter { private readonly PaginationContext _context; public PaginationInterpreter(PaginationContext context) { _context = context; } public IQueryable Apply(IQueryable queryable) { // Skip does not work on queryables by default, because it makes // no sense if the order is not determined. This means we have to // order the queryable first, before we can apply pagination. var isOrdered = queryable.GetType().GetInterfaces() .Where(i => i.IsGenericType) .Any(i => i.GetGenericTypeDefinition() == typeof(IOrderedQueryable<>)); var ordered = isOrdered ? queryable : OrderById(queryable); var filtered = ordered.ApplyQuery(QueryMethod.Skip, _context.Page * _context.PerPage) as IQueryable; filtered = filtered.ApplyQuery(QueryMethod.Take, _context.PerPage) as IQueryable; return filtered; } public IEnumerable Apply(IEnumerable queryable) { var filtered = queryable.ApplyQuery(QueryMethod.Skip, _context.Page * _context.PerPage) as IEnumerable; filtered = filtered.ApplyQuery(QueryMethod.Take, _context.PerPage) as IEnumerable; return filtered; } private static IQueryable OrderById(IQueryable queryable) { var sorting = new SortingContext(new[] { new KeyValuePair<string, string>(Constants.SortingQueryName, "id") }); return Query.ApplySorting(queryable, sorting) as IQueryable; } } }
using System; using System.Collections; using System.Linq; using System.Linq.Expressions; namespace Saule.Queries.Pagination { internal class PaginationInterpreter { private readonly PaginationContext _context; public PaginationInterpreter(PaginationContext context) { _context = context; } public IQueryable Apply(IQueryable queryable) { // Skip does not work on queryables by default, because it makes // no sense if the order is not determined. This means we have to // order the queryable first, before we can apply pagination. var isOrdered = queryable.GetType().GetInterfaces() .Where(i => i.IsGenericType) .Any(i => i.GetGenericTypeDefinition() == typeof(IOrderedQueryable<>)); var ordered = isOrdered ? queryable : OrderById(queryable); var filtered = ordered.ApplyQuery(QueryMethod.Skip, _context.Page * _context.PerPage) as IQueryable; filtered = filtered.ApplyQuery(QueryMethod.Take, _context.PerPage) as IQueryable; return filtered; } public IEnumerable Apply(IEnumerable queryable) { var filtered = queryable.ApplyQuery(QueryMethod.Skip, _context.Page * _context.PerPage) as IEnumerable; filtered = filtered.ApplyQuery(QueryMethod.Take, _context.PerPage) as IEnumerable; return filtered; } private static IQueryable OrderById(IQueryable queryable) { var funcType = typeof(Func<,>).MakeGenericType(queryable.ElementType, typeof(object)); var param = Expression.Parameter(queryable.ElementType, "i"); var property = Expression.Property(param, "Id"); var expressionFactory = typeof(Expression).GetMethods() .Where(m => m.Name == "Lambda") .Select(m => new { Method = m, Params = m.GetParameters(), Args = m.GetGenericArguments() }) .Where(x => x.Params.Length == 2 && x.Args.Length == 1) .Select(x => x.Method) .First() .MakeGenericMethod(funcType); var expression = expressionFactory.Invoke(null, new object[] { property, new[] { param } }); var ordered = queryable.ApplyQuery(QueryMethod.OrderBy, expression) as IQueryable; return ordered; } } }
mit
C#
4a39eca589aab422b35b1deaa756a362401822fc
Use RegisterConsumers Extension Method
maldworth/SignalRChat-MassTransit,maldworth/SignalRChat-MassTransit,maldworth/SignalRChat-MassTransit
SignalRChat.Web.Bootstrapper/Modules/BusModule.cs
SignalRChat.Web.Bootstrapper/Modules/BusModule.cs
namespace SignalRChat.Web.Bootstrapper.Modules { using Autofac; using MassTransit; using System; using System.Configuration; public class BusModule : Module { private readonly System.Reflection.Assembly[] _assembliesToScan; public BusModule(params System.Reflection.Assembly[] assembliesToScan) { _assembliesToScan = assembliesToScan; } protected override void Load(ContainerBuilder builder) { // Registers all consumers with our container builder.RegisterConsumers(_assembliesToScan); // Creates our bus from the factory and registers it as a singleton against two interfaces builder.Register(c => Bus.Factory.CreateUsingRabbitMq(sbc => { var host = sbc.Host(new Uri(ConfigurationManager.AppSettings["RabbitMQHost"]), h => { h.Username(ConfigurationManager.AppSettings["RabbitMQUsername"]); h.Password(ConfigurationManager.AppSettings["RabbitMQPassword"]); }); sbc.ReceiveEndpoint(host, ConfigurationManager.AppSettings["SendQueueName"], ep => ep.LoadFrom(c.Resolve<ILifetimeScope>())); })) .As<IBusControl>() .As<IBus>() .SingleInstance(); } } }
namespace SignalRChat.Web.Bootstrapper.Modules { using Autofac; using MassTransit; using System; using System.Configuration; public class BusModule : Module { private readonly System.Reflection.Assembly[] _assembliesToScan; public BusModule(params System.Reflection.Assembly[] assembliesToScan) { _assembliesToScan = assembliesToScan; } protected override void Load(ContainerBuilder builder) { // Registers all consumers with our container builder.RegisterAssemblyTypes(_assembliesToScan) .Where(t => { var a = typeof(IConsumer).IsAssignableFrom(t); return a; }) .AsSelf(); // Creates our bus from the factory and registers it as a singleton against two interfaces builder.Register(c => Bus.Factory.CreateUsingRabbitMq(sbc => { var host = sbc.Host(new Uri(ConfigurationManager.AppSettings["RabbitMQHost"]), h => { h.Username(ConfigurationManager.AppSettings["RabbitMQUsername"]); h.Password(ConfigurationManager.AppSettings["RabbitMQPassword"]); }); sbc.ReceiveEndpoint(host, ConfigurationManager.AppSettings["SendQueueName"], ep => ep.LoadFrom(c.Resolve<ILifetimeScope>())); })) .As<IBusControl>() .As<IBus>() .SingleInstance(); } } }
mit
C#
96cef32503f6f16376ec86fad04ea91066fa5700
Update HtmlSanitizerOptions.cs
mganss/HtmlSanitizer
src/HtmlSanitizer/HtmlSanitizerOptions.cs
src/HtmlSanitizer/HtmlSanitizerOptions.cs
using AngleSharp.Css.Dom; using System; using System.Collections.Generic; namespace Ganss.XSS { /// <summary> /// Provides options to be used with <see cref="HtmlSanitizer"/>. /// </summary> public class HtmlSanitizerOptions { /// <summary> /// Gets or sets the allowed tag names such as "a" and "div". /// </summary> public ISet<string> AllowedTags { get; set; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets or sets the allowed HTML attributes such as "href" and "alt". /// </summary> public ISet<string> AllowedAttributes { get; set; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets or sets the allowed CSS classes. /// </summary> public ISet<string> AllowedCssClasses { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the allowed CSS properties such as "font" and "margin". /// </summary> public ISet<string> AllowedCssProperties { get; set; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets or sets the allowed CSS at-rules such as "@media" and "@font-face". /// </summary> public ISet<CssRuleType> AllowedAtRules { get; set; } = new HashSet<CssRuleType>(); /// <summary> /// Gets or sets the allowed URI schemes such as "http" and "https". /// </summary> public ISet<string> AllowedSchemes { get; set; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets or sets the HTML attributes that can contain a URI such as "href". /// </summary> public ISet<string> UriAttributes { get; set; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } }
using AngleSharp.Css.Dom; using System; using System.Collections.Generic; namespace Ganss.XSS { /// <summary> /// Provides options to be used with <see cref="HtmlSanitizer"/>. /// </summary> public class HtmlSanitizerOptions { /// <summary> /// Gets or sets the allowed tag names such as "a" and "div". /// </summary> public ISet<string> AllowedTags { get; set; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets or sets the allowed HTML attributes such as "href" and "alt". /// </summary> public ISet<string> AllowedAttributes { get; set; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets or sets the allowed CSS classes. /// </summary> public ISet<string> AllowedCssClasses { get; set; } = new HashSet<string>(); /// <summary> /// Gets or sets the allowed CSS properties such as "font" and "margin". /// </summary> public ISet<string> AllowedCssProperties { get; set; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets or sets the allowed CSS at-rules such as "@media" and "@font-face". /// </summary> public ISet<CssRuleType> AllowedAtRules { get; set; } = new HashSet<CssRuleType>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets or sets the allowed URI schemes such as "http" and "https". /// </summary> public ISet<string> AllowedSchemes { get; set; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets or sets the HTML attributes that can contain a URI such as "href". /// </summary> public ISet<string> UriAttributes { get; set; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } }
mit
C#
db81e8e361684c22173124d661a994f17e8b56df
Add prism xml:ns to PrismApplication (#450)
paulcbetts/splat
src/Splat.Prism.Forms/PrismApplication.cs
src/Splat.Prism.Forms/PrismApplication.cs
// Copyright (c) 2019 .NET Foundation and Contributors. All rights reserved. // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using Prism; using Prism.Ioc; [assembly: Xamarin.Forms.XmlnsDefinition("http://prismlibrary.com", "Splat.Prism.Forms")] namespace Splat.Prism.Forms { /// <summary> /// A application instance which supports Prism types. /// </summary> public abstract class PrismApplication : PrismApplicationBase { /// <summary> /// Initializes a new instance of the <see cref="PrismApplication"/> class. /// </summary> /// <param name="initializer">An initializer for initializing the platform.</param> public PrismApplication(IPlatformInitializer initializer = null) : base(initializer) { } /// <inheritdoc/> protected override IContainerExtension CreateContainerExtension() { return new SplatContainerExtension(); } } }
// Copyright (c) 2019 .NET Foundation and Contributors. All rights reserved. // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using Prism; using Prism.Ioc; namespace Splat.Prism.Forms { /// <summary> /// A application instance which supports Prism types. /// </summary> public abstract class PrismApplication : PrismApplicationBase { /// <summary> /// Initializes a new instance of the <see cref="PrismApplication"/> class. /// </summary> /// <param name="initializer">An initializer for initializing the platform.</param> public PrismApplication(IPlatformInitializer initializer = null) : base(initializer) { } /// <inheritdoc/> protected override IContainerExtension CreateContainerExtension() { return new SplatContainerExtension(); } } }
mit
C#
d68019b653b64a290abcdf085b037f8afb31bcd5
set error type depending on severity
jwldnr/VisualLinter
VisualLinter/Tagging/LinterTag.cs
VisualLinter/Tagging/LinterTag.cs
using jwldnr.VisualLinter.Linting; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; namespace jwldnr.VisualLinter.Tagging { internal class LinterTag : IErrorTag { public string ErrorType { get; } public object ToolTipContent { get; } internal LinterTag(LinterMessage message) { ErrorType = GetErrorType(message); ToolTipContent = GetToolTipContent(message.IsFatal, message.Message, message.RuleId); } private static string GetErrorType(LinterMessage message) { if (message.IsFatal) return PredefinedErrorTypeNames.SyntaxError; return RuleSeverity.Error == message.Severity ? PredefinedErrorTypeNames.SyntaxError : PredefinedErrorTypeNames.Warning; } private static object GetToolTipContent(bool isFatal, string message, string ruleId) { return isFatal ? message : $"{message} ({ruleId})"; } } }
using jwldnr.VisualLinter.Linting; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Tagging; namespace jwldnr.VisualLinter.Tagging { internal class LinterTag : IErrorTag { public string ErrorType { get; } public object ToolTipContent { get; } internal LinterTag(LinterMessage message) { ErrorType = GetErrorType(message.IsFatal); ToolTipContent = GetToolTipContent(message.IsFatal, message.Message, message.RuleId); } private static string GetErrorType(bool isFatal) { return isFatal ? PredefinedErrorTypeNames.SyntaxError : PredefinedErrorTypeNames.Warning; } private static object GetToolTipContent(bool isFatal, string message, string ruleId) { return isFatal ? message : $"{message} ({ruleId})"; } } }
mit
C#
6690478abda55fcb4b3c34620e8dca282f7e4e51
Check when internet connection is disabled
rassvet85/vk,kadkin/vk,HarkBack/vk,vknet/vk,SnakeAce/vk,kkohno/vk,DmitrySafronov/vk,vknet/vk,modink/vk,Soniclev/vk,mainefremov/vk,J2GIS/vk
VkApiGenerator.Console/Program.cs
VkApiGenerator.Console/Program.cs
using System.Net; using VkApiGenerator.Model; namespace VkApiGenerator.Console { class Program { static void Main(string[] args) { var methods = new[] { "notes.get", "notes.getById", "notes.getFriendsNotes", "notes.add", "notes.edit", "notes.delete", "notes.getComments", "notes.createComment", "notes.editComment", "notes.deleteComment", "notes.restoreComment" }; var parser = new VkApiParser(); foreach (string methodName in methods) { System.Console.WriteLine("*** {0} ***", methodName); VkMethodInfo methodInfo; try { methodInfo = parser.Parse(methodName); } catch (WebException ex) { System.Console.WriteLine(ex.Message); continue; } System.Console.WriteLine("DESCRIPTION: {0}", methodInfo.Description); System.Console.WriteLine("RETURN TEXT: {0}", methodInfo.ReturnText); System.Console.WriteLine("RETURN TYPE: {0}", methodInfo.ReturnType); System.Console.WriteLine("PAPAMETERS:"); foreach (var p in methodInfo.Params) { System.Console.WriteLine(" {0} - {1}", p.Name, p.Description); } System.Console.WriteLine("\n========================================\n"); System.Console.ReadLine(); } System.Console.WriteLine("done."); } } }
namespace VkApiGenerator.Console { class Program { static void Main(string[] args) { var methods = new[] { "notes.get", "notes.getById", "notes.getFriendsNotes", "notes.add", "notes.edit", "notes.delete", "notes.getComments", "notes.createComment", "notes.editComment", "notes.deleteComment", "notes.restoreComment" }; var parser = new VkApiParser(); foreach (string methodName in methods) { System.Console.WriteLine("*** {0} ***", methodName); var methodInfo = parser.Parse(methodName); System.Console.WriteLine("DESCRIPTION: {0}", methodInfo.Description); System.Console.WriteLine("RETURN TEXT: {0}", methodInfo.ReturnText); System.Console.WriteLine("RETURN TYPE: {0}", methodInfo.ReturnType); System.Console.WriteLine("PAPAMETERS:"); foreach (var p in methodInfo.Params) { System.Console.WriteLine(" {0} - {1}", p.Name, p.Description); } System.Console.WriteLine("\n========================================\n"); System.Console.ReadLine(); } System.Console.WriteLine("done."); } } }
mit
C#
2173fac4aa6d86899495fc76d6f963eac3429572
Update MartijnVanDijk.cs
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/MartijnVanDijk.cs
src/Firehose.Web/Authors/MartijnVanDijk.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MartijnVanDijk : IAmAMicrosoftMVP, IAmAXamarinMVP { public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://medium.com/feed/@martijn00"); } } public string FirstName => "Martijn"; public string LastName => "Van Dijk"; public string StateOrRegion => "Amsterdam, Netherlands"; public string EmailAddress => "mhvdijk@gmail.com"; public string ShortBioOrTagLine => "is developing apps at Xablu, and working with MvvmCross"; public Uri WebSite => new Uri("https://medium.com/@martijn00"); public string TwitterHandle => "mhvdijk"; public string GravatarHash => "22155f520ab611cf04f76762556ca3f5"; public string GitHubHandle => "martijn00"; public GeoPosition Position => new GeoPosition(52.3702160, 4.8951680); } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MartijnVanDijk : IAmAMicrosoftMVP, IAmAXamarinMVP { public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://medium.com/feed/@martijn00"); } } public string FirstName => "Martijn"; public string LastName => "Van Dijk"; public string StateOrRegion => "Amsterdam, Netherlands"; public string EmailAddress => "mhvdijk@gmail.com"; public string ShortBioOrTagLine => "is a Xamarin and Microsoft MVP working with MvvmCross"; public Uri WebSite => new Uri("https://medium.com/@martijn00"); public string TwitterHandle => "mhvdijk"; public string GravatarHash => "22155f520ab611cf04f76762556ca3f5"; public string GitHubHandle => "martijn00"; public GeoPosition Position => new GeoPosition(52.3702160, 4.8951680); } }
mit
C#
8a6450ff75f5804e230f56b6a7a5e1917163fbf7
Bump version to 2.1.0
dreamer2908/YAXBPC,dreamer2908/YAXBPC
YAXBPC/Properties/AssemblyInfo.cs
YAXBPC/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("Yet Another xdelta-based Patch Creator")] [assembly: AssemblyDescription("Yet Another xdelta-based Patch Creator")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Yet Another xdelta-based Patch Creator")] [assembly: AssemblyCopyright("Copyleft © dreamer2908, 2012 - 2016. All wrongs reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("74ce6b2a-b97c-4a4b-91cc-9343b4a87ecb")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Yet Another xdelta-based Patch Creator")] [assembly: AssemblyDescription("Yet Another xdelta-based Patch Creator")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Yet Another xdelta-based Patch Creator")] [assembly: AssemblyCopyright("Copyleft © dreamer2908, 2012 - 2016. All wrongs reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("74ce6b2a-b97c-4a4b-91cc-9343b4a87ecb")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
apache-2.0
C#
6672e0f3cb88351f98df9388ce756832cfb2caf2
Add the Abort method to the IHttpTransaction interface.
mdavid/manos-spdy,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos
src/Mango/Mango.Server/IHttpTransaction.cs
src/Mango/Mango.Server/IHttpTransaction.cs
using System; using System.Collections; using System.Collections.Generic; namespace Mango.Server { public interface IHttpTransaction { HttpRequest Request { get; } HttpResponse Response { get; } void Write (List<ArraySegment<byte>> data); void SendFile (string file); void Finish (); void Abort (int status, string message, params object [] p); } }
using System; using System.Collections; using System.Collections.Generic; namespace Mango.Server { public interface IHttpTransaction { HttpRequest Request { get; } HttpResponse Response { get; } void Write (List<ArraySegment<byte>> data); void SendFile (string file); void Finish (); } }
mit
C#
65fa98c59e0dc928015bda87f20920f26a752c8b
Add coroutine usage in AEX
appetizermonster/Unity3D-ActionEngine
Assets/DemoScene/AEX/VeryAwesomeAEX.cs
Assets/DemoScene/AEX/VeryAwesomeAEX.cs
using ActionEngine; using System.Collections; using UnityEngine; public static class VeryAwesomeAEX { public static ActionBase Create (IAEScriptContext ctx) { var simpleAEX = ctx.GetAEScript("$simple"); var cube = ctx.GetTransform("$cube"); var sphere = ctx.GetTransform("$sphere"); return AE.Sequence( AE.Parallel( // You can use another AEX simpleAEX.Create(), // Basic tweens cube.AEMove(new Vector3(0, -3, 0), 3.5f).Easing(Easings.BounceInOut), sphere.AEMove(new Vector3(0, 3, 0), 4.5f).Easing(Easings.ElasticOut) ), AE.Parallel( cube.AEMove(new Vector3(0, 3, 0), 2.5f).Relative(true).Easing(Easings.BackOut), sphere.AEMove(new Vector3(0, -3, 0), 3.5f).Relative(true).Easing(Easings.QuadOut) ), AE.Coroutine(() => ExampleCoroutine()), AE.Debug("All Completed!") ); } private static IEnumerator ExampleCoroutine () { Debug.Log("Coroutine Started: " + Time.time); yield return new WaitForSeconds(2f); Debug.Log("Coroutine End: " + Time.time); } }
using UnityEngine; using System.Collections; using ActionEngine; public static class VeryAwesomeAEX { public static ActionBase Create (IAEScriptContext ctx) { var simpleAEX = ctx.GetAEScript("$simple"); var cube = ctx.GetTransform("$cube"); var sphere = ctx.GetTransform("$sphere"); return AE.Sequence( AE.Parallel( // You can use another AEX simpleAEX.Create(), // Basic tweens cube.AEMove(new Vector3(0, -3, 0), 3.5f).Easing(Easings.BounceInOut), sphere.AEMove(new Vector3(0, 3, 0), 4.5f).Easing(Easings.ElasticOut) ), AE.Parallel( cube.AEMove(new Vector3(0, 3, 0), 2.5f).Relative(true).Easing(Easings.BackOut), sphere.AEMove(new Vector3(0, -3, 0), 3.5f).Relative(true).Easing(Easings.QuadOut) ), AE.Delay(0.5f), AE.Debug("All Completed!") ); } }
mit
C#
e8e823e53aa282be2883bebbc01fc7bd1252cd0b
remove duplicated Header Methods
CloudBreadProject/CloudBread-Client-Unity,CloudBreadProject/CloudBread-Client-Unity,CloudBreadProject/CloudBread-Client-Unity,CloudBreadProject/CloudBread-Client-Unity
Assets/Scripts/CloudBread/WWWHelper.cs
Assets/Scripts/CloudBread/WWWHelper.cs
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Text; using AssemblyCSharp; public class WWWHelper : MonoBehaviour { public delegate void HttpRequestDelegate(string id, WWW www); public event HttpRequestDelegate OnHttpRequest; private int requestId; static WWWHelper current = null; static GameObject container = null; // Single-ton public static WWWHelper Instance { get { if (current == null) { container = new GameObject(); container.name = "WWWHelper"; current = container.AddComponent(typeof(WWWHelper)) as WWWHelper; } return current; } } public void get(string url){ WWW www = new WWW (url); StartCoroutine (WaitForRequest ("1", www)); } public void get(string id, string url) { var header = AzureMobileAppRequestHelper.getHeader(); WWW www = new WWW (url, null, header); StartCoroutine(WaitForRequest(id, www)); } // POST with Dictionary JsonData public void POST(int id, string url, Dictionary<string, object> JsonData){ string jsonString = JsonParser.Write (JsonData); POST (id.ToString(), url, jsonString); } // POST with string JsonData public void POST(string id, string url, string JsonData){ var HeaderDic = AzureMobileAppRequestHelper.getHeader(); WWW www = new WWW(url, Encoding.UTF8.GetBytes(JsonData), HeaderDic); StartCoroutine(WaitForRequest(id, www)); } private IEnumerator WaitForRequest(string id, WWW www) { yield return www; bool hasCompleteListener = (OnHttpRequest != null); if (hasCompleteListener) { OnHttpRequest(id, www); } www.Dispose(); } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Text; using AssemblyCSharp; public class WWWHelper : MonoBehaviour { public delegate void HttpRequestDelegate(string id, WWW www); public event HttpRequestDelegate OnHttpRequest; private int requestId; static WWWHelper current = null; static GameObject container = null; // Single-ton public static WWWHelper Instance { get { if (current == null) { container = new GameObject(); container.name = "WWWHelper"; current = container.AddComponent(typeof(WWWHelper)) as WWWHelper; } return current; } } public void get(string url){ WWW www = new WWW (url); StartCoroutine (WaitForRequest ("1", www)); } public void get(string id, string url) { var header = getHeaders (); WWW www = new WWW (url, null, header); StartCoroutine(WaitForRequest(id, www)); } // POST with Dictionary JsonData public void POST(int id, string url, Dictionary<string, object> JsonData){ string jsonString = JsonParser.Write (JsonData); POST (id, url, jsonString); } // POST with string JsonData public void POST(string id, string url, string JsonData){ var HeaderDic = AzureMobileAppRequestHelper.getHeader(); WWW www = new WWW(url, Encoding.UTF8.GetBytes(JsonData), HeaderDic); StartCoroutine(WaitForRequest(id, www)); } private IEnumerator WaitForRequest(string id, WWW www) { yield return www; bool hasCompleteListener = (OnHttpRequest != null); if (hasCompleteListener) { OnHttpRequest(id, www); } www.Dispose(); } private Dictionary<string, string> getHeaders(Dictionary<string, string> header){ header ["Accept-Encoding"] = "gzip"; header ["Accept"] = "application/json"; header["ZUMO-API-VERSION"] = "2.0.0"; header["X-ZUMO-VERSION"] = "ZUMO/2.0 (lang=Managed; os=Windows Store; os_version=--; arch=X86; version=2.0.31217.0)"; header ["X-ZUMO-FEATURES"] = "AJ"; header ["X-ZUMO-INSTALLATION-ID"] = "fe52b710-0312-4cad-8d53-dfd28d4c6f9b"; header ["Content-Type"] = "application/json"; header["User-Agent"] = "ZUMO/2.0 (lang=Managed; os=Windows Store; os_version=--; arch=X86; version=2.0.31217.0)"; header ["x-zumo-auth"] = "ChangeHereForAuthentication"; return header; } private Dictionary<string, string> getHeaders(){ var header = new Dictionary<string, string> (); header ["Accept-Encoding"] = "gzip"; header ["Accept"] = "application/json"; header["ZUMO-API-VERSION"] = "2.0.0"; header["X-ZUMO-VERSION"] = "ZUMO/2.0 (lang=Managed; os=Windows Store; os_version=--; arch=X86; version=2.0.31217.0)"; header ["X-ZUMO-FEATURES"] = "AJ"; header ["X-ZUMO-INSTALLATION-ID"] = "fe52b710-0312-4cad-8d53-dfd28d4c6f9b"; header ["Content-Type"] = "application/json"; header["User-Agent"] = "ZUMO/2.0 (lang=Managed; os=Windows Store; os_version=--; arch=X86; version=2.0.31217.0)"; header ["x-zumo-auth"] = "ChangeHereForAuthentication"; return header; } }
mit
C#
c67704e28c4b7388901ccba1d8b30b986bd9664c
Add ability to return token from rule
jagrem/slang,jagrem/slang,jagrem/slang
slang/Lexing/Rules/Core/Rule.cs
slang/Lexing/Rules/Core/Rule.cs
using slang.Lexing.Tokens; using System; namespace slang.Lexing.Rules.Core { public abstract class Rule { public Func<Token> TokenCreator { get; set; } public static Rule operator | (Rule left, Rule right) { return new Or (left, right); } public static Rule operator + (Rule left, Rule right) { return new And (left, right); } public static implicit operator Rule (char value) { return new Constant (value); } public Rule Returns(Func<Token> tokenCreator = null) { TokenCreator = tokenCreator ?? new Func<Token>(() => Token.Empty); return this; } } }
namespace slang.Lexing.Rules.Core { public abstract class Rule { public static Rule operator | (Rule left, Rule right) { return new Or (left, right); } public static Rule operator + (Rule left, Rule right) { return new And (left, right); } public static implicit operator Rule (char value) { return new Constant (value); } } }
mit
C#
4efe97296dd9b1790f9e016733d5e60bb9e1ae17
Fix version
danielwertheim/mynatsclient,danielwertheim/mynatsclient
buildconfig.cake
buildconfig.cake
public class BuildConfig { private const string Version = "0.4.0"; private const bool IsPreRelease = true; public readonly string SrcDir = "./src/"; public readonly string OutDir = "./build/"; public string Target { get; private set; } public string SemVer { get; private set; } public string BuildProfile { get; private set; } public bool IsTeamCityBuild { get; private set; } public static BuildConfig Create( ICakeContext context, BuildSystem buildSystem) { if (context == null) throw new ArgumentNullException("context"); var target = context.Argument("target", "Default"); var buildRevision = context.Argument("buildrevision", "0"); return new BuildConfig { Target = target, SemVer = Version + (IsPreRelease ? "-b" + buildRevision : string.Empty), BuildProfile = context.Argument("configuration", "Release"), IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity }; } }
public class BuildConfig { private const string Version = "0.4.0"; private const bool IsPreRelease = true; public readonly string SrcDir = "./src/"; public readonly string OutDir = "./build/"; public string Target { get; private set; } public string SemVer { get; private set; } public string BuildProfile { get; private set; } public bool IsTeamCityBuild { get; private set; } public static BuildConfig Create( ICakeContext context, BuildSystem buildSystem) { if (context == null) throw new ArgumentNullException("context"); var target = context.Argument("target", "Default"); var buildRevision = context.Argument("buildrevision", "0"); return new BuildConfig { Target = target, SemVer = Version + (IsPreRelease ? buildRevision : "-b" + buildRevision), BuildProfile = context.Argument("configuration", "Release"), IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity }; } }
mit
C#
d94e1808496e2e22157e702b150f2b9482920070
Add MVC and middleware to listening only for 'api' requests
pawelec/todo-list,pawelec/todo-list,pawelec/todo-list,pawelec/todo-list
TodoList.Web/Startup.cs
TodoList.Web/Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using System.IO; namespace TodoList.Web { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // Redirect any non-api calls to the Angular app. app.Use(async (context, next) => { await next(); if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value) && !context.Request.Path.Value.StartsWith("/api/")) { context.Request.Path = "/index.html"; await next(); } }); app.UseMvcWithDefaultRoute(); app.UseDefaultFiles(); app.UseStaticFiles(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace TodoList.Web { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } } }
mit
C#
f5a07fcdf1610c8a962fc950f91d897c49095ec0
Update WpfTimer.cs
Minesweeper-6-Team-Project-Telerik/Minesweeper-6
src2/WpfMinesweeper/WpfTimer.cs
src2/WpfMinesweeper/WpfTimer.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WpfTimer.cs" company="Telerik Academy"> // Teamwork Project "Minesweeper-6" // </copyright> // <summary> // The wpf timer. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WpfMinesweeper { using System; using System.Windows.Threading; using Minesweeper.Models.Interfaces; /// <summary> /// The wpf timer. /// </summary> public class WpfTimer : IMinesweeperTimer { /// <summary> /// The timer. /// </summary> private readonly DispatcherTimer timer; /// <summary> /// Initializes a new instance of the <see cref="WpfTimer"/> class. /// </summary> /// <param name="timer"> /// The timer. /// </param> /// <param name="span"> /// The span. /// </param> public WpfTimer(DispatcherTimer timer, TimeSpan span) { this.timer = timer; this.timer.Interval = span; } /// <summary> /// The tick event. /// </summary> public event EventHandler TickEvent; /// <summary> /// The start. /// </summary> public void Start() { this.timer.Tick += (sender, args) => { if (this.TickEvent != null) { this.TickEvent(sender, args); } }; this.timer.Start(); } /// <summary> /// The stop. /// </summary> public void Stop() { this.timer.Stop(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WpfTimer.cs" company=""> // // </copyright> // <summary> // The wpf timer. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WpfMinesweeper { using System; using System.Windows.Threading; using Minesweeper.Models.Interfaces; /// <summary> /// The wpf timer. /// </summary> public class WpfTimer : IMinesweeperTimer { /// <summary> /// The timer. /// </summary> private readonly DispatcherTimer timer; /// <summary> /// Initializes a new instance of the <see cref="WpfTimer"/> class. /// </summary> /// <param name="timer"> /// The timer. /// </param> /// <param name="span"> /// The span. /// </param> public WpfTimer(DispatcherTimer timer, TimeSpan span) { this.timer = timer; this.timer.Interval = span; } /// <summary> /// The tick event. /// </summary> public event EventHandler TickEvent; /// <summary> /// The start. /// </summary> public void Start() { this.timer.Tick += (sender, args) => { if (this.TickEvent != null) { this.TickEvent(sender, args); } }; this.timer.Start(); } /// <summary> /// The stop. /// </summary> public void Stop() { this.timer.Stop(); } } }
mit
C#
d64667fbbc8476cfcfa99235f89a3aff221b968f
Update copyright
Seddryck/Cassis,Seddryck/Cassis
src/AssemblyInfo.cs
src/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: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Cédric L. Charlier")] [assembly: AssemblyProduct("Cassis")] [assembly: AssemblyCopyright("Copyright © Cédric L. Charlier 2014-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.5.0.*")] [assembly: AssemblyFileVersion("0.5.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: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Cédric L. Charlier")] [assembly: AssemblyProduct("Cassis")] [assembly: AssemblyCopyright("Copyright © Cédric L. Charlier 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.5.0.*")] [assembly: AssemblyFileVersion("0.5.0.0")]
apache-2.0
C#
7b3379a610bdab172e2d0cc2c6c8dcb48772e69b
Add BaseClassField::.ctor
Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver
src/AsmResolver.Symbols.Pdb/Leaves/BaseClassField.cs
src/AsmResolver.Symbols.Pdb/Leaves/BaseClassField.cs
namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a reference to a base class object in a structure. /// </summary> public class BaseClassField : CodeViewField { private readonly LazyVariable<CodeViewTypeRecord?> _type; /// <summary> /// Initializes an empty base class. /// </summary> /// <param name="typeIndex">The type index to assign to the base class field.</param> protected BaseClassField(uint typeIndex) : base(typeIndex) { _type = new LazyVariable<CodeViewTypeRecord?>(GetBaseType); } /// <summary> /// Creates a new base class field. /// </summary> /// <param name="type">The base type to reference.</param> public BaseClassField(CodeViewTypeRecord type) : base(0) { _type = new LazyVariable<CodeViewTypeRecord?>(type); } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.BClass; /// <summary> /// Gets or sets the base type that this base class is referencing. /// </summary> public CodeViewTypeRecord? Type { get => _type.Value; set => _type.Value = value; } /// <summary> /// Gets or sets the offset of the base within the class. /// </summary> public ulong Offset { get; set; } /// <summary> /// Obtains the base type that the class is referencing. /// </summary> /// <returns>The base type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Type"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetBaseType() => null; /// <inheritdoc /> public override string ToString() => Type?.ToString() ?? "<<<?>>>"; }
namespace AsmResolver.Symbols.Pdb.Leaves; /// <summary> /// Represents a reference to a base class object in a structure. /// </summary> public class BaseClassField : CodeViewField { private readonly LazyVariable<CodeViewTypeRecord?> _type; /// <summary> /// Initializes an empty base class. /// </summary> /// <param name="typeIndex">The type index to assign to the base class field.</param> protected BaseClassField(uint typeIndex) : base(typeIndex) { _type = new LazyVariable<CodeViewTypeRecord?>(GetBaseType); } /// <inheritdoc /> public override CodeViewLeafKind LeafKind => CodeViewLeafKind.BClass; /// <summary> /// Gets or sets the base type that this base class is referencing. /// </summary> public CodeViewTypeRecord? Type { get => _type.Value; set => _type.Value = value; } /// <summary> /// Gets or sets the offset of the base within the class. /// </summary> public ulong Offset { get; set; } /// <summary> /// Obtains the base type that the class is referencing. /// </summary> /// <returns>The base type.</returns> /// <remarks> /// This method is called upon initialization of the <see cref="Type"/> property. /// </remarks> protected virtual CodeViewTypeRecord? GetBaseType() => null; /// <inheritdoc /> public override string ToString() => Type?.ToString() ?? "<<<?>>>"; }
mit
C#
3e5ccfcd4f8451b1990177c04730ac20f05a3a2b
Update Operators_Expressions
neyogiry/Examples_Csharp
Operators_Expressions.cs
Operators_Expressions.cs
using System; public class Operators_Expressions{ static void Main(string[] args){ int x, y, a, b; // Assigment operator x = 3; y = 2; a = 1; b = 0; // There are many mathematical operators // Addittion operator x = 3 + 4; // Subtraction operator x = 4 -3; // Multiplication operator x = 10 * 5; // Division operator x = 10 / 5; // There are many operators used to evaluate values // Equality operator if (x == y) { } // Greater than operator if (x > y) { } // Less operator if (x < y) { } // Greater or equal to operator if (x > y) { } // Less than or equal to operator if (x > y) { } // There are two "conditional" operators as well that can be used to expand / enhance // an evaluation and they can be conbined together multiple times. // Conditional AND operator if ((x > y) && (a > b)) { } // Conditional OR operator if ((x > y) || (a > b)) { } // Also, here's the in-line conditional operator we learned about // in the previous lesson string message = (x == 1) ? "Positive" : "Negative"; // Menber acces and Method invocation Console.WriteLine("Hello Neyo!"); } }
using System; public class Hello_Neyo{ static void Main(string[] args){ int x, y, a, b; // Assigment operator x = 3; y = 2; a = 1; b = 0; // There are many mathematical operators // Addittion operator x = 3 + 4; // Subtraction operator x = 4 -3; // Multiplication operator x = 10 * 5; // Division operator x = 10 / 5; // There are many operators used to evaluate values // Equality operator if (x == y) { } // Greater than operator if (x > y) { } // Less operator if (x < y) { } // Greater or equal to operator if (x > y) { } // Less than or equal to operator if (x > y) { } // There are two "conditional" operators as well that can be used to expand / enhance // an evaluation and they can be conbined together multiple times. // Conditional AND operator if ((x > y) && (a > b)) { } // Conditional OR operator if ((x > y) || (a > b)) { } // Also, here's the in-line conditional operator we learned about // in the previous lesson string message = (x == 1) ? "Positive" : "Negative"; // Menber acces and Method invocation Console.WriteLine("Hello Neyo!"); } }
mpl-2.0
C#
1adbd95b8585f471fe0866d5f83e6e634cb15c70
Mark the playback states with integer values
flagbug/Espera.Network
Espera.Network/NetworkPlaybackState.cs
Espera.Network/NetworkPlaybackState.cs
namespace Espera.Network { public enum NetworkPlaybackState { None = 0, Playing = 1, Paused = 2, Stopped = 3, Finished = 4 } }
namespace Espera.Network { public enum NetworkPlaybackState { None, Playing, Paused, Stopped, Finished } }
mit
C#
e78cf9dd080bff6e1c58002440bd9e57f5c81874
Check the use of default(T) instead exception.
fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,ngbrown/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core
src/NHibernate.Test/NHSpecificTest/NH1119/Fixture.cs
src/NHibernate.Test/NHSpecificTest/NH1119/Fixture.cs
using System; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH1119 { [TestFixture] public class Fixture : BugTestCase { public override string BugNumber { get { return "NH1119"; } } [Test] public void SelectMinFromEmptyTable() { using (ISession s = OpenSession()) { DateTime dt = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime>(); Assert.AreEqual(default(DateTime), dt); } } } }
using NUnit.Framework; using System; using System.Collections.Generic; namespace NHibernate.Test.NHSpecificTest.NH1119 { [TestFixture] public class Fixture : BugTestCase { public override string BugNumber { get { return "NH1119"; } } [Test] public void SelectMinFromEmptyTable() { using (ISession s = OpenSession()) { try { DateTime dt = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime>(); string msg = "Calling UniqueResult<T> where T is a value type" + " should throw InvalidCastException when the result" + " is null"; Assert.Fail(msg); } catch (InvalidCastException) { } } } } }
lgpl-2.1
C#
5b692a09d1999c8aec02aefc96cfc6558984e0b8
Set the detail instead of the title
khellang/Middleware,khellang/Middleware
src/ProblemDetails/Mvc/ProblemDetailsResultFilter.cs
src/ProblemDetails/Mvc/ProblemDetailsResultFilter.cs
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using static Hellang.Middleware.ProblemDetails.ProblemDetailsOptionsSetup; using MvcProblemDetails = Microsoft.AspNetCore.Mvc.ProblemDetails; using MvcProblemDetailsFactory = Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory; namespace Hellang.Middleware.ProblemDetails.Mvc { internal class ProblemDetailsResultFilter : IAlwaysRunResultFilter, IOrderedFilter { public ProblemDetailsResultFilter(MvcProblemDetailsFactory factory) { Factory = factory; } /// <summary> /// The same order as the built-in ClientErrorResultFilter. /// </summary> public int Order => -2000; private MvcProblemDetailsFactory Factory { get; } public void OnResultExecuting(ResultExecutingContext context) { // Only handle ObjectResult for now. if (context.Result is not ObjectResult result) { return; } // Make sure the result should be treated as a problem. if (!IsProblemStatusCode(result.StatusCode)) { return; } // Only handle the string case for now. if (result.Value is not string detail) { return; } var problemDetails = Factory.CreateProblemDetails(context.HttpContext, result.StatusCode, detail: detail); context.Result = new ObjectResult(problemDetails) { StatusCode = problemDetails.Status, ContentTypes = { "application/problem+json", "application/problem+xml", }, }; } void IResultFilter.OnResultExecuted(ResultExecutedContext context) { // Not needed. } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using static Hellang.Middleware.ProblemDetails.ProblemDetailsOptionsSetup; using MvcProblemDetails = Microsoft.AspNetCore.Mvc.ProblemDetails; using MvcProblemDetailsFactory = Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory; namespace Hellang.Middleware.ProblemDetails.Mvc { internal class ProblemDetailsResultFilter : IAlwaysRunResultFilter, IOrderedFilter { public ProblemDetailsResultFilter(MvcProblemDetailsFactory factory) { Factory = factory; } /// <summary> /// The same order as the built-in ClientErrorResultFilter. /// </summary> public int Order => -2000; private MvcProblemDetailsFactory Factory { get; } public void OnResultExecuting(ResultExecutingContext context) { // Only handle ObjectResult for now. if (context.Result is not ObjectResult result) { return; } // Make sure the result should be treated as a problem. if (!IsProblemStatusCode(result.StatusCode)) { return; } // Only handle the string case for now. if (result.Value is not string title) { return; } var problemDetails = Factory.CreateProblemDetails(context.HttpContext, result.StatusCode, title); context.Result = new ObjectResult(problemDetails) { StatusCode = problemDetails.Status, ContentTypes = { "application/problem+json", "application/problem+xml", }, }; } void IResultFilter.OnResultExecuted(ResultExecutedContext context) { // Not needed. } } }
mit
C#
18011c9026bc3fa7273ea877f5b8f1630649c82a
Update AssemblyInfo.cs
elv1s42/NUnitGo
NunitGoCore/Properties/AssemblyInfo.cs
NunitGoCore/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NunitGoCore")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("NunitGo")] [assembly: AssemblyProduct("NunitGoCore")] [assembly: AssemblyCopyright("Copyright © Kosjakov Evgeniy 2015-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("400678df-1078-47c5-b89f-69b27f41e404")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.1.5.0")] [assembly: AssemblyFileVersion("2.1.5.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NunitGoCore")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("NunitGo")] [assembly: AssemblyProduct("NunitGoCore")] [assembly: AssemblyCopyright("Copyright © Kosjakov Evgeniy 2015-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("400678df-1078-47c5-b89f-69b27f41e404")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.1.4.0")] [assembly: AssemblyFileVersion("2.1.4.0")]
mit
C#
c99536bad198e1cd9a35d5cb2303fd541d64a15a
Disable pooling in MSBuild as it's not really needed there
ShikiGami/React.NET,alexsoftua/React.NET,alexsoftua/React.NET,SaltyDH/React.NET,rickbeerendonk/React.NET,alexsoftua/React.NET,reactjs/React.NET,rickbeerendonk/React.NET,reactjs/React.NET,rickbeerendonk/React.NET,radnor/React.NET,ShikiGami/React.NET,reactjs/React.NET,IveWong/React.NET,radnor/React.NET,chriscamplejohn/React.NET,ShikiGami/React.NET,reactjs/React.NET,chriscamplejohn/React.NET,reactjs/React.NET,SaltyDH/React.NET,ShikiGami/React.NET,radnor/React.NET,rickbeerendonk/React.NET,IveWong/React.NET,chriscamplejohn/React.NET,IveWong/React.NET,reactjs/React.NET,SaltyDH/React.NET,radnor/React.NET,chriscamplejohn/React.NET,alexsoftua/React.NET,IveWong/React.NET,SaltyDH/React.NET
src/React.MSBuild/TransformJsx.cs
src/React.MSBuild/TransformJsx.cs
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ using System.Diagnostics; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace React.MSBuild { /// <summary> /// MSBuild task that handles transforming JSX to JavaScript /// </summary> public class TransformJsx : Task { /// <summary> /// The ReactJS.NET environment /// </summary> private IReactEnvironment _environment; /// <summary> /// Directory to process JSX files in. All subdirectories will be searched. /// </summary> [Required] public string SourceDir { get; set; } /// <summary> /// A value indicating if es6 syntax should be rewritten. /// </summary> /// <returns><c>true</c> if support for es6 syntax should be rewritten.</returns> public bool UseHarmony { get; set; } /// <summary> /// Gets or sets whether Flow types should be stripped. /// </summary> public bool StripTypes { get; set; } /// <summary> /// Executes the task. /// </summary> /// <returns><c>true</c> on success</returns> public override bool Execute() { MSBuildHost.EnsureInitialized(); var config = React.AssemblyRegistration.Container.Resolve<IReactSiteConfiguration>(); config .SetReuseJavaScriptEngines(false) .SetUseHarmony(UseHarmony) .SetStripTypes(StripTypes); _environment = React.AssemblyRegistration.Container.Resolve<IReactEnvironment>(); Log.LogMessage("Starting TransformJsx"); var stopwatch = Stopwatch.StartNew(); var result = ExecuteInternal(); Log.LogMessage("TransformJsx completed in {0}", stopwatch.Elapsed); return result; } /// <summary> /// The core of the task. Locates all JSX files and transforms them to JavaScript. /// </summary> /// <returns><c>true</c> on success</returns> private bool ExecuteInternal() { var files = Directory.EnumerateFiles(SourceDir, "*.jsx", SearchOption.AllDirectories); foreach (var path in files) { var relativePath = path.Substring(SourceDir.Length + 1); Log.LogMessage(" -> Processing {0}", relativePath); _environment.JsxTransformer.TransformAndSaveJsxFile(path); } return true; } } }
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ using System.Diagnostics; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace React.MSBuild { /// <summary> /// MSBuild task that handles transforming JSX to JavaScript /// </summary> public class TransformJsx : Task { /// <summary> /// The ReactJS.NET environment /// </summary> private IReactEnvironment _environment; /// <summary> /// Directory to process JSX files in. All subdirectories will be searched. /// </summary> [Required] public string SourceDir { get; set; } /// <summary> /// A value indicating if es6 syntax should be rewritten. /// </summary> /// <returns><c>true</c> if support for es6 syntax should be rewritten.</returns> public bool UseHarmony { get; set; } /// <summary> /// Gets or sets whether Flow types should be stripped. /// </summary> public bool StripTypes { get; set; } /// <summary> /// Executes the task. /// </summary> /// <returns><c>true</c> on success</returns> public override bool Execute() { MSBuildHost.EnsureInitialized(); var config = React.AssemblyRegistration.Container.Resolve<IReactSiteConfiguration>(); config.UseHarmony = UseHarmony; config.StripTypes = StripTypes; _environment = React.AssemblyRegistration.Container.Resolve<IReactEnvironment>(); Log.LogMessage("Starting TransformJsx"); var stopwatch = Stopwatch.StartNew(); var result = ExecuteInternal(); Log.LogMessage("TransformJsx completed in {0}", stopwatch.Elapsed); return result; } /// <summary> /// The core of the task. Locates all JSX files and transforms them to JavaScript. /// </summary> /// <returns><c>true</c> on success</returns> private bool ExecuteInternal() { var files = Directory.EnumerateFiles(SourceDir, "*.jsx", SearchOption.AllDirectories); foreach (var path in files) { var relativePath = path.Substring(SourceDir.Length + 1); Log.LogMessage(" -> Processing {0}", relativePath); _environment.JsxTransformer.TransformAndSaveJsxFile(path); } return true; } } }
bsd-3-clause
C#
357c708653fa5d4d4c2bcbd2b095bbf78e07cbd3
build fix
flubu-core/flubu.core,flubu-core/flubu.core,flubu-core/flubu.core,flubu-core/flubu.core
src/FlubuCore.WebApi/Program.cs
src/FlubuCore.WebApi/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace FlubuCore.WebApi { public class Program { public static void Main(string[] args) { #if NETCOREAPP3_1 var webHostBuilder = Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseKestrel(o => { o.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(10); }) .UseIIS() .UseStartup<Startup>(); }).Build(); webHostBuilder.Run(); #else var host = new WebHostBuilder() .UseKestrel(o => { o.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(10); }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); #endif } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace FlubuCore.WebApi { public class Program { public static void Main(string[] args) { #if NETCOREAPP3_1 var webHostBuilder = Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { .UseKestrel(o => { o.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(10); }) .UseIIS() .UseStartup<Startup>(); }).Build(); webHostBuilder.Run(); #else var host = new WebHostBuilder() .UseKestrel(o => { o.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(10); }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); #endif } } }
bsd-2-clause
C#
9e84857bc8a9003e35f7fc7ecc2fc7ea5355f8b2
format code
mkarpusiewicz/SwiftHelper
src/UnitTests/AllUniqueTests.cs
src/UnitTests/AllUniqueTests.cs
using System.Linq; using SimpleSamples; using SwiftHelper; using Xunit; namespace UnitTests { [Trait("Category", "Production")] public class AllUniqueTests { [Fact] public void AllUniqueByFalse() { var data = Enumerable.Range(1, 100) .Concat(new[] {50, 1, 100}) .Select(i => new SimpleUser {Name = $"Name{i}", Age = i}); var result = data.AllUniqueBy(u => u.Age); Assert.False(result); } [Fact] public void AllUniqueByTrue() { var data = Enumerable.Range(1, 100) .Select(i => new SimpleUser {Name = $"Name{i}", Age = i}); var result = data.AllUniqueBy(u => u.Age); Assert.True(result); } [Fact] public void AllUniqueFalse() { var data = Enumerable.Range(1, 100) .Concat(new[] {50, 1, 100}); var result = data.AllUnique(); Assert.False(result); } [Fact] public void AllUniqueTrue() { var data = Enumerable.Range(1, 100); var result = data.AllUnique(); Assert.True(result); } } }
using System.Linq; using SimpleSamples; using SwiftHelper; using Xunit; namespace UnitTests { [Trait("Category", "Production")] public class AllUniqueTests { [Fact] public void AllUniqueByFalse() { var data = Enumerable.Range(1, 100).Concat(new[] {50, 1, 100}).Select(i => new SimpleUser {Name = $"Name{i}", Age = i}); var result = data.AllUniqueBy(u => u.Age); Assert.False(result); } [Fact] public void AllUniqueByTrue() { var data = Enumerable.Range(1, 100).Select(i => new SimpleUser {Name = $"Name{i}", Age = i}); var result = data.AllUniqueBy(u => u.Age); Assert.True(result); } [Fact] public void AllUniqueFalse() { var data = Enumerable.Range(1, 100).Concat(new[] {50, 1, 100}); var result = data.AllUnique(); Assert.False(result); } [Fact] public void AllUniqueTrue() { var data = Enumerable.Range(1, 100); var result = data.AllUnique(); Assert.True(result); } } }
mit
C#
976946c964223348b7ccb2b07492f6a312ba9012
Update UserSettings_.cs
Developer-ReCap-Autodesk/WpfCSharp
AutodeskWpfReCap/UserSettings_.cs
AutodeskWpfReCap/UserSettings_.cs
// (C) Copyright 2014 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. //- Written by Cyrille Fauvel, Autodesk Developer Network (ADN) //- http://www.autodesk.com/joinadn //- January 20th, 2014 // using System; using System.Collections.Generic; using System.Linq; using System.Text; // Why 'static readonly' vs 'public const string' // http://www.stum.de/2009/01/14/const-strings-a-very-convenient-way-to-shoot-yourself-in-the-foot/ namespace Autodesk.ADN.WpfReCap { public class UserSettings { // Hard coded consumer and secret keys and base URL. // In real world Apps, these values need to secured. // One approach is to encrypt and/or obfuscate these values public static readonly string CONSUMER_KEY ="your_consumer_key" ; public static readonly string CONSUMER_SECRET ="your_consumer_secret_key" ; public static readonly string OAUTH_HOST ="https://accounts.autodesk.com/" ; // Autodesk production accounts server //public static readonly string OAUTH_HOST ="https://accounts-staging.autodesk.com/" ; // Autodesk staging accounts server // ReCap: Fill in these macros with the correct information (only the 2 first are important) public static readonly string ReCapAPIURL ="http://rc-api-adn.autodesk.com/3.1/API/" ; public static readonly string ReCapClientID ="your_ReCap_client_ID" ; //public static readonly string ReCapKey ="your ReCap client key" ; // not used anymore // Do not edit public static readonly string OAUTH_REQUESTTOKEN ="OAuth/RequestToken" ; public static readonly string OAUTH_ACCESSTOKEN ="OAuth/AccessToken" ; public static readonly string OAUTH_AUTHORIZE ="OAuth/Authorize" ; public static readonly string OAUTH_INVALIDATETOKEN ="OAuth/InvalidateToken" ; public static readonly string OAUTH_ALLOW =OAUTH_HOST + "OAuth/Allow" ; } }
// (C) Copyright 2014 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. //- Written by Cyrille Fauvel, Autodesk Developer Network (ADN) //- http://www.autodesk.com/joinadn //- January 20th, 2014 // using System; using System.Collections.Generic; using System.Linq; using System.Text; // Why 'static readonly' vs 'public const string' // http://www.stum.de/2009/01/14/const-strings-a-very-convenient-way-to-shoot-yourself-in-the-foot/ namespace Autodesk.ADN.WpfReCap { public class UserSettings { // Hard coded consumer and secret keys and base URL. // In real world Apps, these values need to secured. // One approach is to encrypt and/or obfuscate these values public static readonly string CONSUMER_KEY ="your consumer key" ; public static readonly string CONSUMER_SECRET ="your consumer secret key" ; public static readonly string OAUTH_HOST ="https://accounts.autodesk.com/" ; // Autodesk production accounts server //public static readonly string OAUTH_HOST ="https://accounts-staging.autodesk.com/" ; // Autodesk staging accounts server // ReCap: Fill in these macros with the correct information (only the 2 first are important) public static readonly string ReCapAPIURL ="http://rc-api-adn.autodesk.com/3.1/API/" ; public static readonly string ReCapClientID ="your ReCap client ID" ; //public static readonly string ReCapKey ="your ReCap client key" ; // not used anymore // Do not edit public static readonly string OAUTH_REQUESTTOKEN ="OAuth/RequestToken" ; public static readonly string OAUTH_ACCESSTOKEN ="OAuth/AccessToken" ; public static readonly string OAUTH_AUTHORIZE ="OAuth/Authorize" ; public static readonly string OAUTH_INVALIDATETOKEN ="OAuth/InvalidateToken" ; public static readonly string OAUTH_ALLOW =OAUTH_HOST + "OAuth/Allow" ; } }
mit
C#
390f72d7628425506e9b0e86b6b4843eccccc795
Check null in LoadProjectSubEntity
joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net
JoinRpg.Services.Impl/DbServiceImplBase.cs
JoinRpg.Services.Impl/DbServiceImplBase.cs
using System.Data.Entity.Validation; using JetBrains.Annotations; using JoinRpg.Dal.Impl; using JoinRpg.DataModel; namespace JoinRpg.Services.Impl { public class DbServiceImplBase { protected readonly IUnitOfWork UnitOfWork; protected DbServiceImplBase(IUnitOfWork unitOfWork) { UnitOfWork = unitOfWork; } [NotNull] protected T LoadProjectSubEntity<T>(int projectId, int subentityId) where T : class, IProjectSubEntity { var field = UnitOfWork.GetDbSet<T>().Find(subentityId); if (field != null && field.ProjectId == projectId) { return field; } throw new DbEntityValidationException(); } protected static string Required(string stringValue) { if (string.IsNullOrWhiteSpace(stringValue)) { throw new DbEntityValidationException(); } return stringValue.Trim(); } protected void SmartDelete<T>(T field) where T:class, IDeletableSubEntity { if (field.CanBePermanentlyDeleted) { UnitOfWork.GetDbSet<T>().Remove(field); } else { field.IsActive = false; } } } }
using System.Data.Entity.Validation; using JoinRpg.Dal.Impl; using JoinRpg.DataModel; namespace JoinRpg.Services.Impl { public class DbServiceImplBase { protected readonly IUnitOfWork UnitOfWork; protected DbServiceImplBase(IUnitOfWork unitOfWork) { UnitOfWork = unitOfWork; } protected T LoadProjectSubEntity<T>(int projectId, int subentityId) where T : class, IProjectSubEntity { var field = UnitOfWork.GetDbSet<T>().Find(subentityId); if (field.ProjectId == projectId) return field; throw new DbEntityValidationException(); } protected static string Required(string stringValue) { if (string.IsNullOrWhiteSpace(stringValue)) { throw new DbEntityValidationException(); } return stringValue.Trim(); } protected void SmartDelete<T>(T field) where T:class, IDeletableSubEntity { if (field.CanBePermanentlyDeleted) { UnitOfWork.GetDbSet<T>().Remove(field); } else { field.IsActive = false; } } } }
mit
C#
cdd9058127285c965be47c70e15d67518276d687
Fix iOS visual tests not using raw keyboard handler
ZLima12/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework
osu.Framework.Tests.iOS/Application.cs
osu.Framework.Tests.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.Framework.Tests.iOS { public class Application { // This is the main entry point of the application. public static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, "GameUIApplication", "AppDelegate"); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using UIKit; namespace osu.Framework.Tests.iOS { public class Application { // This is the main entry point of the application. public static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
mit
C#
958823d8ba285643a283a7b8545c2330ed8d73d2
Fix class name.
Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x
src/unity/Runtime/Ads/NullFullScreenAd.cs
src/unity/Runtime/Ads/NullFullScreenAd.cs
using System; using System.Threading.Tasks; using System.Xml.Xsl; namespace EE { public class NullFullScreenAd : ObserverManager<AdObserver>, IFullScreenAd { public void Destroy() { } public bool IsLoaded { get; } = false; public Task<bool> Load() { return Task.FromResult(false); } public Task<FullScreenAdResult> Show() { return Task.FromResult(FullScreenAdResult.Failed); } } }
using System; using System.Threading.Tasks; using System.Xml.Xsl; namespace EE { public class NullRewardedAd : ObserverManager<AdObserver>, IFullScreenAd { public void Destroy() { throw new NotImplementedException(); } public bool IsLoaded { get; } = false; public Task<bool> Load() { return Task.FromResult(false); } public Task<FullScreenAdResult> Show() { return Task.FromResult(FullScreenAdResult.Failed); } } }
mit
C#
c4bfb31d1fced6e23e636176ef4498e5dfdcaf82
Fix namespace
karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS
src/Package/Impl/Repl/RSessionProvider.cs
src/Package/Impl/Repl/RSessionProvider.cs
using System.Collections.Concurrent; using System.Diagnostics; using System.Linq; using Microsoft.R.Host.Client; namespace Microsoft.VisualStudio.R.Package.Repl { public class RSessionProvider : IRSessionProvider { private readonly ConcurrentDictionary<int, IRSession> _sessions = new ConcurrentDictionary<int, IRSession>(); public IRSession Create(int sessionId) { IRSession session = new RSession(); if (!_sessions.TryAdd(sessionId, session)) { Debug.Fail($"Session with id {sessionId} is created already"); return _sessions[sessionId]; } return session; } public IRSession Current => _sessions.Values.FirstOrDefault(); public void Dispose() { foreach (var session in _sessions.Values) { session.Dispose(); } _sessions.Clear(); } } }
using System.Collections.Concurrent; using System.Diagnostics; using System.Linq; using Microsoft.VisualStudio.R.Package.Repl; namespace Microsoft.R.Host.Client { public class RSessionProvider : IRSessionProvider { private readonly ConcurrentDictionary<int, IRSession> _sessions = new ConcurrentDictionary<int, IRSession>(); public IRSession Create(int sessionId) { IRSession session = new RSession(); if (!_sessions.TryAdd(sessionId, session)) { Debug.Fail($"Session with id {sessionId} is created already"); return _sessions[sessionId]; } return session; } public IRSession Current => _sessions.Values.FirstOrDefault(); public void Dispose() { foreach (var session in _sessions.Values) { session.Dispose(); } _sessions.Clear(); } } }
mit
C#
81124f27b0857a0cf177e6d97fd977afdc7ecd8a
Fix missing logger by moving the expanded detail to the exception
GeertvanHorrik/Costura,GeertvanHorrik/Costura,Fody/Costura,Fody/Costura
Costura.Tasks/ConfigFileFinder.cs
Costura.Tasks/ConfigFileFinder.cs
using System; using System.Collections.Generic; using System.IO; public class ConfigFileFinder { public static List<string> FindWeaverConfigs(string solutionDirectoryPath, string projectDirectory) { var files = new List<string>(); var solutionConfigFilePath = Path.Combine(solutionDirectoryPath, "FodyWeavers.xml"); if (File.Exists(solutionConfigFilePath)) { files.Add(solutionConfigFilePath); } var projectConfigFilePath = Path.Combine(projectDirectory, "FodyWeavers.xml"); if (File.Exists(projectConfigFilePath)) { files.Add(projectConfigFilePath); } if (files.Count == 0) { // ReSharper disable once UnusedVariable var pathsSearched = string.Join("', '", solutionConfigFilePath, projectConfigFilePath); throw new WeavingException($@"Could not find path to weavers file. Searched '{pathsSearched}'. Some project types do not support using NuGet to add content files e.g. netstandard projects. In these cases it is necessary to manually add a FodyWeavers.xml to the project. Example content: <Weavers> <WeaverName/> </Weavers> "); } return files; } }
using System; using System.Collections.Generic; using System.IO; public class ConfigFileFinder { public static List<string> FindWeaverConfigs(string solutionDirectoryPath, string projectDirectory) { var files = new List<string>(); var solutionConfigFilePath = Path.Combine(solutionDirectoryPath, "FodyWeavers.xml"); if (File.Exists(solutionConfigFilePath)) { files.Add(solutionConfigFilePath); logger.LogDebug($"Found path to weavers file '{solutionConfigFilePath}'."); } var projectConfigFilePath = Path.Combine(projectDirectory, "FodyWeavers.xml"); if (!File.Exists(projectConfigFilePath)) { logger.LogDebug($@"Could not file a FodyWeavers.xml at the project level ({projectConfigFilePath}). Some project types do not support using NuGet to add content files e.g. netstandard projects. In these cases it is necessary to manually add a FodyWeavers.xml to the project. Example content: <Weavers> <WeaverName/> </Weavers> "); } else { files.Add(projectConfigFilePath); logger.LogDebug($"Found path to weavers file '{projectConfigFilePath}'."); } if (files.Count == 0) { // ReSharper disable once UnusedVariable var pathsSearched = string.Join("', '", solutionConfigFilePath, projectConfigFilePath); throw new WeavingException($"Could not find path to weavers file. Searched '{pathsSearched}'."); } return files; } }
mit
C#
e26ce15012ebea478dcdcd80a4b179786816238f
Fix bug in new color action
jaquadro/MonoGdx
MonoGdx/Scene2D/Actions/ColorAction.cs
MonoGdx/Scene2D/Actions/ColorAction.cs
/** * Copyright 2011-2013 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Microsoft.Xna.Framework; namespace MonoGdx.Scene2D.Actions { /// <summary> /// Sets the actor's color (or a specified color), from the current to the new color. /// </summary> public class ColorAction : TemporalAction { private Color _startColor; /// <summary> /// Sets the color to modify. If null (default), the <see ref="Actor">actor's</see> color will be used. /// </summary> public Color? Color { get; set; } /// <summary> /// Sets the color to transition to. /// </summary> public Color EndColor { get; set; } protected override void Begin () { if (Color == null) Color = Actor.Color; _startColor = Color.Value; } protected override void Update (float percent) { float r = _startColor.R + (EndColor.R - _startColor.R) * percent; float g = _startColor.G + (EndColor.G - _startColor.G) * percent; float b = _startColor.B + (EndColor.B - _startColor.B) * percent; float a = _startColor.A + (EndColor.A - _startColor.A) * percent; Color = new Color((byte)r, (byte)g, (byte)b, (byte)a); Actor.Color = Color.Value; } public override void Reset () { base.Reset(); Color = null; } } }
/** * Copyright 2011-2013 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Microsoft.Xna.Framework; namespace MonoGdx.Scene2D.Actions { /// <summary> /// Sets the actor's color (or a specified color), from the current to the new color. /// </summary> public class ColorAction : TemporalAction { private Color _startColor; /// <summary> /// Sets the color to modify. If null (default), the <see ref="Actor">actor's</see> color will be used. /// </summary> public Color? Color { get; set; } /// <summary> /// Sets the color to transition to. /// </summary> public Color EndColor { get; set; } protected override void Begin () { if (Color == null) Color = Actor.Color; _startColor = Color.Value; } protected override void Update (float percent) { float r = _startColor.R + (EndColor.R - _startColor.R) * percent; float g = _startColor.G + (EndColor.G - _startColor.G) * percent; float b = _startColor.B + (EndColor.B - _startColor.B) * percent; float a = _startColor.A + (EndColor.A - _startColor.A) * percent; Color = new Color((byte)r, (byte)g, (byte)b, (byte)a); } public override void Reset () { base.Reset(); Color = null; } } }
apache-2.0
C#
b984bb22f515e18b242cbee868af675f78a94b90
add missing case Theme.System
DecaTec/windows-universal,altima/windows-universal,scherke/windows-universal,altima/windows-universal,TheScientist/windows-universal,DecaTec/windows-universal,scherke/windows-universal,SunboX/windows-universal,scherke/windows-universal,SunboX/windows-universal,scherke85/windows-universal,TheScientist/windows-universal,SunboX/windows-universal,scherke85/windows-universal,scherke85/windows-universal,altima/windows-universal,DecaTec/windows-universal,TheScientist/windows-universal
NextcloudApp/Controls/ThemeablePage.cs
NextcloudApp/Controls/ThemeablePage.cs
using System.ComponentModel; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using NextcloudApp.Services; using NextcloudApp.Utils; namespace NextcloudApp.Controls { public class ThemeablePage : Page { public ThemeablePage() { var theme = SettingsService.Instance.RoamingSettings.Theme; switch (theme) { case Theme.System: RequestedTheme = ElementTheme.Default; break; case Theme.Dark: RequestedTheme = ElementTheme.Dark; break; case Theme.Light: RequestedTheme = ElementTheme.Light; break; } SettingsService.Instance.RoamingSettings.PropertyChanged += RoamingSettingsOnPropertyChanged; } private void RoamingSettingsOnPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName.Equals("Theme")) { var theme = SettingsService.Instance.RoamingSettings.Theme; switch (theme) { case Theme.System: RequestedTheme = ElementTheme.Default; break; case Theme.Dark: RequestedTheme = ElementTheme.Dark; break; case Theme.Light: RequestedTheme = ElementTheme.Light; break; } } } } }
using System.ComponentModel; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using NextcloudApp.Services; using NextcloudApp.Utils; namespace NextcloudApp.Controls { public class ThemeablePage : Page { public ThemeablePage() { var theme = SettingsService.Instance.RoamingSettings.Theme; switch (theme) { case Theme.Dark: RequestedTheme = ElementTheme.Dark; break; case Theme.Light: RequestedTheme = ElementTheme.Light; break; } SettingsService.Instance.RoamingSettings.PropertyChanged += RoamingSettingsOnPropertyChanged; } private void RoamingSettingsOnPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName.Equals("Theme")) { var theme = SettingsService.Instance.RoamingSettings.Theme; switch (theme) { case Theme.Dark: RequestedTheme = ElementTheme.Dark; break; case Theme.Light: RequestedTheme = ElementTheme.Light; break; } } } } }
mpl-2.0
C#
08df3b769dc0850f179642b88741c2dabc8f1cec
Change LinterVersion output to json format
repometric/linterhub-cli,repometric/linterhub-cli,binore/linterhub-cli,binore/linterhub-cli,binore/linterhub-cli,repometric/linterhub-cli
src/cli/Strategy/LinterVersionStrategy.cs
src/cli/Strategy/LinterVersionStrategy.cs
namespace Linterhub.Cli.Strategy { using Runtime; using Engine; using Linterhub.Engine.Exceptions; using Newtonsoft.Json; using System.Dynamic; public class LinterVersionStrategy : IStrategy { public object Run(RunContext context, LinterFactory factory, LogManager log) { if (string.IsNullOrEmpty(context.Linter)) { throw new LinterEngineException("Linter is not specified: " + context.Linter); } dynamic result = new ExpandoObject(); var versionCmd = factory.BuildVersionCommand(context.Linter); var version = new LinterhubWrapper(context).LinterVersion(context.Linter, versionCmd).Trim(); result.LinterName = context.Linter; result.Installed = version.Contains("Can\'t find " + context.Linter) ? "No" : "Yes"; result.Version = ((string)result.Installed).Contains("No") ? "Unknown" : version; return JsonConvert.SerializeObject(result); } } }
namespace Linterhub.Cli.Strategy { using Runtime; using Engine; using Linterhub.Engine.Exceptions; public class LinterVersionStrategy : IStrategy { public object Run(RunContext context, LinterFactory factory, LogManager log) { if (string.IsNullOrEmpty(context.Linter)) { throw new LinterEngineException("Linter is not specified: " + context.Linter); } var result = ""; var versionCmd = factory.BuildVersionCommand(context.Linter); //System.Console.WriteLine(versionCmd); var version = string.IsNullOrEmpty(versionCmd) ? "Unknown" : new LinterhubWrapper(context).LinterVersion(context.Linter, versionCmd).Trim(); result += $"\n{context.Linter}: {version}"; return result; } } }
mit
C#
6f09f07d071a5953551e779f92066fc0c805036f
Update run.cake to use the addin package
jzeferino/ResxConverter,jzeferino/ResxConverter
run.cake
run.cake
// #r src/Cake.ResxConverter/bin/Release/ResxConverter.Core.dll // #r src/Cake.ResxConverter/bin/Release/ResxConverter.Mobile.dll // #r src/Cake.ResxConverter/bin/Release/Cake.ResxConverter.dll // using ResxConverter.Mobile; // Task("Run") // .Does(() => // { // CleanDirectory("artifacts/generated"); // var resxFolder = "test/ResxConverter.Mobile.Tests/Resources"; // ResxConverters.Android.Convert(resxFolder, "artifacts/generated/android"); // ResxConverters.iOS.Convert(resxFolder, "artifacts/generated/ios"); // }); #addin nuget:?package=Cake.ResxConverter&prerelease Task("Run") .Does(() => { var resxFolder = "test/ResxConverter.Mobile.Tests/Resources"; ResxConverter.ConvertToAndroid(resxFolder, "artifacts/generated/android"); ResxConverter.ConvertToiOS(resxFolder, "artifacts/generated/ios"); }); RunTarget("Run");
#r src/Cake.ResxConverter/bin/Release/ResxConverter.Core.dll #r src/Cake.ResxConverter/bin/Release/ResxConverter.Mobile.dll #r src/Cake.ResxConverter/bin/Release/Cake.ResxConverter.dll using ResxConverter.Mobile; Task("Run") .Does(() => { CleanDirectory("artifacts/generated"); var resxFolder = "test/ResxConverter.Mobile.Tests/Resources"; ResxConverters.Android.Convert(resxFolder, "artifacts/generated/android"); ResxConverters.iOS.Convert(resxFolder, "artifacts/generated/ios"); }); // #addin nuget:?package=Cake.ResxConverter&prerelease // Task("Run") // .Does(() => // { // var resxFolder = "test/ResxConverter.Mobile.Tests/Resources"; // ResxConverter.ConvertToAndroid(resxFolder, "artifacts/generated/android"); // ResxConverter.ConvertToiOS(resxFolder, "artifacts/generated/ios"); // }); RunTarget("Run");
mit
C#
0edef34b42389fa503b116e324ce23ee0ecf7c29
Remove try-catch in ConverterBase (=Fail fast)
thomasgalliker/ValueConverters.NET
ValueConverters.NetFx/ConverterBase.cs
ValueConverters.NetFx/ConverterBase.cs
using System; using System.Globalization; #if (NETFX || WINDOWS_PHONE) using System.Windows; using System.Windows.Data; #elif (WINDOWS_APP || WINDOWS_PHONE_APP) using Windows.UI.Xaml; using Windows.UI.Xaml.Data; #endif namespace ValueConverters { public abstract class ConverterBase : DependencyObject, IValueConverter { protected abstract object Convert(object value, Type targetType, object parameter, CultureInfo culture); protected virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(string.Format("Converter '{0}' does not support backward conversion.", this.GetType().Name)); } #if NETFX || WINDOWS_PHONE object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { return this.Convert(value, targetType, parameter, culture); } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return this.ConvertBack(value, targetType, parameter, culture); } #elif (WINDOWS_APP || WINDOWS_PHONE_APP) object IValueConverter.Convert(object value, Type targetType, object parameter, string culture) { return this.Convert(value, targetType, parameter, new CultureInfo(culture)); } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, string culture) { return this.ConvertBack(value, targetType, parameter, new CultureInfo(culture)); } #endif } }
using System; using System.Globalization; #if (NETFX || WINDOWS_PHONE) using System.Windows; using System.Windows.Data; #elif (WINDOWS_APP || WINDOWS_PHONE_APP) using Windows.UI.Xaml; using Windows.UI.Xaml.Data; #endif namespace ValueConverters { public abstract class ConverterBase : DependencyObject, IValueConverter { protected abstract object Convert(object value, Type targetType, object parameter, CultureInfo culture); protected virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(string.Format("Converter '{0}' does not support backward conversion.", this.GetType().Name)); } #if NETFX || WINDOWS_PHONE object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { return this.Convert(value, targetType, parameter, culture); } catch { return DependencyProperty.UnsetValue; } } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { try { return this.ConvertBack(value, targetType, parameter, culture); } catch { return DependencyProperty.UnsetValue; } } #elif (WINDOWS_APP || WINDOWS_PHONE_APP) object IValueConverter.Convert(object value, Type targetType, object parameter, string culture) { try { return this.Convert(value, targetType, parameter, new CultureInfo(culture)); } catch { return DependencyProperty.UnsetValue; } } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, string culture) { try { return this.ConvertBack(value, targetType, parameter, new CultureInfo(culture)); } catch { return DependencyProperty.UnsetValue; } } #endif } }
mit
C#
a24f3cc37c08dd2d2b01ad34f32430b3d6f39729
Fix issue #28 #27
vertigra/NetTelebot-2.0,themehrdad/NetTelebot
NetTelebot/ReplyKeyboardMarkup.cs
NetTelebot/ReplyKeyboardMarkup.cs
using System.Linq; using System.Text; namespace NetTelebot { /// <summary> /// This object represents a custom keyboard with reply options /// </summary> public class ReplyKeyboardMarkup : IReplyMarkup { /// <summary> /// Array of button rows, each represented by an Array of Strings /// </summary> public string[][] Keyboard { get; set; } /// <summary> /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). /// Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. /// </summary> public bool? ResizeKeyboard { get; set; } /// <summary> /// Optional. Requests clients to hide the keyboard as soon as it's been used. Defaults to false. /// </summary> public bool? OneTimeKeyboard { get; set; } /// <summary> /// Optional. Use this parameter if you want to show the keyboard to specific users only. /// Targets: /// 1) users that are @mentioned in the text of the Message object; /// 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message. /// </summary> public bool? Selective { get; set; } public string GetJson() { var builder = new StringBuilder(); var keyboard = GetKeyboardJson(); builder.AppendFormat("{{ \"keyboard\" : [{0}] ",keyboard); if (ResizeKeyboard.HasValue) builder.AppendFormat(", \"resize_keyboard\" : {0} ", ResizeKeyboard.Value.ToString().ToLower()); if (OneTimeKeyboard.HasValue) builder.AppendFormat(", \"one_time_keyboard\" : {0} ", OneTimeKeyboard.Value.ToString().ToLower()); if (Selective.HasValue) builder.AppendFormat(", \"selective\" : {0} ", Selective.Value.ToString().ToLower()); builder.Append("}"); return builder.ToString(); } private string GetKeyboardJson() { return string.Join(",", Keyboard.Select(line => $"[{string.Join(",", line.Select(item => $"\"{item}\"").ToArray())}]").ToArray()); } } }
using System.Linq; using System.Text; namespace NetTelebot { /// <summary> /// This object represents a custom keyboard with reply options /// </summary> public class ReplyKeyboardMarkup : IReplyMarkup { /// <summary> /// Array of button rows, each represented by an Array of Strings /// </summary> public string[][] Keyboard { get; set; } /// <summary> /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. /// </summary> public bool? ResizeKeyboard { get; set; } /// <summary> /// Optional. Requests clients to hide the keyboard as soon as it's been used. Defaults to false. /// </summary> public bool? OneTimeKeyboard { get; set; } /// <summary> /// Optional. Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message. /// </summary> public bool? Selective { get; set; } public string GetJson() { var builder = new StringBuilder(); var keyboard = GetKeyboardJson(); builder.AppendFormat("{{ \"keyboard\" : [{0}] ",keyboard); if (ResizeKeyboard.HasValue) builder.AppendFormat(", \"resize_keyboard\" : {0} ", ResizeKeyboard.Value.ToString().ToLower()); if (OneTimeKeyboard.HasValue) builder.AppendFormat(", \"one_time_keyboard\" : {0} ", OneTimeKeyboard.Value.ToString().ToLower()); if (Selective.HasValue) builder.AppendFormat(", \"selective\" : {0} ", Selective.Value.ToString().ToLower()); builder.Append("}"); return builder.ToString(); } private string GetKeyboardJson() { return string.Join(",", Keyboard.Select(line => string.Format("[{0}]", string.Join(",", line.Select(item => string.Format("\"{0}\"", item)).ToArray()))).ToArray()); } } }
mit
C#
dec012f9c2292c1cd69f8c060884119abf87c83b
add SM binary serialization test
Spreads/Spreads
tests/Spreads.Extensions.Tests/SerializationTests.cs
tests/Spreads.Extensions.Tests/SerializationTests.cs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; using NUnit.Framework; using Spreads.Buffers; using Spreads.Collections; using Spreads.Serialization; using Newtonsoft.Json; namespace Spreads.Extensions.Tests { [TestFixture] public class SerializationTests { [Test] public void CouldSerializeSortedMapWithJsonNet() { var sm = new SortedMap<DateTime, double>(); for (int i = 0; i < 10; i++) { sm.Add(DateTime.UtcNow.Date.AddDays(i), i); } var str = JsonConvert.SerializeObject(sm); Console.WriteLine(str); var sm2 = JsonConvert.DeserializeObject<SortedMap<DateTime, double>>(str); Assert.IsTrue(sm.SequenceEqual(sm2)); } [Test] public void CouldSerializeSortedMapWithBinary() { SortedMap<DateTime, double>.Init(); var sm = new SortedMap<DateTime, double>(); for (int i = 0; i < 10; i++) { sm.Add(DateTime.UtcNow.Date.AddDays(i), i); } MemoryStream tmp; var len = BinarySerializer.SizeOf(sm, out tmp); Console.WriteLine(len); var dest = BufferPool.PreserveMemory(len); var len2 = BinarySerializer.Write(sm, ref dest, 0, tmp); Assert.AreEqual(len, len2); SortedMap<DateTime, double> sm2 = null; BinarySerializer.Read<SortedMap<DateTime, double>>(dest, 0, ref sm2); Assert.IsTrue(sm.SequenceEqual(sm2)); } } }
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. using System; using System.Linq; using System.Runtime.InteropServices; using NUnit.Framework; using Spreads.Buffers; using Spreads.Collections; using Spreads.Serialization; using Newtonsoft.Json; namespace Spreads.Extensions.Tests { [TestFixture] public class SerializationTests { [Test] public void CouldSerializeSortedMapWithJsonNet() { var sm = new SortedMap<DateTime, double>(); for (int i = 0; i < 10; i++) { sm.Add(DateTime.UtcNow.Date.AddDays(i), i); } var str = JsonConvert.SerializeObject(sm); Console.WriteLine(str); var sm2 = JsonConvert.DeserializeObject<SortedMap<DateTime, double>>(str); Assert.IsTrue(sm.SequenceEqual(sm2)); } } }
mpl-2.0
C#
fce00804f1e03abb9acd043dc1c6bed12a39bcd9
fix #14 and close milestone v0.3
dimaaan/pgEdit
PgEdit/Properties/AssemblyInfo.cs
PgEdit/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("PgEdit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PgEdit")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("8f5629c9-4c6e-4537-8b0d-3b3908f695d1")] // 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.3.0.0")] [assembly: AssemblyFileVersion("0.3.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("PgEdit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PgEdit")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("8f5629c9-4c6e-4537-8b0d-3b3908f695d1")] // 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.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")]
mit
C#
5871a4e7642a1fa231fce955ac013932d0f81400
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.
autofac/Autofac.Extras.FakeItEasy
Properties/VersionAssemblyInfo.cs
Properties/VersionAssemblyInfo.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.FakeItEasy 3.0.0-beta")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34003 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Extras.FakeItEasy 3.0.0-beta")]
mit
C#
5b2219a692761b1d1e4413f61ac210cb54cdeb7e
Add back test cleanup before run
ppy/osu,2yangk23/osu,smoogipoo/osu,Drezi126/osu,UselessToucan/osu,DrabWeb/osu,naoey/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,ZLima12/osu,EVAST9919/osu,EVAST9919/osu,DrabWeb/osu,peppy/osu,naoey/osu,Frontear/osuKyzer,UselessToucan/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,2yangk23/osu,smoogipooo/osu,johnneijzen/osu,peppy/osu-new,ZLima12/osu,peppy/osu,ppy/osu,ppy/osu,Nabile-Rahmani/osu,johnneijzen/osu,naoey/osu,DrabWeb/osu
osu.Game/Tests/Visual/OsuTestCase.cs
osu.Game/Tests/Visual/OsuTestCase.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Game.Tests.Visual { public abstract class OsuTestCase : TestCase { public override void RunTest() { using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false)) { host.Storage.DeleteDirectory(string.Empty); host.Run(new OsuTestCaseTestRunner(this)); } } public class OsuTestCaseTestRunner : OsuGameBase { private readonly OsuTestCase testCase; public OsuTestCaseTestRunner(OsuTestCase testCase) { this.testCase = testCase; } protected override void LoadComplete() { base.LoadComplete(); Add(new TestCaseTestRunner.TestRunner(testCase)); } } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Game.Tests.Visual { public abstract class OsuTestCase : TestCase { public override void RunTest() { using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false)) { host.Run(new OsuTestCaseTestRunner(this)); } // clean up after each run //storage.DeleteDirectory(string.Empty); } public class OsuTestCaseTestRunner : OsuGameBase { private readonly OsuTestCase testCase; public OsuTestCaseTestRunner(OsuTestCase testCase) { this.testCase = testCase; } protected override void LoadComplete() { base.LoadComplete(); Add(new TestCaseTestRunner.TestRunner(testCase)); } } } }
mit
C#
0b0c9a584fa64877dcf012de1b19d25aa5d14ae7
Use UsePlatformDetect
wieslawsoltes/AvaloniaBehaviors,XamlBehaviors/XamlBehaviors,XamlBehaviors/XamlBehaviors,wieslawsoltes/AvaloniaBehaviors
samples/BehaviorsTestApplication/Program.cs
samples/BehaviorsTestApplication/Program.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using BehaviorsTestApplication.Views; using Avalonia.Controls; using Avalonia.Logging.Serilog; using Serilog; using System.Windows.Threading; namespace BehaviorsTestApplication { internal class Program { private static void Main() { var foo = Dispatcher.CurrentDispatcher; InitializeLogging(); AppBuilder.Configure<BehaviorsTestApp>() .UsePlatformDetect() .Start<MainWindow>(); } private static void InitializeLogging() { #if DEBUG SerilogLogger.Initialize(new LoggerConfiguration() .MinimumLevel.Warning() .WriteTo.Trace(outputTemplate: "{Area}: {Message}") .CreateLogger()); #endif } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using BehaviorsTestApplication.Views; using Avalonia; using Avalonia.Controls; using Avalonia.Logging.Serilog; using Serilog; using System.Windows.Threading; namespace BehaviorsTestApplication { internal class Program { private static void Main() { var foo = Dispatcher.CurrentDispatcher; InitializeLogging(); AppBuilder.Configure<BehaviorsTestApp>() .UseWin32() .UseDirect2D1() .Start<MainWindow>(); } private static void InitializeLogging() { #if DEBUG SerilogLogger.Initialize(new LoggerConfiguration() .MinimumLevel.Warning() .WriteTo.Trace(outputTemplate: "{Area}: {Message}") .CreateLogger()); #endif } } }
mit
C#
21ae5d8a19874b6782309874e7fa82e1794caa44
Enumerate drives in macOS
awaescher/RepoZ,awaescher/RepoZ
RepoZ.Api.Mac/IO/MacDriveEnumerator.cs
RepoZ.Api.Mac/IO/MacDriveEnumerator.cs
using RepoZ.Api.IO; using System; using System.Linq; namespace RepoZ.Api.Mac.IO { public class MacDriveEnumerator : IPathProvider { public string[] GetPaths() { return System.IO.DriveInfo.GetDrives() .Where(d => d.DriveType == System.IO.DriveType.Fixed) .Where(p => !p.RootDirectory.FullName.StartsWith("/private", StringComparison.OrdinalIgnoreCase)) .Select(d => d.RootDirectory.FullName) .ToArray(); } } }
using RepoZ.Api.IO; using System; using System.Linq; namespace RepoZ.Api.Mac.IO { public class MacDriveEnumerator : IPathProvider { public string[] GetPaths() { // TODO return new string[] { "/Users/andreaswascher/develop/" }; } } }
mit
C#
9fc7c8c32090871ec54354819bf2d02cd11fea21
Fix sidereal calculations for sun
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer
Client/Extensions/CelestialBodyExtension.cs
Client/Extensions/CelestialBodyExtension.cs
using System; namespace LunaClient.Extensions { public static class CelestialBodyExtension { public static double SiderealDayLength(this CelestialBody body) { //Taken from CelestialBody.Start() //body.solarRotationPeriod will be false if it's the sun! if (body == null || body.orbit == null || !body.solarRotationPeriod) return 0; var siderealOrbitalPeriod = 6.28318530717959 * Math.Sqrt(Math.Pow(Math.Abs(body.orbit.semiMajorAxis), 3) / body.orbit.referenceBody.gravParameter); return body.rotationPeriod * siderealOrbitalPeriod / (siderealOrbitalPeriod + body.rotationPeriod); } } }
using System; namespace LunaClient.Extensions { public static class CelestialBodyExtension { public static double SiderealDayLength(this CelestialBody body) { //Taken from CelestialBody.Start() if (body == null) return 0; var siderealOrbitalPeriod = 6.28318530717959 * Math.Sqrt(Math.Pow(Math.Abs(body.orbit.semiMajorAxis), 3) / body.orbit.referenceBody.gravParameter); return body.rotationPeriod * siderealOrbitalPeriod / (siderealOrbitalPeriod + body.rotationPeriod); } } }
mit
C#
5a9d8feebd7dc6495c64c1307a8e6b47077b763a
add ActivationChanged event to the Activator
pragmatrix/Konstruktor2
Konstruktor2/Activator.cs
Konstruktor2/Activator.cs
using System; using System.Diagnostics; using Konstruktor2.Detail; namespace Konstruktor2 { public class Activator<ParamT, ResultT> : IDisposable where ResultT : class { readonly Func<ParamT, Owned<ResultT>> _generator; Owned<ResultT> _generated_; ParamT _param; public ParamT Param { get { Debug.Assert(IsActive); return _param; } } public ResultT Instance_ { get { return IsActive ? _generated_.Value : null; } } public bool IsActive { get { return _generated_ != null; } } public Activator(Func<ParamT, Owned<ResultT>> generator) { _generator = generator; } public void Dispose() { if (IsActive) deactivate(); } public void activate(ParamT param) { if (IsActive) deactivate(); _param = param; _generated_ = _generator(param); activated(param); Activated.raise(param); ActivationChanged.raise(); } public void deactivate() { if (_generated_ == null) return; Deactivating.raise(); deactivating(); _generated_.Dispose(); _generated_ = null; _param = default(ParamT); ActivationChanged.raise(); } protected virtual void activated(ParamT param) { } protected virtual void deactivating() { } public event Action<ParamT> Activated; public event Action Deactivating; public event Action ActivationChanged; } }
using System; using System.Diagnostics; using Konstruktor2.Detail; namespace Konstruktor2 { public class Activator<ParamT, ResultT> : IDisposable where ResultT : class { readonly Func<ParamT, Owned<ResultT>> _generator; Owned<ResultT> _generated_; ParamT _param; public ParamT Param { get { Debug.Assert(IsActive); return _param; } } public ResultT Instance_ { get { return IsActive ? _generated_.Value : null; } } public bool IsActive { get { return _generated_ != null; } } public Activator(Func<ParamT, Owned<ResultT>> generator) { _generator = generator; } public void Dispose() { if (IsActive) deactivate(); } public void activate(ParamT param) { if (IsActive) deactivate(); _param = param; _generated_ = _generator(param); activated(param); Activated.raise(param); } public void deactivate() { if (_generated_ == null) return; Deactivating.raise(); deactivating(); _generated_.Dispose(); _generated_ = null; _param = default(ParamT); } protected virtual void activated(ParamT param) { } protected virtual void deactivating() { } public event Action<ParamT> Activated; public event Action Deactivating; } }
bsd-3-clause
C#
a68626df0464e7654de5b3d3a1dc251fad0af561
Use Smtp PickUp delivery for stubbing saving of emails locally
ValuationOffice/VORBS,ValuationOffice/VORBS,ValuationOffice/VORBS
VORBS/Utils/StubbedEmailClient.cs
VORBS/Utils/StubbedEmailClient.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mail; using System.Text; using System.Web; using VORBS.Utils.interfaces; namespace VORBS.Utils { public class StubbedEmailClient : ISmtpClient { private NLog.Logger _logger; public StubbedEmailClient() { _logger = NLog.LogManager.GetCurrentClassLogger(); _logger.Trace(LoggerHelper.InitializeClassMessage()); } public LinkedResource GetLinkedResource(string path, string id) { LinkedResource resource = new LinkedResource(path); resource.ContentId = id; _logger.Trace(LoggerHelper.ExecutedFunctionMessage(resource, path, id)); return resource; } public void Send(MailMessage message) { SmtpClient client = new SmtpClient("stubbedhostname"); client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; string rootDirectory = $@"{AppDomain.CurrentDomain.SetupInformation.ApplicationBase}Logs/{DateTime.Now.ToString("yyyy-MM-dd")}/EmailLogs/{message.To.FirstOrDefault().User}"; if (!Directory.Exists(rootDirectory)) Directory.CreateDirectory(rootDirectory); client.PickupDirectoryLocation = rootDirectory; client.Send(message); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mail; using System.Text; using System.Web; using VORBS.Utils.interfaces; namespace VORBS.Utils { public class StubbedEmailClient : ISmtpClient { private NLog.Logger _logger; public StubbedEmailClient() { _logger = NLog.LogManager.GetCurrentClassLogger(); _logger.Trace(LoggerHelper.InitializeClassMessage()); } public LinkedResource GetLinkedResource(string path, string id) { LinkedResource resource = new LinkedResource(path); resource.ContentId = id; _logger.Trace(LoggerHelper.ExecutedFunctionMessage(resource, path, id)); return resource; } public void Send(MailMessage message) { string rootDirectory = $@"{AppDomain.CurrentDomain.SetupInformation.ApplicationBase}Logs/{DateTime.Now.ToString("yyyy-MM-dd")}/EmailLogs/{message.To.FirstOrDefault().User}"; if (!Directory.Exists(rootDirectory)) Directory.CreateDirectory(rootDirectory); string fileName = $"{message.Subject}_{DateTime.Now.ToString("hh-mm-ss")}"; using (FileStream fs = File.Create($"{rootDirectory}/{fileName}.html")) { StringBuilder builder = new StringBuilder(); builder.AppendLine($"From: {message.From}"); builder.AppendLine($"To: {message.To}"); builder.AppendLine($"BCC: {message.Bcc}"); builder.AppendLine($"Subject: {message.Subject}"); builder.AppendLine(message.Body); byte[] info = new UTF8Encoding(true).GetBytes(builder.ToString()); fs.Write(info, 0, info.Length); // writing data in bytes already byte[] data = new byte[] { 0x0 }; fs.Write(data, 0, data.Length); } } } }
apache-2.0
C#
d9eb33b6149c11e8936457b6c898e1edd7dbb875
Update ConfigurationSource.cs
WojcikMike/docs.particular.net
Snippets/Snippets_4/Forwarding/ConfigurationSource.cs
Snippets/Snippets_4/Forwarding/ConfigurationSource.cs
namespace Snippets4.Forwarding { using System.Configuration; using NServiceBus.Config; using NServiceBus.Config.ConfigurationSource; #region ConfigurationSourceForMessageForwarding public class ConfigurationSource : IConfigurationSource { public T GetConfiguration<T>() where T : class, new() { //To Provide UnicastBusConfig if (typeof(T) == typeof(UnicastBusConfig)) { UnicastBusConfig forwardingConfig = new UnicastBusConfig { ForwardReceivedMessagesTo = "destinationQueue@machine" }; return forwardingConfig as T; } // To in app.config for other sections not defined in this method, otherwise return null. return ConfigurationManager.GetSection(typeof(T).Name) as T; } } #endregion }
namespace Snippets4.Forwarding { using System.Configuration; using NServiceBus.Config; using NServiceBus.Config.ConfigurationSource; #region ConfigurationSourceForMessageForwarding public class ConfigurationSource : IConfigurationSource { public T GetConfiguration<T>() where T : class, new() { //To Provide FLR Config if (typeof(T) == typeof(UnicastBusConfig)) { UnicastBusConfig forwardingConfig = new UnicastBusConfig { ForwardReceivedMessagesTo = "destinationQueue@machine" }; return forwardingConfig as T; } // To in app.config for other sections not defined in this method, otherwise return null. return ConfigurationManager.GetSection(typeof(T).Name) as T; } } #endregion }
apache-2.0
C#
f0494b18bdba6dbef7df147a01f40accb561260a
Fix issue #351. Resize Window event was not triggered when GameWindow.AllowUserResizing=true
sharpdx/Toolkit,sharpdx/Toolkit,tomba/Toolkit
Source/Toolkit/SharpDX.Toolkit.Game/GameWindowForm.cs
Source/Toolkit/SharpDX.Toolkit.Game/GameWindowForm.cs
// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // 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. #if !W8CORE using System; using System.Drawing; using System.Windows.Forms; using SharpDX.Windows; namespace SharpDX.Toolkit { internal class GameWindowForm : RenderForm { private bool allowUserResizing; public GameWindowForm() : this("SharpDX") { } public GameWindowForm(string text) : base(text) { // By default, non resizable MaximizeBox = false; FormBorderStyle = FormBorderStyle.FixedSingle; } internal bool AllowUserResizing { get { return allowUserResizing; } set { if (allowUserResizing != value) { allowUserResizing = value; MaximizeBox = allowUserResizing; FormBorderStyle = allowUserResizing ? FormBorderStyle.Sizable : FormBorderStyle.FixedSingle; } } } } } #endif
// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // 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. #if !W8CORE using System.Windows.Forms; using SharpDX.Windows; namespace SharpDX.Toolkit { internal class GameWindowForm : RenderForm { private bool allowUserResizing; private bool isFullScreenMaximized; private bool isMouseVisible; private bool isMouseCurrentlyHidden; public GameWindowForm() : this("SharpDX") { } public GameWindowForm(string text) : base(text) { // By default, non resizable MaximizeBox = false; FormBorderStyle = FormBorderStyle.FixedSingle; } internal bool AllowUserResizing { get { return allowUserResizing; } set { if (allowUserResizing != value) { allowUserResizing = value; MaximizeBox = allowUserResizing; FormBorderStyle = allowUserResizing ? FormBorderStyle.Sizable : FormBorderStyle.FixedSingle; } } } } } #endif
mit
C#
c82d41179dd4a11aa13075d03917db9d61a0c526
Remove dead code
projecteon/thecollection,projecteon/thecollection,projecteon/thecollection,projecteon/thecollection
TheCollection.Web/Services/ApplicationUserAccessor.cs
TheCollection.Web/Services/ApplicationUserAccessor.cs
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using System.Threading.Tasks; using TheCollection.Web.Models; namespace TheCollection.Web.Services { public interface IApplicationUserAccessor { Task<ApplicationUser> GetUser(); } public class ApplicationUserAccessor : IApplicationUserAccessor { private readonly UserManager<ApplicationUser> _userManager; private readonly IHttpContextAccessor _context; public ApplicationUserAccessor(UserManager<ApplicationUser> userManager, IHttpContextAccessor context) { _userManager = userManager; _context = context; } public Task<ApplicationUser> GetUser() { return _userManager.GetUserAsync(_context.HttpContext.User); } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TheCollection.Web.Models; namespace TheCollection.Web.Services { public interface IApplicationUserAccessor { Task<ApplicationUser> GetUser(); } public class ApplicationUserAccessor : IApplicationUserAccessor { private readonly UserManager<ApplicationUser> _userManager; private readonly IHttpContextAccessor _context; public ApplicationUserAccessor(UserManager<ApplicationUser> userManager, IHttpContextAccessor context) { _userManager = userManager; _context = context; } public Task<ApplicationUser> GetUser() { return _userManager.GetUserAsync(_context.HttpContext.User); } } }
apache-2.0
C#
981a31e2464f8012764b9d944ccd7e64bd073952
Use TryGetValue instead of ContainsKey
accidentaldeveloper/word-processor
WordProcessor/US.WordProcessor/Internal/Dictionary.cs
WordProcessor/US.WordProcessor/Internal/Dictionary.cs
using System; using System.Collections.Generic; namespace US.WordProcessor.Internal { internal class Dictionary { private static readonly Dictionary<string, Definition> KnownWords = new Dictionary<string, Definition>(StringComparer.CurrentCultureIgnoreCase) { // pronouns {"susan", new Definition(WordType.ProperNoun, "Susan", "")}, {"susans", new Definition(WordType.ProperNoun, "Susan", "s")}, {"susan's", new Definition(WordType.ProperNoun, "Susan", "s")}, {"susans'", new Definition(WordType.ProperNoun, "Susan", "s")}, {"barry", new Definition(WordType.ProperNoun, "Barry", "")}, {"barrys", new Definition(WordType.ProperNoun, "Barry", "s")}, {"barry's", new Definition(WordType.ProperNoun, "Barry", "s")}, {"barrys'", new Definition(WordType.ProperNoun, "Barry", "s")}, // nouns {"hat", new Definition(WordType.Noun, "Hat", "")}, {"airplane", new Definition(WordType.Noun, "Airplane", "")}, {"airplanes", new Definition(WordType.Noun, "Airplane", "s")}, {"airplane's", new Definition(WordType.Noun, "Airplane", "s")}, {"airplanes'", new Definition(WordType.Noun, "Airplane", "s")}, }; public Definition Define(string word) { return KnownWords.TryGetValue(word, out var definition) ? definition : new Definition(WordType.NotAvailable, word, ""); } } }
using System; using System.Collections.Generic; namespace US.WordProcessor.Internal { internal class Dictionary { private static readonly Dictionary<string, Definition> KnownWords = new Dictionary<string, Definition>(StringComparer.CurrentCultureIgnoreCase) { // pronouns {"susan", new Definition(WordType.ProperNoun, "Susan", "")}, {"susans", new Definition(WordType.ProperNoun, "Susan", "s")}, {"susan's", new Definition(WordType.ProperNoun, "Susan", "s")}, {"susans'", new Definition(WordType.ProperNoun, "Susan", "s")}, {"barry", new Definition(WordType.ProperNoun, "Barry", "")}, {"barrys", new Definition(WordType.ProperNoun, "Barry", "s")}, {"barry's", new Definition(WordType.ProperNoun, "Barry", "s")}, {"barrys'", new Definition(WordType.ProperNoun, "Barry", "s")}, // nouns {"hat", new Definition(WordType.Noun, "Hat", "")}, {"airplane", new Definition(WordType.Noun, "Airplane", "")}, {"airplanes", new Definition(WordType.Noun, "Airplane", "s")}, {"airplane's", new Definition(WordType.Noun, "Airplane", "s")}, {"airplanes'", new Definition(WordType.Noun, "Airplane", "s")}, }; public Definition Define(string word) { return KnownWords.ContainsKey(word) ? KnownWords[word] : new Definition(WordType.NotAvailable, word, ""); } } }
mit
C#
6384a3c2de9db4eba293dc841457ff52d5e8e47f
Update RestoreDeletedContacts.cs
brminnick/XamList
XamList.Functions/Functions/RestoreDeletedContacts.cs
XamList.Functions/Functions/RestoreDeletedContacts.cs
using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using XamList.Backend.Shared; namespace XamList.Functions { public static class RestoreDeletedContacts { [FunctionName(nameof(RestoreDeletedContacts))] public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "RestoreDeletedContacts/")]HttpRequestMessage req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); try { var deletedContactModelList = XamListDatabase.GetAllContactModels(x => x.IsDeleted); var undeletedContactModelList = deletedContactModelList.Select(x => { x.IsDeleted = false; return x; }).ToList(); foreach (var contact in undeletedContactModelList) await XamListDatabase.PatchContactModel(contact).ConfigureAwait(false); return new OkObjectResult($"Number of Deleted Contacts Restored: {undeletedContactModelList.Count}"); } catch (System.Exception e) { log.LogError(e, e.Message); throw; } } } }
using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using XamList.Backend.Shared; namespace XamList.Functions { public static class RestoreDeletedContacts { [FunctionName(nameof(RestoreDeletedContacts))] public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "RestoreDeletedContacts/")]HttpRequestMessage req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); try { var contactModelList = XamListDatabase.GetAllContactModels(); var deletedContactModelList = contactModelList.Where(x => x.IsDeleted); var undeletedContactModelList = deletedContactModelList.Select(x => { x.IsDeleted = false; return x; }).ToList(); foreach (var contact in undeletedContactModelList) await XamListDatabase.PatchContactModel(contact).ConfigureAwait(false); return new OkObjectResult($"Number of Deleted Contacts Restored: {undeletedContactModelList.Count}"); } catch (System.Exception e) { log.LogError(e, e.Message); throw; } } } }
mit
C#
96155a1fbaf840570e41219590fc5f32ea4522d9
Sort members, check parameters
murador/xsp,murador/xsp,arthot/xsp,stormleoxia/xsp,murador/xsp,arthot/xsp,arthot/xsp,stormleoxia/xsp,murador/xsp,arthot/xsp,stormleoxia/xsp,stormleoxia/xsp
src/Mono.WebServer.FastCgi/BufferManager.cs
src/Mono.WebServer.FastCgi/BufferManager.cs
// // BufferManager.cs // // Author: // Leonardo Taglialegne <leonardo.taglialegne@gmail.com> // // Copyright (C) 2013 Leonardo Taglialegne // // 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; namespace Mono.WebServer.FastCgi { public class BufferManager { const int CLIENTS_PER_BUFFER = 100; readonly int segmentSize; /// <summary> /// The size of a complete buffer. /// Warning: the code assumes this to be an exact multiple of <see cref="segmentSize" /> /// </summary> readonly int bufferSize; readonly object bufferLock = new object (); readonly Stack<CompatArraySegment<byte>> buffers = new Stack<CompatArraySegment<byte>>(); public BufferManager (int segmentSize) { if (segmentSize < 0) throw new ArgumentOutOfRangeException ("segmentSize", segmentSize, "Should be positive"); this.segmentSize = segmentSize; bufferSize = CLIENTS_PER_BUFFER * this.segmentSize; } public void ReturnBuffer(CompatArraySegment<byte> buffer) { lock (bufferLock) { buffers.Push(buffer); // TODO: if we have enough buffers we could release some } } void Expand () { var toadd = new byte[bufferSize]; for (int i = 0; i < bufferSize; i += segmentSize) buffers.Push (new CompatArraySegment<byte> (toadd, i, segmentSize)); } public CompatArraySegment<byte>? ClaimBuffer () { lock (bufferLock) { if (buffers.Count < 1) { Expand(); } return buffers.Pop(); } } } }
// // BufferManager.cs // // Author: // Leonardo Taglialegne <leonardo.taglialegne@gmail.com> // // Copyright (C) 2013 Leonardo Taglialegne // // 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.Collections.Generic; using System; namespace Mono.WebServer.FastCgi { public class BufferManager { readonly int segmentSize; const int CLIENTS_PER_BUFFER = 100; /// <summary> /// The size of a complete buffer. /// Warning: the code assumes this to be an exact multiple of <see cref="segmentSize" /> /// </summary> readonly int bufferSize; readonly object bufferLock = new object (); readonly Stack<CompatArraySegment<byte>> buffers = new Stack<CompatArraySegment<byte>>(); public BufferManager (int segmentSize) { this.segmentSize = segmentSize; bufferSize = CLIENTS_PER_BUFFER * this.segmentSize; } public void ReturnBuffer(CompatArraySegment<byte> buffer) { lock (bufferLock) { buffers.Push(buffer); // TODO: if we have enough buffers we could release some } } void Expand () { var toadd = new byte[bufferSize]; for (int i = 0; i < bufferSize; i += segmentSize) buffers.Push (new CompatArraySegment<byte> (toadd, i, segmentSize)); } public CompatArraySegment<byte>? ClaimBuffer () { lock (bufferLock) { if (buffers.Count < 1) { Expand(); } return buffers.Pop(); } } } }
mit
C#
318e55470a1fc56cc984c806d1938f1251315049
Bump assembly versions
maxmind/minfraud-api-dotnet
MaxMind.MinFraud/Properties/AssemblyInfo.cs
MaxMind.MinFraud/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MaxMind.MinFraud")] [assembly: AssemblyDescription("API for MaxMind minFraud Score and Insights web services")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MaxMind, Inc.")] [assembly: AssemblyProduct("MaxMind.MinFraud")] [assembly: AssemblyCopyright("Copyright © 2015-2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7208d9c8-f862-4675-80e5-77a2f8901b96")] [assembly: CLSCompliant(true)] // 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("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0")] [assembly: AssemblyInformationalVersion("3.0.0")]
using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MaxMind.MinFraud")] [assembly: AssemblyDescription("API for MaxMind minFraud Score and Insights web services")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MaxMind, Inc.")] [assembly: AssemblyProduct("MaxMind.MinFraud")] [assembly: AssemblyCopyright("Copyright © 2015-2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7208d9c8-f862-4675-80e5-77a2f8901b96")] [assembly: CLSCompliant(true)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0")] [assembly: AssemblyInformationalVersion("2.0.0")]
apache-2.0
C#
2bc5c4d36aa643e43304532127e8c63eb7fa93df
Revert "Seed methods"
Ico093/NoMoreSusi,Ico093/NoMoreSusi
NoMoreSusi.Data/Migrations/Configuration.cs
NoMoreSusi.Data/Migrations/Configuration.cs
namespace NoMoreSusi.Data.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; public sealed class Configuration : DbMigrationsConfiguration<NoMoreSusi.Data.NoMoreSusiDbContext> { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; } protected override void Seed(NoMoreSusi.Data.NoMoreSusiDbContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } } }
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using NoMoreSusi.Models; namespace NoMoreSusi.Data.Migrations { using System.Data.Entity.Migrations; using System.Linq; public sealed class Configuration : DbMigrationsConfiguration<NoMoreSusiDbContext> { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; } protected override void Seed(NoMoreSusiDbContext context) { if (!context.Roles.Any()) { SeedRoles(context); } if (!context.Users.Any() && context.Roles.Any()) { SeedUsers(context); } if (!context.Rooms.Any()) { SeedRooms(context); } } private void SeedRoles(NoMoreSusiDbContext context) { var role = new IdentityRole { Name = "Administrator", }; context.Roles.Add(role); } private void SeedUsers(NoMoreSusiDbContext context) { var userStore = new UserStore<User>(context); UserManager<User> um = new UserManager<User>(userStore); var user = new User { UserName = "admin", Email = "admin@admin.com" }; var result = um.CreateAsync(user, "password").Result; } private void SeedRooms(NoMoreSusiDbContext context) { } } }
mit
C#
981e8115790ff28b4a29e6709076bad296721246
test push
adurdin/ggj2015
Alcove/Assets/GameSession/GameConstants.cs
Alcove/Assets/GameSession/GameConstants.cs
using UnityEngine; using System.Collections; public class GameConstants { // Gameplay public const int PLAYER_COUNT = 2; public const int NUM_TRIBES_PER_PLAYER = 4; public const float RECRUITMENT_AREA_DEFAULT_SPAWN_TIME = 0.5f; public const float RECRUITMENT_AREA_GROUND_WIDTH = 15.0f; public const float RECRUITMENT_AREA_GROUND_Y = -0.54f; public const float RECRUITMENT_UNIT_WALK_SPEED = 0.5f; public const float RECRUITMENT_UNIT_ANIMATION_SPEED = 8.5f; public const float RECRUITMENT_UNIT_RUN_SPEED = 2.0f; public const float WORKING_AREA_GROUND_WIDTH = 5.0f; public const float WORKING_AREA_GROUND_Y = -0.54f; public const int PREGAME_DISPLAY_TIME = 110; public const int GO_MESSAGE_DISPLAY_TIME = 40; public const int MAX_NUMBER_OF_ACTIVE_LABORATORIES = 1; /* Balancing */ public const int TRIBE_STARTING_UNIT_COUNT = 4; public const int TRIBE_UNITS_PER_BEDCHAMBER = 4; public const float BASE_TOWER_SEGMENT_ACTION_TIME = 15.0f; // Always takes this full time public const int CONSTRUCTION_TOWER_SEGMENT_TRIBE_COST = 0; public const float BEDCHAMBERS_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float BALLISTA_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float BALLISTA_TOWER_SEGMENT_ACTION_TIME = 180.0f; public const int BALLISTA_TOWER_SEGMENT_TRIBE_COST = 6; public const float CANNONS_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float CANNONS_TOWER_SEGMENT_ACTION_TIME = 120.0f; public const int CANNONS_TOWER_SEGMENT_TRIBE_COST = 9; public const float LABORATORY_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float LABORATORY_TOWER_SEGMENT_ACTION_TIME = 50.0f; public const int LABORATORY_TOWER_SEGMENT_TRIBE_COST = 6; public const float WIZARDTOWER_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float WIZARDTOWER_TOWER_SEGMENT_ACTION_TIME = 120.0f; public const int WIZARDTOWER_TOWER_SEGMENT_TRIBE_COST = 8; public const float MURDERHOLES_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float MURDERHOLES_TOWER_SEGMENT_ACTION_TIME = 60.0f; public const int MURDERHOLES_TOWER_SEGMENT_TRIBE_COST = 4; public const float WIN_TOWER_SEGMENT_BUILD_TIME = 30.0f; // Always takes this full time public const int WIN_TOWER_SEGMENT_TRIBE_SIZE = 20; // Number of workers consumed per tribe when building }
using UnityEngine; using System.Collections; public class GameConstants { // Gameplay public const int PLAYER_COUNT = 2; public const int NUM_TRIBES_PER_PLAYER = 4; public const float RECRUITMENT_AREA_DEFAULT_SPAWN_TIME = 2.0f; public const float RECRUITMENT_AREA_GROUND_WIDTH = 15.0f; public const float RECRUITMENT_AREA_GROUND_Y = -0.54f; public const float RECRUITMENT_UNIT_WALK_SPEED = 0.5f; public const float RECRUITMENT_UNIT_ANIMATION_SPEED = 8.5f; public const float RECRUITMENT_UNIT_RUN_SPEED = 2.0f; public const float WORKING_AREA_GROUND_WIDTH = 5.0f; public const float WORKING_AREA_GROUND_Y = -0.54f; public const int PREGAME_DISPLAY_TIME = 110; public const int GO_MESSAGE_DISPLAY_TIME = 40; public const int MAX_NUMBER_OF_ACTIVE_LABORATORIES = 1; /* Balancing */ public const int TRIBE_STARTING_UNIT_COUNT = 4; public const int TRIBE_UNITS_PER_BEDCHAMBER = 4; public const float BASE_TOWER_SEGMENT_ACTION_TIME = 15.0f; // Always takes this full time public const int CONSTRUCTION_TOWER_SEGMENT_TRIBE_COST = 0; public const float BEDCHAMBERS_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float BALLISTA_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float BALLISTA_TOWER_SEGMENT_ACTION_TIME = 180.0f; public const int BALLISTA_TOWER_SEGMENT_TRIBE_COST = 6; public const float CANNONS_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float CANNONS_TOWER_SEGMENT_ACTION_TIME = 120.0f; public const int CANNONS_TOWER_SEGMENT_TRIBE_COST = 9; public const float LABORATORY_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float LABORATORY_TOWER_SEGMENT_ACTION_TIME = 50.0f; public const int LABORATORY_TOWER_SEGMENT_TRIBE_COST = 6; public const float WIZARDTOWER_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float WIZARDTOWER_TOWER_SEGMENT_ACTION_TIME = 120.0f; public const int WIZARDTOWER_TOWER_SEGMENT_TRIBE_COST = 8; public const float MURDERHOLES_TOWER_SEGMENT_BUILD_TIME = 60.0f; public const float MURDERHOLES_TOWER_SEGMENT_ACTION_TIME = 60.0f; public const int MURDERHOLES_TOWER_SEGMENT_TRIBE_COST = 4; public const float WIN_TOWER_SEGMENT_BUILD_TIME = 30.0f; // Always takes this full time public const int WIN_TOWER_SEGMENT_TRIBE_SIZE = 20; // Number of workers consumed per tribe when building }
mit
C#
c797ab7da98adde47d0b4c65f342b1101f4fdb97
complete camera movement to x
GROWrepo/Santa_Inc
Assets/script/monoBehavior/playerCamera.cs
Assets/script/monoBehavior/playerCamera.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class playerCamera : MonoBehaviour { public GameObject player; Transform[] landscapes; Transform leftEnd; Transform rightEnd; // Use this for initialization void Start () { player = GameObject.FindGameObjectWithTag("Player"); landscapes = GameObject.Find("LandScapeManager").transform.GetComponentsInChildren<Transform>(); leftEnd = landscapes[1].GetChild(0); rightEnd = landscapes[1].GetChild(1); } // Update is called once per frame void Update () { if (player.transform.position.x >= (leftEnd.position.x + 8.4) && player.transform.position.x <= (rightEnd.position.x - 8.4)) { Debug.Log("update"); this.transform.Translate(new Vector3(player.transform.position.x - this.transform.position.x, 0, 0)); } if (player.transform.position.y >= (landscapes[2].position.y + 4.5)) { Debug.Log("update"); this.transform.Translate(new Vector3(0, player.transform.position.y - this.transform.position.y), 0); } } void updatePosition() { if (player.transform.position.x >= (leftEnd.position.x + 8.4) && player.transform.position.x <= (rightEnd.position.x - 8.4)) { Debug.Log(player.transform.position.x); this.transform.Translate(new Vector3(player.transform.position.x - this.transform.position.x, 0, 0)); } if (player.transform.position.y >= (landscapes[2].position.y + 4.5)) { Debug.Log("update"); this.transform.Translate(new Vector3(0, player.transform.position.y - this.transform.position.y), 0); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class playerCamera : MonoBehaviour { public GameObject player; Transform[] landscapes; Transform[] ends; // Use this for initialization void Start () { player = GameObject.FindGameObjectWithTag("Player"); landscapes = GameObject.Find("LandScapeManager").transform.GetComponentsInChildren<Transform>(); ends = landscapes[1].GetComponentsInChildren<Transform>(); } // Update is called once per frame void Update () { updatePosition(); } void updatePosition() { Debug.Log(ends[1]); if (player.transform.position.x >= (ends[1].position.x + 8.4) && player.transform.position.x <= (ends[2].position.x - 8.4)) { this.transform.Translate(new Vector2(player.transform.position.x - this.transform.position.x, 0)); } if (player.transform.position.y >= (landscapes[2].position.y + 4.5)) { this.transform.Translate(new Vector2(0, player.transform.position.y - this.transform.position.y)); } } }
mit
C#
1d03b6d4b71c3e44c8b610a674313c30c2479211
Add `#nullable enable` to texture store interface
ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework
osu.Framework/Graphics/Textures/ITextureStore.cs
osu.Framework/Graphics/Textures/ITextureStore.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. #nullable enable using System.Threading; using System.Threading.Tasks; using osu.Framework.Graphics.OpenGL.Textures; using osu.Framework.IO.Stores; namespace osu.Framework.Graphics.Textures { public interface ITextureStore : IResourceStore<Texture> { /// <summary> /// Retrieves a texture from the store. /// </summary> /// <param name="name">The name of the texture.</param> /// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param> /// <param name="wrapModeT">The texture wrap mode in vertical direction.</param> /// <returns>The texture.</returns> Texture? Get(string name, WrapMode wrapModeS, WrapMode wrapModeT); /// <summary> /// Retrieves a texture from the store asynchronously. /// </summary> /// <param name="name">The name of the texture.</param> /// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param> /// <param name="wrapModeT">The texture wrap mode in vertical direction.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns>The texture.</returns> Task<Texture?> GetAsync(string name, WrapMode wrapModeS, WrapMode wrapModeT, CancellationToken cancellationToken = default); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using System.Threading.Tasks; using osu.Framework.Graphics.OpenGL.Textures; using osu.Framework.IO.Stores; namespace osu.Framework.Graphics.Textures { public interface ITextureStore : IResourceStore<Texture> { /// <summary> /// Retrieves a texture from the store. /// </summary> /// <param name="name">The name of the texture.</param> /// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param> /// <param name="wrapModeT">The texture wrap mode in vertical direction.</param> /// <returns>The texture.</returns> Texture Get(string name, WrapMode wrapModeS, WrapMode wrapModeT); /// <summary> /// Retrieves a texture from the store asynchronously. /// </summary> /// <param name="name">The name of the texture.</param> /// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param> /// <param name="wrapModeT">The texture wrap mode in vertical direction.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns>The texture.</returns> Task<Texture> GetAsync(string name, WrapMode wrapModeS, WrapMode wrapModeT, CancellationToken cancellationToken = default); } }
mit
C#
e48fe053f6ee3c0aa24554f47296129a50049aef
Fix spacing
pojala/electrino,pojala/electrino,pojala/electrino
Electrino/win10/Electrino/MainPage.xaml.cs
Electrino/win10/Electrino/MainPage.xaml.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace Electrino { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private static MainPage instance = null; public MainPage() { instance = this; InitializeComponent(); webView1.ScriptNotify += ScriptNotify; webView1.ContainsFullScreenElementChanged += webView1_ContainsFullScreenElementChanged; //webView1.Navigate(new Uri("ms-appx-web:///test-app/index.html")); } public static bool LoadURL(string url) { if (instance == null) { return false; } instance.webView1.Navigate(new Uri(url)); return true; } private void WebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) { AddRenderApis(); } void ScriptNotify(object sender, NotifyEventArgs e) { App.Log($"Event received from {e.CallingUri}: \"{e.Value}\""); } private void AddRenderApis() { webView1.AddWebAllowedObject("process", new RenderAPI.JSProcess()); } private void webView1_ContainsFullScreenElementChanged(WebView sender, object args) { var applicationView = ApplicationView.GetForCurrentView(); if (sender.ContainsFullScreenElement) { applicationView.TryEnterFullScreenMode(); } else if (applicationView.IsFullScreenMode) { applicationView.ExitFullScreenMode(); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace Electrino { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private static MainPage instance = null; public MainPage() { instance = this; InitializeComponent(); webView1.ScriptNotify += ScriptNotify; webView1.ContainsFullScreenElementChanged += webView1_ContainsFullScreenElementChanged; //webView1.Navigate(new Uri("ms-appx-web:///test-app/index.html")); } public static bool LoadURL(string url) { if (instance == null) { return false; } instance.webView1.Navigate(new Uri(url)); return true; } private void WebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) { AddRenderApis(); } void ScriptNotify(object sender, NotifyEventArgs e) { App.Log($"Event received from {e.CallingUri}: \"{e.Value}\""); } private void AddRenderApis() { webView1.AddWebAllowedObject("process", new RenderAPI.JSProcess()); } private void webView1_ContainsFullScreenElementChanged(WebView sender, object args) { var applicationView = ApplicationView.GetForCurrentView(); if (sender.ContainsFullScreenElement) { applicationView.TryEnterFullScreenMode(); } else if (applicationView.IsFullScreenMode) { applicationView.ExitFullScreenMode(); } } } }
mit
C#
7ab8d2ecf9830f124543c0d4b2bedd1c00e9ef20
Update CCPlace to extend CCActionInstantState.
netonjm/CocosSharp,MSylvia/CocosSharp,haithemaraissia/CocosSharp,hig-ag/CocosSharp,zmaruo/CocosSharp,mono/CocosSharp,zmaruo/CocosSharp,hig-ag/CocosSharp,netonjm/CocosSharp,TukekeSoft/CocosSharp,TukekeSoft/CocosSharp,haithemaraissia/CocosSharp,mono/CocosSharp,MSylvia/CocosSharp
cocos2d/actions/action_instants/CCPlace.cs
cocos2d/actions/action_instants/CCPlace.cs
namespace CocosSharp { public class CCPlace : CCActionInstant { public CCPoint Position { get; private set; } #region Constructors public CCPlace(CCPoint pos) { Position = pos; } public CCPlace(int posX, int posY) { Position = new CCPoint (posX, posY); } #endregion Constructors protected internal override CCActionState StartAction (CCNode target) { return new CCPlaceState (this, target); } // Take me out later - See comments in CCAction public override bool HasState { get { return true; } } } public class CCPlaceState : CCActionInstantState { public CCPlaceState (CCPlace action, CCNode target) : base(action, target) { Target.Position = action.Position; } } }
namespace CocosSharp { public class CCPlace : CCActionInstant { public CCPoint Position { get; private set; } #region Constructors public CCPlace(CCPoint pos) { Position = pos; } public CCPlace(int posX, int posY) { Position = new CCPoint (posX, posY); } #endregion Constructors protected internal override CCActionState StartAction (CCNode target) { return new CCPlaceState (this, target); } // Take me out later - See comments in CCAction public override bool HasState { get { return true; } } } public class CCPlaceState : CCFiniteTimeActionState { protected CCPoint Position { get; set; } public CCPlaceState (CCPlace action, CCNode target) : base(action, target) { Position = action.Position; Target.Position = Position; } // This can be taken out once CCActionInstant has it's State separated public override void Step(float dt) { Update(1); } } }
mit
C#
9c134c5f49664c7820589a2ff1bf67567201afaa
修改BatchGetUserInfoData.lang属性为int类型
wanddy/WeiXinMPSDK,lishewen/WeiXinMPSDK,down4u/WeiXinMPSDK,lishewen/WeiXinMPSDK,wanddy/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,wanddy/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK,down4u/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,lishewen/WeiXinMPSDK,mc7246/WeiXinMPSDK,mc7246/WeiXinMPSDK,down4u/WeiXinMPSDK
src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/User/UserJson/BatchGetUserInfoData.cs
src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/User/UserJson/BatchGetUserInfoData.cs
/*---------------------------------------------------------------- Copyright (C) 2017 Senparc 文件名:BatchGetUserInfoData.cs 文件功能描述:批量获取用户基本信息数据 创建标识:Senparc - 20150727 修改标识:Senparc - 20170114 修改描述:v14.3.119 暂时修改lang属性为int类型 ----------------------------------------------------------------*/ namespace Senparc.Weixin.MP.AdvancedAPIs.User { /// <summary> /// 批量获取用户基本信息数据 /// </summary> public class BatchGetUserInfoData { /// <summary> /// 用户的标识,对当前公众号唯一 /// 必填 /// </summary> public string openid { get; set; } /// <summary> /// 国家地区语言版本,请使用Language范围内的值:zh_CN 简体,zh_TW 繁体,en 英语,默认为zh-CN /// 非必填 /// </summary> public int lang { get; set; } } }
/*---------------------------------------------------------------- Copyright (C) 2017 Senparc 文件名:BatchGetUserInfoData.cs 文件功能描述:批量获取用户基本信息数据 创建标识:Senparc - 20150727 ----------------------------------------------------------------*/ namespace Senparc.Weixin.MP.AdvancedAPIs.User { /// <summary> /// 批量获取用户基本信息数据 /// </summary> public class BatchGetUserInfoData { /// <summary> /// 用户的标识,对当前公众号唯一 /// 必填 /// </summary> public string openid { get; set; } /// <summary> /// 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语,默认为zh-CN /// 非必填 /// </summary> public Language lang { get; set; } } }
apache-2.0
C#
4b8a6d834b3c5386dcc13fc9578d22440961246d
include creator for now
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Controllers/ReviewerController.cs
Anlab.Mvc/Controllers/ReviewerController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Anlab.Core.Data; using Microsoft.EntityFrameworkCore; using Anlab.Core.Models; using Microsoft.AspNetCore.Authorization; using AnlabMvc.Models.Roles; namespace AnlabMvc.Controllers { [Authorize(Roles = RoleCodes.Admin)] public class ReviewerController : ApplicationController { private readonly ApplicationDbContext _context; public ReviewerController(ApplicationDbContext context) { _context = context; } public async Task<IActionResult> Index() { var model = await _context.Orders.Include(i=> i.Creator).Where(a => a.Status == OrderStatusCodes.Finalized).ToArrayAsync(); return View(model); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Anlab.Core.Data; using Microsoft.EntityFrameworkCore; using Anlab.Core.Models; using Microsoft.AspNetCore.Authorization; using AnlabMvc.Models.Roles; namespace AnlabMvc.Controllers { [Authorize(Roles = RoleCodes.Admin)] public class ReviewerController : ApplicationController { private readonly ApplicationDbContext _context; public ReviewerController(ApplicationDbContext context) { _context = context; } public async Task<IActionResult> Index() { var model = await _context.Orders.Where(a => a.Status == OrderStatusCodes.Finalized).ToArrayAsync(); return View(model); } } }
mit
C#
454294be0eaa4efcfc83d0a5458336fc152c3d06
Change version to 1.22
EricSten-MSFT/kudu,kali786516/kudu,oliver-feng/kudu,bbauya/kudu,projectkudu/kudu,juoni/kudu,sitereactor/kudu,kali786516/kudu,oliver-feng/kudu,shrimpy/kudu,MavenRain/kudu,sitereactor/kudu,juvchan/kudu,juvchan/kudu,kenegozi/kudu,duncansmart/kudu,puneet-gupta/kudu,duncansmart/kudu,badescuga/kudu,MavenRain/kudu,YOTOV-LIMITED/kudu,oliver-feng/kudu,kali786516/kudu,mauricionr/kudu,kenegozi/kudu,puneet-gupta/kudu,shrimpy/kudu,uQr/kudu,projectkudu/kudu,EricSten-MSFT/kudu,WeAreMammoth/kudu-obsolete,oliver-feng/kudu,shrimpy/kudu,barnyp/kudu,chrisrpatterson/kudu,EricSten-MSFT/kudu,EricSten-MSFT/kudu,WeAreMammoth/kudu-obsolete,mauricionr/kudu,kenegozi/kudu,EricSten-MSFT/kudu,juoni/kudu,barnyp/kudu,YOTOV-LIMITED/kudu,duncansmart/kudu,WeAreMammoth/kudu-obsolete,shanselman/kudu,dev-enthusiast/kudu,juoni/kudu,uQr/kudu,chrisrpatterson/kudu,shibayan/kudu,badescuga/kudu,MavenRain/kudu,mauricionr/kudu,mauricionr/kudu,shibayan/kudu,projectkudu/kudu,projectkudu/kudu,chrisrpatterson/kudu,juvchan/kudu,shanselman/kudu,badescuga/kudu,projectkudu/kudu,dev-enthusiast/kudu,juoni/kudu,chrisrpatterson/kudu,dev-enthusiast/kudu,shibayan/kudu,dev-enthusiast/kudu,sitereactor/kudu,badescuga/kudu,barnyp/kudu,barnyp/kudu,kenegozi/kudu,MavenRain/kudu,sitereactor/kudu,duncansmart/kudu,uQr/kudu,shibayan/kudu,juvchan/kudu,puneet-gupta/kudu,bbauya/kudu,shrimpy/kudu,shibayan/kudu,shanselman/kudu,badescuga/kudu,YOTOV-LIMITED/kudu,puneet-gupta/kudu,uQr/kudu,puneet-gupta/kudu,juvchan/kudu,bbauya/kudu,sitereactor/kudu,bbauya/kudu,YOTOV-LIMITED/kudu,kali786516/kudu
Common/CommonAssemblyInfo.cs
Common/CommonAssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyVersion("1.22.0.0")] [assembly: AssemblyFileVersion("1.22.0.0")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyVersion("1.21.0.0")] [assembly: AssemblyFileVersion("1.21.0.0")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)]
apache-2.0
C#
665ec6935be5bf50be33964146539408253a9404
Add Google Plus +1 to AddThis defaults
opencolorado/.NET-Wrapper-for-CKAN-API,DenverDev/.NET-Wrapper-for-CKAN-API,opencolorado/.NET-Wrapper-for-CKAN-API,DenverDev/.NET-Wrapper-for-CKAN-API,opencolorado/.NET-Wrapper-for-CKAN-API
CkanDotNet.Web/Views/Shared/_AddThis.cshtml
CkanDotNet.Web/Views/Shared/_AddThis.cshtml
@using CkanDotNet.Web.Models.Helpers <!-- AddThis Button BEGIN --> <div class="share-buttons"> <div class="addthis_toolbox addthis_default_style "> <a class="addthis_button_preferred_1"></a> <a class="addthis_button_preferred_2"></a> <a class="addthis_button_preferred_3"></a> <a class="addthis_button_preferred_4"></a> <a class="addthis_button_google_plusone"></a> <a class="addthis_button_compact"></a> <a class="addthis_counter addthis_bubble_style"></a> </div> </div> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=@SettingsHelper.GetAddThisProfileId()"></script> <!-- AddThis Button END -->
@using CkanDotNet.Web.Models.Helpers <!-- AddThis Button BEGIN --> <div class="share-buttons"> <div class="addthis_toolbox addthis_default_style "> <a class="addthis_button_preferred_1"></a> <a class="addthis_button_preferred_2"></a> <a class="addthis_button_preferred_3"></a> <a class="addthis_button_preferred_4"></a> <a class="addthis_button_compact"></a> <a class="addthis_counter addthis_bubble_style"></a> </div> </div> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=@SettingsHelper.GetAddThisProfileId()"></script> <!-- AddThis Button END -->
apache-2.0
C#
f9d97d84915d8be63fee566b623a6ac3e82f9ba9
Update shield constructor
andrewjleavitt/SpaceThing
Assets/Scripts/ShieldBehavior.cs
Assets/Scripts/ShieldBehavior.cs
using UnityEngine; public class ShieldBehavior { public float amount = 0.0f; public float rechargeRate = 0.0f; private float capacity = 0.0f; private float nextRecharge = 0.0f; private string shieldName; public ShieldBehavior(string newShieldName, float newCapacity, float newRechargeRate) { shieldName = newShieldName; capacity = newCapacity; rechargeRate = newRechargeRate; amount = capacity; } public void Recharge() { if (amount == capacity) { return; } if (Time.time < nextRecharge) { return; } amount = Mathf.Min(capacity, amount += 1); nextRecharge = Time.time + rechargeRate; } public string Status() { return amount.ToString(); } }
using UnityEngine; public class ShieldBehavior { public float amount = 0.0f; public float rechargeRate = 0.0f; private float capacity = 0.0f; private float nextRecharge = 0.0f; private string shieldName; public ShieldBehavior(string newShieldName, float newCapacity, float newRechargeAmount, float rechargeRate) { shieldName = newShieldName; capacity = newCapacity; rechargeRate = newRechargeAmount; amount = capacity; } public void Recharge() { if (amount == capacity) { return; } if (Time.time < nextRecharge) { return; } amount = Mathf.Min(capacity, amount += 1); nextRecharge = Time.time + rechargeRate; } public string Status() { return amount.ToString(); } }
unlicense
C#
c6ba7ddf8806415748ae84fe2c75af2b5e74538f
Implement proper disposable pattern to satisfy sonarcloud's compaint of a code smell :/
ivanpointer/NuLog,ivanpointer/NuLog,ivanpointer/NuLog,ivanpointer/NuLog,ivanpointer/NuLog
Take2/NuLog.CLI.Benchmarking/DummyTarget.cs
Take2/NuLog.CLI.Benchmarking/DummyTarget.cs
/* © 2019 Ivan Pointer MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE Source on GitHub: https://github.com/ivanpointer/NuLog */ using NuLog.Configuration; using NuLog.LogEvents; using System; namespace NuLog.CLI.Benchmarking { /// <summary> /// A dummy target for performance testing - we need to see the raw results of the engine, not /// the individual target. /// </summary> public class DummyTarget : ITarget { public string Name { get; set; } public void Configure(TargetConfig config) { // noop } public void Write(LogEvent logEvent) { // noop } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // noop } // noop disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); GC.SuppressFinalize(this); } #endregion IDisposable Support } }
/* © 2019 Ivan Pointer MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE Source on GitHub: https://github.com/ivanpointer/NuLog */ using NuLog.Configuration; using NuLog.LogEvents; using System; namespace NuLog.CLI.Benchmarking { /// <summary> /// A dummy target for performance testing - we need to see the raw results of the engine, not /// the individual target. /// </summary> public class DummyTarget : ITarget { public string Name { get; set; } public void Configure(TargetConfig config) { // noop } public void Dispose() { // noop } public void Write(LogEvent logEvent) { // noop } } }
mit
C#
1c380f5eff1c0e930984adf0ce941a1733e2702f
Remove usage of legacy code
asarium/FSOLauncher
UI/WPF/Modules/UI.WPF.Modules.Installation/ViewModels/Installation/InstallationViewModel.cs
UI/WPF/Modules/UI.WPF.Modules.Installation/ViewModels/Installation/InstallationViewModel.cs
#region Usings using System; using System.Collections.Generic; using System.Windows.Input; using ReactiveUI; using UI.WPF.Launcher.Common.Classes; #endregion namespace UI.WPF.Modules.Installation.ViewModels.Installation { public class InstallationViewModel : ReactiveObjectBase { private InstallationItemParent _installationParent; private InstallationItemParent _uninstallationParent; public ICommand CloseCommand { get; private set; } public InstallationViewModel(Action closeAction) { var cmd = ReactiveCommand.Create(); cmd.Subscribe(_ => closeAction()); CloseCommand = cmd; } public InstallationItemParent InstallationParent { get { return _installationParent; } private set { RaiseAndSetIfPropertyChanged(ref _installationParent, value); } } public InstallationItemParent UninstallationParent { get { return _uninstallationParent; } private set { RaiseAndSetIfPropertyChanged(ref _uninstallationParent, value); } } public IEnumerable<InstallationItem> InstallationItems { set { InstallationParent = new InstallationItemParent(null, value); } } public IEnumerable<InstallationItem> UninstallationItems { set { UninstallationParent = new InstallationItemParent(null, value); } } } }
#region Usings using System; using System.Collections.Generic; using System.Windows.Input; using ReactiveUI.Legacy; using UI.WPF.Launcher.Common.Classes; #endregion namespace UI.WPF.Modules.Installation.ViewModels.Installation { public class InstallationViewModel : ReactiveObjectBase { private InstallationItemParent _installationParent; private InstallationItemParent _uninstallationParent; public ICommand CloseCommand { get; private set; } public InstallationViewModel(Action closeAction) { var cmd = new ReactiveCommand(); cmd.Subscribe(_ => closeAction()); CloseCommand = cmd; } public InstallationItemParent InstallationParent { get { return _installationParent; } private set { RaiseAndSetIfPropertyChanged(ref _installationParent, value); } } public InstallationItemParent UninstallationParent { get { return _uninstallationParent; } private set { RaiseAndSetIfPropertyChanged(ref _uninstallationParent, value); } } public IEnumerable<InstallationItem> InstallationItems { set { InstallationParent = new InstallationItemParent(null, value); } } public IEnumerable<InstallationItem> UninstallationItems { set { UninstallationParent = new InstallationItemParent(null, value); } } } }
mit
C#
2bd6b936341fd79a44fb17980328a9aba35a039a
Remove unused constant
Wyamio/Wyam,mgnslndh/Wyam,adamclifford/Wyam,adamclifford/Wyam,adamclifford/Wyam,dodyg/Wyam,mgnslndh/Wyam,Wyamio/Wyam,adamclifford/Wyam,dodyg/Wyam,heavenwing/Wyam,heavenwing/Wyam,Wyamio/Wyam,adamclifford/Wyam
Wyam.Modules.ImageProcessor/MetadataKeys.cs
Wyam.Modules.ImageProcessor/MetadataKeys.cs
namespace Wyam.Modules.ImageProcessor { public static class MetadataKeys { public const string SourceFilePath = "SourceFilePath"; public const string SourceFileExt = "SourceFileExt"; } }
namespace Wyam.Modules.ImageProcessor { public static class MetadataKeys { public const string Base64 = "Base64"; public const string SourceFilePath = "SourceFilePath"; public const string SourceFileExt = "SourceFileExt"; } }
mit
C#
dd5b2671dddd1bbf15c205b41e6368cd3258dcf1
Update ValuesOut.cs
EricZimmerman/RegistryPlugins
RegistryPlugin.LastVisitedMRU/ValuesOut.cs
RegistryPlugin.LastVisitedMRU/ValuesOut.cs
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.LastVisitedMRU { public class ValuesOut:IValueOut { public ValuesOut(string valueName, string executable, string directory, int mruPosition, DateTimeOffset? openedOn) { Executable = executable; Directory = directory; ValueName = valueName; MruPosition = mruPosition; OpenedOn = openedOn?.UtcDateTime; } public string ValueName { get; } public int MruPosition { get; } public string Executable { get; } public string Directory { get; } public DateTime? OpenedOn { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"Exe: {Executable} Folder: {Executable} Directory: {Directory}"; public string BatchValueData2 => $"Opened: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff})"; public string BatchValueData3 => $"MRU: {MruPosition}"; } }
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.LastVisitedMRU { public class ValuesOut:IValueOut { public ValuesOut(string valueName, string executable, string directory, int mruPosition, DateTimeOffset? openedOn) { Executable = executable; Directory = directory; ValueName = valueName; MruPosition = mruPosition; OpenedOn = openedOn?.UtcDateTime; } public string ValueName { get; } public int MruPosition { get; } public string Executable { get; } public string Directory { get; } public DateTime? OpenedOn { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"Exe: {Executable} Folder: {Executable} Directory: {Directory}"; public string BatchValueData2 => $"Opened: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff})"; public string BatchValueData3 => $"Mru: {MruPosition}"; } }
mit
C#
6d38d0616388fb0b4acc5ac97e7321f3efd3e4b6
Fix occasional crash when solution changes
tom-englert/ResXResourceManager
ResXManager.View/Visuals/ShellViewModel.cs
ResXManager.View/Visuals/ShellViewModel.cs
namespace tomenglertde.ResXManager.View.Visuals { using System.Collections.Specialized; using System.ComponentModel.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Windows.Threading; using JetBrains.Annotations; using tomenglertde.ResXManager.Infrastructure; using tomenglertde.ResXManager.Model; using Throttle; using TomsToolbox.Desktop; using TomsToolbox.Wpf; using TomsToolbox.Wpf.Composition; [Export] [VisualCompositionExport(RegionId.Shell)] public class ShellViewModel : ObservableObject { [NotNull] private readonly ResourceViewModel _resourceViewModel; [ImportingConstructor] public ShellViewModel([NotNull] ResourceViewModel resourceViewModel) { Contract.Requires(resourceViewModel != null); _resourceViewModel = resourceViewModel; resourceViewModel.SelectedEntities.CollectionChanged += SelectedEntities_CollectionChanged; } public bool IsLoading { get; set; } public int SelectedTabIndex { get; set; } public void SelectEntry([NotNull] ResourceTableEntry entry) { SelectedTabIndex = 0; Dispatcher.BeginInvoke(DispatcherPriority.Background, () => { _resourceViewModel.SelectEntry(entry); }); } private void SelectedEntities_CollectionChanged([NotNull] object sender, [NotNull] NotifyCollectionChangedEventArgs e) { Update(); IsLoading = true; try { Dispatcher.ProcessMessages(DispatcherPriority.Render); } catch { // sometimes dispatcher processing is suspended, just ignore, as this is only used to improve UI responsiveness } } [Throttled(typeof(DispatcherThrottle), (int)DispatcherPriority.Background)] private void Update() { IsLoading = false; } } }
namespace tomenglertde.ResXManager.View.Visuals { using System.Collections.Specialized; using System.ComponentModel.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Windows.Threading; using JetBrains.Annotations; using tomenglertde.ResXManager.Infrastructure; using tomenglertde.ResXManager.Model; using Throttle; using TomsToolbox.Desktop; using TomsToolbox.Wpf; using TomsToolbox.Wpf.Composition; [Export] [VisualCompositionExport(RegionId.Shell)] public class ShellViewModel : ObservableObject { [NotNull] private readonly ResourceViewModel _resourceViewModel; [ImportingConstructor] public ShellViewModel([NotNull] ResourceViewModel resourceViewModel) { Contract.Requires(resourceViewModel != null); _resourceViewModel = resourceViewModel; resourceViewModel.SelectedEntities.CollectionChanged += SelectedEntities_CollectionChanged; } public bool IsLoading { get; set; } public int SelectedTabIndex { get; set; } public void SelectEntry([NotNull] ResourceTableEntry entry) { SelectedTabIndex = 0; Dispatcher.BeginInvoke(DispatcherPriority.Background, () => { _resourceViewModel.SelectEntry(entry); }); } private void SelectedEntities_CollectionChanged([NotNull] object sender, [NotNull] NotifyCollectionChangedEventArgs e) { Update(); IsLoading = true; Dispatcher.ProcessMessages(DispatcherPriority.Render); } [Throttled(typeof(DispatcherThrottle), (int)DispatcherPriority.Background)] private void Update() { IsLoading = false; } } }
mit
C#
547701886f54bce0149c78c95e050d25b6efa436
Use file name as the name of a Cursor Set
mysticfall/Alensia
Assets/Alensia/Core/UI/Cursor/CursorSet.cs
Assets/Alensia/Core/UI/Cursor/CursorSet.cs
using System.Collections.Generic; using System.Linq; using Alensia.Core.Common; using UnityEngine; namespace Alensia.Core.UI.Cursor { public class CursorSet : ScriptableObject, INamed, IDirectory<CursorDefinition>, IEditorSettings { public string Name => name; protected IDictionary<string, CursorDefinition> CursorMap { get { lock (this) { if (_cursorMap != null) return _cursorMap; _cursorMap = new Dictionary<string, CursorDefinition>(); foreach (var cursor in _cursors.Concat<CursorDefinition>(_animatedCursors)) { _cursorMap.Add(cursor.Name, cursor); } return _cursorMap; } } } [SerializeField] private StaticCursor[] _cursors; [SerializeField] private AnimatedCursor[] _animatedCursors; private IDictionary<string, CursorDefinition> _cursorMap; public bool Contains(string key) => CursorMap.ContainsKey(key); public CursorDefinition this[string key] => CursorMap[key]; private void OnEnable() { _cursors = _cursors?.OrderBy(c => c.Name).ToArray(); _animatedCursors = _animatedCursors?.OrderBy(c => c.Name).ToArray(); } private void OnValidate() => _cursorMap = null; private void OnDestroy() => _cursorMap = null; } }
using System.Collections.Generic; using System.Linq; using Alensia.Core.Common; using UnityEngine; namespace Alensia.Core.UI.Cursor { public class CursorSet : ScriptableObject, IDirectory<CursorDefinition>, IEditorSettings { protected IDictionary<string, CursorDefinition> CursorMap { get { lock (this) { if (_cursorMap != null) return _cursorMap; _cursorMap = new Dictionary<string, CursorDefinition>(); foreach (var cursor in _cursors.Concat<CursorDefinition>(_animatedCursors)) { _cursorMap.Add(cursor.Name, cursor); } return _cursorMap; } } } [SerializeField] private StaticCursor[] _cursors; [SerializeField] private AnimatedCursor[] _animatedCursors; private IDictionary<string, CursorDefinition> _cursorMap; public bool Contains(string key) => CursorMap.ContainsKey(key); public CursorDefinition this[string key] => CursorMap[key]; private void OnEnable() { _cursors = _cursors?.OrderBy(c => c.Name).ToArray(); _animatedCursors = _animatedCursors?.OrderBy(c => c.Name).ToArray(); } private void OnValidate() => _cursorMap = null; private void OnDestroy() => _cursorMap = null; } }
apache-2.0
C#
24506c4903fde535452ac89103d30f59687967b5
Update Demo
sunkaixuan/SqlSugar
Src/Asp.Net/SqliteTest/Config.cs
Src/Asp.Net/SqliteTest/Config.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrmTest { public class Config { public static string GetCurrentProjectPath { get { return Environment.CurrentDirectory.Replace(@"\bin\Debug", ""); } } public static string ConnectionString = @"DataSource=GetCurrentProjectPath\DataBase\SqlSugar4xTest.sqlite"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrmTest { public class Config { public static string ConnectionString = @"DataSource=F:\MyOpenSource\SqlSugar4.XNew\SqlSugar\Src\Asp.Net\SqliteTest\DataBase\SqlSugar4xTest.sqlite"; } }
apache-2.0
C#
9bf4f1e6f91a7615a28376b5751cc88e6b2a5c30
add overload for creating property from json object
ntent-ad/Metrics.NET,Recognos/Metrics.NET,huoxudong125/Metrics.NET,Recognos/Metrics.NET,huoxudong125/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,etishor/Metrics.NET,mnadel/Metrics.NET,alhardy/Metrics.NET,Liwoj/Metrics.NET,DeonHeyns/Metrics.NET,etishor/Metrics.NET,Liwoj/Metrics.NET,DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET,cvent/Metrics.NET,alhardy/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET
Src/Metrics/Json/JsonProperty.cs
Src/Metrics/Json/JsonProperty.cs
using System.Collections.Generic; namespace Metrics.Json { public class JsonProperty { public JsonProperty(string name, IEnumerable<JsonObject> objects) : this(name, new CollectionJsonValue(objects)) { } public JsonProperty(string name, IEnumerable<JsonProperty> properties) : this(name, new ObjectJsonValue(properties)) { } public JsonProperty(string name, JsonObject @object) : this(name, new ObjectJsonValue(@object)) { } public JsonProperty(string name, string value) : this(name, new StringJsonValue(value)) { } public JsonProperty(string name, long value) : this(name, new LongJsonValue(value)) { } public JsonProperty(string name, double value) : this(name, new DoubleJsonValue(value)) { } public JsonProperty(string name, bool value) : this(name, new BoolJsonValue(value)) { } public JsonProperty(string name, JsonValue value) { this.Name = name; this.Value = value; } public string Name { get; private set; } public JsonValue Value { get; private set; } public string AsJson(bool indented, int indent) { indent = indented ? indent : 0; return string.Format("{0}\"{1}\":{2}", new string(' ', indent), JsonValue.Escape(this.Name), this.Value.AsJson(indented, indent + 2)); } } }
using System.Collections.Generic; namespace Metrics.Json { public class JsonProperty { public JsonProperty(string name, IEnumerable<JsonObject> objects) : this(name, new CollectionJsonValue(objects)) { } public JsonProperty(string name, IEnumerable<JsonProperty> properties) : this(name, new ObjectJsonValue(properties)) { } public JsonProperty(string name, string value) : this(name, new StringJsonValue(value)) { } public JsonProperty(string name, long value) : this(name, new LongJsonValue(value)) { } public JsonProperty(string name, double value) : this(name, new DoubleJsonValue(value)) { } public JsonProperty(string name, bool value) : this(name, new BoolJsonValue(value)) { } public JsonProperty(string name, JsonValue value) { this.Name = name; this.Value = value; } public string Name { get; private set; } public JsonValue Value { get; private set; } public string AsJson(bool indented, int indent) { indent = indented ? indent : 0; return string.Format("{0}\"{1}\":{2}", new string(' ', indent), JsonValue.Escape(this.Name), this.Value.AsJson(indented, indent + 2)); } } }
apache-2.0
C#
4f203b28f2d2bbd2d8cb56b5948a37d58b09bb16
Fix new lines in console
SteamDatabase/ValveResourceFormat
GUI/Utils/ConsoleTab.cs
GUI/Utils/ConsoleTab.cs
using System; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace GUI.Utils { internal class ConsoleTab { internal class MyLogger : TextWriter { private TextBox control; public MyLogger(TextBox control) { this.control = control; } public override Encoding Encoding => null; public override void WriteLine(string value) { var logLine = $"[{DateTime.Now.ToString("HH:mm:ss.fff")}] {value}{Environment.NewLine}"; control.AppendText(logLine); } } public TabPage CreateTab() { var control = new TextBox { Dock = DockStyle.Fill, Multiline = true, ReadOnly = true, WordWrap = true, ScrollBars = ScrollBars.Vertical, BorderStyle = BorderStyle.None, BackColor = Color.Black, ForeColor = Color.WhiteSmoke, }; var tab = new TabPage("Console"); tab.Controls.Add(control); Console.SetOut(new MyLogger(control)); return tab; } } }
using System; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace GUI.Utils { internal class ConsoleTab { internal class MyLogger : TextWriter { private TextBox control; public MyLogger(TextBox control) { this.control = control; } public override Encoding Encoding => null; public override void WriteLine(string value) { var logLine = $"[{DateTime.Now.ToString("HH:mm:ss.fff")}] {value}\n"; control.AppendText(logLine); } } public TabPage CreateTab() { var control = new TextBox { Dock = DockStyle.Fill, Multiline = true, ReadOnly = true, WordWrap = true, ScrollBars = ScrollBars.Vertical, BorderStyle = BorderStyle.None, BackColor = Color.Black, ForeColor = Color.WhiteSmoke, }; var tab = new TabPage("Console"); tab.Controls.Add(control); Console.SetOut(new MyLogger(control)); return tab; } } }
mit
C#
9a2f828ba60d852f0aed9a3a50eb3645489b542f
Modify DialogsPage to allow testing of startup location.
wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Perspex,Perspex/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,akrisiun/Perspex,SuperJMN/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex
samples/ControlCatalog/Pages/DialogsPage.xaml.cs
samples/ControlCatalog/Pages/DialogsPage.xaml.cs
using Avalonia.Controls; using Avalonia.Markup.Xaml; #pragma warning disable 4014 namespace ControlCatalog.Pages { public class DialogsPage : UserControl { public DialogsPage() { this.InitializeComponent(); this.FindControl<Button>("OpenFile").Click += delegate { new OpenFileDialog() { Title = "Open file" }.ShowAsync(GetWindow()); }; this.FindControl<Button>("SaveFile").Click += delegate { new SaveFileDialog() { Title = "Save file" }.ShowAsync(GetWindow()); }; this.FindControl<Button>("SelectFolder").Click += delegate { new OpenFolderDialog() { Title = "Select folder" }.ShowAsync(GetWindow()); }; this.FindControl<Button>("DecoratedWindow").Click += delegate { new DecoratedWindow().Show(); }; this.FindControl<Button>("DecoratedWindowDialog").Click += delegate { new DecoratedWindow().ShowDialog(GetWindow()); }; this.FindControl<Button>("Dialog").Click += delegate { var window = new Window(); window.Height = 200; window.Width = 200; window.Content = new TextBlock { Text = "Hello world!" }; window.WindowStartupLocation = WindowStartupLocation.CenterScreen; window.ShowDialog(GetWindow()); }; } Window GetWindow() => (Window)this.VisualRoot; private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
using Avalonia.Controls; using Avalonia.Markup.Xaml; #pragma warning disable 4014 namespace ControlCatalog.Pages { public class DialogsPage : UserControl { public DialogsPage() { this.InitializeComponent(); this.FindControl<Button>("OpenFile").Click += delegate { new OpenFileDialog() { Title = "Open file" }.ShowAsync(GetWindow()); }; this.FindControl<Button>("SaveFile").Click += delegate { new SaveFileDialog() { Title = "Save file" }.ShowAsync(GetWindow()); }; this.FindControl<Button>("SelectFolder").Click += delegate { new OpenFolderDialog() { Title = "Select folder" }.ShowAsync(GetWindow()); }; this.FindControl<Button>("DecoratedWindow").Click += delegate { new DecoratedWindow().Show(); }; this.FindControl<Button>("DecoratedWindowDialog").Click += delegate { new DecoratedWindow().ShowDialog(GetWindow()); }; this.FindControl<Button>("Dialog").Click += delegate { new MainWindow().ShowDialog(GetWindow()); }; } Window GetWindow() => (Window)this.VisualRoot; private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
mit
C#
3455b4168ba407dbe6838f028af3596b00baa3d6
Simplify test
JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop
src/BloomTests/Book/BookInfoTests.cs
src/BloomTests/Book/BookInfoTests.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Bloom.Book; using NUnit.Framework; using Palaso.IO; using Palaso.Reporting; using Palaso.TestUtilities; namespace BloomTests.Book { public class BookInfoTests { private TemporaryFolder _fixtureFolder; private TemporaryFolder _folder; [SetUp] public void Setup() { _fixtureFolder = new TemporaryFolder("BloomBookStorageTest"); _folder = new TemporaryFolder(_fixtureFolder, "theBook"); } [TearDown] public void TearDown() { _fixtureFolder.Dispose(); } [Test] public void Constructor_LoadsMetaDataFromJson() { var jsonPath = Path.Combine(_folder.Path, BookInfo.MetaDataFileName); File.WriteAllText(jsonPath, @"{'folio':'true','experimental':'true','suitableForMakingShells':'true'}"); var bi = new BookInfo(_folder.Path, true); Assert.That(bi.IsExperimental); Assert.That(bi.IsFolio); Assert.That(bi.IsSuitableForMakingShells); } [Test] public void Constructor_FallsBackToTags() { var tagsPath = Path.Combine(_folder.Path, "tags.txt"); File.WriteAllText(tagsPath, @"folio\nexperimental\nsuitableForMakingShells\n"); var bi = new BookInfo(_folder.Path, true); Assert.That(bi.IsExperimental); Assert.That(bi.IsFolio); Assert.That(bi.IsSuitableForMakingShells); // Check that json takes precedence var jsonPath = Path.Combine(_folder.Path, BookInfo.MetaDataFileName); File.WriteAllText(jsonPath, @"{'folio':'false','experimental':'true','suitableForMakingShells':'false'}"); bi = new BookInfo(_folder.Path, true); Assert.That(bi.IsExperimental); Assert.That(bi.IsFolio, Is.False); Assert.That(bi.IsSuitableForMakingShells, Is.False); } [Test] public void TitleSetter_FixesTitleWithXml() { var jsonPath = Path.Combine(_folder.Path, BookInfo.MetaDataFileName); File.WriteAllText(jsonPath, "{'title':'<span class=\"sentence-too-long\" data-segment=\"sentence\">Book on &lt;span&gt;s\r\n</span>'}"); var bi = new BookInfo(_folder.Path, true); // loads metadata, but doesn't use Title setter // SUT bi.Title = bi.Title; // exercises setter Assert.AreEqual("Book on <span>s\r\n", bi.Title); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Bloom.Book; using NUnit.Framework; using Palaso.IO; using Palaso.Reporting; using Palaso.TestUtilities; namespace BloomTests.Book { public class BookInfoTests { private TemporaryFolder _fixtureFolder; private TemporaryFolder _folder; [SetUp] public void Setup() { _fixtureFolder = new TemporaryFolder("BloomBookStorageTest"); _folder = new TemporaryFolder(_fixtureFolder, "theBook"); } [TearDown] public void TearDown() { _fixtureFolder.Dispose(); } [Test] public void Constructor_LoadsMetaDataFromJson() { var jsonPath = Path.Combine(_folder.Path, BookInfo.MetaDataFileName); File.WriteAllText(jsonPath, @"{'folio':'true','experimental':'true','suitableForMakingShells':'true'}"); var bi = new BookInfo(_folder.Path, true); Assert.That(bi.IsExperimental); Assert.That(bi.IsFolio); Assert.That(bi.IsSuitableForMakingShells); } [Test] public void Constructor_FallsBackToTags() { var tagsPath = Path.Combine(_folder.Path, "tags.txt"); File.WriteAllText(tagsPath, @"folio\nexperimental\nsuitableForMakingShells\n"); var bi = new BookInfo(_folder.Path, true); Assert.That(bi.IsExperimental); Assert.That(bi.IsFolio); Assert.That(bi.IsSuitableForMakingShells); // Check that json takes precedence var jsonPath = Path.Combine(_folder.Path, BookInfo.MetaDataFileName); File.WriteAllText(jsonPath, @"{'folio':'false','experimental':'true','suitableForMakingShells':'false'}"); bi = new BookInfo(_folder.Path, true); Assert.That(bi.IsExperimental); Assert.That(bi.IsFolio, Is.False); Assert.That(bi.IsSuitableForMakingShells, Is.False); } [Test] public void TitleSetter_FixesTitleWithXml() { var jsonPath = Path.Combine(_folder.Path, BookInfo.MetaDataFileName); File.WriteAllText(jsonPath, "{'suitableForMakingShells':true,'experimental':false,'title':'<span class=\"sentence-too-long\" data-segment=\"sentence\">Book on &lt;span&gt;s\r\n</span>'}"); var bi = new BookInfo(_folder.Path, true); // loads metadata, but doesn't use Title setter // SUT bi.Title = bi.Title; // exercises setter Assert.That(bi.IsExperimental, Is.False); Assert.AreEqual("Book on <span>s\r\n", bi.Title); } } }
mit
C#
9a2ee69a93a1966a154370228efe4e7822e55110
Implement .net SqlClientDriver
lecaillon/Evolve
src/Evolve/Driver/SqlClientDriver.cs
src/Evolve/Driver/SqlClientDriver.cs
using System; using System.Data; namespace Evolve.Driver { #if NETSTANDARD public class SqlClientDriver : IDriver { public IDbConnection CreateConnection() { throw new NotImplementedException(); } } #else public class SqlClientDriver : IDriver { public IDbConnection CreateConnection() { return new System.Data.SqlClient.SqlConnection(); } } #endif }
using System; using System.Collections.Generic; using System.Data; using System.Text; namespace Evolve.Driver { public class SqlClientDriver : IDriver { public IDbConnection CreateConnection() { throw new NotImplementedException(); } } }
mit
C#
7b527f786b46b0c86b4893eee5d01ac47ea183b8
Add copyright to one more .cs source file.
GoogleCloudPlatform/pubsub-shout-csharp,GoogleCloudPlatform/pubsub-shout-csharp,SurferJeffAtGoogle/pubsub-shout-csharp,GoogleCloudPlatform/pubsub-shout-csharp,SurferJeffAtGoogle/pubsub-shout-csharp,SurferJeffAtGoogle/pubsub-shout-csharp,SurferJeffAtGoogle/pubsub-shout-csharp,GoogleCloudPlatform/pubsub-shout-csharp
windows-csharp/ShoutLib/Constants.cs
windows-csharp/ShoutLib/Constants.cs
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace ShoutLib { internal class Constants { public const string ProjectId = "YOUR-PROJECT-ID"; public const string ServiceAccountEmail = "YOUR-SERVICE-ACCOUNT@developer.gserviceaccount.com"; public const string ServiceAccountP12KeyPath = @"C:\PATH\TO\YOUR\FILE.p12"; public const string Subscription = "shout-tasks-workers"; public const string UserAgent = "Shouter"; } }
namespace ShoutLib { internal class Constants { public const string ProjectId = "YOUR-PROJECT-ID"; public const string ServiceAccountEmail = "YOUR-SERVICE-ACCOUNT@developer.gserviceaccount.com"; public const string ServiceAccountP12KeyPath = @"C:\PATH\TO\YOUR\FILE.p12"; public const string Subscription = "shout-tasks-workers"; public const string UserAgent = "Shouter"; } }
apache-2.0
C#
75c51d5893ec0f83d9e01bdb6aba77f64e192ba4
Improve naming of tests to clearly indicate the feature to be tested
oliverzick/Delizious-Filtering
src/Library.Test/GreaterThanTests.cs
src/Library.Test/GreaterThanTests.cs
#region Copyright and license // // <copyright file="GreaterThanTests.cs" company="Oliver Zick"> // // Copyright (c) 2016 Oliver Zick. All rights reserved. // // </copyright> // // <author>Oliver Zick</author> // // <license> // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // </license> #endregion namespace Delizious.Filtering { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public sealed class GreaterThanTests { [TestMethod] public void Match_Succeeds_When_Value_To_Match_Is_Greater_Than_Reference() { Assert.IsTrue(Match.GreaterThan(0).Matches(1)); } [TestMethod] public void Match_Fails_When_Value_To_Match_And_Reference_Are_Equal() { Assert.IsFalse(Match.GreaterThan(0).Matches(0)); } [TestMethod] public void Match_Fails_When_Value_To_Match_Is_Less_Than_Reference() { Assert.IsFalse(Match.GreaterThan(0).Matches(-1)); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Throws_Exception_On_Creation_When_Reference_Is_Null() { Match.GreaterThan<string>(null); } } }
#region Copyright and license // // <copyright file="GreaterThanTests.cs" company="Oliver Zick"> // // Copyright (c) 2016 Oliver Zick. All rights reserved. // // </copyright> // // <author>Oliver Zick</author> // // <license> // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // </license> #endregion namespace Delizious.Filtering { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public sealed class GreaterThanTests { [TestMethod] public void Succeed__When_Value_Is_Greater_Than_Reference() { Assert.IsTrue(Match.GreaterThan(0).Matches(1)); } [TestMethod] public void Fail__When_Reference_And_Value_Are_Equal() { Assert.IsFalse(Match.GreaterThan(0).Matches(0)); } [TestMethod] public void Fail__When_Value_Is_Less_Than_Reference() { Assert.IsFalse(Match.GreaterThan(0).Matches(-1)); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Throw_Exception__When_Reference_Is_Null() { Match.GreaterThan<string>(null); } } }
apache-2.0
C#
b0057e403f1c6817679521f4dfed16d08163fdb0
Fix "All Decks" get sort with other decks
AnkiUniversal/Anki-Universal,AnkiUniversal/Anki-Universal,AnkiUniversal/Anki-Universal
AnkiU/ViewModels/DeckNameViewModel.cs
AnkiU/ViewModels/DeckNameViewModel.cs
/* Copyright (C) 2016 Anki Universal Team <ankiuniversal@outlook.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using AnkiU.AnkiCore; using AnkiU.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnkiU.ViewModels { public class DeckNameViewModel { public const int ALL_DECKS_ID = -1; public ObservableCollection<DeckInformation> Decks; public int TotalNumberOfCards { get; set; } public DeckNameViewModel(Collection collection, bool isIncludeAllDeck = true, bool isIncludeDynamicDeck = true) { var deckList = collection.Deck.All(); List<DeckInformation> temp = new List<DeckInformation>(); foreach (var deck in deckList) { long did = (long)deck.GetNamedNumber("id"); if (did == Constant.DEFAULTDECK_ID) continue; string name = deck.GetNamedString("name"); bool isDynamic = collection.Deck.IsDyn(did); if (!isIncludeDynamicDeck && isDynamic) continue; temp.Add(new DeckInformation(name, 0, 0, did, isDynamic)); } temp.Sort((a, b) => { return a.BaseName.CompareTo(b.BaseName); }); if (isIncludeAllDeck) temp.Insert(0, new DeckInformation("All decks", 0, 0, ALL_DECKS_ID, false)); Decks = new ObservableCollection<DeckInformation>(temp); } } }
/* Copyright (C) 2016 Anki Universal Team <ankiuniversal@outlook.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using AnkiU.AnkiCore; using AnkiU.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnkiU.ViewModels { public class DeckNameViewModel { public const int ALL_DECKS_ID = -1; public ObservableCollection<DeckInformation> Decks; public int TotalNumberOfCards { get; set; } public DeckNameViewModel(Collection collection, bool isIncludeAllDeck = true, bool isIncludeDynamicDeck = true) { var deckList = collection.Deck.All(); List<DeckInformation> temp = new List<DeckInformation>(); if (isIncludeAllDeck) temp.Add(new DeckInformation("All decks", 0, 0, ALL_DECKS_ID, false)); foreach (var deck in deckList) { long did = (long)deck.GetNamedNumber("id"); if (did == Constant.DEFAULTDECK_ID) continue; string name = deck.GetNamedString("name"); bool isDynamic = collection.Deck.IsDyn(did); if (!isIncludeDynamicDeck && isDynamic) continue; temp.Add(new DeckInformation(name, 0, 0, did, isDynamic)); } temp.Sort((a, b) => { return a.Name.CompareTo(b.Name); }); Decks = new ObservableCollection<DeckInformation>(temp); } } }
agpl-3.0
C#
8f29b22b499394feb8d29472fb47e3e0f41640b7
Update version
alexvictoor/BrowserLog,alexvictoor/BrowserLog,alexvictoor/BrowserLog
BrowserLog/Properties/AssemblyInfo.cs
BrowserLog/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("BrowserLog")] [assembly: AssemblyDescription("log4net appender based on HTML5 SSE")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alexandre Victoor")] [assembly: AssemblyProduct("BrowserLog")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8edd155e-8b7a-4af6-8554-92ddd02bb8c9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BrowserLog")] [assembly: AssemblyDescription("log4net appender based on HTML5 SSE")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alexandre Victoor")] [assembly: AssemblyProduct("BrowserLog")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8edd155e-8b7a-4af6-8554-92ddd02bb8c9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#