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
7476c31e91c000c3ec95f1fe20c717ddb8b01a35
support query without paramaters
tocsoft/GraphQLCodeGen,tocsoft/GraphQLCodeGen
Tocsoft.GraphQLCodeGen/ObjectModel/Operation.cs
Tocsoft.GraphQLCodeGen/ObjectModel/Operation.cs
using System; using System.Collections.Generic; using System.Text; using GraphQLParser.AST; using System.Linq; using Tocsoft.GraphQLCodeGen.ObjectModel.Selections; namespace Tocsoft.GraphQLCodeGen.ObjectModel { internal class Operation : IGraphQLInitter { private GraphQLOperationDefinition operation; public string Name { get; set; } public IDictionary<string, ValueTypeReference> Paramaters { get; set; } public SetSelection Selection { get; set; } public string Query { get; private set; } public string Path { get; private set; } public IEnumerable<SetSelection> DecendentsAndSelf() { yield return Selection; foreach (var s in Selection.Fields.SelectMany(f => f.DecendentsAndSelf())) { yield return s; } } public Operation(GraphQLOperationDefinition op) { this.operation = op; Name = op.Name?.Value; Selection = new SetSelection(operation.SelectionSet); } public void Resolve(GraphQLDocument doc) { Paramaters = operation.VariableDefinitions?.ToDictionary(x => x.Variable.Name.Value, x => doc.ResolveValueType(x.Type)) ?? new Dictionary<string, ValueTypeReference>(); var rootType = doc.ResolveType(operation.Operation) as IGraphQLFieldCollection; (this.Query, this.Path) = doc.ResolveQuery(operation.Location); Selection.Resolve(doc, rootType); } } }
using System; using System.Collections.Generic; using System.Text; using GraphQLParser.AST; using System.Linq; using Tocsoft.GraphQLCodeGen.ObjectModel.Selections; namespace Tocsoft.GraphQLCodeGen.ObjectModel { internal class Operation : IGraphQLInitter { private GraphQLOperationDefinition operation; public string Name { get; set; } public IDictionary<string, ValueTypeReference> Paramaters { get; set; } public SetSelection Selection { get; set; } public string Query { get; private set; } public string Path { get; private set; } public IEnumerable<SetSelection> DecendentsAndSelf() { yield return Selection; foreach (var s in Selection.Fields.SelectMany(f => f.DecendentsAndSelf())) { yield return s; } } public Operation(GraphQLOperationDefinition op) { this.operation = op; Name = op.Name?.Value; Selection = new SetSelection(operation.SelectionSet); } public void Resolve(GraphQLDocument doc) { Paramaters = operation.VariableDefinitions.ToDictionary(x => x.Variable.Name.Value, x => doc.ResolveValueType(x.Type)); var rootType = doc.ResolveType(operation.Operation) as IGraphQLFieldCollection; (this.Query, this.Path) = doc.ResolveQuery(operation.Location); Selection.Resolve(doc, rootType); } } }
mit
C#
4dc062ba50b076ea38a6b818bb0285c26531533f
Allow connections to MongoDB 1.5.2+ that now returns 'ok' in the status message as a boolean, not a decimal
atheken/NoRM,atheken/NoRM
NoRM/Protocol/SystemMessages/Responses/BaseStatusMessage.cs
NoRM/Protocol/SystemMessages/Responses/BaseStatusMessage.cs
using Norm.Configuration; using Norm.BSON; using System.Collections.Generic; using System.Linq; namespace Norm.Responses { /// <summary> /// Represents a message with an Ok status /// </summary> public class BaseStatusMessage : IExpando { private Dictionary<string, object> _properties = new Dictionary<string, object>(0); /// <summary> /// This is the raw value returned from the response. /// It is required for serializer support, use "WasSuccessful" if you need a boolean value. /// </summary> /// <remarks>This maps to the "OK" value of the response which can be a decimal (pre-1.5.2) or boolean (1.5.2+).</remarks> public bool WasSuccessful { get { return this["ok"].Equals(true) || this["ok"].Equals(1d); } } /// <summary> /// Additional, non-static properties of this message. /// </summary> /// <returns></returns> public IEnumerable<ExpandoProperty> AllProperties() { return this._properties.Select(j => new ExpandoProperty(j.Key, j.Value)); } public void Delete(string propertyName) { this._properties.Remove(propertyName); } public object this[string propertyName] { get { return this._properties[propertyName]; } set { this._properties[propertyName] = value; } } } }
using Norm.Configuration; using Norm.BSON; using System.Collections.Generic; using System.Linq; namespace Norm.Responses { /// <summary> /// Represents a message with an Ok status /// </summary> public class BaseStatusMessage : IExpando { private Dictionary<string, object> _properties = new Dictionary<string, object>(0); /// <summary> /// This is the raw value returned from the response. /// It is required for serializer support, use "WasSuccessful" if you need a boolean value. /// </summary> protected double? ok { get; set; } /// <summary> /// Did this message return correctly? /// </summary> /// <remarks>This maps to the "OK" value of the response.</remarks> public bool WasSuccessful { get { return this.ok == 1d ? true : false; } } /// <summary> /// Additional, non-static properties of this message. /// </summary> /// <returns></returns> public IEnumerable<ExpandoProperty> AllProperties() { return this._properties.Select(j => new ExpandoProperty(j.Key, j.Value)); } public void Delete(string propertyName) { this._properties.Remove(propertyName); } public object this[string propertyName] { get { return this._properties[propertyName]; } set { this._properties[propertyName] = value; } } } }
bsd-3-clause
C#
61ce75cd3cd3ace636845038d2be79f1735f16ee
remove IsLowPopulation in MultiEnumDN
AlejandroCano/framework,signumsoftware/framework,avifatal/framework,AlejandroCano/framework,signumsoftware/framework,avifatal/framework
Signum.Entities/Basics/MultiEnum.cs
Signum.Entities/Basics/MultiEnum.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Entities; using Signum.Utilities; using System.Linq.Expressions; namespace Signum.Entities.Basics { [Serializable, EntityKind(EntityKind.SystemString, EntityData.Master)] public abstract class MultiEnumDN : IdentifiableEntity { [NotNullable, SqlDbType(Size = 100), UniqueIndex] string key; [StringLengthValidator(AllowNulls = false, Min = 3, Max = 100)] public string Key { get { return key; } internal set { Set(ref key, value, () => Key); } } static readonly Expression<Func<MultiEnumDN, string>> ToStringExpression = e => e.key; public override string ToString() { return ToStringExpression.Evaluate(this); } public static string UniqueKey(Enum a) { return "{0}.{1}".Formato(a.GetType().Name, a.ToString()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Entities; using Signum.Utilities; using System.Linq.Expressions; namespace Signum.Entities.Basics { [Serializable, EntityKind(EntityKind.SystemString, EntityData.Master, IsLowPopulation = true)] public abstract class MultiEnumDN : IdentifiableEntity { [NotNullable, SqlDbType(Size = 100), UniqueIndex] string key; [StringLengthValidator(AllowNulls = false, Min = 3, Max = 100)] public string Key { get { return key; } internal set { Set(ref key, value, () => Key); } } static readonly Expression<Func<MultiEnumDN, string>> ToStringExpression = e => e.key; public override string ToString() { return ToStringExpression.Evaluate(this); } public static string UniqueKey(Enum a) { return "{0}.{1}".Formato(a.GetType().Name, a.ToString()); } } }
mit
C#
241c2cf1f038f6e27d4e41a6848de385b7fd044f
Use math round for nodes
AlbericTrancart/karambaToSofistik
Source/GhToSofistik/Classes/Node.cs
Source/GhToSofistik/Classes/Node.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GhToSofistik.Classes { class Node { public int id; public double x, y, z; public List<string> constraints; public Node(Karamba.Nodes.Node node = null) { id = 1; x = y = z = 0; constraints = new List<string>(); if (node != null) hydrate(node); } public void hydrate(Karamba.Nodes.Node node) { x = Math.Round(node.pos.X, 3); y = Math.Round(node.pos.Y, 3); z = Math.Round(node.pos.Z, 3); id = node.ind + 1; //Sofistik begins at 1 not 0 } public string sofistring() { string sofi = ""; sofi += "NODE NO " + id + " X " + x + " Y " + y + " Z " + z; if (constraints.Count != 0) { sofi += " FIX "; foreach (string condition in constraints) { sofi += condition; } } return sofi; } public void addConstraint(Karamba.Supports.Support support) { string[] cons = new string[] {"PX", "PY", "PZ", "MX", "MY", "MZ"}; int i = 0; foreach(bool boolean in support._condition) { if(boolean) constraints.Add(cons[i]); // TODO: prescribed displacement i++; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GhToSofistik.Classes { class Node { public int id; public double x, y, z; public List<string> constraints; public Node(Karamba.Nodes.Node node = null) { id = 1; x = y = z = 0; constraints = new List<string>(); if (node != null) hydrate(node); } public void hydrate(Karamba.Nodes.Node node) { x = node.pos.X; y = node.pos.Y; z = node.pos.Z; id = node.ind + 1; //Sofistik begins at 1 not 0 } public string sofistring() { string sofi = ""; sofi += "NODE NO " + id + " X " + x.ToString("F3") + " Y " + y.ToString("F3") + " Z " + z.ToString("F3"); //We only want three decimals if (constraints.Count != 0) { sofi += " FIX "; foreach (string condition in constraints) { sofi += condition; } } return sofi; } public void addConstraint(Karamba.Supports.Support support) { string[] cons = new string[] {"PX", "PY", "PZ", "MX", "MY", "MZ"}; int i = 0; foreach(bool boolean in support._condition) { if(boolean) constraints.Add(cons[i]); // TODO: prescribed displacement i++; } } } }
apache-2.0
C#
c036b9ee9b0ece284cad73a21148e439fc1c6064
Add HasDirectory trait to HasSys trait
louthy/language-ext,StanJav/language-ext
LanguageExt.Sys/Traits/SysIO.cs
LanguageExt.Sys/Traits/SysIO.cs
using LanguageExt.Effects.Traits; namespace LanguageExt.Sys.Traits { /// <summary> /// Convenience trait - captures the BCL IO behaviour /// </summary> /// <typeparam name="RT">Runtime</typeparam> public interface HasSys<RT> : HasCancel<RT>, HasConsole<RT>, HasEncoding<RT>, HasFile<RT>, HasDirectory<RT>, HasTextRead<RT>, HasTime<RT> where RT : struct, HasCancel<RT>, HasConsole<RT>, HasFile<RT>, HasDirectory<RT>, HasTextRead<RT>, HasTime<RT>, HasEncoding<RT> { } }
using LanguageExt.Effects.Traits; namespace LanguageExt.Sys.Traits { /// <summary> /// Convenience trait - captures the BCL IO behaviour /// </summary> /// <typeparam name="RT">Runtime</typeparam> public interface HasSys<RT> : HasCancel<RT>, HasConsole<RT>, HasEncoding<RT>, HasFile<RT>, HasTextRead<RT>, HasTime<RT> where RT : struct, HasCancel<RT>, HasConsole<RT>, HasFile<RT>, HasTextRead<RT>, HasTime<RT>, HasEncoding<RT> { } }
mit
C#
19c9ed45c194176dbaba37f2acd4d46f38a5a4ec
Load list of quotes into a dictionary
fredatgithub/GetQuote
CreateXMLFile/Program.cs
CreateXMLFile/Program.cs
using System; using System.Collections.Generic; using System.IO; namespace CreateXMLFile { internal static class Program { private static void Main() { const string fileName = "quotes.txt"; Dictionary<string, string> dicoQuotes = new Dictionary<string, string>(); List<string> quotesList = new List<string>(); StreamReader sr = new StreamReader(fileName); string line = string.Empty; while ((line = sr.ReadLine()) != null) { //Console.WriteLine(line); quotesList.Add(line); } for (int i = 0; i < quotesList.Count; i = i + 2) { if (!dicoQuotes.ContainsKey(quotesList[i])) { dicoQuotes.Add(quotesList[i], quotesList[i + 1]); } else { Console.WriteLine(quotesList[i]); } } Console.WriteLine("Press a key to exit:"); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.IO; namespace CreateXMLFile { internal static class Program { private static void Main() { const string fileName = "quotes.txt"; Dictionary<string, string> dicoQuotes = new Dictionary<string, string>(); List<string> quotesList = new List<string>(); StreamReader sr = new StreamReader(fileName); string line = string.Empty; while ((line = sr.ReadLine()) != null) { //Console.WriteLine(line); quotesList.Add(line); } } } }
mit
C#
1e174b36cfd57eab6be32a2263c3c350d251c081
remove binding context on disappear
nukedbit/nukedbit-mvvm
NukedBit.Mvvm/Views/ViewBase.cs
NukedBit.Mvvm/Views/ViewBase.cs
/*************************************************************************** Copyright 2015 Sebastian Faltoni aka NukedBit Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ using System; using NukedBit.Mvvm.ViewModels; using Xamarin.Forms; namespace NukedBit.Mvvm.Views { public class ViewBase<T> : ContentPage, IDisposable, IView where T : IViewModel { private T _viewModel; public T ViewModel => _viewModel; IViewModel IView.ViewModel => _viewModel; protected ViewBase(T viewmodel) { _viewModel = viewmodel; BindingContext = _viewModel; } protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); if (!(ViewModel is ViewModelBase)) return; var modelBase = ViewModel as ViewModelBase; modelBase.Navigation = Navigation; } protected override void OnDisappearing() { base.OnDisappearing(); BindingContext = null; } protected override void OnAppearing() { base.OnAppearing(); BindingContext = ViewModel; } public virtual void Dispose() { _viewModel = default(T); } } }
/*************************************************************************** Copyright 2015 Sebastian Faltoni aka NukedBit Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ using System; using NukedBit.Mvvm.ViewModels; using Xamarin.Forms; namespace NukedBit.Mvvm.Views { public class ViewBase<T> : ContentPage, IDisposable, IView where T : IViewModel { private T _viewModel; public T ViewModel => _viewModel; IViewModel IView.ViewModel => _viewModel; protected ViewBase(T viewmodel) { _viewModel = viewmodel; BindingContext = _viewModel; } protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); if (!(ViewModel is ViewModelBase)) return; var modelBase = ViewModel as ViewModelBase; modelBase.Navigation = Navigation; } public virtual void Dispose() { } } }
apache-2.0
C#
b88d931f3121dc312ad35c0ca544ce54602f1696
Replace the Obsolete method of SecurityRequirementsOperationFilter
aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template
aspnet-core/src/AbpCompanyName.AbpProjectName.Web.Host/Startup/SecurityRequirementsOperationFilter.cs
aspnet-core/src/AbpCompanyName.AbpProjectName.Web.Host/Startup/SecurityRequirementsOperationFilter.cs
using System.Collections.Generic; using System.Linq; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using Abp.Authorization; namespace AbpCompanyName.AbpProjectName.Web.Host.Startup { public class SecurityRequirementsOperationFilter : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { var actionAttrs = context.ControllerActionDescriptor.MethodInfo.GetCustomAttributes(true).ToList(); if (actionAttrs.OfType<AbpAllowAnonymousAttribute>().Any()) { return; } var controllerAttrs = context.ControllerActionDescriptor.ControllerTypeInfo.GetCustomAttributes(true); var actionAbpAuthorizeAttrs = actionAttrs.OfType<AbpAuthorizeAttribute>().ToList(); if (!actionAbpAuthorizeAttrs.Any() && controllerAttrs.OfType<AbpAllowAnonymousAttribute>().Any()) { return; } var controllerAbpAuthorizeAttrs = controllerAttrs.OfType<AbpAuthorizeAttribute>().ToList(); if (controllerAbpAuthorizeAttrs.Any() || actionAbpAuthorizeAttrs.Any()) { operation.Responses.Add("401", new Response { Description = "Unauthorized" }); var permissions = controllerAbpAuthorizeAttrs.Union(actionAbpAuthorizeAttrs) .SelectMany(p => p.Permissions) .Distinct().ToList(); if (permissions.Any()) { operation.Responses.Add("403", new Response { Description = "Forbidden" }); } operation.Security = new List<IDictionary<string, IEnumerable<string>>> { new Dictionary<string, IEnumerable<string>> { { "bearerAuth", permissions } } }; } } } }
using System.Collections.Generic; using System.Linq; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using Abp.Authorization; namespace AbpCompanyName.AbpProjectName.Web.Host.Startup { public class SecurityRequirementsOperationFilter : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { var actionAttrs = context.ApiDescription.ActionAttributes(); if (actionAttrs.OfType<AbpAllowAnonymousAttribute>().Any()) { return; } var controllerAttrs = context.ApiDescription.ControllerAttributes(); var actionAbpAuthorizeAttrs = actionAttrs.OfType<AbpAuthorizeAttribute>(); if (!actionAbpAuthorizeAttrs.Any() && controllerAttrs.OfType<AbpAllowAnonymousAttribute>().Any()) { return; } var controllerAbpAuthorizeAttrs = controllerAttrs.OfType<AbpAuthorizeAttribute>(); if (controllerAbpAuthorizeAttrs.Any() || actionAbpAuthorizeAttrs.Any()) { operation.Responses.Add("401", new Response { Description = "Unauthorized" }); var permissions = controllerAbpAuthorizeAttrs.Union(actionAbpAuthorizeAttrs) .SelectMany(p => p.Permissions) .Distinct(); if (permissions.Any()) { operation.Responses.Add("403", new Response { Description = "Forbidden" }); } operation.Security = new List<IDictionary<string, IEnumerable<string>>> { new Dictionary<string, IEnumerable<string>> { { "bearerAuth", permissions } } }; } } } }
mit
C#
629abcbdbc9f46c8448989b12ca8008d56b8b334
Fix for issue 278 (https://github.com/dotnet/corert/issues/278) The CreateDynamicDelegate API is a dead one. Deleting it... (linq expressions use CreateObjectArrayDelegate when compiled without FEATURE_DYNAMIC_DELEGATE)
gregkalapos/corert,yizhang82/corert,krytarowski/corert,krytarowski/corert,botaberg/corert,yizhang82/corert,yizhang82/corert,tijoytom/corert,shrah/corert,sandreenko/corert,krytarowski/corert,gregkalapos/corert,tijoytom/corert,tijoytom/corert,sandreenko/corert,shrah/corert,shrah/corert,krytarowski/corert,gregkalapos/corert,botaberg/corert,botaberg/corert,sandreenko/corert,shrah/corert,gregkalapos/corert,botaberg/corert,tijoytom/corert,yizhang82/corert,sandreenko/corert
src/System.Private.CoreLib/src/Internal/Runtime/Augments/DynamicDelegateAugments.cs
src/System.Private.CoreLib/src/Internal/Runtime/Augments/DynamicDelegateAugments.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //Internal.Runtime.Augments //------------------------------------------------- // Why does this exist?: // Reflection.Execution cannot physically live in System.Private.CoreLib.dll // as it has a dependency on System.Reflection.Metadata. Its inherently // low-level nature means, however, it is closely tied to System.Private.CoreLib.dll. // This contract provides the two-communication between those two .dll's. // // // Implemented by: // System.Private.CoreLib.dll // // Consumed by: // Reflection.Execution.dll using System; namespace Internal.Runtime.Augments { public static class DynamicDelegateAugments { // // Helper to create a interpreted delegate for LINQ and DLR expression trees // public static Delegate CreateObjectArrayDelegate(Type delegateType, Func<object[], object> invoker) { return Delegate.CreateObjectArrayDelegate(delegateType, invoker); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //Internal.Runtime.Augments //------------------------------------------------- // Why does this exist?: // Reflection.Execution cannot physically live in System.Private.CoreLib.dll // as it has a dependency on System.Reflection.Metadata. Its inherently // low-level nature means, however, it is closely tied to System.Private.CoreLib.dll. // This contract provides the two-communication between those two .dll's. // // // Implemented by: // System.Private.CoreLib.dll // // Consumed by: // Reflection.Execution.dll using System; namespace Internal.Runtime.Augments { public static class DynamicDelegateAugments { // // Helper to create a interpreted delegate for LINQ and DLR expression trees // public static Delegate CreateObjectArrayDelegate(Type delegateType, Func<object[], object> invoker) { return Delegate.CreateObjectArrayDelegate(delegateType, invoker); } // // Returns a new delegate which can only be dynamically invoked (dlg.DynamicInvoke) // public static Delegate CreateDynamicDelegate(Func<object[], object> handler) { // implementation is provied by ILTransform throw NotImplemented.ByDesign; } } }
mit
C#
03f5460dd2e269c28ae116df0ebd7317f7df9137
Mark OsuModTestScene as abstract
smoogipooo/osu,smoogipoo/osu,ppy/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu
osu.Game.Rulesets.Osu.Tests/Mods/OsuModTestScene.cs
osu.Game.Rulesets.Osu.Tests/Mods/OsuModTestScene.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 osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Osu.Tests.Mods { public abstract class OsuModTestScene : ModTestScene { protected override Ruleset CreatePlayerRuleset() => new OsuRuleset(); } }
// 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 osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Osu.Tests.Mods { public class OsuModTestScene : ModTestScene { protected override Ruleset CreatePlayerRuleset() => new OsuRuleset(); } }
mit
C#
9d61854c550b84cac4bb4e1994238fb2433b6de8
Update UrlHelperTests.cs
Particular/SyncOMatic
src/Tests/UrlHelperTests.cs
src/Tests/UrlHelperTests.cs
using System.Threading.Tasks; using VerifyXunit; using Xunit; [UsesVerify] public class UrlHelperTests { [Fact] public Task Company() { return Verifier.Verify(UrlHelper.GetCompany("https://github.com/org/repository")); } [Fact] public Task Project() { return Verifier.Verify(UrlHelper.GetProject("https://github.com/org/repository")); } }
using System.Threading.Tasks; using VerifyXunit; using Xunit; public class UrlHelperTests { [Fact] public Task Company() { return Verifier.Verify(UrlHelper.GetCompany("https://github.com/org/repository")); } [Fact] public Task Project() { return Verifier.Verify(UrlHelper.GetProject("https://github.com/org/repository")); } }
mit
C#
68ed6170769154463098b046aa81eaa2c72b0bf6
Remove PublicClient and AllowPromptNone Add missing AllowPlainTextPkce
diogodamiani/IdentityServer4.MongoDB,diogodamiani/IdentityServer4.MongoDB,diogodamiani/IdentityServer4.MongoDB
src/IdentityServer4.MongoDB/Entities/Client.cs
src/IdentityServer4.MongoDB/Entities/Client.cs
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using MongoDB.Bson; using System.Collections.Generic; namespace IdentityServer4.MongoDB.Entities { public class Client { public ObjectId Id { get; set; } public string ClientId { get; set; } public string ClientName { get; set; } public bool Enabled { get; set; } public List<ClientSecret> ClientSecrets { get; set; } public bool RequireClientSecret { get; set; } public string ClientUri { get; set; } public string LogoUri { get; set; } public bool RequireConsent { get; set; } public bool AllowRememberConsent { get; set; } public List<ClientGrantType> AllowedGrantTypes { get; set; } public bool RequirePkce { get; set; } public bool AllowPlainTextPkce { get; set; } public bool AllowAccessTokensViaBrowser { get; set; } public List<ClientRedirectUri> RedirectUris { get; set; } public List<ClientPostLogoutRedirectUri> PostLogoutRedirectUris { get; set; } public string LogoutUri { get; set; } public bool LogoutSessionRequired { get; set; } public bool AllowAccessToAllScopes { get; set; } public List<ClientScope> AllowedScopes { get; set; } public int IdentityTokenLifetime { get; set; } public int AccessTokenLifetime { get; set; } public int AuthorizationCodeLifetime { get; set; } public int AbsoluteRefreshTokenLifetime { get; set; } public int SlidingRefreshTokenLifetime { get; set; } public int RefreshTokenUsage { get; set; } public bool UpdateAccessTokenClaimsOnRefresh { get; set; } public int RefreshTokenExpiration { get; set; } public int AccessTokenType { get; set; } public bool EnableLocalLogin { get; set; } public List<ClientIdPRestriction> IdentityProviderRestrictions { get; set; } public bool IncludeJwtId { get; set; } public List<ClientClaim> Claims { get; set; } public bool AlwaysSendClientClaims { get; set; } public bool PrefixClientClaims { get; set; } public List<ClientCorsOrigin> AllowedCorsOrigins { get; set; } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using MongoDB.Bson; using System.Collections.Generic; namespace IdentityServer4.MongoDB.Entities { public class Client { public ObjectId Id { get; set; } public string ClientId { get; set; } public string ClientName { get; set; } public bool Enabled { get; set; } public List<ClientSecret> ClientSecrets { get; set; } public bool RequireClientSecret { get; set; } public string ClientUri { get; set; } public string LogoUri { get; set; } public bool RequireConsent { get; set; } public bool AllowRememberConsent { get; set; } public List<ClientGrantType> AllowedGrantTypes { get; set; } public bool RequirePkce { get; set; } public bool AllowAccessTokensViaBrowser { get; set; } public List<ClientRedirectUri> RedirectUris { get; set; } public List<ClientPostLogoutRedirectUri> PostLogoutRedirectUris { get; set; } public string LogoutUri { get; set; } public bool LogoutSessionRequired { get; set; } public bool AllowAccessToAllScopes { get; set; } public List<ClientScope> AllowedScopes { get; set; } public int IdentityTokenLifetime { get; set; } public int AccessTokenLifetime { get; set; } public int AuthorizationCodeLifetime { get; set; } public int AbsoluteRefreshTokenLifetime { get; set; } public int SlidingRefreshTokenLifetime { get; set; } public int RefreshTokenUsage { get; set; } public bool UpdateAccessTokenClaimsOnRefresh { get; set; } public int RefreshTokenExpiration { get; set; } public int AccessTokenType { get; set; } public bool EnableLocalLogin { get; set; } public List<ClientIdPRestriction> IdentityProviderRestrictions { get; set; } public bool IncludeJwtId { get; set; } public List<ClientClaim> Claims { get; set; } public bool AlwaysSendClientClaims { get; set; } public bool PrefixClientClaims { get; set; } public List<ClientCorsOrigin> AllowedCorsOrigins { get; set; } public bool PublicClient { get; set; } public bool AllowPromptNone { get; set; } } }
apache-2.0
C#
73d7ff36fb5a06728c7475b748e052f1abf30b22
reset the listview selecteditem
sander1095/DnD_Soundboard_Edres
DnDSoundboard/ViewModels/SoundboardItemViewModel.cs
DnDSoundboard/ViewModels/SoundboardItemViewModel.cs
using System; using System.ComponentModel; using Xamarin.Forms; using System.Collections.ObjectModel; using DnDSoundboard.Models; using DnDSoundboard.DependencyServices.Interfaces; namespace DnDSoundboard.ViewModels { public class SoundboardItemViewModel : INotifyPropertyChanged { private ListView listview { get; set; } public event PropertyChangedEventHandler PropertyChanged; public ObservableCollection<SoundboardItem> SoundboardItems { get; set; } SoundboardItem _selectedSoundboardItem; public SoundboardItem selectedSoundboardItem { get { return _selectedSoundboardItem; } set{ if (_selectedSoundboardItem != value && value != null) { _selectedSoundboardItem = value; PlaySound (value); } } } public SoundboardItemViewModel (ListView lv) { this.listview = lv; FillList (); } /// <summary> /// Fills the list with SoundboardItems /// </summary> public void FillList() { SoundboardItems = new ObservableCollection<SoundboardItem> (); SoundboardItems.Add(new SoundboardItem("test","test")); } public void PlaySound(SoundboardItem item) { this.listview.SelectedItem = null; _selectedSoundboardItem = null; DependencyService.Get<ISoundPlayer> ().PlaySound (item); } } }
using System; using System.ComponentModel; using Xamarin.Forms; using System.Collections.ObjectModel; using DnDSoundboard.Models; using DnDSoundboard.DependencyServices.Interfaces; namespace DnDSoundboard.ViewModels { public class SoundboardItemViewModel : INotifyPropertyChanged { private ListView listview { get; set; } public event PropertyChangedEventHandler PropertyChanged; public ObservableCollection<SoundboardItem> SoundboardItems { get; set; } SoundboardItem _selectedSoundboardItem; public SoundboardItem selectedSoundboardItem { get { return _selectedSoundboardItem; } set{ if (_selectedSoundboardItem != value && value != null) { _selectedSoundboardItem = value; PlaySound (value); } } } public SoundboardItemViewModel (ListView lv) { this.listview = lv; FillList (); } /// <summary> /// Fills the list with SoundboardItems /// </summary> public void FillList() { SoundboardItems = new ObservableCollection<SoundboardItem> (); SoundboardItems.Add(new SoundboardItem("test","test")); } public void PlaySound(SoundboardItem item) { //this.listview.SelectedItem = null; _selectedSoundboardItem = null; DependencyService.Get<ISoundPlayer> ().PlaySound (item); } } }
mit
C#
202f86d8308994c364b74009fe974c56c796fbba
Update Program.cs
vishipayyallore/CSharp-DotNet-Core-Samples
LearningDesignPatterns/Source/DataStructures/LinkedLists/LinkedList.Demos/Program.cs
LearningDesignPatterns/Source/DataStructures/LinkedLists/LinkedList.Demos/Program.cs
using System; using System.Runtime.InteropServices; using static System.Console; namespace LinkedList.Demos { public class Node { public int Value { get; set; } public Node NextNode { get; set; } public override string ToString() { GCHandle handle = GCHandle.Alloc(this, GCHandleType.WeakTrackResurrection); IntPtr address = GCHandle.ToIntPtr(handle); return $"Value: {Value} at Address: {address}"; } } class Program { static void Main(string[] args) { var node = new Node { Value = 101 }; WriteLine(node); //GCHandle handle = GCHandle.Alloc(node, GCHandleType.WeakTrackResurrection); //IntPtr address = GCHandle.ToIntPtr(handle); //WriteLine($"Value: {node.Value} at Address: {address}"); WriteLine("\n\nPress any key ..."); ReadKey(); } } }
using System; using System.Runtime.InteropServices; using static System.Console; namespace LinkedList.Demos { public class Node { public int Value { get; set; } } class Program { static void Main(string[] args) { var node = new Node { Value = 101 }; GCHandle handle = GCHandle.Alloc(node, GCHandleType.WeakTrackResurrection); IntPtr address = GCHandle.ToIntPtr(handle); WriteLine($"Value: {node.Value} at Address: {address}"); WriteLine("\n\nPress any key ..."); ReadKey(); } } }
apache-2.0
C#
b23b0c34dc89eab1153cdbe77835147a70040d44
Make CilInstructionLabel a class and mutable.
Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver
src/AsmResolver.PE/DotNet/Cil/CilInstructionLabel.cs
src/AsmResolver.PE/DotNet/Cil/CilInstructionLabel.cs
using System; namespace AsmResolver.PE.DotNet.Cil { /// <summary> /// Represents a label that references an instruction by its instruction object in a CIL method body. /// </summary> public struct CilInstructionLabel : ICilLabel { /// <summary> /// Creates a new instruction label. /// </summary> /// <param name="instruction">The instruction to reference.</param> public CilInstructionLabel(CilInstruction instruction) { Instruction = instruction ?? throw new ArgumentNullException(nameof(instruction)); } /// <summary> /// Gets or sets the referenced instruction. /// </summary> public CilInstruction Instruction { get; set; } /// <inheritdoc /> public int Offset => Instruction.Offset; /// <inheritdoc /> public override string ToString() => "IL_" + Offset.ToString("X4"); } }
using System; namespace AsmResolver.PE.DotNet.Cil { /// <summary> /// Represents a label that references an instruction by its instruction object in a CIL method body. /// </summary> public struct CilInstructionLabel : ICilLabel { /// <summary> /// Creates a new instruction label. /// </summary> /// <param name="instruction">The instruction to reference.</param> public CilInstructionLabel(CilInstruction instruction) { Instruction = instruction ?? throw new ArgumentNullException(nameof(instruction)); } /// <summary> /// Gets the referenced instruction. /// </summary> public CilInstruction Instruction { get; } /// <inheritdoc /> public int Offset => Instruction.Offset; /// <inheritdoc /> public override string ToString() => "IL_" + Offset.ToString("X4"); } }
mit
C#
7ca4c6e53086847a9808368e61e334e71284700a
Update Singleton.cs
efruchter/UnityUtilities
Patterns/Singleton.cs
Patterns/Singleton.cs
using UnityEngine.Assertions; namespace Patterns { /// <summary> /// Singleton manager. /// </summary> public static class Singleton<T> where T : class { public delegate void SingletonReady(T t); private static T _singleton; private static SingletonReady _onAdd; /// <summary> /// O(1) Fetch or add a singleton. /// </summary> public static T Instance { set { AddSingleton(value); } get { return GetSingleton(); } } public static bool Exists { get { return _singleton != null && !_singleton.Equals(null); } } /// <summary> /// Get a singleton. /// </summary> /// <returns>The singleton if available.</returns> public static T GetSingleton() { return _singleton; } /// <summary> /// Perform an action as soon as the singleton is available. /// </summary> public static SingletonReady InstanceReady { set { GetSingletonDeferred(value); } } /// <summary> /// Get a singleton whenever it is available. /// </summary> /// <param name="onAdd">The callback to run when singleton Exists</param> public static void GetSingletonDeferred(SingletonReady onAdd) { if (onAdd == null) { return; } if (Exists) { onAdd(GetSingleton()); } else if (_onAdd == null) { _onAdd = onAdd; } else { _onAdd += onAdd; } } /// <summary> /// Register a singleton. Replacement is illegal. /// </summary> /// <param name="singleton">The instance.</param> public static void AddSingleton(T singleton) { AddSingleton(singleton, false); } /// <summary> /// Release the singleton so others can use it. /// </summary> public static void Release() { _singleton = null; _onAdd = null; } /// <summary> /// Register a singleton. /// </summary> /// <param name="singleton">The instance.</param> /// <param name="allowReplace">If true, allow replacement without warning.</param> public static void AddSingleton(T singleton, bool allowReplace) { if (singleton == null) { Release(); return; } Assert.IsFalse(!allowReplace && Exists, "Replacing a singleton that already exists. Check the stack trace for more info. If you would like to allow replacement, call AddSingleton and set allowReplace to true."); _singleton = singleton; if (_onAdd != null) { _onAdd(singleton); _onAdd = null; } } } }
using System; using UnityEngine.Assertions; namespace Patterns { /// <summary> /// Singleton manager. Provides a warning when trying to double-add or get null singletons. /// </summary> public static class Singleton<T> where T : class { private static T _singleton; private static Action<T> _onAdd; /// <summary> /// O(1) Fetch or add of singleton. /// </summary> public static T Instance { set { AddSingleton(value); } get { return GetSingleton(); } } public static bool Exists { get { return _singleton != null; } } /// <summary> /// Get a singleton. Warning if not available. /// </summary> /// <returns>The singleton if available.</returns> public static T GetSingleton() { Assert.IsTrue(Exists, "Singleton does not exist at this moment. Advice: Fetch Singletons with GetSingletonDeferred, or later in the frame."); return _singleton; } /// <summary> /// Perform an action as soon as the singleton is available. /// </summary> public static Action<T> InstanceReady { set { GetSingletonDeferred(value); } } /// <summary> /// Get a singleton whenever it is available. /// </summary> /// <param name="onAdd">The callback to run when singleton Exists</param> public static void GetSingletonDeferred(Action<T> onAdd) { Assert.IsNotNull(onAdd, "Callback can not be null."); if (Exists) { onAdd(GetSingleton()); } else if (_onAdd == null) { _onAdd = onAdd; } else { _onAdd += onAdd; } } /// <summary> /// Register a singleton. Replacement is illegal. /// </summary> /// <param name="singleton">The instance.</param> public static void AddSingleton(T singleton) { AddSingleton(singleton, false); } /// <summary> /// Release the singleton so others can use it. /// </summary> public static void Release() { _singleton = null; _onAdd = null; } /// <summary> /// Register a singleton. /// </summary> /// <param name="singleton">The instance.</param> /// <param name="allowReplace">If true, allow replacement without warning.</param> public static void AddSingleton(T singleton, bool allowReplace) { if (singleton == null) { Release(); return; } Assert.IsFalse(!allowReplace && Exists, "Attempting to replace a singleton that already exists."); _singleton = singleton; if (_onAdd != null) { _onAdd(singleton); _onAdd = null; } } } }
mit
C#
ee9297293a22bd812d518496d9094021d2875c8c
Fix typo in icon picker style tag (#3265)
petedavis/Orchard2,xkproject/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,petedavis/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,OrchardCMS/Brochard
src/OrchardCore.Modules/OrchardCore.ContentFields/Views/TextField-IconPicker.Edit.cshtml
src/OrchardCore.Modules/OrchardCore.ContentFields/Views/TextField-IconPicker.Edit.cshtml
@model OrchardCore.ContentFields.ViewModels.EditTextFieldViewModel @using OrchardCore.ContentManagement.Metadata.Models @using OrchardCore.ContentFields.Settings; @{ var settings = Model.PartFieldDefinition.Settings.ToObject<TextFieldSettings>(); } <style name="fontpickerStyle" at="Head" asp-src="~/OrchardCore.ContentFields/Styles/fontawesome-iconpicker.min.css" debug-src="~/OrchardCore.ContentFields/Styles/fontawesome-iconpicker.css"></style> <style name="fontpickerCustomStyle" at="Head" asp-src="~/OrchardCore.ContentFields/Styles/iconpicker-custom.css"></style> <script name="fontpickerScript" asp-src="~/OrchardCore.ContentFields/Scripts/fontawesome-iconpicker.min.js" debug-src="~/OrchardCore.ContentFields/Scripts/fontawesome-iconpicker.js" at="Foot" depends-on="jquery"></script> <script name="iconpickerCustomScript" asp-src="~/OrchardCore.ContentFields/Scripts/iconpicker-custom.js" at="Foot"></script> <fieldset class="form-group"> <label asp-for="Text">@Model.PartFieldDefinition.DisplayName()</label> <input type="hidden" asp-for="Text" id="@Html.IdFor(m=>m.Text)" /> <div class="btn-group input-group"> <button type="button" class="btn btn-primary iconpicker-component"> <i class="fa fa-fw fa-heart"></i> </button> <button type="button" id="@Html.IdForModel()" class="icp icp-dd btn btn-primary dropdown-toggle" data-selected="fa-car" data-toggle="dropdown"> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <div class="dropdown-menu"></div> </div> @if (!String.IsNullOrEmpty(settings.Hint)) { <span class="hint">@settings.Hint</span> } </fieldset> <script at="Foot"> $(function () { $('#@Html.IdForModel()').iconpicker(); var storedIcon = $('#@Html.IdFor(m=>m.Text)').val(); if (storedIcon) { $('#@Html.IdForModel()').data('iconpicker').update(storedIcon); $('#@Html.IdForModel()').on('iconpickerSelected', function (e) { $('#@Html.IdFor(m=>m.Text)').val(e.iconpickerInstance.options.fullClassFormatter(e.iconpickerValue)); }); } }); </script>
@model OrchardCore.ContentFields.ViewModels.EditTextFieldViewModel @using OrchardCore.ContentManagement.Metadata.Models @using OrchardCore.ContentFields.Settings; @{ var settings = Model.PartFieldDefinition.Settings.ToObject<TextFieldSettings>(); } <style name="fontpickerStyle" at="Head" asp-src="~/OrchardCore.ContentFields/Styles/fontawesome-iconpicker-min.css" debug-src="~/OrchardCore.ContentFields/Styles/fontawesome-iconpicker.css"></style> <style name="fontpickerCustomStyle" at="Head" asp-src="~/OrchardCore.ContentFields/Styles/iconpicker-custom.css"></style> <script name="fontpickerScript" asp-src="~/OrchardCore.ContentFields/Scripts/fontawesome-iconpicker.min.js" debug-src="~/OrchardCore.ContentFields/Scripts/fontawesome-iconpicker.js" at="Foot" depends-on="jquery"></script> <script name="iconpickerCustomScript" asp-src="~/OrchardCore.ContentFields/Scripts/iconpicker-custom.js" at="Foot"></script> <fieldset class="form-group"> <label asp-for="Text">@Model.PartFieldDefinition.DisplayName()</label> <input type="hidden" asp-for="Text" id="@Html.IdFor(m=>m.Text)" /> <div class="btn-group input-group"> <button type="button" class="btn btn-primary iconpicker-component"> <i class="fa fa-fw fa-heart"></i> </button> <button type="button" id="@Html.IdForModel()" class="icp icp-dd btn btn-primary dropdown-toggle" data-selected="fa-car" data-toggle="dropdown"> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <div class="dropdown-menu"></div> </div> @if (!String.IsNullOrEmpty(settings.Hint)) { <span class="hint">@settings.Hint</span> } </fieldset> <script at="Foot"> $(function () { $('#@Html.IdForModel()').iconpicker(); var storedIcon = $('#@Html.IdFor(m=>m.Text)').val(); if (storedIcon) { $('#@Html.IdForModel()').data('iconpicker').update(storedIcon); $('#@Html.IdForModel()').on('iconpickerSelected', function (e) { $('#@Html.IdFor(m=>m.Text)').val(e.iconpickerInstance.options.fullClassFormatter(e.iconpickerValue)); }); } }); </script>
bsd-3-clause
C#
7eea796babbab24677dc38b3a664338198df857a
Change Test Attribute
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork
src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/SpecialTests/SqlDialogueHelperTests.cs
src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/SpecialTests/SqlDialogueHelperTests.cs
using Dapper.FastCrud; using NUnit.Framework; using Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.ExampleTests.Repository; using Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers; using Smooth.IoC.Dapper.Repository.UnitOfWork.Helpers; namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.SpecialTests { [TestFixture] public class SqlDialogueHelperTests : CommonTestDataSetup { [Test] public static void SetDialogueIfNeeded_AddsMappedIsFroozenToDictionary() { var target = SqlDialogueHelper.Instance; target.SetDialogueIfNeeded<Brave>(SqlDialect.SqLite); var result = target.GetEntityState<Brave>(); Assert.That(result.HasValue, Is.True); } [Test, Category("Integration")] public static void SetDialogueIfNeeded_SetsIsFroozenInDictionary() { var repo = new BraveRepository(Factory); repo.GetKey<ITestSession>(1); var target = SqlDialogueHelper.Instance; var result = target.GetEntityState<Brave>(); Assert.That(result.HasValue, Is.True); Assert.That(result.Value, Is.True); } } }
using Dapper.FastCrud; using NUnit.Framework; using Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.ExampleTests.Repository; using Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers; using Smooth.IoC.Dapper.Repository.UnitOfWork.Helpers; namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.SpecialTests { [TestFixture] public class SqlDialogueHelperTests : CommonTestDataSetup { [Test] public static void SetDialogueIfNeeded_AddsMappedIsFroozenToDictionary() { var target = SqlDialogueHelper.Instance; target.SetDialogueIfNeeded<Brave>(SqlDialect.SqLite); var result = target.GetEntityState<Brave>(); Assert.That(result.HasValue, Is.True); } [Test] public static void SetDialogueIfNeeded_SetsIsFroozenInDictionary() { var repo = new BraveRepository(Factory); repo.GetKey<ITestSession>(1); var target = SqlDialogueHelper.Instance; var result = target.GetEntityState<Brave>(); Assert.That(result.HasValue, Is.True); Assert.That(result.Value, Is.True); } } }
mit
C#
8abac92b2bc3cb215b84d401511d47bdee27de3a
Remove unused property from view locator
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewLocator.cs
WalletWasabi.Fluent/ViewLocator.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Controls; using Avalonia.Controls.Templates; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Fluent { public class ViewLocator : IDataTemplate { public IControl Build(object data) { var name = data.GetType().FullName!.Replace("ViewModel", "View"); var type = Type.GetType(name); if (type != null) { var result = Activator.CreateInstance(type) as Control; if (result is null) { throw new Exception($"Unable to activate type: {type}"); } return result; } else { return new TextBlock { Text = "Not Found: " + name }; } } public bool Match(object data) { return data is ViewModelBase; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Controls; using Avalonia.Controls.Templates; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Fluent { public class ViewLocator : IDataTemplate { public bool SupportsRecycling => false; public IControl Build(object data) { var name = data.GetType().FullName!.Replace("ViewModel", "View"); var type = Type.GetType(name); if (type != null) { var result = Activator.CreateInstance(type) as Control; if (result is null) { throw new Exception($"Unable to activate type: {type}"); } return result; } else { return new TextBlock { Text = "Not Found: " + name }; } } public bool Match(object data) { return data is ViewModelBase; } } }
mit
C#
fbc7ac0e8bb34766e36327a52d7ce9af4fc7d546
set precompiled output to updatable
kjelliverb/condep-dsl-operations
ConDep.Dsl/Operations/PreCompile/PreCompileOperation.cs
ConDep.Dsl/Operations/PreCompile/PreCompileOperation.cs
using System; using System.Diagnostics; using System.IO; using System.Web.Compilation; using ConDep.Dsl.Builders; using ConDep.Dsl.Operations.WebDeploy.Model; namespace ConDep.Dsl { public class PreCompileOperation : IOperateConDep { private readonly string _webApplicationName; private readonly string _webApplicationPhysicalPath; private readonly string _preCompileOutputpath; public PreCompileOperation(string webApplicationName, string webApplicationPhysicalPath, string preCompileOutputpath) { _webApplicationName = webApplicationName; _webApplicationPhysicalPath = webApplicationPhysicalPath; _preCompileOutputpath = preCompileOutputpath; } public WebDeploymentStatus Execute(EventHandler<WebDeployMessageEventArgs> output, EventHandler<WebDeployMessageEventArgs> outputError, WebDeploymentStatus webDeploymentStatus) { try { if(Directory.Exists(_preCompileOutputpath)) Directory.Delete(_preCompileOutputpath, true); var buildManager = new ClientBuildManager(_webApplicationName, _webApplicationPhysicalPath, _preCompileOutputpath, new ClientBuildManagerParameter{ PrecompilationFlags = PrecompilationFlags.Updatable }); buildManager.PrecompileApplication(new PreCompileCallback(output, outputError)); } catch (Exception ex) { var args = new WebDeployMessageEventArgs { Level = TraceLevel.Error, Message = ex.Message }; outputError(this, args); throw; } return webDeploymentStatus; } public bool IsValid(Notification notification) { return true; } } }
using System; using System.Diagnostics; using System.IO; using System.Web.Compilation; using ConDep.Dsl.Builders; using ConDep.Dsl.Operations.WebDeploy.Model; namespace ConDep.Dsl { public class PreCompileOperation : IOperateConDep { private readonly string _webApplicationName; private readonly string _webApplicationPhysicalPath; private readonly string _preCompileOutputpath; public PreCompileOperation(string webApplicationName, string webApplicationPhysicalPath, string preCompileOutputpath) { _webApplicationName = webApplicationName; _webApplicationPhysicalPath = webApplicationPhysicalPath; _preCompileOutputpath = preCompileOutputpath; } public WebDeploymentStatus Execute(EventHandler<WebDeployMessageEventArgs> output, EventHandler<WebDeployMessageEventArgs> outputError, WebDeploymentStatus webDeploymentStatus) { try { if(Directory.Exists(_preCompileOutputpath)) Directory.Delete(_preCompileOutputpath, true); var buildManager = new ClientBuildManager(_webApplicationName, _webApplicationPhysicalPath, _preCompileOutputpath); buildManager.PrecompileApplication(new PreCompileCallback(output, outputError)); } catch (Exception ex) { var args = new WebDeployMessageEventArgs { Level = TraceLevel.Error, Message = ex.Message }; outputError(this, args); throw; } return webDeploymentStatus; } public bool IsValid(Notification notification) { return true; } } }
bsd-2-clause
C#
685b186eb12861ffabff81ff33816722866cfebe
Update replicas only on single index
adam-mccoy/elasticsearch-net,TheFireCookie/elasticsearch-net,elastic/elasticsearch-net,CSGOpenSource/elasticsearch-net,elastic/elasticsearch-net,TheFireCookie/elasticsearch-net,TheFireCookie/elasticsearch-net,adam-mccoy/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,CSGOpenSource/elasticsearch-net
src/Tests/Indices/IndexSettings/UpdateIndicesSettings/UpdateIndexSettingsApiTests.cs
src/Tests/Indices/IndexSettings/UpdateIndicesSettings/UpdateIndexSettingsApiTests.cs
using System; using System.Collections.Generic; using Elasticsearch.Net; using Nest; using Tests.Framework; using Tests.Framework.Integration; using Xunit; using static Nest.Infer; namespace Tests.Indices.IndexSettings.UpdateIndicesSettings { [Collection(TypeOfCluster.Indexing)] public class UpdateIndexSettingsApiTests : ApiIntegrationTestBase<IUpdateIndexSettingsResponse, IUpdateIndexSettingsRequest, UpdateIndexSettingsDescriptor, UpdateIndexSettingsRequest> { public UpdateIndexSettingsApiTests(IndexingCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override void IntegrationSetup(IElasticClient client, CallUniqueValues values) { foreach (var value in values) { var index = value.Value; var createIndexResponse = client.CreateIndex(index); if (!createIndexResponse.IsValid) throw new Exception($"Invalid response when setting up index for integration test {this.GetType().Name}"); } } protected override LazyResponses ClientUsage() => Calls( fluent: (client, f) => client.UpdateIndexSettings(CallIsolatedValue, f), fluentAsync: (client, f) => client.UpdateIndexSettingsAsync(CallIsolatedValue, f), request: (client, r) => client.UpdateIndexSettings(r), requestAsync: (client, r) => client.UpdateIndexSettingsAsync(r) ); protected override bool ExpectIsValid => true; protected override int ExpectStatusCode => 200; protected override HttpMethod HttpMethod => HttpMethod.PUT; protected override string UrlPath => $"{CallIsolatedValue}/_settings"; protected override object ExpectJson { get; } = new Dictionary<string, object> { { "index.blocks.write", false }, { "index.number_of_replicas", 2 } }; protected override Func<UpdateIndexSettingsDescriptor, IUpdateIndexSettingsRequest> Fluent => d => d .Index(CallIsolatedValue) .IndexSettings(i => i .BlocksWrite(false) .NumberOfReplicas(2) ); protected override UpdateIndexSettingsRequest Initializer => new UpdateIndexSettingsRequest(CallIsolatedValue) { IndexSettings = new Nest.IndexSettings { BlocksWrite = false, NumberOfReplicas = 2 } }; } }
using System; using System.Collections.Generic; using Elasticsearch.Net; using Nest; using Tests.Framework; using Tests.Framework.Integration; using Xunit; using static Nest.Infer; namespace Tests.Indices.IndexSettings.UpdateIndicesSettings { [Collection(TypeOfCluster.Indexing)] public class UpdateIndexSettingsApiTests : ApiIntegrationTestBase<IUpdateIndexSettingsResponse, IUpdateIndexSettingsRequest, UpdateIndexSettingsDescriptor, UpdateIndexSettingsRequest> { public UpdateIndexSettingsApiTests(IndexingCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override LazyResponses ClientUsage() => Calls( fluent: (client, f) => client.UpdateIndexSettings(AllIndices, f), fluentAsync: (client, f) => client.UpdateIndexSettingsAsync(AllIndices, f), request: (client, r) => client.UpdateIndexSettings(r), requestAsync: (client, r) => client.UpdateIndexSettingsAsync(r) ); protected override bool ExpectIsValid => true; protected override int ExpectStatusCode => 200; protected override HttpMethod HttpMethod => HttpMethod.PUT; protected override string UrlPath => $"/_settings"; protected override object ExpectJson { get; } = new Dictionary<string, object> { { "index.blocks.write", false }, { "index.number_of_replicas", 2 } }; protected override Func<UpdateIndexSettingsDescriptor, IUpdateIndexSettingsRequest> Fluent => d => d .IndexSettings(i => i .BlocksWrite(false) .NumberOfReplicas(2) ); protected override UpdateIndexSettingsRequest Initializer => new UpdateIndexSettingsRequest { IndexSettings = new Nest.IndexSettings { BlocksWrite = false, NumberOfReplicas = 2 } }; } }
apache-2.0
C#
06af4afa2b6038c87b34d10ad92e42a2b00334ff
Add TagsClient to GitHubClient inteface
octokit/octokit.net,forki/octokit.net,octokit/octokit.net,kolbasov/octokit.net,nsnnnnrn/octokit.net,chunkychode/octokit.net,yonglehou/octokit.net,magoswiat/octokit.net,ivandrofly/octokit.net,cH40z-Lord/octokit.net,Red-Folder/octokit.net,darrelmiller/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,octokit-net-test/octokit.net,SamTheDev/octokit.net,Sarmad93/octokit.net,takumikub/octokit.net,fake-organization/octokit.net,Sarmad93/octokit.net,ChrisMissal/octokit.net,dampir/octokit.net,mminns/octokit.net,M-Zuber/octokit.net,rlugojr/octokit.net,eriawan/octokit.net,octokit-net-test-org/octokit.net,hitesh97/octokit.net,thedillonb/octokit.net,gdziadkiewicz/octokit.net,devkhan/octokit.net,geek0r/octokit.net,SamTheDev/octokit.net,khellang/octokit.net,shana/octokit.net,TattsGroup/octokit.net,hahmed/octokit.net,editor-tools/octokit.net,daukantas/octokit.net,fffej/octokit.net,alfhenrik/octokit.net,thedillonb/octokit.net,rlugojr/octokit.net,M-Zuber/octokit.net,dampir/octokit.net,shiftkey/octokit.net,shana/octokit.net,kdolan/octokit.net,gabrielweyer/octokit.net,dlsteuer/octokit.net,shiftkey-tester/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,TattsGroup/octokit.net,yonglehou/octokit.net,shiftkey/octokit.net,ivandrofly/octokit.net,shiftkey-tester/octokit.net,hahmed/octokit.net,SmithAndr/octokit.net,chunkychode/octokit.net,eriawan/octokit.net,gabrielweyer/octokit.net,SmithAndr/octokit.net,devkhan/octokit.net,SLdragon1989/octokit.net,editor-tools/octokit.net,mminns/octokit.net,naveensrinivasan/octokit.net,adamralph/octokit.net,brramos/octokit.net,nsrnnnnn/octokit.net,gdziadkiewicz/octokit.net,alfhenrik/octokit.net,khellang/octokit.net,octokit-net-test-org/octokit.net,bslliw/octokit.net,michaKFromParis/octokit.net
Octokit/IGitHubClient.cs
Octokit/IGitHubClient.cs
using Octokit.Internal; namespace Octokit { public interface IGitHubClient { IConnection Connection { get; } IAuthorizationsClient Authorization { get; } IIssuesClient Issue { get; } IMiscellaneousClient Miscellaneous { get; } IOrganizationsClient Organization { get; } IRepositoriesClient Repository { get; } IReleasesClient Release { get; } ISshKeysClient SshKey { get; } IUsersClient User { get; } INotificationsClient Notification { get; } ITagsClient Tag { get; } } }
using Octokit.Internal; namespace Octokit { public interface IGitHubClient { IConnection Connection { get; } IAuthorizationsClient Authorization { get; } IIssuesClient Issue { get; } IMiscellaneousClient Miscellaneous { get; } IOrganizationsClient Organization { get; } IRepositoriesClient Repository { get; } IReleasesClient Release { get; } ISshKeysClient SshKey { get; } IUsersClient User { get; } INotificationsClient Notification { get; } } }
mit
C#
eb04820d01a1957a4cf0ec37642d0a63f622c874
fix possible NRE if empty filter was called
stormleoxia/teamcity-nuget-support,JetBrains/teamcity-nuget-support,stormleoxia/teamcity-nuget-support,JetBrains/teamcity-nuget-support,stormleoxia/teamcity-nuget-support,JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support
nuget-extensions/nuget-commands/src/ListCommandBase.cs
nuget-extensions/nuget-commands/src/ListCommandBase.cs
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Linq.Expressions; using JetBrains.TeamCity.NuGet.ExtendedCommands.Util; using NuGet; namespace JetBrains.TeamCity.NuGet.ExtendedCommands { public abstract class ListCommandBase : CommandBase { [Import] public IPackageRepositoryFactory RepositoryFactory { get; set; } [Import] public IPackageSourceProvider SourceProvider { get; set; } protected IEnumerable<IPackage> GetAllPackages(string source, IEnumerable<string> ids) { IPackageRepository packageRepository = RepositoryFactory.CreateRepository(source); var param = Expression.Parameter(typeof (IPackageMetadata)); Expression result = ids .Select(id => Expression.Equal(Expression.Property(param, "Id"), Expression.Constant(id))) .Aggregate<Expression, Expression>(null, (acc, element) => acc != null ? Expression.Or(element, acc) : element); var items = packageRepository.GetPackages(); if (result == null) return items; return items.Where(Expression.Lambda<Func<IPackage, bool>>(result, param)); } /// <summary> /// There was a change in signature in NuGet poset 1.5. IPackage.get_Version now returns Semantic version instead of Version /// Here is no difference here, so we can stick to dynamic object as there are tests for this method. /// </summary> protected static void PrintPackageInfo(string id, string version) { var msg = ServiceMessageFormatter.FormatMessage( "nuget-package", new ServiceMessageProperty("Id", id), new ServiceMessageProperty("Version", version) ); System.Console.Out.WriteLine(msg); } } public static class PackageExtensions { public static string VersionString(this IPackage package) { return ((dynamic) package).Version.ToString(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Linq.Expressions; using JetBrains.TeamCity.NuGet.ExtendedCommands.Util; using NuGet; namespace JetBrains.TeamCity.NuGet.ExtendedCommands { public abstract class ListCommandBase : CommandBase { [Import] public IPackageRepositoryFactory RepositoryFactory { get; set; } [Import] public IPackageSourceProvider SourceProvider { get; set; } protected IEnumerable<IPackage> GetAllPackages(string source, IEnumerable<string> ids) { IPackageRepository packageRepository = RepositoryFactory.CreateRepository(source); var param = Expression.Parameter(typeof (IPackageMetadata)); Expression result = ids .Select(id => Expression.Equal(Expression.Property(param, "Id"), Expression.Constant(id))) .Aggregate<BinaryExpression, Expression>(null, (current, action) => current != null ? Expression.Or(action, current) : action); return packageRepository.GetPackages().Where(Expression.Lambda<Func<IPackage, bool>>(result, param)); } /// <summary> /// There was a change in signature in NuGet poset 1.5. IPackage.get_Version now returns Semantic version instead of Version /// Here is no difference here, so we can stick to dynamic object as there are tests for this method. /// </summary> protected static void PrintPackageInfo(string id, string version) { var msg = ServiceMessageFormatter.FormatMessage( "nuget-package", new ServiceMessageProperty("Id", id), new ServiceMessageProperty("Version", version) ); System.Console.Out.WriteLine(msg); } } public static class PackageExtensions { public static string VersionString(this IPackage package) { return ((dynamic) package).Version.ToString(); } } }
apache-2.0
C#
bad30d9e602537a6e2afbfb41333d89d9235a4c4
Fix dialog dangerous button being clickable at edges
NeoAdonis/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu
osu.Game/Overlays/Dialog/PopupDialogDangerousButton.cs
osu.Game/Overlays/Dialog/PopupDialogDangerousButton.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 osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osu.Game.Graphics; using osu.Game.Graphics.Containers; namespace osu.Game.Overlays.Dialog { public class PopupDialogDangerousButton : PopupDialogButton { private Box progressBox; private DangerousConfirmContainer confirmContainer; [BackgroundDependencyLoader] private void load(OsuColour colours) { ButtonColour = colours.Red3; ColourContainer.Add(progressBox = new Box { RelativeSizeAxes = Axes.Both, Blending = BlendingParameters.Additive, }); AddInternal(confirmContainer = new DangerousConfirmContainer { Action = () => Action(), RelativeSizeAxes = Axes.Both, }); } protected override void LoadComplete() { base.LoadComplete(); confirmContainer.Progress.BindValueChanged(progress => progressBox.Width = (float)progress.NewValue, true); } private class DangerousConfirmContainer : HoldToConfirmContainer { protected override double? HoldActivationDelay => 500; protected override bool OnMouseDown(MouseDownEvent e) { BeginConfirm(); return true; } protected override void OnMouseUp(MouseUpEvent e) { if (!e.HasAnyButtonPressed) AbortConfirm(); } } } }
// 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 osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osu.Game.Graphics; using osu.Game.Graphics.Containers; namespace osu.Game.Overlays.Dialog { public class PopupDialogDangerousButton : PopupDialogButton { [BackgroundDependencyLoader] private void load(OsuColour colours) { ButtonColour = colours.Red3; ColourContainer.Add(new ConfirmFillBox { Action = () => Action(), RelativeSizeAxes = Axes.Both, Blending = BlendingParameters.Additive, }); } private class ConfirmFillBox : HoldToConfirmContainer { private Box box; protected override double? HoldActivationDelay => 500; protected override void LoadComplete() { base.LoadComplete(); Child = box = new Box { RelativeSizeAxes = Axes.Both, }; Progress.BindValueChanged(progress => box.Width = (float)progress.NewValue, true); } protected override bool OnMouseDown(MouseDownEvent e) { BeginConfirm(); return true; } protected override void OnMouseUp(MouseUpEvent e) { if (!e.HasAnyButtonPressed) AbortConfirm(); } } } }
mit
C#
9b978def26979a79cc449c64291aa4b816ee4d18
Add DynamicTemplates tests
toddams/RazorLight,toddams/RazorLight
tests/RazorLight.Tests/RazorLightEngineTest.cs
tests/RazorLight.Tests/RazorLightEngineTest.cs
using System.Collections.Generic; using System.Dynamic; using RazorLight.Razor; using RazorLight.Tests.Razor; using RazorLight.Tests.Utils; namespace RazorLight.Tests { using System.Threading.Tasks; using Xunit; public class RazorLightEngineTest { [Fact] public async Task Ensure_Option_Disable_Encoding_Renders_Models_Raw() { //Arrange var engine = new RazorLightEngineBuilder() .UseMemoryCachingProvider() #if NETFRAMEWORK .SetOperatingAssembly(typeof(Root).Assembly) #endif .UseFileSystemProject(DirectoryUtils.RootDirectory) .DisableEncoding() .Build(); string key = "key"; string content = "@Model.Entity"; var model = new { Entity = "<pre></pre>" }; // act var result = await engine.CompileRenderStringAsync(key, content, model); // assert Assert.Contains("<pre></pre>", result); } [Fact] public async Task Ensure_QuickStart_Demo_Code_Works() { var engine = new RazorLightEngineBuilder() #if NETFRAMEWORK .SetOperatingAssembly(typeof(Root).Assembly) #endif .UseEmbeddedResourcesProject(typeof(Root)) .UseMemoryCachingProvider() .Build(); string template = "Hello, @Model.Name. Welcome to RazorLight repository"; var model = new { Name = "John Doe" }; string result = await engine.CompileRenderStringAsync("templateKey", template, model); Assert.Equal("Hello, John Doe. Welcome to RazorLight repository", result); } [Fact] public async Task Ensure_Content_Added_To_DynamicTemplates() { var options = new RazorLightOptions(); const string key = "key"; const string content = "content"; var project = new TestRazorProject {Value = new TextSourceRazorProjectItem(key, content)}; var engine = new RazorLightEngineBuilder() #if NETFRAMEWORK .SetOperatingAssembly(typeof(Root).Assembly) #endif .UseProject(project) .UseOptions(options) .AddDynamicTemplates(new Dictionary<string, string> { [key] = content, }) .Build(); var actual = await engine.CompileRenderStringAsync(key, content, new object(), new ExpandoObject()); Assert.NotEmpty(options.DynamicTemplates); Assert.Contains(options.DynamicTemplates, t => t.Key == key && t.Value == content); Assert.Equal(content, actual); } [Fact] public async Task Ensure_Content_Added_To_DynamicTemplates_When_Options_Not_Set_Explicitly() { const string key = "key"; const string content = "content"; var project = new TestRazorProject { Value = new TextSourceRazorProjectItem(key, content) }; var engine = new RazorLightEngineBuilder() #if NETFRAMEWORK .SetOperatingAssembly(typeof(Root).Assembly) #endif .UseProject(project) .AddDynamicTemplates(new Dictionary<string, string> { [key] = content, }) .Build(); var actual = await engine.CompileRenderStringAsync(key, content, new object(), new ExpandoObject()); Assert.NotEmpty(engine.Options.DynamicTemplates); Assert.Contains(engine.Options.DynamicTemplates, t => t.Key == key && t.Value == content); Assert.Equal(content, actual); } } }
using RazorLight.Tests.Utils; namespace RazorLight.Tests { using System.Threading.Tasks; using Xunit; public class RazorLightEngineTest { [Fact] public async Task Ensure_Option_Disable_Encoding_Renders_Models_Raw() { //Arrange var engine = new RazorLightEngineBuilder() .UseMemoryCachingProvider() #if NETFRAMEWORK .SetOperatingAssembly(typeof(Root).Assembly) #endif .UseFileSystemProject(DirectoryUtils.RootDirectory) .DisableEncoding() .Build(); string key = "key"; string content = "@Model.Entity"; var model = new { Entity = "<pre></pre>" }; // act var result = await engine.CompileRenderStringAsync(key, content, model); // assert Assert.Contains("<pre></pre>", result); } [Fact] public async Task Ensure_QuickStart_Demo_Code_Works() { var engine = new RazorLightEngineBuilder() #if NETFRAMEWORK .SetOperatingAssembly(typeof(Root).Assembly) #endif .UseEmbeddedResourcesProject(typeof(Root)) .UseMemoryCachingProvider() .Build(); string template = "Hello, @Model.Name. Welcome to RazorLight repository"; var model = new { Name = "John Doe" }; string result = await engine.CompileRenderStringAsync("templateKey", template, model); Assert.Equal("Hello, John Doe. Welcome to RazorLight repository", result); } //[Fact] //public async Task Ensure_Content_Added_To_DynamicTemplates() //{ // var options = new RazorLightOptions(); // string key = "key"; // string content = "content"; // var project = new TestRazorProject(); // project.Value = new TextSourceRazorProjectItem(key, content); // var engine = new RazorLightEngineBuilder() // .UseProject(project) // .Build(); // await engine.CompileRenderStringAsync(key, content, new object(), new ExpandoObject()); // Assert.NotEmpty(options.DynamicTemplates); // Assert.Contains(options.DynamicTemplates, t => t.Key == key && t.Value == content); //} } }
apache-2.0
C#
2aedd82e27a490a09c5efe526e2e45a7120b12e0
Document room states and remove unnecessary WaitingForResults state
UselessToucan/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,ppy/osu,ppy/osu,ppy/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu
osu.Game/Online/RealtimeMultiplayer/MultiplayerRoomState.cs
osu.Game/Online/RealtimeMultiplayer/MultiplayerRoomState.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 namespace osu.Game.Online.RealtimeMultiplayer { /// <summary> /// The current overall state of a realtime multiplayer room. /// </summary> public enum MultiplayerRoomState { /// <summary> /// The room is open and accepting new players. /// </summary> Open, /// <summary> /// A game start has been triggered but players have not finished loading. /// </summary> WaitingForLoad, /// <summary> /// A game is currently ongoing. /// </summary> Playing, /// <summary> /// The room has been disbanded and closed. /// </summary> Closed } }
// 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 namespace osu.Game.Online.RealtimeMultiplayer { /// <summary> /// The current overall state of a realtime multiplayer room. /// </summary> public enum MultiplayerRoomState { Open, WaitingForLoad, Playing, WaitingForResults, Closed } }
mit
C#
2a2f285430d53a4b5628b7fa1c9d5843f1030ff1
Fix LogError argument order in WebAssemblyErrorBoundaryLogger (#39223)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyErrorBoundaryLogger.cs
src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyErrorBoundaryLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Components.Web; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Components.WebAssembly.Services; internal sealed class WebAssemblyErrorBoundaryLogger : IErrorBoundaryLogger { private readonly ILogger<ErrorBoundary> _errorBoundaryLogger; public WebAssemblyErrorBoundaryLogger(ILogger<ErrorBoundary> errorBoundaryLogger) { _errorBoundaryLogger = errorBoundaryLogger ?? throw new ArgumentNullException(nameof(errorBoundaryLogger)); } public ValueTask LogErrorAsync(Exception exception) { // For, client-side code, all internal state is visible to the end user. We can just // log directly to the console. _errorBoundaryLogger.LogError(exception, exception.ToString()); return ValueTask.CompletedTask; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Components.Web; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Components.WebAssembly.Services; internal sealed class WebAssemblyErrorBoundaryLogger : IErrorBoundaryLogger { private readonly ILogger<ErrorBoundary> _errorBoundaryLogger; public WebAssemblyErrorBoundaryLogger(ILogger<ErrorBoundary> errorBoundaryLogger) { _errorBoundaryLogger = errorBoundaryLogger ?? throw new ArgumentNullException(nameof(errorBoundaryLogger)); ; } public ValueTask LogErrorAsync(Exception exception) { // For, client-side code, all internal state is visible to the end user. We can just // log directly to the console. _errorBoundaryLogger.LogError(exception.ToString(), exception); return ValueTask.CompletedTask; } }
apache-2.0
C#
adb563bc0323dda13e55e92ebfa57a24fdd3fbbc
Remove pipeline draft
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/Execution/BuildExtensionAttributeBase.cs
source/Nuke.Common/Execution/BuildExtensionAttributeBase.cs
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Linq; namespace Nuke.Common.Execution { public interface IBuildExtension { void Execute(NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets); } public interface IPreLogoBuildExtension : IBuildExtension { } public interface IPostLogoBuildExtension : IBuildExtension { } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Linq; namespace Nuke.Common.Execution { public interface IBuildExtension { void Execute(NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets); } public interface IPreLogoBuildExtension : IBuildExtension { } public interface IPostLogoBuildExtension : IBuildExtension { } public class Pipeline { public static Pipeline Create() { return new Pipeline(); } internal List<Target> Targets { get; } = new List<Target>(); public Pipeline AddTarget(Target target) { Targets.Add(target); return this; } } public class SupportPipelinesAttribute : Attribute, IPreLogoBuildExtension { public void Execute(NukeBuild build, IReadOnlyCollection<ExecutableTarget> executableTargets) { var pipelines = build.GetType().GetProperties(ReflectionService.All) .Where(x => x.PropertyType == typeof(Pipeline)) .Select(x => x.GetValue(obj: build)).Cast<Pipeline>(); foreach (var pipeline in pipelines) { var targets = pipeline.Targets.Select(x => executableTargets.Single(y => y.Factory == x)).ToList(); for (var i = 0; i < targets.Count - 1; i++) targets[i + 1].ExecutionDependencies.Add(targets[i]); } } } }
mit
C#
5963a131c5bef7dc5b7fa06dfb5bfdf320cbee11
Enable comments
davidebbo-test/BlogConverter
BlogConverter/Program.cs
BlogConverter/Program.cs
using HtmlAgilityPack; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace BlogConverter { class Program { static void Main(string[] args) { var root = XElement.Load(args[0]); XNamespace ns = "http://www.w3.org/2005/Atom"; var entries = from entry in root.Elements(ns + "entry") where entry.Element(ns + "category").Attribute("term").Value.Contains("kind#post") select entry; foreach (var entry in entries) { string title = entry.Element(ns + "title").Value; title = Util.FixQuotes(title); var link = entry.Elements(ns + "link").Where(e => e.Attribute("rel").Value == "alternate").FirstOrDefault(); if (link == null) continue; string fileName = Path.GetFileNameWithoutExtension(link.Attribute("href").Value); DateTime publishedDate = DateTime.Parse(entry.Element(ns + "published").Value); string publishedString = publishedDate.ToString("yyyy-MM-dd"); var tags = from category in entry.Elements(ns + "category") where category.Attribute("scheme").Value.Contains("ns#") select category.Attribute("term").Value; string tagString = String.Join(" ", tags); Console.WriteLine(tagString); string content = entry.Element(ns + "content").Value; var converter = new HtmlToMarkDownConverter(content); string markDown = converter.Convert(); string fullFileName = String.Format("{0}-{1}.markdown", publishedString, fileName); Console.WriteLine(fullFileName); string contentTemplate= @"--- layout: post title: ""{0}"" comments: true categories: {1} --- {2} "; File.WriteAllText(fullFileName, String.Format(contentTemplate, title, tagString, markDown)); } } } }
using HtmlAgilityPack; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace BlogConverter { class Program { static void Main(string[] args) { var root = XElement.Load(args[0]); XNamespace ns = "http://www.w3.org/2005/Atom"; var entries = from entry in root.Elements(ns + "entry") where entry.Element(ns + "category").Attribute("term").Value.Contains("kind#post") select entry; foreach (var entry in entries) { string title = entry.Element(ns + "title").Value; title = Util.FixQuotes(title); var link = entry.Elements(ns + "link").Where(e => e.Attribute("rel").Value == "alternate").FirstOrDefault(); if (link == null) continue; string fileName = Path.GetFileNameWithoutExtension(link.Attribute("href").Value); DateTime publishedDate = DateTime.Parse(entry.Element(ns + "published").Value); string publishedString = publishedDate.ToString("yyyy-MM-dd"); var tags = from category in entry.Elements(ns + "category") where category.Attribute("scheme").Value.Contains("ns#") select category.Attribute("term").Value; string tagString = String.Join(" ", tags); Console.WriteLine(tagString); string content = entry.Element(ns + "content").Value; var converter = new HtmlToMarkDownConverter(content); string markDown = converter.Convert(); string fullFileName = String.Format("{0}-{1}.markdown", publishedString, fileName); Console.WriteLine(fullFileName); string contentTemplate= @"--- layout: post title: ""{0}"" categories: {1} --- {2} "; File.WriteAllText(fullFileName, String.Format(contentTemplate, title, tagString, markDown)); } } } }
apache-2.0
C#
94db82167b42463d4cc070f6f6d2d87356edba1d
Remove dots from built in variables
anilmujagic/DeploymentCockpit,anilmujagic/DeploymentCockpit,anilmujagic/DeploymentCockpit
src/DeploymentCockpit.Core/Common/VariableHelper.cs
src/DeploymentCockpit.Core/Common/VariableHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Insula.Common; namespace DeploymentCockpit.Common { public static class VariableHelper { public const string ProductVersionVariable = "ProductVersion"; public const string TargetComputerNameVariable = "TargetComputerName"; public const string CredentialUsernameVariable = "CredentialUsername"; public const string CredentialPasswordVariable = "CredentialPassword"; public static string FormatPlaceholder(string variableName) { return "{0}{1}{2}".FormatString( DomainContext.VariablePlaceholderPrefix, variableName, DomainContext.VariablePlaceholderSuffix); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Insula.Common; namespace DeploymentCockpit.Common { public static class VariableHelper { public const string ProductVersionVariable = "ProductVersion"; public const string TargetComputerNameVariable = "Target.ComputerName"; public const string CredentialUsernameVariable = "Credential.Username"; public const string CredentialPasswordVariable = "Credential.Password"; public static string FormatPlaceholder(string variableName) { return "{0}{1}{2}".FormatString( DomainContext.VariablePlaceholderPrefix, variableName, DomainContext.VariablePlaceholderSuffix); } } }
apache-2.0
C#
0005bd70ff56702898bc79c624ca987b74fe85a0
add comments to IGherkinLine
dg-ratiodata/gherkin3,pjlsergeant/gherkin,amaniak/gherkin3,concertman/gherkin3,thetutlage/gherkin3,chebizarro/gherkin3,dg-ratiodata/gherkin3,chiranjith/gherkin,SabotageAndi/gherkin,curzona/gherkin3,cucumber/gherkin3,thiblahute/gherkin3,thr0w/gherkin3,dg-ratiodata/gherkin3,moreirap/gherkin3,dirkrombauts/gherkin3,SabotageAndi/gherkin,hayd/gherkin3,hayd/gherkin3,Zearin/gherkin3,thiblahute/gherkin3,dirkrombauts/gherkin3,thiblahute/gherkin3,amaniak/gherkin3,thetutlage/gherkin3,cucumber/gherkin3,araines/gherkin3,chiranjith/gherkin,concertman/gherkin3,concertman/gherkin3,hayd/gherkin3,dg-ratiodata/gherkin3,pjlsergeant/gherkin,vincent-psarga/gherkin3,vincent-psarga/gherkin3,thiblahute/gherkin3,thetutlage/gherkin3,thetutlage/gherkin3,chebizarro/gherkin3,concertman/gherkin3,chebizarro/gherkin3,cucumber/gherkin3,araines/gherkin3,curzona/gherkin3,thetutlage/gherkin3,thr0w/gherkin3,SabotageAndi/gherkin,curzona/gherkin3,cucumber/gherkin3,Zearin/gherkin3,hayd/gherkin3,araines/gherkin3,chebizarro/gherkin3,amaniak/gherkin3,thr0w/gherkin3,chebizarro/gherkin3,curzona/gherkin3,chebizarro/gherkin3,SabotageAndi/gherkin,amaniak/gherkin3,curzona/gherkin3,curzona/gherkin3,dg-ratiodata/gherkin3,amaniak/gherkin3,vincent-psarga/gherkin3,SabotageAndi/gherkin,SabotageAndi/gherkin,Zearin/gherkin3,dirkrombauts/gherkin3,dg-ratiodata/gherkin3,thiblahute/gherkin3,chiranjith/gherkin,pjlsergeant/gherkin,thr0w/gherkin3,moreirap/gherkin3,thiblahute/gherkin3,dirkrombauts/gherkin3,thr0w/gherkin3,concertman/gherkin3,araines/gherkin3,Zearin/gherkin3,araines/gherkin3,curzona/gherkin3,SabotageAndi/gherkin,moreirap/gherkin3,thr0w/gherkin3,thetutlage/gherkin3,hayd/gherkin3,pjlsergeant/gherkin,Zearin/gherkin3,dirkrombauts/gherkin3,vincent-psarga/gherkin3,cucumber/gherkin3,pjlsergeant/gherkin,cucumber/gherkin3,thetutlage/gherkin3,amaniak/gherkin3,Zearin/gherkin3,cucumber/gherkin3,concertman/gherkin3,thr0w/gherkin3,araines/gherkin3,moreirap/gherkin3,vincent-psarga/gherkin3,moreirap/gherkin3,cucumber/gherkin3,dirkrombauts/gherkin3,chiranjith/gherkin,pjlsergeant/gherkin,dirkrombauts/gherkin3,amaniak/gherkin3,curzona/gherkin3,hayd/gherkin3,cucumber/gherkin3,vincent-psarga/gherkin3,Zearin/gherkin3,thiblahute/gherkin3,moreirap/gherkin3,SabotageAndi/gherkin,araines/gherkin3,vincent-psarga/gherkin3,pjlsergeant/gherkin,chebizarro/gherkin3,SabotageAndi/gherkin,pjlsergeant/gherkin,concertman/gherkin3,hayd/gherkin3,moreirap/gherkin3,pjlsergeant/gherkin,dirkrombauts/gherkin3,concertman/gherkin3,vincent-psarga/gherkin3,amaniak/gherkin3,thetutlage/gherkin3,hayd/gherkin3,chiranjith/gherkin,dg-ratiodata/gherkin3,moreirap/gherkin3,chebizarro/gherkin3,Zearin/gherkin3,dg-ratiodata/gherkin3,araines/gherkin3,thiblahute/gherkin3
csharp/Gherkin/IGherkinLine.cs
csharp/Gherkin/IGherkinLine.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Gherkin { /// <summary> /// Represents a line of a Gherkin file /// </summary> public interface IGherkinLine { /// <summary> /// One-based line number /// </summary> int LineNumber { get; } /// <summary> /// Called by the parser to indicate non-streamed reading (e.g. during look-ahead). /// </summary> /// <remarks> /// If the implementation depends on streamed reading behavior, with this method, it can clone itself, so that it will be detached. /// </remarks> void Detach(); /// <summary> /// The number of whitespace characters in the beginning of the line. /// </summary> int Indent { get; } /// <summary> /// Gets if the line is empty or contains whitespaces only. /// </summary> /// <returns>true, if empty or contains whitespaces only; otherwise, false.</returns> bool IsEmpty(); /// <summary> /// Determines whether the beginning of the line (wihtout whitespaces) matches a specified string. /// </summary> /// <param name="text">The string to compare. </param> /// <returns>true if text matches the beginning of this line; otherwise, false.</returns> bool StartsWith(string text); /// <summary> /// Determines whether the beginning of the line (wihtout whitespaces) matches a specified title keyword (ie. a keyword followed by a ':' character). /// </summary> /// <param name="keyword">The keyword to compare. </param> /// <returns>true if keyword matches the beginning of this line and followed by a ':' character; otherwise, false.</returns> bool StartsWithTitleKeyword(string keyword); /// <summary> /// Returns the line text /// </summary> /// <param name="indentToRemove">The maximum number of whitespace characters to remove. -1 removes all whitespaces.</param> /// <returns>The line text.</returns> string GetLineText(int indentToRemove = -1); /// <summary> /// Returns the remaining part of the line. /// </summary> /// <param name="length"></param> /// <returns></returns> string GetRestTrimmed(int length); /// <summary> /// Tries parsing the line as a tag list, and returns the tags wihtout the leading '@' characters. /// </summary> /// <returns></returns> IEnumerable<string> GetTags(); /// <summary> /// Tries parsing the line as table row and returns the trimmed cell values. /// </summary> /// <returns></returns> IEnumerable<string> GetTableCells(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Gherkin { public interface IGherkinLine { int LineNumber { get; } void Detach(); int Indent { get; } bool IsEmpty(); bool StartsWith(string text); bool StartsWithTitleKeyword(string text); string GetLineText(int indentToRemove = -1); string GetRestTrimmed(int length); IEnumerable<string> GetTags(); IEnumerable<string> GetTableCells(); } }
mit
C#
dddbc8e0ed599e0591d8bfb219b2be2b6e8ccdac
Add user images
davidebbo/ForumScorer
ForumScorer/index.cshtml
ForumScorer/index.cshtml
@using Newtonsoft.Json; @{ string dataFile = Server.MapPath("~/App_Data/data.json"); string json = File.ReadAllText(dataFile); var data = (IEnumerable<dynamic>)JsonConvert.DeserializeObject(json); } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Forum Scorer</title> </head> <body> <h1>MSDN Forum Scorer for the Web Apps team</h1> <h2>This week's leaderboard (the week ends on Friday)</h2> <ul> @foreach (var user in data.OrderByDescending(u=>u.WeekScore)) { if (user.WeekScore == 0) { break; } <li><img src="https://i1.social.s-msft.com/profile/u/avatar.jpg?displayname=@user.Name" /> <a href="https://social.msdn.microsoft.com/Profile/@user.Name/activity">@user.Name</a>: @user.WeekScore</li> } </ul> <h2>Last week's leaderboard</h2> <ul> @foreach (var user in data.OrderByDescending(u => u.PreviousWeekScore)) { if (user.PreviousWeekScore == 0) { break; } <li><img src="https://i1.social.s-msft.com/profile/u/avatar.jpg?displayname=@user.Name" /> <a href="https://social.msdn.microsoft.com/Profile/@user.Name/activity">@user.Name</a>: @user.PreviousWeekScore</li> } </ul> <h3>Notes</h3> <ul> <li>This counts activity in all MSDN forums; not just <a href="https://social.msdn.microsoft.com/Forums/azure/en-US/home?forum=windowsazurewebsitespreview">Web Apps</a></li> <li>Click on a user's name to see their activity detail on MSDN</li> <li>Counts are updated every hour using a WebJob</li> <li>Sources are on <a href="https://github.com/davidebbo/ForumScorer">https://github.com/davidebbo/ForumScorer</a> if you want to make a pull request</li> </ul> Points are given as follows: <ul> <li>20 points for quickly answering a question</li> <li>15 points for answering a question</li> <li>5 points for contributing a helpful post</li> <li>1 for responding to a question (additional responses to the same question don't count)</li> </ul> </body> </html>
@using Newtonsoft.Json; @{ string dataFile = Server.MapPath("~/App_Data/data.json"); string json = File.ReadAllText(dataFile); var data = (IEnumerable<dynamic>)JsonConvert.DeserializeObject(json); } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Forum Scorer</title> </head> <body> <h1>MSDN Forum Scorer for the Web Apps team</h1> <h2>This week's leaderboard (the week ends on Friday)</h2> <ul> @foreach (var user in data.OrderByDescending(u=>u.WeekScore)) { if (user.WeekScore == 0) { break; } <li><a href="https://social.msdn.microsoft.com/Profile/@user.Name/activity">@user.Name</a>: @user.WeekScore</li> } </ul> <h2>Last week's leaderboard</h2> <ul> @foreach (var user in data.OrderByDescending(u => u.PreviousWeekScore)) { if (user.PreviousWeekScore == 0) { break; } <li><a href="https://social.msdn.microsoft.com/Profile/@user.Name/activity">@user.Name</a>: @user.PreviousWeekScore</li> } </ul> <h3>Notes</h3> <ul> <li>This counts activity in all MSDN forums; not just <a href="https://social.msdn.microsoft.com/Forums/azure/en-US/home?forum=windowsazurewebsitespreview">Web Apps</a></li> <li>Click on a user's name to see their activity detail on MSDN</li> <li>Counts are updated every hour using a WebJob</li> <li>Sources are on <a href="https://github.com/davidebbo/ForumScorer">https://github.com/davidebbo/ForumScorer</a> if you want to make a pull request</li> </ul> Points are given as follows: <ul> <li>20 points for quickly answering a question</li> <li>15 points for answering a question</li> <li>5 points for contributing a helpful post</li> <li>1 for responding to a question (additional responses to the same question don't count)</li> </ul> </body> </html>
apache-2.0
C#
51d8fd005ea6c452d18b1f2cb32733b6227866d1
Remove obsolete documentation.
mysql-net/MySqlConnector,mysql-net/MySqlConnector
src/MySqlConnector/Protocol/Serialization/IByteHandler.cs
src/MySqlConnector/Protocol/Serialization/IByteHandler.cs
using System; using System.Threading.Tasks; using MySqlConnector.Utilities; namespace MySqlConnector.Protocol.Serialization { internal interface IByteHandler : IDisposable { /// <summary> /// The remaining timeout (in milliseconds) for the next I/O read. Use <see cref="Constants.InfiniteTimeout"/> to represent no (or, infinite) timeout. /// </summary> int RemainingTimeout { get; set; } /// <summary> /// Reads data from this byte handler. /// </summary> /// <param name="buffer">The buffer to read into.</param> /// <param name="ioBehavior">The <see cref="IOBehavior"/> to use when reading data.</param> /// <returns>A <see cref="ValueTask{Int32}"/> holding the number of bytes read. If reading failed, this will be zero.</returns> ValueTask<int> ReadBytesAsync(ArraySegment<byte> buffer, IOBehavior ioBehavior); /// <summary> /// Writes data to this byte handler. /// </summary> /// <param name="data">The data to write.</param> /// <param name="ioBehavior">The <see cref="IOBehavior"/> to use when writing.</param> /// <returns>A <see cref="ValueTask{Int32}"/>. The value of this object is not defined.</returns> ValueTask<int> WriteBytesAsync(ArraySegment<byte> data, IOBehavior ioBehavior); } }
using System; using System.Threading.Tasks; using MySqlConnector.Utilities; namespace MySqlConnector.Protocol.Serialization { internal interface IByteHandler : IDisposable { /// <summary> /// The remaining timeout (in milliseconds) for the next I/O read. Use <see cref="Constants.InfiniteTimeout"/> to represent no (or, infinite) timeout. /// </summary> int RemainingTimeout { get; set; } /// <summary> /// Reads data from this byte handler. /// </summary> /// <param name="buffer">The buffer to read into.</param> /// <param name="ioBehavior">The <see cref="IOBehavior"/> to use when reading data.</param> /// <returns>A <see cref="ValueTask{Int32}"/>. Number of bytes read.</returns> /// If reading failed, zero bytes will be returned. This /// <see cref="ArraySegment{Byte}"/> will be valid to read from until the next time <see cref="ReadBytesAsync"/> or /// <see cref="WriteBytesAsync"/> is called. ValueTask<int> ReadBytesAsync(ArraySegment<byte> buffer, IOBehavior ioBehavior); /// <summary> /// Writes data to this byte handler. /// </summary> /// <param name="data">The data to write.</param> /// <param name="ioBehavior">The <see cref="IOBehavior"/> to use when writing.</param> /// <returns>A <see cref="ValueTask{Int32}"/>. The value of this object is not defined.</returns> ValueTask<int> WriteBytesAsync(ArraySegment<byte> data, IOBehavior ioBehavior); } }
mit
C#
8e37f4c24d450853a0f750211d8c6a7ea63d557e
Add extension methods for pinning to top and bottom layout guide
mallibone/PureLayout.Net
PureLayout.Binding/PureLayout.Binding/Extras.cs
PureLayout.Binding/PureLayout.Binding/Extras.cs
using System; using UIKit; namespace PureLayout.Net { public partial class UIViewPureLayout { public static NSLayoutConstraint[] AutoPinEdgesToSuperviewEdgesExcludingEdge(this UIView view, ALEdge excludingEdge) { return view.AutoPinEdgesToSuperviewEdgesExcludingEdge(ALHelpers.ALEdgeInsetsZero, excludingEdge); } public static NSLayoutConstraint AutoPinToBottomLayoutGuideOfViewController(this UIView view, UIViewController viewController) { return view.AutoPinToBottomLayoutGuideOfViewController(viewController, 0f); } public static NSLayoutConstraint AutoPinToTopLayoutGuideOfViewController(this UIView view, UIViewController viewController) { return view.AutoPinToTopLayoutGuideOfViewController(viewController, 0f); } } }
using System; using UIKit; namespace PureLayout.Net { public partial class UIViewPureLayout { public static NSLayoutConstraint[] AutoPinEdgesToSuperviewEdgesExcludingEdge(this UIView view, ALEdge excludingEdge) { return view.AutoPinEdgesToSuperviewEdgesExcludingEdge(ALHelpers.ALEdgeInsetsZero, excludingEdge); } } }
mit
C#
a01de4dc4212d34c6e5f507e8b741d92b4a7e53c
Remove redundant 'base()' call.
proyecto26/RestClient
src/Proyecto26.RestClient/Utils/RequestException.cs
src/Proyecto26.RestClient/Utils/RequestException.cs
using System; namespace Proyecto26 { public class RequestException : Exception { private bool _isHttpError; public bool IsHttpError { get { return _isHttpError; } private set { _isHttpError = value; } } private bool _isNetworkError; public bool IsNetworkError { get { return _isNetworkError; } private set { _isNetworkError = value; } } private long _statusCode; public long StatusCode { get { return _statusCode; } private set { _statusCode = value; } } private string _serverMessage; public string ServerMessage { get { return _serverMessage; } set { _serverMessage = value; } } public RequestException() { } public RequestException(string message): base(message) { } public RequestException(string format, params object[] args): base(string.Format(format, args)) { } public RequestException(string message, bool isHttpError, bool isNetworkError, long statusCode) : base(message) { _isHttpError = isHttpError; _isNetworkError = isNetworkError; _statusCode = statusCode; } } }
using System; namespace Proyecto26 { public class RequestException : Exception { private bool _isHttpError; public bool IsHttpError { get { return _isHttpError; } private set { _isHttpError = value; } } private bool _isNetworkError; public bool IsNetworkError { get { return _isNetworkError; } private set { _isNetworkError = value; } } private long _statusCode; public long StatusCode { get { return _statusCode; } private set { _statusCode = value; } } private string _serverMessage; public string ServerMessage { get { return _serverMessage; } set { _serverMessage = value; } } public RequestException(): base() { } public RequestException(string message): base(message) { } public RequestException(string format, params object[] args): base(string.Format(format, args)) { } public RequestException(string message, bool isHttpError, bool isNetworkError, long statusCode) : base(message) { _isHttpError = isHttpError; _isNetworkError = isNetworkError; _statusCode = statusCode; } } }
mit
C#
65dc49ee2b92343265ceb66778e14628f82da310
add validation route
Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek
Tweek.ApiService.NetCore/Controllers/ValidationController.cs
Tweek.ApiService.NetCore/Controllers/ValidationController.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Engine.Core.Rules; using Engine.Drivers.Rules; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Engine.Core.Rules; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace Tweek.ApiService.NetCore.Controllers { [Route("validation")] public class ValidationController : Controller { private IRuleParser _parser; // GET: api/values public ValidationController(IRuleParser parser) { _parser = parser; } public bool IsParsable(string payload) { try { _parser.Parse(payload); return true; } catch { return false; } } [HttpGet] public async Task<dynamic> Validate() { Dictionary<string, RuleDefinition> ruleset = null; try { var raw = await (new StreamReader(HttpContext.Request.Body).ReadToEndAsync()); ruleset = JsonConvert.DeserializeObject<Dictionary<string, RuleDefinition>>(raw); } catch (Exception) { return BadRequest("Invalid ruleset"); } var failures = ruleset .Where(x => !IsParsable(x.Value.Payload)) .Select(x => x.Key); if (failures.Any()) return BadRequest(failures); return true; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Engine.Core.Rules; using Engine.Drivers.Rules; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Engine.Core.Rules; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace Tweek.ApiService.NetCore.Controllers { [Route("api/[controller]")] public class ValidationController : Controller { private IRuleParser _parser; // GET: api/values public ValidationController(IRuleParser parser) { _parser = parser; } public bool IsParsable(string payload) { try { _parser.Parse(payload); return true; } catch { return false; } } public async Task<dynamic> Validate() { Dictionary<string, RuleDefinition> ruleset = null; try { var raw = await (new StreamReader(HttpContext.Request.Body).ReadToEndAsync()); ruleset = JsonConvert.DeserializeObject<Dictionary<string, RuleDefinition>>(raw); } catch (Exception) { throw new HttpRequestException("Invalid ruleset"); } var failures = ruleset .Where(x => !IsParsable(x.Value.Payload)) .Select(x => x.Key); if (failures.Any()) return failures; return true; } } }
mit
C#
ded56395b79f4ce2535e537fdedf5f69dbbeb90f
Clean up whitespace and file header on type enumeration
jcolag/CreditCardValidator
CreditCardRange/CreditCardRange/CreditCardType.cs
CreditCardRange/CreditCardRange/CreditCardType.cs
//----------------------------------------------------------------------- // <copyright file="CreditCardType.cs" company="Colagioia Industries"> // Provided under the terms of the AGPL v3. // </copyright> //----------------------------------------------------------------------- /// <summary> /// Credit card type. /// </summary> namespace CreditCardProcessing { using System.ComponentModel; /// <summary> /// Credit card type. /// </summary> public enum CreditCardType { /// <summary> /// Unknown issuers. /// </summary> [Description("Unknown Issuer")] Unknown, /// <summary> /// American Express cards. /// </summary> [Description("American Express")] AmEx, /// <summary> /// Discover Card cards. /// </summary> [Description("Discover Card")] Discover, /// <summary> /// MasterCard cards. /// </summary> [Description("MasterCard")] MasterCard, /// <summary> /// Visa cards. /// </summary> [Description("Visa")] Visa, } }
/// <summary> /// Credit card type. /// </summary> namespace CreditCardProcessing { using System.ComponentModel; /// <summary> /// Credit card type. /// </summary> public enum CreditCardType { /// <summary> /// Unknown issuers. /// </summary> [Description("Unknown Issuer")] Unknown, /// <summary> /// American Express. /// </summary> [Description("American Express")] AmEx, /// <summary> /// Discover Card. /// </summary> [Description("Discover Card")] Discover, /// <summary> /// Master Card. /// </summary> [Description("MasterCard")] MasterCard, /// <summary> /// Visa. /// </summary> [Description("Visa")] Visa, } }
agpl-3.0
C#
b6837aaba5112436738e2eb1e4de65b79d98b4f8
Refactor RootedObjectEventHandler
MatterHackers/agg-sharp,larsbrubaker/agg-sharp,jlewin/agg-sharp
agg/RootedObjectEventHandler.cs
agg/RootedObjectEventHandler.cs
using System; using System.Collections.Generic; namespace MatterHackers.Agg { public class RootedObjectEventHandler { private EventHandler internalEvent; public void RegisterEvent(EventHandler functionToCallOnEvent, ref EventHandler unregisterEvents) { internalEvent += functionToCallOnEvent; unregisterEvents += (sender, e) => { internalEvent -= functionToCallOnEvent; }; } public void UnregisterEvent(EventHandler functionToCallOnEvent, ref EventHandler unregisterEvents) { internalEvent -= functionToCallOnEvent; // After we remove it, it will still be removed again in the unregisterEvents // But it is valid to attempt remove more than once. } public void CallEvents(Object sender, EventArgs e) { internalEvent?.Invoke(sender, e); } } }
using System; using System.Collections.Generic; namespace MatterHackers.Agg { #if false public interface IReceiveRootedWeakEvent { void RootedEvent(string eventType, EventArgs e); } public class RootedObjectWeakEventHandler { List<WeakReference> classesToCall = new List<WeakReference>(); List<string> eventTypes = new List<string>(); public void Register(IReceiveRootedWeakEvent objectToCall, string eventType) { classesToCall.Add(new WeakReference(objectToCall)); eventTypes.Add(eventType); } public void Unregister(IReceiveRootedWeakEvent objectToCall) { for (int i = classesToCall.Count - 1; i >= 0; i--) { if (classesToCall[i].Target == objectToCall) { classesToCall.RemoveAt(i); } } } public void CallEvents(Object sender, EventArgs e) { for(int i=classesToCall.Count-1; i>=0; i--) { IReceiveRootedWeakEvent reciever = classesToCall[i].Target as IReceiveRootedWeakEvent; if (reciever == null) { classesToCall.RemoveAt(i); eventTypes.RemoveAt(i); } else { reciever.RootedEvent(eventTypes[i], e); } } } } #endif public class RootedObjectEventHandler { #if DEBUG private event EventHandler InternalEventForDebug; private List<EventHandler> DebugEventDelegates = new List<EventHandler>(); private event EventHandler InternalEvent { //Wraps the PrivateClick event delegate so that we can track which events have been added and clear them if necessary add { InternalEventForDebug += value; DebugEventDelegates.Add(value); } remove { InternalEventForDebug -= value; DebugEventDelegates.Remove(value); } } #else EventHandler InternalEvent; #endif public void RegisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent) { InternalEvent += functionToCallOnEvent; functionThatWillBeCalledToUnregisterEvent += (sender, e) => { InternalEvent -= functionToCallOnEvent; }; } public void UnregisterEvent(EventHandler functionToCallOnEvent, ref EventHandler functionThatWillBeCalledToUnregisterEvent) { InternalEvent -= functionToCallOnEvent; // After we remove it, it will still be removed again in the functionThatWillBeCalledToUnregisterEvent // But it is valid to attempt remove more than once. } public void CallEvents(Object sender, EventArgs e) { #if DEBUG InternalEventForDebug?.Invoke(sender, e); #else InternalEvent?.Invoke(sender, e); #endif } } }
bsd-2-clause
C#
33c91ceca966eae98f18258955620c5a4fdb1e13
Set default back to sqlite
sharwell/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,physhi/roslyn,sharwell/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,mavasani/roslyn,physhi/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,bartdesmet/roslyn,wvdd007/roslyn,diryboy/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,wvdd007/roslyn,mavasani/roslyn,diryboy/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,weltkante/roslyn,weltkante/roslyn,wvdd007/roslyn,sharwell/roslyn,dotnet/roslyn,eriawan/roslyn
src/Workspaces/Core/Portable/Storage/StorageOptions.cs
src/Workspaces/Core/Portable/Storage/StorageOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Storage { internal static class StorageOptions { internal const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\"; public const string OptionName = "FeatureManager/Storage"; public static readonly Option<StorageDatabase> Database = new(OptionName, nameof(Database), defaultValue: StorageDatabase.SQLite); public static readonly Option<bool> DatabaseMustSucceed = new(OptionName, nameof(DatabaseMustSucceed), defaultValue: false); public static readonly Option<bool> PrintDatabaseLocation = new(OptionName, nameof(PrintDatabaseLocation), defaultValue: false); } [ExportOptionProvider, Shared] internal class RemoteHostOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteHostOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( StorageOptions.Database, StorageOptions.DatabaseMustSucceed, StorageOptions.PrintDatabaseLocation); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Storage { internal static class StorageOptions { internal const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\"; public const string OptionName = "FeatureManager/Storage"; public static readonly Option<StorageDatabase> Database = new(OptionName, nameof(Database), defaultValue: StorageDatabase.CloudCache); public static readonly Option<bool> DatabaseMustSucceed = new(OptionName, nameof(DatabaseMustSucceed), defaultValue: false); public static readonly Option<bool> PrintDatabaseLocation = new(OptionName, nameof(PrintDatabaseLocation), defaultValue: false); } [ExportOptionProvider, Shared] internal class RemoteHostOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteHostOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( StorageOptions.Database, StorageOptions.DatabaseMustSucceed, StorageOptions.PrintDatabaseLocation); } }
mit
C#
e2b07aff4d1b5a872b7e928b4785309fa7b333c4
Fix RavenConfiguration for Embedded mode.
alastairs/cgowebsite,alastairs/cgowebsite
src/CGO.Web/NinjectModules/RavenModule.cs
src/CGO.Web/NinjectModules/RavenModule.cs
using Ninject; using Ninject.Modules; using Ninject.Web.Common; using Raven.Client; using Raven.Client.Embedded; namespace CGO.Web.NinjectModules { public class RavenModule : NinjectModule { public override void Load() { Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope(); Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope(); } private static IDocumentStore InitialiseDocumentStore() { var documentStore = new EmbeddableDocumentStore { DataDirectory = "CGO.raven", UseEmbeddedHttpServer = true, Configuration = { Port = 28645 } }; documentStore.InitializeProfiling(); documentStore.Initialize(); return documentStore; } } }
using Ninject; using Ninject.Modules; using Ninject.Web.Common; using Raven.Client; using Raven.Client.Embedded; namespace CGO.Web.NinjectModules { public class RavenModule : NinjectModule { public override void Load() { Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope(); Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope(); } private static IDocumentStore InitialiseDocumentStore() { var documentStore = new EmbeddableDocumentStore { DataDirectory = "CGO.raven", UseEmbeddedHttpServer = true }; documentStore.InitializeProfiling(); documentStore.Initialize(); return documentStore; } } }
mit
C#
83a2539fe629e0a43588c5c52fcf67583d3f8090
Update MaciejHorbacz.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/MaciejHorbacz.cs
src/Firehose.Web/Authors/MaciejHorbacz.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MaciejHorbacz : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Maciej"; public string LastName => "Horbacz"; public string ShortBioOrTagLine => "PowerShell and Intune are my thing ⚔️"; public string StateOrRegion => "Gdansk, Poland"; public string EmailAddress => "maciej.horbacz@gmail.com"; public string TwitterHandle => "Universecitiz3n"; public string GitHubHandle => "Universecitiz3n"; public string GravatarHash => "f59ba35493d7f1b99e25b6455dc39f5b"; public GeoPosition Position => new GeoPosition(54.3520,18.6466); public Uri WebSite => new Uri("https://universecitiz3n.tech"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://universecitiz3n.tech/feed.xml"); } } public string FeedLanguageCode => "en"; public bool Filter(SyndicationItem item) { return item.Categories?.Any(c => c.Name.ToLowerInvariant().Equals("powershell")) ?? false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MaciejHorbacz : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Maciej"; public string LastName => "Horbacz"; public string ShortBioOrTagLine => "PowerShell and Intune are my thing ⚔️"; public string StateOrRegion => "Gdansk, Poland"; public string EmailAddress => "maciej.horbacz@gmail.com"; public string TwitterHandle => "Universecitiz3n"; public string GitHubHandle => "Universecitiz3n"; public string GravatarHash => "f59ba35493d7f1b99e25b6455dc39f5b"; public GeoPosition Position => new GeoPosition(54.3520,18.6466); public Uri WebSite => new Uri("https://www.universecitiz3n.tech"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.universecitiz3n.tech/feed.xml"); } } public string FeedLanguageCode => "en"; public bool Filter(SyndicationItem item) { return item.Categories?.Any(c => c.Name.ToLowerInvariant().Equals("powershell")) ?? false; } } }
mit
C#
e1e166ae66421c038c24c05e5d71481d6c86cb20
Revert "Revert "Update Examples/.vs/Aspose.Email.Examples.CSharp/v15/Server/sqlite3/storage.ide-wal""
aspose-email/Aspose.Email-for-.NET,asposeemail/Aspose_Email_NET
Examples/CSharp/Outlook/OLM/LoadAndReadOLMFile.cs
Examples/CSharp/Outlook/OLM/LoadAndReadOLMFile.cs
using System; using Aspose.Email.Storage.Olm; using Aspose.Email.Mapi; namespace Aspose.Email.Examples.CSharp.Email.Outlook.OLM { class LoadAndReadOLMFile { public static void Run() { // The path to the File directory. string dataDir = RunExamples.GetDataDir_Outlook(); string dst = dataDir + "OutlookforMac.olm"; // ExStart:LoadAndReadOLMFile using (OlmStorage storage = new OlmStorage(dst)) { foreach (OlmFolder folder in storage.FolderHierarchy) { if (folder.HasMessages) { // extract messages from folder foreach (MapiMessage msg in storage.EnumerateMessages(folder)) { Console.WriteLine("Subject: " + msg.Subject); } } // read sub-folders if (folder.SubFolders.Count > 0) { foreach (OlmFolder sub_folder in folder.SubFolders) { Console.WriteLine("Subfolder: " + sub_folder.Name); } } } } // ExEnd:LoadAndReadOLMFile } } }
using System; using Aspose.Email.Storage.Olm; using Aspose.Email.Mapi; namespace Aspose.Email.Examples.CSharp.Email.Outlook.OLM { class LoadAndReadOLMFile { public static void Run() { // The path to the File directory. string dataDir = RunExamples.GetDataDir_Outlook(); string dst = dataDir + "OutlookforMac.olm"; // ExStart:LoadAndReadOLMFile using (OlmStorage storage = new OlmStorage(dst)) { foreach (OlmFolder folder in storage.FolderHierarchy) { if (folder.HasMessages) { // extract messages from folder foreach (MapiMessage msg in storage.EnumerateMessages(folder)) { Console.WriteLine("Subject: " + msg.Subject); } } // read sub-folders if (folder.SubFolders.Count > 0) { foreach (OlmFolder sub_folder in folder.SubFolders) { Console.WriteLine("Subfolder: " + sub_folder.Name); } } } } // ExEnd:LoadAndReadOLMFile } } }
mit
C#
e963c6bd4b6f7760df861b18733a10c2d30e7c0c
Fix "change password message" view
ssh-git/training-manager,ssh-git/training-manager,ssh-git/training-manager,ssh-git/training-manager
src/TM.UI.MVC/Views/Manage/Message.cshtml
src/TM.UI.MVC/Views/Manage/Message.cshtml
@model string @section Title{ Message } <h2>@Model</h2>
@model string @section Title{ Message } <h2>@ViewBag.StatusMessage</h2>
mit
C#
c14f5b3e9a85b6c654406fbeab0f8fb3017d42b1
use next working day if D+2 falls into weekend in spot tiles
AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud
src/server/Adaptive.ReactiveTrader.Server.Pricing/MeanReversionRandomWalkPriceGenerator.cs
src/server/Adaptive.ReactiveTrader.Server.Pricing/MeanReversionRandomWalkPriceGenerator.cs
using System; using System.Diagnostics; using Adaptive.ReactiveTrader.Contract; namespace Adaptive.ReactiveTrader.Server.Pricing { public sealed class MeanReversionRandomWalkPriceGenerator : BaseWalkPriceGenerator, IPriceGenerator { private readonly decimal _halfSpreadPercentage; private readonly decimal _reversion; private readonly decimal _vol; public MeanReversionRandomWalkPriceGenerator(CurrencyPair currencyPair, decimal initial, int precision, decimal reversionCoefficient = 0.001m, decimal volatility = 5m) : base(currencyPair, initial, precision) { _reversion = reversionCoefficient; var power = (decimal)Math.Pow(10, precision); _vol = volatility * 1m / power; _halfSpreadPercentage = Random.Value.Next(2, 16) / power / _initial; } public override void UpdateWalkPrice() { var random = (decimal)Random.Value.NextNormal(); lock (_lock) { _previousMid += _reversion * (_initial - _previousMid) + random * _vol; } _priceChanges.OnNext( new SpotPriceDto { Symbol = CurrencyPair.Symbol, ValueDate = DateTime.UtcNow.AddDays(2).Date.ToWeekday(), Mid = Format(_previousMid), Ask = Format(_previousMid * (1 + _halfSpreadPercentage)), Bid = Format(_previousMid * (1 - _halfSpreadPercentage)), CreationTimestamp = Stopwatch.GetTimestamp() }); } private decimal Format(decimal price) { var power = (decimal)Math.Pow(10, _precision); var mid = (int)(price * power); return mid / power; } } }
using System; using System.Diagnostics; using Adaptive.ReactiveTrader.Contract; namespace Adaptive.ReactiveTrader.Server.Pricing { public sealed class MeanReversionRandomWalkPriceGenerator : BaseWalkPriceGenerator, IPriceGenerator { private readonly decimal _halfSpreadPercentage; private readonly decimal _reversion; private readonly decimal _vol; public MeanReversionRandomWalkPriceGenerator(CurrencyPair currencyPair, decimal initial, int precision, decimal reversionCoefficient = 0.001m, decimal volatility = 5m) : base(currencyPair, initial, precision) { _reversion = reversionCoefficient; var power = (decimal)Math.Pow(10, precision); _vol = volatility * 1m / power; _halfSpreadPercentage = Random.Value.Next(2, 16) / power / _initial; } public override void UpdateWalkPrice() { var random = (decimal)Random.Value.NextNormal(); lock (_lock) { _previousMid += _reversion * (_initial - _previousMid) + random * _vol; } _priceChanges.OnNext( new SpotPriceDto { Symbol = CurrencyPair.Symbol, ValueDate = DateTime.UtcNow.AddDays(2).Date, Mid = Format(_previousMid), Ask = Format(_previousMid * (1 + _halfSpreadPercentage)), Bid = Format(_previousMid * (1 - _halfSpreadPercentage)), CreationTimestamp = Stopwatch.GetTimestamp() }); } private decimal Format(decimal price) { var power = (decimal)Math.Pow(10, _precision); var mid = (int)(price * power); return mid / power; } } }
apache-2.0
C#
a5b1f1a688fe3d9ad0bd2e87b89f45e3c403ad6a
mark the string as nullable.
ppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,peppy/osu
osu.Game/Extensions/TypeExtensions.cs
osu.Game/Extensions/TypeExtensions.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; namespace osu.Game.Extensions { internal static class TypeExtensions { /// <summary> /// Returns <paramref name="type"/>'s <see cref="Type.AssemblyQualifiedName"/> /// with the assembly version, culture and public key token values removed. /// </summary> /// <remarks> /// This method is usually used in extensibility scenarios (i.e. for custom rulesets or skins) /// when a version-agnostic identifier associated with a C# class - potentially originating from /// an external assembly - is needed. /// Leaving only the type and assembly names in such a scenario allows to preserve compatibility /// across assembly versions. /// </remarks> internal static string GetInvariantInstantiationInfo(this Type type) { string? assemblyQualifiedName = type.AssemblyQualifiedName; if (assemblyQualifiedName == null) throw new ArgumentException($"{type}'s assembly-qualified name is null. Ensure that it is a concrete type and not a generic type parameter.", nameof(type)); return string.Join(',', assemblyQualifiedName.Split(',').Take(2)); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; namespace osu.Game.Extensions { internal static class TypeExtensions { /// <summary> /// Returns <paramref name="type"/>'s <see cref="Type.AssemblyQualifiedName"/> /// with the assembly version, culture and public key token values removed. /// </summary> /// <remarks> /// This method is usually used in extensibility scenarios (i.e. for custom rulesets or skins) /// when a version-agnostic identifier associated with a C# class - potentially originating from /// an external assembly - is needed. /// Leaving only the type and assembly names in such a scenario allows to preserve compatibility /// across assembly versions. /// </remarks> internal static string GetInvariantInstantiationInfo(this Type type) { string assemblyQualifiedName = type.AssemblyQualifiedName; if (assemblyQualifiedName == null) throw new ArgumentException($"{type}'s assembly-qualified name is null. Ensure that it is a concrete type and not a generic type parameter.", nameof(type)); return string.Join(',', assemblyQualifiedName.Split(',').Take(2)); } } }
mit
C#
1acfc1bbabf365c15401b121a6c2f1eab9b46c1f
Fix ModHardRock not properly clamping Drain/OD
peppy/osu-new,ppy/osu,DrabWeb/osu,DrabWeb/osu,EVAST9919/osu,UselessToucan/osu,naoey/osu,NeoAdonis/osu,2yangk23/osu,naoey/osu,ZLima12/osu,ppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,johnneijzen/osu,DrabWeb/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,johnneijzen/osu,naoey/osu,EVAST9919/osu,2yangk23/osu,ppy/osu,UselessToucan/osu,ZLima12/osu
osu.Game/Rulesets/Mods/ModHardRock.cs
osu.Game/Rulesets/Mods/ModHardRock.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Beatmaps; using osu.Game.Graphics; namespace osu.Game.Rulesets.Mods { public abstract class ModHardRock : Mod, IApplicableToDifficulty { public override string Name => "Hard Rock"; public override string ShortenedName => "HR"; public override FontAwesome Icon => FontAwesome.fa_osu_mod_hardrock; public override ModType Type => ModType.DifficultyIncrease; public override string Description => "Everything just got a bit harder..."; public override Type[] IncompatibleMods => new[] { typeof(ModEasy) }; public void ApplyToDifficulty(BeatmapDifficulty difficulty) { const float ratio = 1.4f; difficulty.CircleSize *= 1.3f; // CS uses a custom 1.3 ratio. difficulty.ApproachRate = Math.Min(difficulty.ApproachRate * ratio, 10.0f); difficulty.DrainRate = Math.Min(difficulty.DrainRate * ratio, 10.0f); difficulty.OverallDifficulty = Math.Min(difficulty.OverallDifficulty * ratio, 10.0f); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Beatmaps; using osu.Game.Graphics; namespace osu.Game.Rulesets.Mods { public abstract class ModHardRock : Mod, IApplicableToDifficulty { public override string Name => "Hard Rock"; public override string ShortenedName => "HR"; public override FontAwesome Icon => FontAwesome.fa_osu_mod_hardrock; public override ModType Type => ModType.DifficultyIncrease; public override string Description => "Everything just got a bit harder..."; public override Type[] IncompatibleMods => new[] { typeof(ModEasy) }; public void ApplyToDifficulty(BeatmapDifficulty difficulty) { const float ratio = 1.4f; difficulty.CircleSize *= 1.3f; // CS uses a custom 1.3 ratio. difficulty.ApproachRate = Math.Min(difficulty.ApproachRate * ratio, 10.0f); difficulty.DrainRate *= ratio; difficulty.OverallDifficulty *= ratio; } } }
mit
C#
385438e492db445668240ecfdcfc67f8de92d590
Fix error
PTRPlay/SchoolWebProject,PTRPlay/SchoolWebProject,PTRPlay/SchoolWebProject
SchoolWebProject.Data/Infrastructure/DbFactory.cs
SchoolWebProject.Data/Infrastructure/DbFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SchoolWebProject.Domain.Models; namespace SchoolWebProject.Data.Infrastructure { public class DbFactory : Disposable, IDbFactory { private SchoolContext dbContext; public SchoolContext Init() { return this.dbContext ?? (this.dbContext = new SchoolContext()); } protected override void DisposeCore() { if (this.dbContext != null) { this.dbContext.Dispose(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SchoolWebProject.Domain.Models; namespace SchoolWebProject.Data.Infrastructure { public class DbFactory : IDbFactory { private SchoolContext dbContext; public SchoolContext Init() { return this.dbContext ?? (this.dbContext = new SchoolContext()); } protected override void DisposeCore() { if (this.dbContext != null) { this.dbContext.Dispose(); } } } }
isc
C#
93fc9cb6d4a566774a4e23074500ad5fe3084167
Add expiration to token response
dhawalharsora/connectedcare-sdk,SnapMD/connectedcare-sdk
SnapMD.VirtualCare.ApiModels/SerializableToken.cs
SnapMD.VirtualCare.ApiModels/SerializableToken.cs
#region Copyright // Copyright 2016 SnapMD, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; namespace SnapMD.VirtualCare.ApiModels { public class SerializableToken { public string access_token { get; set; } public DateTimeOffset? expires { get; set; } } }
#region Copyright // Copyright 2016 SnapMD, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace SnapMD.VirtualCare.ApiModels { public class SerializableToken { public string access_token { get; set; } } }
apache-2.0
C#
b7a3ebf09257e151a3406168265211fc83fc4d85
Add try catch to support clean startup abort on missing starterGear.json (#3713)
ACEmulator/ACE,ACEmulator/ACE,LtRipley36706/ACE,LtRipley36706/ACE,ACEmulator/ACE,LtRipley36706/ACE
Source/ACE.Server/Factories/StarterGearFactory.cs
Source/ACE.Server/Factories/StarterGearFactory.cs
using System; using System.IO; using System.Reflection; using ACE.Server.Entity; using log4net; using Newtonsoft.Json; namespace ACE.Server.Factories { public class StarterGearFactory { private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static StarterGearConfiguration _config = LoadConfigFromResource(); private static StarterGearConfiguration LoadConfigFromResource() { // Look for the starterGear.json first in the current environment directory, then in the ExecutingAssembly location var exeLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var containerConfigDirectory = "/ace/Config"; var starterGearFileName = "starterGear.json"; var starterGearFile = Path.Combine(exeLocation, starterGearFileName); var starterGearFileContainer = Path.Combine(containerConfigDirectory, starterGearFileName); if (Program.IsRunningInContainer && File.Exists(starterGearFileContainer)) File.Copy(starterGearFileContainer, starterGearFile, true); StarterGearConfiguration config; try { var starterGearText = File.ReadAllText(starterGearFile); config = JsonConvert.DeserializeObject<StarterGearConfiguration>(starterGearText); return config; } catch (Exception ex) { log.Error($"StarterGearFactory.LoadConfigFromResource() - {ex}: {ex.Message}; {ex.InnerException}: {ex.InnerException.Message}"); } return null; } public static StarterGearConfiguration GetStarterGearConfiguration() { try { return _config; } catch { return null; } } } }
using System; using System.IO; using System.Reflection; using ACE.Server.Entity; using log4net; using Newtonsoft.Json; namespace ACE.Server.Factories { public class StarterGearFactory { private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static StarterGearConfiguration _config = LoadConfigFromResource(); private static StarterGearConfiguration LoadConfigFromResource() { // Look for the starterGear.json first in the current environment directory, then in the ExecutingAssembly location var exeLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var containerConfigDirectory = "/ace/Config"; var starterGearFileName = "starterGear.json"; var starterGearFile = Path.Combine(exeLocation, starterGearFileName); var starterGearFileContainer = Path.Combine(containerConfigDirectory, starterGearFileName); if (Program.IsRunningInContainer && File.Exists(starterGearFileContainer)) File.Copy(starterGearFileContainer, starterGearFile, true); StarterGearConfiguration config; try { var starterGearText = File.ReadAllText(starterGearFile); config = JsonConvert.DeserializeObject<StarterGearConfiguration>(starterGearText); return config; } catch (Exception ex) { log.Error($"StarterGearFactory.LoadConfigFromResource() - {ex}: {ex.Message}; {ex.InnerException}: {ex.InnerException.Message}"); } return null; } public static StarterGearConfiguration GetStarterGearConfiguration() { return _config; } } }
agpl-3.0
C#
a1d7d8080b8ea2c823b3617097e9b7891b147be9
Fix cross-commit contamination
peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework
osu.Framework.Tests/IO/FontStoreTest.cs
osu.Framework.Tests/IO/FontStoreTest.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 NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.IO.Stores; using osu.Framework.Text; namespace osu.Framework.Tests.IO { [TestFixture] public class FontStoreTest { private ResourceStore<byte[]> fontResourceStore; private TemporaryNativeStorage storage; [OneTimeSetUp] public void OneTimeSetUp() { storage = new TemporaryNativeStorage("fontstore-test", createIfEmpty: true); fontResourceStore = new NamespacedResourceStore<byte[]>(new DllResourceStore(typeof(Drawable).Assembly.Location), "Resources.Fonts.OpenSans"); } [Test] public void TestNestedScaleAdjust() { var fontStore = new FontStore(new GlyphStore(fontResourceStore, "OpenSans") { CacheStorage = storage }, scaleAdjust: 100); var nestedFontStore = new FontStore(new GlyphStore(fontResourceStore, "OpenSans-Bold") { CacheStorage = storage }, 10); fontStore.AddStore(nestedFontStore); var normalGlyph = (TexturedCharacterGlyph)fontStore.Get("OpenSans", 'a'); var boldGlyph = (TexturedCharacterGlyph)fontStore.Get("OpenSans-Bold", 'a'); Assert.That(normalGlyph.Scale, Is.EqualTo(1f / 100)); Assert.That(boldGlyph.Scale, Is.EqualTo(1f / 10)); } [OneTimeTearDown] public void TearDown() { storage.Dispose(); } } }
// 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 NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.IO.Stores; using osu.Framework.Text; namespace osu.Framework.Tests.IO { [TestFixture] public class FontStoreTest { private ResourceStore<byte[]> fontResourceStore; private TemporaryNativeStorage storage; [OneTimeSetUp] public void OneTimeSetUp() { storage = new TemporaryNativeStorage("fontstore-test", createIfEmpty: true); fontResourceStore = new NamespacedResourceStore<byte[]>(new DllResourceStore(typeof(Drawable).Assembly.Location), "Resources.Fonts.OpenSans"); } [Test] public void TestNestedScaleAdjust() { var fontStore = new FontStore(new RawCachingGlyphStore(fontResourceStore, "OpenSans") { CacheStorage = storage }, scaleAdjust: 100); var nestedFontStore = new FontStore(new RawCachingGlyphStore(fontResourceStore, "OpenSans-Bold") { CacheStorage = storage }, 10); fontStore.AddStore(nestedFontStore); var normalGlyph = (TexturedCharacterGlyph)fontStore.Get("OpenSans", 'a'); var boldGlyph = (TexturedCharacterGlyph)fontStore.Get("OpenSans-Bold", 'a'); Assert.That(normalGlyph.Scale, Is.EqualTo(1f / 100)); Assert.That(boldGlyph.Scale, Is.EqualTo(1f / 10)); } [OneTimeTearDown] public void TearDown() { storage.Dispose(); } } }
mit
C#
2188f76a91b43fd27ad5a30600fca70edc6a3ee1
Remove unused System.Net.Http reference
larsbrubaker/MatterControl,jlewin/MatterControl,rytz/MatterControl,mmoening/MatterControl,rytz/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,MatterHackers/MatterControl,tellingmachine/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,tellingmachine/MatterControl,MatterHackers/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,rytz/MatterControl,jlewin/MatterControl,MatterHackers/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl
VersionManagement/RetrievePublicProfileRequest.cs
VersionManagement/RetrievePublicProfileRequest.cs
using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.SettingsManagement; using System.IO; using System.Net; namespace MatterHackers.MatterControl.VersionManagement { class RetrievePublicProfileRequest { internal static string DownloadBaseUrl { get; set; } public RetrievePublicProfileRequest() { #if DEBUG DownloadBaseUrl = "https://mattercontrol-test.appspot.com/api/1/device/get-public-profile"; #else DownloadBaseUrl = "https://mattercontrol.appspot.com/api/1/device/get-public-profile"; #endif } public string getPrinterProfileByMakeModel(string make, string model) { string deviceToken = OemSettings.Instance.OemProfiles[make][model]; string profiletext = DownloadPrinterProfile(deviceToken); return profiletext; } internal static string DownloadPrinterProfile(string deviceToken) { // TODO: Enable caching //Keept track of version. When retrieving check version string url = DownloadBaseUrl + string.Format("/{0}",deviceToken); string profilePath = Path.Combine(ApplicationDataStorage.ApplicationUserDataPath,"Profiles",string.Format("{0}.json",deviceToken)); WebClient client = new WebClient(); string profileText = client.DownloadString(url); //File.WriteAllText(profileText, profilePath); return profileText; //HttpClient client = new HttpClient(); //Get a pemporaty path to write to during download. If download completes without error we move this file to the proper path //string tempFilePath = ApplicationDataStorage.Instance.GetTempFileName(".json"); //byte[] buffer = new byte[65536]; //using (var writeStream = File.Create(tempFilePath)) //using (var instream = await client.GetStreamAsync(url)) //{ // int bytesRead = await instream.ReadAsync(buffer, 0, buffer.Length); // while(bytesRead != 0) // { // writeStream.Write(buffer, 0, bytesRead); // bytesRead = await instream.ReadAsync(buffer, 0, buffer.Length); // } //} //File.Move(tempFilePath, profilePath); //return profilePath; } //Used in test to access test server before changes go onto live server } }
using MatterHackers.MatterControl.DataStorage; using MatterHackers.MatterControl.SettingsManagement; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace MatterHackers.MatterControl.VersionManagement { class RetrievePublicProfileRequest { internal static string DownloadBaseUrl { get; set; } public RetrievePublicProfileRequest() { #if DEBUG DownloadBaseUrl = "https://mattercontrol-test.appspot.com/api/1/device/get-public-profile"; #else DownloadBaseUrl = "https://mattercontrol.appspot.com/api/1/device/get-public-profile"; #endif } public string getPrinterProfileByMakeModel(string make, string model) { string deviceToken = OemSettings.Instance.OemProfiles[make][model]; string profiletext = DownloadPrinterProfile(deviceToken); return profiletext; } internal static string DownloadPrinterProfile(string deviceToken) { // TODO: Enable caching //Keept track of version. When retrieving check version string url = DownloadBaseUrl + string.Format("/{0}",deviceToken); string profilePath = Path.Combine(ApplicationDataStorage.ApplicationUserDataPath,"Profiles",string.Format("{0}.json",deviceToken)); WebClient client = new WebClient(); string profileText = client.DownloadString(url); //File.WriteAllText(profileText, profilePath); return profileText; //HttpClient client = new HttpClient(); //Get a pemporaty path to write to during download. If download completes without error we move this file to the proper path //string tempFilePath = ApplicationDataStorage.Instance.GetTempFileName(".json"); //byte[] buffer = new byte[65536]; //using (var writeStream = File.Create(tempFilePath)) //using (var instream = await client.GetStreamAsync(url)) //{ // int bytesRead = await instream.ReadAsync(buffer, 0, buffer.Length); // while(bytesRead != 0) // { // writeStream.Write(buffer, 0, bytesRead); // bytesRead = await instream.ReadAsync(buffer, 0, buffer.Length); // } //} //File.Move(tempFilePath, profilePath); //return profilePath; } //Used in test to access test server before changes go onto live server } }
bsd-2-clause
C#
d76a94d16a1d345f3bbe4c48fc8ef65740cdc7f7
Update Contact View.
Programazing/Open-School-Library,Programazing/Open-School-Library
src/Open-School-Library/Views/Home/Contact.cshtml
src/Open-School-Library/Views/Home/Contact.cshtml
@{ ViewData["Title"] = "Contact"; } <h2>@ViewData["Title"]</h2> <br /> <address> <strong>Project Issues Page:</strong> <a href="https://github.com/Programazing/Open-School-Library/issues">https://github.com/Programazing/Open-School-Library/issues</a> <br /> <strong>Creator:</strong> <a href="mailto:chris@thatamazingprogrammer.com?subject=Open School Library">chris@thatamazingprogrammer.com</a> <br /> </address>
@{ ViewData["Title"] = "Contact"; } <h2>@ViewData["Title"].</h2> <h3>@ViewData["Message"]</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> </address>
mit
C#
d3e2031e211bcfe4150db27d4f4ba00f29749953
Trim whitespace
DrabWeb/osu-framework,naoey/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,paparony03/osu-framework,peppy/osu-framework,ppy/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,smoogipooo/osu-framework,default0/osu-framework,default0/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,paparony03/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,naoey/osu-framework
osu.Framework.VisualTests/Tests/TestCaseBufferedContainer.cs
osu.Framework.VisualTests/Tests/TestCaseBufferedContainer.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using OpenTK; using System; namespace osu.Framework.VisualTests.Tests { internal class TestCaseBufferedContainer : TestCaseMasking { public override string Description => @"Buffered containers containing almost all visual effects."; private readonly BufferedContainer buffer; public TestCaseBufferedContainer() { Remove(TestContainer); Add(buffer = new BufferedContainer { RelativeSizeAxes = Axes.Both, Children = new[] { TestContainer } }); } protected override void LoadComplete() { base.LoadComplete(); buffer.BlurTo(new Vector2(20), 1000).Then().BlurTo(Vector2.Zero, 1000).Loop(); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using OpenTK; using System; namespace osu.Framework.VisualTests.Tests { internal class TestCaseBufferedContainer : TestCaseMasking { public override string Description => @"Buffered containers containing almost all visual effects."; private readonly BufferedContainer buffer; public TestCaseBufferedContainer() { Remove(TestContainer); Add(buffer = new BufferedContainer { RelativeSizeAxes = Axes.Both, Children = new[] { TestContainer } }); } protected override void LoadComplete() { base.LoadComplete(); buffer.Loop(b => b.BlurTo(new Vector2(20), 1000).Then().BlurTo(Vector2.Zero, 1000)); } } }
mit
C#
08a92c38d728e030b64bc0135607ce25ce01f5cd
adjust naming
UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,smoogipooo/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,EVAST9919/osu,johnneijzen/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,johnneijzen/osu,NeoAdonis/osu,ppy/osu,ZLima12/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,2yangk23/osu,ZLima12/osu,peppy/osu,peppy/osu
osu.Game/Screens/Multi/Match/Components/MatchBeatmapPanel.cs
osu.Game/Screens/Multi/Match/Components/MatchBeatmapPanel.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 osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Overlays.Direct; using osu.Game.Rulesets; namespace osu.Game.Screens.Multi.Match.Components { public class MatchBeatmapPanel : MultiplayerComposite { [Resolved] private IAPIProvider api { get; set; } [Resolved] private RulesetStore rulesets { get; set; } private GetBeatmapSetRequest request; public MatchBeatmapPanel() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { CurrentItem.BindValueChanged(item => { var onlineId = item.NewValue?.Beatmap.OnlineBeatmapID ?? 0; if (onlineId != 0) { request?.Cancel(); request = new GetBeatmapSetRequest(onlineId, BeatmapSetLookupType.BeatmapId); request.Success += beatmap => { ClearInternal(); var panel = new DirectGridPanel(beatmap.ToBeatmapSet(rulesets)); LoadComponentAsync(panel, p => { AddInternal(panel); }); }; api.Queue(request); } }, true); } } }
// 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 osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Overlays.Direct; using osu.Game.Rulesets; namespace osu.Game.Screens.Multi.Match.Components { public class MatchBeatmapPanel : MultiplayerComposite { [Resolved] private IAPIProvider api { get; set; } [Resolved] private RulesetStore rulesets { get; set; } private GetBeatmapSetRequest request; public MatchBeatmapPanel() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { CurrentItem.BindValueChanged(item => { var id = item.NewValue?.Beatmap.OnlineBeatmapID ?? 0; if (id != 0) { request?.Cancel(); request = new GetBeatmapSetRequest(id, BeatmapSetLookupType.BeatmapId); request.Success += beatmap => { ClearInternal(); var panel = new DirectGridPanel(beatmap.ToBeatmapSet(rulesets)); LoadComponentAsync(panel, p => { AddInternal(panel); }); }; api.Queue(request); } }, true); } } }
mit
C#
53668fc84a0518850f1eb57147242de6272636a5
Add a cast missing from #259. Closes #261
rabbitmq/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials,rabbitmq/rabbitmq-tutorials
dotnet/Worker/Worker.cs
dotnet/Worker/Worker.cs
using System; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System.Text; using System.Threading; class Worker { public static void Main() { var factory = new ConnectionFactory() { HostName = "localhost" }; using(var connection = factory.CreateConnection()) using(var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "task_queue", durable: true, exclusive: false, autoDelete: false, arguments: null); channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); Console.WriteLine(" [*] Waiting for messages."); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); int dots = message.Split('.').Length - 1; Thread.Sleep(dots * 1000); Console.WriteLine(" [x] Done"); ((IModel)model).BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; channel.BasicConsume(queue: "task_queue", autoAck: false, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } } }
using System; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System.Text; using System.Threading; class Worker { public static void Main() { var factory = new ConnectionFactory() { HostName = "localhost" }; using(var connection = factory.CreateConnection()) using(var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "task_queue", durable: true, exclusive: false, autoDelete: false, arguments: null); channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); Console.WriteLine(" [*] Waiting for messages."); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); int dots = message.Split('.').Length - 1; Thread.Sleep(dots * 1000); Console.WriteLine(" [x] Done"); model.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; channel.BasicConsume(queue: "task_queue", autoAck: false, consumer: consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } } }
apache-2.0
C#
dbbd0cfc4385dcb1b05406c46645dbaaa9669140
Remove list
A408a/Projekt
ChangeDatabase/ChangeDatabase/ChangeDatabase/Program.cs
ChangeDatabase/ChangeDatabase/ChangeDatabase/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChangeDatabase { class Program { static void Main(string[] args) { int start = 0; if (start == 1) { AutomaticRemoveFromDatabase Run = new AutomaticRemoveFromDatabase(); Run.FindOutdatedFolder(); } else { /*ChangeDatabase Run2 = new ChangeDatabase("test.txt"); Run2.RemoveArticleFromDatabase(); LoadEachWordToList TextA = new LoadEachWordToList(@"C:\Users\Jesper\Dropbox\AAU\P2\Program\Nyheder_Database\Crime\True\12_09_2016_New_York_Post_Anthony_Weiner_accused_of_sexting_relationship_with_15_year_old_girl.txt"); ChangeDatabase Run = new ChangeDatabase(TextA.Words); Run.AddArticle(); Console.ReadLine();*/ ChangeDatabase Run1 = new ChangeDatabase("test.txt"); Run1.RemoveArticleFromTag("abc", "True"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LoadTextLibrary; namespace ChangeDatabase { class Program { static void Main(string[] args) { int start = 0; if (start == 1) { AutomaticRemoveFromDatabase Run = new AutomaticRemoveFromDatabase(); Run.FindOutdatedFolder(); } else { /*ChangeDatabase Run2 = new ChangeDatabase("test.txt"); Run2.RemoveArticleFromDatabase(); LoadEachWordToList TextA = new LoadEachWordToList(@"C:\Users\Jesper\Dropbox\AAU\P2\Program\Nyheder_Database\Crime\True\12_09_2016_New_York_Post_Anthony_Weiner_accused_of_sexting_relationship_with_15_year_old_girl.txt"); ChangeDatabase Run = new ChangeDatabase(TextA.Words); Run.AddArticle(); Console.ReadLine();*/ ChangeDatabase Run1 = new ChangeDatabase("test.txt"); Run1.RemoveArticleFromTag("abc", "True"); } } } }
mit
C#
9ff8c4adf9cb2943012ffc0579fcfac034a05336
build fix
Chinchilla-Software-Com/CQRS,cdmdotnet/CQRS
Framework/Cqrs.Tests/Substitutes/TestHandleRegistrar.cs
Framework/Cqrs.Tests/Substitutes/TestHandleRegistrar.cs
using System; using System.Collections.Generic; using Cqrs.Bus; using Cqrs.Messages; namespace Cqrs.Tests.Substitutes { public class TestHandleRegistrar : IEventHandlerRegistrar, ICommandHandlerRegistrar { public static readonly IList<TestHandlerListItem> HandlerList = new List<TestHandlerListItem>(); public void RegisterHandler<T>(Action<T> handler, Type targetedType, bool holdMessageLock = true) where T : IMessage { HandlerList.Add(new TestHandlerListItem {Type = typeof(T),Handler = handler}); } /// <summary> /// Register an event or command handler that will listen and respond to events or commands. /// </summary> public void RegisterHandler<TMessage>(Action<TMessage> handler, bool holdMessageLock = true) where TMessage : IMessage { RegisterHandler(handler, null, holdMessageLock); } } public class TestHandlerListItem { public Type Type { get; set; } public dynamic Handler { get; set; } } }
using System; using System.Collections.Generic; using Cqrs.Bus; using Cqrs.Messages; namespace Cqrs.Tests.Substitutes { public class TestHandleRegistrar : IEventHandlerRegistrar, ICommandHandlerRegistrar { public static readonly IList<TestHandlerListItem> HandlerList = new List<TestHandlerListItem>(); public void RegisterHandler<T>(Action<T> handler, Type targetedType) where T : IMessage { HandlerList.Add(new TestHandlerListItem {Type = typeof(T),Handler = handler}); } /// <summary> /// Register an event or command handler that will listen and respond to events or commands. /// </summary> public void RegisterHandler<TMessage>(Action<TMessage> handler) where TMessage : IMessage { RegisterHandler(handler, null); } } public class TestHandlerListItem { public Type Type { get; set; } public dynamic Handler { get; set; } } }
lgpl-2.1
C#
c9d86ac6de20662aa594e7a9eb35eeed82844401
Clarify documentation.
jkoritzinsky/Avalonia,MrDaedra/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,susloparovdenis/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,OronDF343/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,susloparovdenis/Perspex,wieslawsoltes/Perspex,susloparovdenis/Avalonia,grokys/Perspex,akrisiun/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,grokys/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,MrDaedra/Avalonia,wieslawsoltes/Perspex,OronDF343/Avalonia,jazzay/Perspex,Perspex/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,susloparovdenis/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia
src/Avalonia.SceneGraph/Platform/IBitmapImpl.cs
src/Avalonia.SceneGraph/Platform/IBitmapImpl.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.IO; namespace Avalonia.Platform { /// <summary> /// Defines the platform-specific interface for a <see cref="Avalonia.Media.Imaging.Bitmap"/>. /// </summary> public interface IBitmapImpl { /// <summary> /// Gets the width of the bitmap, in pixels. /// </summary> int PixelWidth { get; } /// <summary> /// Gets the height of the bitmap, in pixels. /// </summary> int PixelHeight { get; } /// <summary> /// Saves the bitmap to a file. /// </summary> /// <param name="fileName">The filename.</param> void Save(string fileName); /// <summary> /// Saves the bitmap to a stream in png format. /// </summary> /// <param name="stream">The stream.</param> void Save(Stream stream); } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.IO; namespace Avalonia.Platform { /// <summary> /// Defines the platform-specific interface for a <see cref="Avalonia.Media.Imaging.Bitmap"/>. /// </summary> public interface IBitmapImpl { /// <summary> /// Gets the width of the bitmap, in pixels. /// </summary> int PixelWidth { get; } /// <summary> /// Gets the height of the bitmap, in pixels. /// </summary> int PixelHeight { get; } /// <summary> /// Saves the bitmap to a file. /// </summary> /// <param name="fileName">The filename.</param> void Save(string fileName); /// <summary> /// Saves the bitmap to a stream. /// </summary> /// <param name="stream">The stream.</param> void Save(Stream stream); } }
mit
C#
26d342bde9df9a7d303b8919b3c2c9c45c45e697
Bump version
Weingartner/ReactiveCompositeCollections
ReactiveCompositeCollections/Properties/AssemblyInfo.cs
ReactiveCompositeCollections/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("ReactiveCompositeCollections")] [assembly: AssemblyDescription("ReactiveCompositeCollections")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Weingartner Maschinenbau GmbH")] [assembly: AssemblyProduct("ReactiveCompositeCollections")] [assembly: AssemblyCopyright("Copyright Weingartner Maschinenbau GmbH © HP 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("5b586874-8d3e-4137-9ba8-e982413416d5")] // 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.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")] [assembly: AssemblyInformationalVersion("1.0.2")]
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("ReactiveCompositeCollections")] [assembly: AssemblyDescription("ReactiveCompositeCollections")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Weingartner Maschinenbau GmbH")] [assembly: AssemblyProduct("ReactiveCompositeCollections")] [assembly: AssemblyCopyright("Copyright Weingartner Maschinenbau GmbH © HP 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("5b586874-8d3e-4137-9ba8-e982413416d5")] // 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.1.0")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1")]
mit
C#
27f6929e898d01bff14b4683eef349122660d460
write first failing test
fffej/codekatas,fffej/codekatas,fffej/codekatas
MineField/MineSweeperTest.cs
MineField/MineSweeperTest.cs
using NUnit.Framework; using FluentAssertions; namespace Fatvat.Katas.MineSweeper { [TestFixture] public class MineSweeperTest { // ReSharper disable InconsistentNaming [Test] public void Given_Simplest_MineField_Can_ProduceOutput() { const string mineFieldInput = "1 1\n*"; const string expectedOutput = "*\n"; Assert.That(MineField.Read(mineFieldInput).Display(), Is.EqualTo(expectedOutput)); } // ReSharper restore InconsistentNaming } public class MineField { public static MineField Read(string input) { return new MineField(); } public string Display() { return ""; } } }
using NUnit.Framework; using FluentAssertions; namespace Fatvat.Katas.MineSweeper { [TestFixture] public class MineSweeperTest { } }
mit
C#
ca0f14e353952a4c5222fc64239ca1152ce8d30c
Fix broken unit test
mike-ward/tweetz-desktop
tweetz5/tweetz5UnitTests/Controls/TimelineControllerTests.cs
tweetz5/tweetz5UnitTests/Controls/TimelineControllerTests.cs
// Copyright (c) 2012 Blue Onion Software - All rights reserved using System; using System.Collections.Generic; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using tweetz5.Controls; using tweetz5.Model; using tweetz5.Utilities.System; namespace tweetz5UnitTests { [TestClass] public class TimelineControllerTests { [TestCleanup] public void Cleanup() { SysTimer.ImplementationOverride = null; } [TestMethod] public void ConstructingControllerStartsTimelines() { var checkTimelines = new Mock<ITimer>(); var updateTimelines = new Mock<ITimer>(); var friendsBlockedTimelines = new Mock<ITimer>(); var queue = new Queue<ITimer>(); queue.Enqueue(checkTimelines.Object); queue.Enqueue(updateTimelines.Object); SysTimer.ImplementationOverride = queue.Dequeue; var timelines = new Mock<ITimelines>(); var controller = new TimelineController(timelines.Object); controller.StartTimelines(); checkTimelines.Raise(c => c.Elapsed += null, EventArgs.Empty); updateTimelines.Raise(u => u.Elapsed += null, EventArgs.Empty); friendsBlockedTimelines.Raise(u => u.Elapsed += null, EventArgs.Empty); checkTimelines.VerifySet(c => c.Interval = 100); checkTimelines.VerifySet(c => c.Interval = 70000); checkTimelines.Verify(c => c.Start()); timelines.Verify(t => t.HomeTimeline()); timelines.Verify(t => t.MentionsTimeline()); updateTimelines.VerifySet(u => u.Interval = 100); updateTimelines.VerifySet(u => u.Interval = 30000); updateTimelines.Verify(u => u.Start()); timelines.Verify(t => t.UpdateTimeStamps()); controller.Should().NotBeNull(); } } }
// Copyright (c) 2012 Blue Onion Software - All rights reserved using System; using System.Collections.Generic; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using tweetz5.Controls; using tweetz5.Model; using tweetz5.Utilities.System; namespace tweetz5UnitTests { [TestClass] public class TimelineControllerTests { [TestCleanup] public void Cleanup() { SysTimer.ImplementationOverride = null; } [TestMethod] public void ConstructingControllerStartsTimelines() { var checkTimelines = new Mock<ITimer>(); var updateTimelines = new Mock<ITimer>(); var friendsBlockedTimelines = new Mock<ITimer>(); var queue = new Queue<ITimer>(); queue.Enqueue(checkTimelines.Object); queue.Enqueue(updateTimelines.Object); SysTimer.ImplementationOverride = queue.Dequeue; var timelines = new Mock<ITimelines>(); var controller = new TimelineController(timelines.Object); controller.StartTimelines(); checkTimelines.Raise(c => c.Elapsed += null, EventArgs.Empty); updateTimelines.Raise(u => u.Elapsed += null, EventArgs.Empty); friendsBlockedTimelines.Raise(u => u.Elapsed += null, EventArgs.Empty); checkTimelines.VerifySet(c => c.Interval = 100); checkTimelines.VerifySet(c => c.Interval = 90000); checkTimelines.Verify(c => c.Start()); timelines.Verify(t => t.HomeTimeline()); timelines.Verify(t => t.MentionsTimeline()); updateTimelines.VerifySet(u => u.Interval = 100); updateTimelines.VerifySet(u => u.Interval = 30000); updateTimelines.Verify(u => u.Start()); timelines.Verify(t => t.UpdateTimeStamps()); controller.Should().NotBeNull(); } } }
mit
C#
bbce8c3e4f9457828bb12f6d1859cd4e335a838f
Fix item collection reset event occurring when changing build
mihailim/PoESkillTree,EmmittJ/PoESkillTree,PoESkillTree/PoESkillTree
WPFSKillTree/Model/ObservableItemCollectionConverter.cs
WPFSKillTree/Model/ObservableItemCollectionConverter.cs
using System.Collections; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using MoreLinq; using PoESkillTree.GameModel.Items; using POESKillTree.Utils.Extensions; using OldItem = POESKillTree.Model.Items.Item; namespace POESKillTree.Model { public class ObservableItemCollectionConverter { private ObservableCollection<OldItem> _oldCollection; public ObservableCollection<(Item, ItemSlot)> Collection { get; } = new ObservableCollection<(Item, ItemSlot)>(); public void ConvertFrom(ObservableCollection<OldItem> oldCollection) { if (_oldCollection != null) { _oldCollection.CollectionChanged -= OldCollectionChanged; } _oldCollection = oldCollection; Reset(); _oldCollection.CollectionChanged += OldCollectionChanged; } private void OldCollectionChanged(object sender, NotifyCollectionChangedEventArgs args) { if (args.Action == NotifyCollectionChangedAction.Reset) { Reset(); return; } if (args.NewItems is IList newItems) { Add(newItems); } if (args.OldItems is IList oldItems) { Remove(oldItems); } } private void Reset() { // When the old collection is removed, the replacement should be an INotifyCollectionChanged implementation // that can raise proper multi-item events (ObservableList, similar to ObservableSet). Collection.ToList().ForEach(i => Collection.Remove(i)); Collection.AddRange(_oldCollection.Select(Convert)); } private void Add(IEnumerable newItems) { var items = newItems.Cast<OldItem>().Select(Convert); Collection.AddRange(items); } private void Remove(IEnumerable oldItems) { var items = oldItems.Cast<OldItem>().Select(Convert); items.ForEach(i => Collection.Remove(i)); } private static (Item, ItemSlot) Convert(OldItem oldItem) => (ModelConverter.Convert(oldItem), oldItem.Slot); } }
using System.Collections; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using MoreLinq; using PoESkillTree.GameModel.Items; using POESKillTree.Utils.Extensions; using OldItem = POESKillTree.Model.Items.Item; namespace POESKillTree.Model { public class ObservableItemCollectionConverter { private ObservableCollection<OldItem> _oldCollection; public ObservableCollection<(Item, ItemSlot)> Collection { get; } = new ObservableCollection<(Item, ItemSlot)>(); public void ConvertFrom(ObservableCollection<OldItem> oldCollection) { if (_oldCollection != null) { _oldCollection.CollectionChanged -= OldCollectionChanged; } _oldCollection = oldCollection; Reset(); _oldCollection.CollectionChanged += OldCollectionChanged; } private void OldCollectionChanged(object sender, NotifyCollectionChangedEventArgs args) { if (args.Action == NotifyCollectionChangedAction.Reset) { Reset(); return; } if (args.NewItems is IList newItems) { Add(newItems); } if (args.OldItems is IList oldItems) { Remove(oldItems); } } private void Reset() { Collection.Clear(); Collection.AddRange(_oldCollection.Select(Convert)); } private void Add(IEnumerable newItems) { var items = newItems.Cast<OldItem>().Select(Convert); Collection.AddRange(items); } private void Remove(IEnumerable oldItems) { var items = oldItems.Cast<OldItem>().Select(Convert); items.ForEach(i => Collection.Remove(i)); } private static (Item, ItemSlot) Convert(OldItem oldItem) => (ModelConverter.Convert(oldItem), oldItem.Slot); } }
mit
C#
6f197eed2b4bc6728a310f2bcd8388be43c901e2
Add more comments to DbContextFactory
aliencube/Entity-Context-Library,aliencube/Entity-Context-Library,aliencube/Entity-Context-Library
SourceCodes/EntityContextLibrary/DbContextFactory.cs
SourceCodes/EntityContextLibrary/DbContextFactory.cs
using System; using System.Data.Entity; using Aliencube.EntityContextLibrary.Interfaces; namespace Aliencube.EntityContextLibrary { /// <summary> /// This represents the factory entity for <c>DbContext</c>. /// </summary> /// <typeparam name="TContext"> /// Type parameter of the context class inheriting <see cref="DbContext" />. /// </typeparam> public class DbContextFactory<TContext> : IDbContextFactory where TContext : DbContext { private TContext _dbContext; private bool _disposed; /// <summary> /// Gets the <c>DbContext</c> instance. /// </summary> public virtual DbContext Context { get { if (this._dbContext == null) { this._dbContext = Activator.CreateInstance<TContext>(); } return this._dbContext; } } /// <summary> /// Gets the type of the <c>DbContext</c> instance. /// </summary> public Type DbContextType { get { return typeof(TContext); } } /// <summary> /// Creates the <c>DbContext</c> instance. /// </summary> /// <returns>Returns the <c>DbContext</c> instance.</returns> [Obsolete("Use this.Context property instead.")] public virtual DbContext CreateContext() { if (this._dbContext == null) { this._dbContext = Activator.CreateInstance<TContext>(); } return this._dbContext; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, /// or resetting unmanaged resources. /// </summary> public void Dispose() { if (this._disposed) { return; } this._disposed = true; } } }
using System; using System.Data.Entity; using Aliencube.EntityContextLibrary.Interfaces; namespace Aliencube.EntityContextLibrary { /// <summary> /// This represents the factory entity for <c>DbContext</c>. /// </summary> public class DbContextFactory<TContext> : IDbContextFactory where TContext : DbContext { private TContext _dbContext; private bool _disposed; /// <summary> /// Gets the <c>DbContext</c> instance. /// </summary> public virtual DbContext Context { get { if (this._dbContext == null) { this._dbContext = Activator.CreateInstance<TContext>(); } return this._dbContext; } } /// <summary> /// Gets the type of the <c>DbContext</c> instance. /// </summary> public Type DbContextType { get { return typeof(TContext); } } /// <summary> /// Creates the <c>DbContext</c> instance. /// </summary> /// <returns>Returns the <c>DbContext</c> instance.</returns> [Obsolete("Use this.Context property instead.")] public virtual DbContext CreateContext() { if (this._dbContext == null) { this._dbContext = Activator.CreateInstance<TContext>(); } return this._dbContext; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, /// or resetting unmanaged resources. /// </summary> public void Dispose() { if (this._disposed) { return; } this._disposed = true; } } }
mit
C#
ef9820745c15b4d5d13804c5f393608fccdac38d
fix converter
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TCC.Core/Converters/GuardianPointsStringConverter.cs
TCC.Core/Converters/GuardianPointsStringConverter.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace TCC.Converters { class GuardianPointsStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var v = System.Convert.ToUInt32(value); if (v == 100000) return "Max"; else if (v >= 1000) return v / 1000 + "k"; else return v; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace TCC.Converters { class GuardianPointsStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var v = (uint)value; if (v == 100000) return "Max"; else if (v >= 1000) return v / 1000 + "k"; else return v; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
mit
C#
f79d3365eae76939ed502f81bff596ae0daede10
resolve #389
rollbar/Rollbar.NET
UnitTest.Rollbar/AccessTokenQueuesMetadataFixture.cs
UnitTest.Rollbar/AccessTokenQueuesMetadataFixture.cs
namespace UnitTest.Rollbar { using global::Rollbar; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; /// <summary> /// Defines test class AccessTokenQueuesMetadataFixture. /// </summary> [TestClass] [TestCategory(nameof(AccessTokenQueuesMetadataFixture))] public class AccessTokenQueuesMetadataFixture { /// <summary> /// Setups the fixture. /// </summary> [TestInitialize] public void SetupFixture() { } /// <summary> /// Tears down fixture. /// </summary> [TestCleanup] public void TearDownFixture() { } /// <summary> /// Defines the test method ConstructionTest. /// </summary> [TestMethod] public void ConstructionTest() { var metadata = new AccessTokenQueuesMetadata(RollbarUnitTestSettings.AccessToken); Assert.AreEqual(RollbarUnitTestSettings.AccessToken, metadata.AccessToken); Assert.IsNotNull(metadata.Queues); Assert.IsTrue(metadata.NextTimeTokenUsage <= DateTimeOffset.Now); } } }
namespace UnitTest.Rollbar { using global::Rollbar; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; /// <summary> /// Defines test class AccessTokenQueuesMetadataFixture. /// </summary> [TestClass] [TestCategory(nameof(AccessTokenQueuesMetadataFixture))] public class AccessTokenQueuesMetadataFixture { /// <summary> /// Setups the fixture. /// </summary> [TestInitialize] public void SetupFixture() { } /// <summary> /// Tears down fixture. /// </summary> [TestCleanup] public void TearDownFixture() { } /// <summary> /// Defines the test method ConstructionTest. /// </summary> [TestMethod] public void ConstructionTest() { var metadata = new AccessTokenQueuesMetadata(RollbarUnitTestSettings.AccessToken); Assert.AreEqual(RollbarUnitTestSettings.AccessToken, metadata.AccessToken); Assert.IsNotNull(metadata.Queues); Assert.IsTrue(metadata.NextTimeTokenUsage < DateTimeOffset.Now); } } }
mit
C#
fc459071868ec616ac50ec31d7d3180518ce9adf
Put back to match nhibernate in svn.
lingxyd/fluent-nhibernate,lingxyd/fluent-nhibernate,oceanho/fluent-nhibernate,oceanho/fluent-nhibernate,HermanSchoenfeld/fluent-nhibernate,owerkop/fluent-nhibernate,HermanSchoenfeld/fluent-nhibernate,bogdan7/nhibernate,MiguelMadero/fluent-nhibernate,hzhgis/ss,chester89/fluent-nhibernate,narnau/fluent-nhibernate,bogdan7/nhibernate,chester89/fluent-nhibernate,MiguelMadero/fluent-nhibernate,hzhgis/ss,owerkop/fluent-nhibernate,chester89/fluent-nhibernate,bogdan7/nhibernate,narnau/fluent-nhibernate,hzhgis/ss
src/FluentNHibernate.Framework/SessionSource.cs
src/FluentNHibernate.Framework/SessionSource.cs
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using NHibernate; using NHibernate.Cfg; namespace FluentNHibernate.Framework { public interface ISessionSource { ISession CreateSession(); void BuildSchema(); PersistenceModel Model { get; } } public class SessionSource : ISessionSource { private ISessionFactory _sessionFactory; private Configuration _configuration; private PersistenceModel _model; public SessionSource(IDictionary<string, string> properties, PersistenceModel model) { _configuration = new Configuration(); _configuration.AddProperties(properties); model.Configure(_configuration); _model = model; _sessionFactory = _configuration.BuildSessionFactory(); } public PersistenceModel Model { get { return _model; } } public ISession CreateSession() { return _sessionFactory.OpenSession(); } public void BuildSchema() { ISession session = CreateSession(); IDbConnection connection = session.Connection; string[] drops = _configuration.GenerateDropSchemaScript(_sessionFactory.Dialect); executeScripts(drops, connection); string[] scripts = _configuration.GenerateSchemaCreationScript(_sessionFactory.Dialect); executeScripts(scripts, connection); } private static void executeScripts(string[] scripts, IDbConnection connection) { foreach (var script in scripts) { IDbCommand command = connection.CreateCommand(); command.CommandText = script; command.ExecuteNonQuery(); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; namespace FluentNHibernate.Framework { public interface ISessionSource { ISession CreateSession(); void BuildSchema(); PersistenceModel Model { get; } } public class SessionSource : ISessionSource { private ISessionFactory _sessionFactory; private Configuration _configuration; private PersistenceModel _model; public SessionSource(IDictionary<string, string> properties, PersistenceModel model) { _configuration = new Configuration(); _configuration.AddProperties(properties); model.Configure(_configuration); _model = model; _sessionFactory = _configuration.BuildSessionFactory(); } public PersistenceModel Model { get { return _model; } } public ISession CreateSession() { return _sessionFactory.OpenSession(); } public void BuildSchema() { ISession session = CreateSession(); IDbConnection connection = session.Connection; string[] drops = _configuration.GenerateDropSchemaScript(Dialect.GetDialect()); executeScripts(drops, connection); string[] scripts = _configuration.GenerateSchemaCreationScript(Dialect.GetDialect()); executeScripts(scripts, connection); } private static void executeScripts(string[] scripts, IDbConnection connection) { foreach (var script in scripts) { IDbCommand command = connection.CreateCommand(); command.CommandText = script; command.ExecuteNonQuery(); } } } }
bsd-3-clause
C#
4a1a06c4369e25b5fb59ec3dbeb505bdc3bfaa2f
add new mwthods 9jio
Nahalius/testo,Nahalius/testo
DataTypes/Methods/Methods/ConsoleApplication1/MethodsShort.cs
DataTypes/Methods/Methods/ConsoleApplication1/MethodsShort.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class MethodsShort { static void Main(string[] args) { var number = 5; string text = "some text"; //String.Format("Hello {0}",text) - for display InputData(); OutputData(number); //With number IfStatement(); } static void InputData() { Console.ReadLine(); } static void OutputData(int number) { Console.WriteLine(number); } static void IfStatement() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class MethodsShort { static void Main(string[] args) { InputData(); OutputData(); } static void InputData() { Console.ReadLine(); } static void OutputData() { Console.WriteLine(); } } }
mit
C#
9d8b4782a68c1718b463db8cc2f9adc1d3cf70cb
remove array
Appleseed/base,Appleseed/base
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Appleseed.Base.Alerts.Model { class SolrResponseItem { public string id { get; set; } public string item_type { get; set; } public string address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string[] postal_code { get; set; } public string[] product_description { get; set; } public string[] product_quantity { get; set; } public string[] product_type { get; set; } public string[] code_info { get; set; } public string[] reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string[] recall_number { get; set; } public string recalling_firm { get; set; } public string[] voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string[] status { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Appleseed.Base.Alerts.Model { class SolrResponseItem { public string id { get; set; } public string item_type { get; set; } public string[] address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string[] postal_code { get; set; } public string[] product_description { get; set; } public string[] product_quantity { get; set; } public string[] product_type { get; set; } public string[] code_info { get; set; } public string[] reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string[] recall_number { get; set; } public string recalling_firm { get; set; } public string[] voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string[] status { get; set; } } }
apache-2.0
C#
0454a8e109cbafeae2b6cd98e0d107038de00e9c
Remove [NonSerialized] attribute.
dlemstra/Magick.NET,dlemstra/Magick.NET
src/Magick.NET/Shared/Exceptions/MagickException.cs
src/Magick.NET/Shared/Exceptions/MagickException.cs
// Copyright 2013-2019 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. using System; using System.Collections.Generic; namespace ImageMagick { /// <summary> /// Encapsulation of the ImageMagick exception object. /// </summary> public abstract class MagickException : Exception { private List<MagickException> _relatedExceptions; /// <summary> /// Initializes a new instance of the <see cref="MagickException"/> class. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> internal MagickException(string message) : base(message) { } /// <summary> /// Gets the exceptions that are related to this exception. /// </summary> public IEnumerable<MagickException> RelatedExceptions { get { if (_relatedExceptions == null) return new MagickException[0]; return _relatedExceptions; } } internal void SetRelatedException(List<MagickException> relatedExceptions) { _relatedExceptions = relatedExceptions; } } }
// Copyright 2013-2019 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. using System; using System.Collections.Generic; namespace ImageMagick { /// <summary> /// Encapsulation of the ImageMagick exception object. /// </summary> public abstract class MagickException : Exception { [NonSerialized] private List<MagickException> _relatedExceptions; /// <summary> /// Initializes a new instance of the <see cref="MagickException"/> class. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> internal MagickException(string message) : base(message) { } /// <summary> /// Gets the exceptions that are related to this exception. /// </summary> public IEnumerable<MagickException> RelatedExceptions { get { if (_relatedExceptions == null) return new MagickException[0]; return _relatedExceptions; } } internal void SetRelatedException(List<MagickException> relatedExceptions) { _relatedExceptions = relatedExceptions; } } }
apache-2.0
C#
c14a74f4e0871ddb4f09916d27b3e75b40275b2a
Add default TryConvertFromString to test converter
cemdervis/SharpConfig
Tests/CustomConverterTest.cs
Tests/CustomConverterTest.cs
// Copyright (c) 2013-2018 Cemalettin Dervis, MIT License. // https://github.com/cemdervis/SharpConfig using System; using SharpConfig; using NUnit.Framework; namespace Tests { class Person { public string Name { get; set; } public int Age { get; set; } } class PersonStringConverter : TypeStringConverter<Person> { // This method is responsible for converting a Person object to a string. public override string ConvertToString(object value) { var person = (Person)value; return string.Format("[{0};{1}]", person.Name, person.Age); } // This method is responsible for converting a string to a Person object. public override object ConvertFromString(string value, Type hint) { var split = value.Trim('[', ']').Split(';'); var person = new Person(); person.Name = split[0]; person.Age = int.Parse(split[1]); return person; } // This method attempts to convert the value to a Person object. // It is used instead when Setting.GetOrDefault<T> is called. public override object TryConvertFromString(string value, Type hint) { try { return ConvertFromString(value, hint); } catch { return null; } } } [TestFixture] public sealed class CustomConverterTest { [Test] public void CustomConverter() { Configuration.RegisterTypeStringConverter(new PersonStringConverter()); var p = new Person() { Name = "TestPerson", Age = 123 }; var cfg = new Configuration(); cfg["TestSection"]["Person"].SetValue(p); var pp = cfg["TestSection"]["Person"].GetValue<Person>(); Assert.AreEqual(p.Name, pp.Name); Assert.AreEqual(p.Age, pp.Age); } } }
// Copyright (c) 2013-2018 Cemalettin Dervis, MIT License. // https://github.com/cemdervis/SharpConfig using System; using SharpConfig; using NUnit.Framework; namespace Tests { class Person { public string Name { get; set; } public int Age { get; set; } } class PersonStringConverter : TypeStringConverter<Person> { // This method is responsible for converting a Person object to a string. public override string ConvertToString(object value) { var person = (Person)value; return string.Format("[{0};{1}]", person.Name, person.Age); } // This method is responsible for converting a string to a Person object. public override object ConvertFromString(string value, Type hint) { var split = value.Trim('[', ']').Split(';'); var person = new Person(); person.Name = split[0]; person.Age = int.Parse(split[1]); return person; } } [TestFixture] public sealed class CustomConverterTest { [Test] public void CustomConverter() { Configuration.RegisterTypeStringConverter(new PersonStringConverter()); var p = new Person() { Name = "TestPerson", Age = 123 }; var cfg = new Configuration(); cfg["TestSection"]["Person"].SetValue(p); var pp = cfg["TestSection"]["Person"].GetValue<Person>(); Assert.AreEqual(p.Name, pp.Name); Assert.AreEqual(p.Age, pp.Age); } } }
mit
C#
49e35332ea39edb95399f40fca54befeeb81bb48
Add missing tests.
jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr
test/app.tests/WebApi/HelloWorldControllerTest.cs
test/app.tests/WebApi/HelloWorldControllerTest.cs
using System.Threading.Tasks; using System.Net; using Microsoft.AspNetCore.Mvc; using Xunit; using Moq; using FluentAssertions; using HelloWorldApp.WebApi.Actions; using HelloWorldApp.WebApi.Messages; using HelloWorldApp.WebApi; namespace HelloWorldApp.Test { public class HelloWorldControllerTest { [Fact] public async Task SayHelloWorldTest() { var sayHelloWorldAction = new Mock<ISayHelloWorldAction>(); sayHelloWorldAction.Setup(m => m.ExecuteAsync("You")).ReturnsAsync(new SayHelloWorldResponse{ Greeting = "Hello You!" }); var actionFactory = Mock.Of<IActionFactory>(m => m.CreateSayHelloWorldAction() == sayHelloWorldAction.Object); var sut = new HelloWorldController(actionFactory); var response = await sut.SayHelloWorldAsync("You"); response.Should().NotBeNull(); var okResponse = response.As<OkObjectResult>(); okResponse.Should().NotBeNull(); okResponse.StatusCode.Should().Be((int)HttpStatusCode.OK); var content = okResponse.Value.As<SayHelloWorldResponse>(); content.Should().NotBeNull(); content.Greeting.Should().Be("Hello You!"); } [Fact] public async Task NoGreetingsShouldReturnNoContentTest() { var getLastTenGreetingsAction = new Mock<IGetLastTenGreetingsAction>(); getLastTenGreetingsAction.Setup(m => m.ExecuteAsync()).ReturnsAsync(new SavedGreeting[0]); var actionFactory = Mock.Of<IActionFactory>(m => m.CreateGetLastTenGreetingsAction() == getLastTenGreetingsAction.Object); var sut = new HelloWorldController(actionFactory); var response = await sut.GetLastTenGreetingsAsync(); response.Should().NotBeNull(); var okResponse = response.As<NoContentResult>(); okResponse.Should().NotBeNull(); } [Fact] public async Task SomeGreetingsShouldReturnGreetingsTest() { var getLastTenGreetingsAction = new Mock<IGetLastTenGreetingsAction>(); getLastTenGreetingsAction.Setup(m => m.ExecuteAsync()).ReturnsAsync(new []{new SavedGreeting{Greeting = "mygreeting"}}); var actionFactory = Mock.Of<IActionFactory>(m => m.CreateGetLastTenGreetingsAction() == getLastTenGreetingsAction.Object); var sut = new HelloWorldController(actionFactory); var response = await sut.GetLastTenGreetingsAsync(); var okResponse = response.As<OkObjectResult>(); okResponse.Should().NotBeNull(); okResponse.StatusCode.Should().Be((int)HttpStatusCode.OK); var content = okResponse.Value.As<SavedGreeting[]>(); content.Should().NotBeNull(); content[0].Greeting.Should().Be("mygreeting"); } } }
using System.Threading.Tasks; using System.Net; using Microsoft.AspNetCore.Mvc; using Xunit; using Moq; using FluentAssertions; using HelloWorldApp.WebApi.Actions; using HelloWorldApp.WebApi.Messages; using HelloWorldApp.WebApi; namespace HelloWorldApp.Test { public class HelloWorldControllerTest { [Fact] public async Task SayHelloWorldTest(){ var sayHelloWorldAction = new Mock<ISayHelloWorldAction>(); sayHelloWorldAction.Setup(a => a.ExecuteAsync("You")).Returns( Task.FromResult(new SayHelloWorldResponse{ Greeting = "Hello You!" })); var actionFactory = Mock.Of<IActionFactory>(f => f.CreateSayHelloWorldAction() == sayHelloWorldAction.Object); var sut = new HelloWorldController(actionFactory); var response = await sut.SayHelloWorldAsync("You"); response.Should().NotBeNull(); var okResponse = response.As<OkObjectResult>(); okResponse.Should().NotBeNull(); okResponse.StatusCode.Should().Be((int)HttpStatusCode.OK); var content = okResponse.Value.As<SayHelloWorldResponse>(); content.Should().NotBeNull(); content.Greeting.Should().Be("Hello You!"); } } }
mit
C#
15d2b14e7de89972b7b787baf8a1df9c5507a5eb
remove unused param
volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity
src/Serenity.Net.Core/ComponentModel/Extensibility/DefaultTypeSource.cs
src/Serenity.Net.Core/ComponentModel/Extensibility/DefaultTypeSource.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Serenity.Abstractions { /// <summary> /// Default implementation for a type source /// </summary> public class DefaultTypeSource : ITypeSource { private readonly IEnumerable<Assembly> assemblies; /// <summary> /// Creates a new instance /// </summary> /// <param name="assemblies">List of assemblies</param> public DefaultTypeSource(IEnumerable<Assembly> assemblies) { this.assemblies = assemblies ?? throw new ArgumentNullException(nameof(assemblies)); } /// <summary> /// Gets all attributes for assemblies with given type /// </summary> /// <returns>List of attributes for assemblies</returns> public IEnumerable<Attribute> GetAssemblyAttributes(Type attributeType) { return assemblies.SelectMany(x => x.GetCustomAttributes(attributeType)); } /// <summary> /// Gets all types /// </summary> /// <returns></returns> public IEnumerable<Type> GetTypes() { return assemblies.SelectMany(x => x.GetTypes()); } /// <summary> /// Gets all types that implement an interface /// </summary> /// <param name="interfaceType">Interface type</param> /// <returns>Types with that interface type</returns> public IEnumerable<Type> GetTypesWithInterface(Type interfaceType) { return assemblies.SelectMany(asm => asm.GetTypes()) .Where(type => interfaceType.IsAssignableFrom(type)); } /// <summary> /// Gets all types that has an attribute /// </summary> /// <param name="attributeType">Attribute type</param> /// <returns>Types with that attribute type</returns> public IEnumerable<Type> GetTypesWithAttribute(Type attributeType) { return assemblies.SelectMany(asm => asm.GetTypes()) .Where(type => type.GetCustomAttribute(attributeType) != null); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Serenity.Abstractions { /// <summary> /// Default implementation for a type source /// </summary> public class DefaultTypeSource : ITypeSource { private readonly IEnumerable<Assembly> assemblies; /// <summary> /// Creates a new instance /// </summary> /// <param name="assemblies">List of assemblies</param> /// <param name="additionalTypes"> public DefaultTypeSource(IEnumerable<Assembly> assemblies, IEnumerable<Type> additionalTypes = null) { this.assemblies = assemblies ?? throw new ArgumentNullException(nameof(assemblies)); } /// <summary> /// Gets all attributes for assemblies with given type /// </summary> /// <returns>List of attributes for assemblies</returns> public IEnumerable<Attribute> GetAssemblyAttributes(Type attributeType) { return assemblies.SelectMany(x => x.GetCustomAttributes(attributeType)); } /// <summary> /// Gets all types /// </summary> /// <returns></returns> public IEnumerable<Type> GetTypes() { return assemblies.SelectMany(x => x.GetTypes()); } /// <summary> /// Gets all types that implement an interface /// </summary> /// <param name="interfaceType">Interface type</param> /// <returns>Types with that interface type</returns> public IEnumerable<Type> GetTypesWithInterface(Type interfaceType) { return assemblies.SelectMany(asm => asm.GetTypes()) .Where(type => interfaceType.IsAssignableFrom(type)); } /// <summary> /// Gets all types that has an attribute /// </summary> /// <param name="attributeType">Attribute type</param> /// <returns>Types with that attribute type</returns> public IEnumerable<Type> GetTypesWithAttribute(Type attributeType) { return assemblies.SelectMany(asm => asm.GetTypes()) .Where(type => type.GetCustomAttribute(attributeType) != null); } } }
mit
C#
a05871afba9749b9c9b87220fb837a1ef4a8c561
make sure view renders partial interface
tkirill/elasticsearch-net,elastic/elasticsearch-net,robertlyson/elasticsearch-net,adam-mccoy/elasticsearch-net,LeoYao/elasticsearch-net,ststeiger/elasticsearch-net,DavidSSL/elasticsearch-net,azubanov/elasticsearch-net,SeanKilleen/elasticsearch-net,UdiBen/elasticsearch-net,abibell/elasticsearch-net,UdiBen/elasticsearch-net,TheFireCookie/elasticsearch-net,faisal00813/elasticsearch-net,KodrAus/elasticsearch-net,TheFireCookie/elasticsearch-net,faisal00813/elasticsearch-net,tkirill/elasticsearch-net,starckgates/elasticsearch-net,RossLieberman/NEST,wawrzyn/elasticsearch-net,RossLieberman/NEST,robrich/elasticsearch-net,starckgates/elasticsearch-net,amyzheng424/elasticsearch-net,cstlaurent/elasticsearch-net,junlapong/elasticsearch-net,amyzheng424/elasticsearch-net,cstlaurent/elasticsearch-net,DavidSSL/elasticsearch-net,abibell/elasticsearch-net,TheFireCookie/elasticsearch-net,KodrAus/elasticsearch-net,abibell/elasticsearch-net,DavidSSL/elasticsearch-net,junlapong/elasticsearch-net,mac2000/elasticsearch-net,jonyadamit/elasticsearch-net,elastic/elasticsearch-net,geofeedia/elasticsearch-net,jonyadamit/elasticsearch-net,ststeiger/elasticsearch-net,starckgates/elasticsearch-net,LeoYao/elasticsearch-net,azubanov/elasticsearch-net,faisal00813/elasticsearch-net,robertlyson/elasticsearch-net,adam-mccoy/elasticsearch-net,gayancc/elasticsearch-net,robrich/elasticsearch-net,RossLieberman/NEST,amyzheng424/elasticsearch-net,robertlyson/elasticsearch-net,SeanKilleen/elasticsearch-net,robrich/elasticsearch-net,wawrzyn/elasticsearch-net,LeoYao/elasticsearch-net,UdiBen/elasticsearch-net,mac2000/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,joehmchan/elasticsearch-net,joehmchan/elasticsearch-net,tkirill/elasticsearch-net,CSGOpenSource/elasticsearch-net,joehmchan/elasticsearch-net,gayancc/elasticsearch-net,SeanKilleen/elasticsearch-net,mac2000/elasticsearch-net,ststeiger/elasticsearch-net,wawrzyn/elasticsearch-net,geofeedia/elasticsearch-net,geofeedia/elasticsearch-net,CSGOpenSource/elasticsearch-net,KodrAus/elasticsearch-net,cstlaurent/elasticsearch-net,gayancc/elasticsearch-net,azubanov/elasticsearch-net,jonyadamit/elasticsearch-net,junlapong/elasticsearch-net
src/CodeGeneration/CodeGeneration.LowLevelClient/Views/IElasticsearchClient.Generated.cshtml
src/CodeGeneration/CodeGeneration.LowLevelClient/Views/IElasticsearchClient.Generated.cshtml
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using Elasticsearch.Net.Connection; ///Generated File Please Do Not Edit Manually namespace Elasticsearch.Net { ///<summary> ///Raw operations with elasticsearch ///<pre> ///This file is automatically generated from https://github.com/elasticsearch/elasticsearch-rest-api-spec ///</pre> ///<pre> ///Generated of commit @Model.Commit ///</pre> ///</summary> public partial interface IElasticsearchClient { //IConnection Connection { get; } //IConnectionConfigurationValues Settings { get; } //IElasticsearchSerializer Serializer { get; } @foreach(var kv in Model.Endpoints) { var identifier = kv.Key; var endpoint = kv.Value; foreach(var method in endpoint.GetCsharpMethods()) { <text>///<summary>Represents a @method.HttpMethod on @method.Path ///<para></para>Returns: @Raw(method.ReturnDescription) ///<para>See also: @method.Documentation</para> ///</summary> @foreach (var part in method.Parts) { <text>@Raw("///<param name=\""+part.Name+"\">")@part.Description@Raw("</param>")</text> } @Raw(@"///<param name=""requestParameters""> ///Optional function to specify any additional request parameters ///<para>Querystring values, connection configuration specific to this request, deserialization state.</para> ///</param>") @Raw("///<returns>"+method.ReturnDescription) ///@Raw("</returns>") @Raw(method.ReturnType) @(method.FullName)@(Raw(method.ReturnTypeGeneric))(@Raw(method.Arguments)); </text> } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using Elasticsearch.Net.Connection; ///Generated File Please Do Not Edit Manually namespace Elasticsearch.Net { ///<summary> ///Raw operations with elasticsearch ///<pre> ///This file is automatically generated from https://github.com/elasticsearch/elasticsearch-rest-api-spec ///</pre> ///<pre> ///Generated of commit @Model.Commit ///</pre> ///</summary> public interface IElasticsearchClient { //IConnection Connection { get; } //IConnectionConfigurationValues Settings { get; } //IElasticsearchSerializer Serializer { get; } @foreach(var kv in Model.Endpoints) { var identifier = kv.Key; var endpoint = kv.Value; foreach(var method in endpoint.GetCsharpMethods()) { <text>///<summary>Represents a @method.HttpMethod on @method.Path ///<para></para>Returns: @Raw(method.ReturnDescription) ///<para>See also: @method.Documentation</para> ///</summary> @foreach (var part in method.Parts) { <text>@Raw("///<param name=\""+part.Name+"\">")@part.Description@Raw("</param>")</text> } @Raw(@"///<param name=""requestParameters""> ///Optional function to specify any additional request parameters ///<para>Querystring values, connection configuration specific to this request, deserialization state.</para> ///</param>") @Raw("///<returns>"+method.ReturnDescription) ///@Raw("</returns>") @Raw(method.ReturnType) @(method.FullName)@(Raw(method.ReturnTypeGeneric))(@Raw(method.Arguments)); </text> } } } }
apache-2.0
C#
51e946e81892111970604dfef8b4df520ac91cb9
Add Epsilon within Within in TestKitSampleTest.cs
simonlaroche/akka.net,simonlaroche/akka.net
docs/examples/DocsExamples/Testkit/TestKitSampleTest.cs
docs/examples/DocsExamples/Testkit/TestKitSampleTest.cs
using System; using Akka.Actor; using Akka.TestKit.Xunit2; using Xunit; namespace DocsExamples.Testkit { public class SomeActor : ReceiveActor { IActorRef target = null; public SomeActor() { Receive<string>(s => s.Equals("hello"), (message) => { Sender.Tell("world", Self); if (target != null) target.Forward(message); }); Receive<IActorRef>(actorRef => { target = actorRef; Sender.Tell("done"); }); } } public class TestKitSampleTest : TestKit { private TimeSpan EpsilonValueForWithins => new TimeSpan(0, 0, 1); // https://github.com/akkadotnet/akka.net/issues/2130 [Fact] public void Test() { var subject = this.Sys.ActorOf<SomeActor>(); var probe = this.CreateTestProbe(); //inject the probe by passing it to the test subject //like a real resource would be passing in production subject.Tell(probe.Ref, this.TestActor); ExpectMsg("done", TimeSpan.FromSeconds(1)); // the action needs to finish within 3 seconds Within(TimeSpan.FromSeconds(3), () => { subject.Tell("hello", this.TestActor); // This is a demo: would normally use expectMsgEquals(). // Wait time is bounded by 3-second deadline above. AwaitCondition(() => probe.HasMessages); // response must have been enqueued to us before probe ExpectMsg("world", TimeSpan.FromSeconds(0)); // check that the probe we injected earlier got the msg probe.ExpectMsg("hello", TimeSpan.FromSeconds(0)); Assert.Equal(TestActor, probe.Sender); // Will wait for the rest of the 3 seconds ExpectNoMsg(); }, EpsilonValueForWithins); } } }
using System; using Akka.Actor; using Akka.TestKit.Xunit2; using Xunit; namespace DocsExamples.Testkit { public class SomeActor : ReceiveActor { IActorRef target = null; public SomeActor() { Receive<string>(s => s.Equals("hello"), (message) => { Sender.Tell("world", Self); if (target != null) target.Forward(message); }); Receive<IActorRef>(actorRef => { target = actorRef; Sender.Tell("done"); }); } } public class TestKitSampleTest : TestKit { [Fact] public void Test() { var subject = this.Sys.ActorOf<SomeActor>(); var probe = this.CreateTestProbe(); //inject the probe by passing it to the test subject //like a real resource would be passing in production subject.Tell(probe.Ref, this.TestActor); ExpectMsg("done", TimeSpan.FromSeconds(1)); // the action needs to finish within 3 seconds Within(TimeSpan.FromSeconds(3), () => { subject.Tell("hello", this.TestActor); // This is a demo: would normally use expectMsgEquals(). // Wait time is bounded by 3-second deadline above. AwaitCondition(() => probe.HasMessages); // response must have been enqueued to us before probe ExpectMsg("world", TimeSpan.FromSeconds(0)); // check that the probe we injected earlier got the msg probe.ExpectMsg("hello", TimeSpan.FromSeconds(0)); Assert.Equal(TestActor, probe.Sender); // Will wait for the rest of the 3 seconds ExpectNoMsg(); }); } } }
apache-2.0
C#
09f2db031c845f021f02a93910afb47bfac12d98
Update PlayFabCommon.Build.cs (#539)
PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator,PlayFab/SDKGenerator
targets/UnrealMarketplacePlugin/source/PlayFab/Source/PlayFabCommon/PlayFabCommon.Build.cs
targets/UnrealMarketplacePlugin/source/PlayFab/Source/PlayFabCommon/PlayFabCommon.Build.cs
////////////////////////////////////////////////////// // Copyright (C) Microsoft. 2018. All rights reserved. ////////////////////////////////////////////////////// using UnrealBuildTool; using System.IO; public class PlayFabCommon : ModuleRules { public PlayFabCommon(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PublicIncludePaths.Add(Path.Combine(ModuleDirectory, "Public")); PrivateIncludePaths.Add(Path.Combine(ModuleDirectory, "Private")); PublicDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "Engine", "HTTP", "Json", "JsonUtilities", } ); if (Target.bBuildEditor == true) { PrivateDependencyModuleNames.AddRange(new string[] { "Settings" }); } BuildVersion Version; BuildVersion.TryRead(BuildVersion.GetDefaultFileName(), out Version); System.Console.WriteLine("MAJOR VERSION {0} MINOR VERSION {1}", Version.MajorVersion, Version.MinorVersion); PublicDefinitions.Add(string.Format("ENGINE_MAJOR_VERSION={0}", Version.MajorVersion)); PublicDefinitions.Add(string.Format("ENGINE_MINOR_VERSION={0}", Version.MinorVersion)); } }
////////////////////////////////////////////////////// // Copyright (C) Microsoft. 2018. All rights reserved. ////////////////////////////////////////////////////// using UnrealBuildTool; using System.IO; public class PlayFabCommon : ModuleRules { public PlayFabCommon(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PublicIncludePaths.Add(Path.Combine(ModuleDirectory, "Public")); PrivateIncludePaths.Add(Path.Combine(ModuleDirectory, "Private")); PublicDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "Engine", "HTTP", "Json", "JsonUtilities", } ); if (Target.bBuildEditor == true) { PrivateDependencyModuleNames.AddRange(new string[] { "Settings" }); } BuildVersion Version; BuildVersion.TryRead(BuildVersion.GetDefaultFileName(), out Version); System.Console.WriteLine("MAJOR VERSION {0} MINOR VERSION {1}", Version.MajorVersion, Version.MinorVersion); Definitions.Add(string.Format("ENGINE_MAJOR_VERSION={0}", Version.MajorVersion)); Definitions.Add(string.Format("ENGINE_MINOR_VERSION={0}", Version.MinorVersion)); } }
apache-2.0
C#
daeab0d7d333515399afe3e881949a9734566dd1
Leverage query syntax for cleaner Spawn implementation
weblinq/WebLinq,atifaziz/WebLinq,atifaziz/WebLinq,weblinq/WebLinq
src/Core/Sys/SysQuery.cs
src/Core/Sys/SysQuery.cs
#region Copyright (c) 2016 Atif Aziz. 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. // #endregion namespace WebLinq.Sys { using System; using System.Collections.Generic; using Mannex.Collections.Generic; public static class SysQuery { public static Query<string> Spawn(string path, string args) => Spawn(path, args, output => output, null); public static Query<KeyValuePair<T, string>> Spawn<T>(string path, string args, T stdoutKey, T stderrKey) => Spawn(path, args, stdout => stdoutKey.AsKeyTo(stdout), stderr => stderrKey.AsKeyTo(stderr)); public static Query<T> Spawn<T>(string path, string args, Func<string, T> stdoutSelector, Func<string, T> stderrSelector) => from s in Query.GetService<ISpawnService>() from e in s.Spawn(path, args, stdoutSelector, stderrSelector).ToQuery() select e; } }
#region Copyright (c) 2016 Atif Aziz. 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. // #endregion namespace WebLinq.Sys { using System; using System.Collections.Generic; using System.Linq; using Mannex.Collections.Generic; public static class SysQuery { public static Query<string> Spawn(string path, string args) => Spawn(path, args, output => output, null); public static Query<KeyValuePair<T, string>> Spawn<T>(string path, string args, T stdoutKey, T stderrKey) => Spawn(path, args, stdout => stdoutKey.AsKeyTo(stdout), stderr => stderrKey.AsKeyTo(stderr)); public static Query<T> Spawn<T>(string path, string args, Func<string, T> stdoutSelector, Func<string, T> stderrSelector) => Query.Create(context => QueryResult.Create(from e in context.Eval((ISpawnService s) => s.Spawn(path, args, stdoutSelector, stderrSelector)) select QueryResultItem.Create(context, e))); } }
apache-2.0
C#
45348c2f7de3d784c6898ae31120f74e4a9d072a
add WhereIf single parameters. useful in mongoDB
SorenZ/Alamut
src/Alamut.Data/Linq/QueryExtensions.cs
src/Alamut.Data/Linq/QueryExtensions.cs
using System; using System.Linq; using System.Linq.Expressions; namespace Alamut.Data.Linq { /// <summary> /// IQueryable Helpers /// </summary> public static class QueryExtensions { /// <summary> /// 'Select' by condition before query executed in provider. /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="source">The source.</param> /// <param name="condition">the condition</param> /// <param name="trueExpression">The expression that will apply if <see cref="condition"/> is true.</param> /// <param name="falseExpression">The expression that will apply if <see cref="condition"/> is false.</param> /// <returns> /// filtered query /// </returns> public static IQueryable<TResult> SelectIf<TSource, TResult>( this IQueryable<TSource> source, bool condition, Expression<Func<TSource, TResult>> trueExpression, Expression<Func<TSource, TResult>> falseExpression) { return condition ? source.Select(trueExpression) : source.Select(falseExpression); } /// <summary> /// Conditional 'Where', decide about predicate before query executed in provider. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="condition">the condition</param> /// <param name="trueExpression">The expression that will apply if <see cref="condition"/> is true.</param> /// <param name="falseExpression">The expression that will apply if <see cref="condition"/> is false.</param> /// <returns> /// filtered query /// </returns> public static IQueryable<T> WhereIf<T>( this IQueryable<T> source, bool condition, Expression<Func<T, bool>> trueExpression, Expression<Func<T, bool>> falseExpression) { return condition ? source.Where(trueExpression) : source.Where(falseExpression); } /// <summary> /// conditional 'where', execute expressioin when condition is true /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="condition"></param> /// <param name="trueExpression"></param> /// <returns></returns> public static IQueryable<T> WhereIf<T>(this IQueryable<T> source, bool condition, Expression<Func<T, bool>> trueExpression) { return condition ? source.Where(trueExpression) : source; } } }
using System; using System.Linq; using System.Linq.Expressions; namespace Alamut.Data.Linq { /// <summary> /// IQueryable Helpers /// </summary> public static class QueryExtensions { /// <summary> /// 'Select' by condition before query executed in provider. /// </summary> /// <typeparam name="TSource">The type of the source.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="source">The source.</param> /// <param name="condition">the condition</param> /// <param name="trueExpression">The expression that will apply if <see cref="condition"/> is true.</param> /// <param name="falseExpression">The expression that will apply if <see cref="condition"/> is false.</param> /// <returns> /// filtered query /// </returns> public static IQueryable<TResult> SelectIf<TSource, TResult>( this IQueryable<TSource> source, bool condition, Expression<Func<TSource, TResult>> trueExpression, Expression<Func<TSource, TResult>> falseExpression) { return condition ? source.Select(trueExpression) : source.Select(falseExpression); } /// <summary> /// Conditional 'Where', decide about predicate before query executed in provider. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="condition">the condition</param> /// <param name="trueExpression">The expression that will apply if <see cref="condition"/> is true.</param> /// <param name="falseExpression">The expression that will apply if <see cref="condition"/> is false.</param> /// <returns> /// filtered query /// </returns> public static IQueryable<T> WhereIf<T>( this IQueryable<T> source, bool condition, Expression<Func<T, bool>> trueExpression, Expression<Func<T, bool>> falseExpression) { return condition ? source.Where(trueExpression) : source.Where(falseExpression); } } }
mit
C#
0bb5a612a7a60bb835d6c3cb83a338728d9fb853
Add description to AssemblyInfo
EnableSoftware/Enable.Common.Argument
src/Argument/Properties/AssemblyInfo.cs
src/Argument/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Enable.Common.Argument")] [assembly: AssemblyDescription("Enable.Common.Argument")] [assembly: AssemblyCompany("Enable · enable.com")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] [assembly: AssemblyVersion("1.0.*")]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Enable.Common.Argument")] [assembly: AssemblyCompany("Enable · enable.com")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] [assembly: AssemblyVersion("1.0.*")]
mit
C#
79837ded7ed3c80ab950851b49ea3c45661e5e41
use AppDomain root to locate the logs directory
mdavid/SuperSocket,mdavid/SuperSocket,mdavid/SuperSocket
mainline/Common/LogUtil.cs
mainline/Common/LogUtil.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; using log4net.Config; namespace SuperSocket.Common { public class LogUtil { private static ILogger m_logger; public static void Setup() { Setup(@"Config\log4net.config"); } public static void Setup(string log4netConfig) { if (!Path.IsPathRooted(log4netConfig)) log4netConfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, log4netConfig); XmlConfigurator.Configure(new FileInfo(log4netConfig)); m_logger = new Log4NetLogger(); } public static void Setup(ILogger logger) { m_logger = logger; } public static ILogger GetRootLogger() { return m_logger; } public static void LogError(Exception e) { if (m_logger != null) m_logger.LogError(e); } public static void LogError(string title, Exception e) { if (m_logger != null) m_logger.LogError(title, e); } public static void LogError(string message) { if (m_logger != null) m_logger.LogError(message); } public static void LogDebug(string message) { if (m_logger != null) m_logger.LogDebug(message); } public static void LogInfo(string message) { if (m_logger != null) m_logger.LogInfo(message); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using log4net.Config; namespace SuperSocket.Common { public class LogUtil { private static ILogger m_logger; public static void Setup() { Setup(@"Config\log4net.config"); } public static void Setup(string log4netConfig) { XmlConfigurator.Configure(new FileInfo(log4netConfig)); m_logger = new Log4NetLogger(); } public static void Setup(ILogger logger) { m_logger = logger; } public static ILogger GetRootLogger() { return m_logger; } public static void LogError(Exception e) { if (m_logger != null) m_logger.LogError(e); } public static void LogError(string title, Exception e) { if (m_logger != null) m_logger.LogError(title, e); } public static void LogError(string message) { if (m_logger != null) m_logger.LogError(message); } public static void LogDebug(string message) { if (m_logger != null) m_logger.LogDebug(message); } public static void LogInfo(string message) { if (m_logger != null) m_logger.LogInfo(message); } } }
apache-2.0
C#
42f2bc18e959f5fa1ebe2e3f93eb6d5e805a0206
Update run test endpoint name
DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,nabychan/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,jtbm37/omnisharp-roslyn,nabychan/omnisharp-roslyn,jtbm37/omnisharp-roslyn
src/OmniSharp.Abstractions/Endpoints.cs
src/OmniSharp.Abstractions/Endpoints.cs
using System.Threading.Tasks; using OmniSharp.Mef; namespace OmniSharp { public interface RequestHandler<TRequest, TResponse> : IRequestHandler { Task<TResponse> Handle(TRequest request); } public interface IAggregateResponse { IAggregateResponse Merge(IAggregateResponse response); } public interface IRequest { } public static class OmnisharpEndpoints { public const string GotoDefinition = "/gotodefinition"; public const string FindSymbols = "/findsymbols"; public const string UpdateBuffer = "/updatebuffer"; public const string ChangeBuffer = "/changebuffer"; public const string CodeCheck = "/codecheck"; public const string FilesChanged = "/filesChanged"; public const string FormatAfterKeystroke = "/formatAfterKeystroke"; public const string FormatRange = "/formatRange"; public const string CodeFormat = "/codeformat"; public const string Highlight = "/highlight"; public const string AutoComplete = "/autocomplete"; public const string FindImplementations = "/findimplementations"; public const string FindUsages = "/findusages"; public const string GotoFile = "/gotofile"; public const string GotoRegion = "/gotoregion"; public const string NavigateUp = "/navigateup"; public const string NavigateDown = "/navigatedown"; public const string TypeLookup = "/typelookup"; public const string GetCodeAction = "/getcodeactions"; public const string RunCodeAction = "/runcodeaction"; public const string Rename = "/rename"; public const string SignatureHelp = "/signatureHelp"; public const string MembersTree = "/currentfilemembersastree"; public const string MembersFlat = "/currentfilemembersasflat"; public const string TestCommand = "/gettestcontext"; public const string Metadata = "/metadata"; public const string PackageSource = "/packagesource"; public const string PackageSearch = "/packagesearch"; public const string PackageVersion = "/packageversion"; public const string WorkspaceInformation = "/projects"; public const string ProjectInformation = "/project"; public const string FixUsings = "/fixusings"; public const string CheckAliveStatus = "/checkalivestatus"; public const string CheckReadyStatus = "/checkreadystatus"; public const string StopServer = "/stopserver"; public static class V2 { public const string GetCodeActions = "/v2/getcodeactions"; public const string RunCodeAction = "/v2/runcodeaction"; } public const string GetTestStartInfo = "/v2/getteststartinfo"; public const string RunDotNetTest = "/v2/runtest"; } }
using System.Threading.Tasks; using OmniSharp.Mef; namespace OmniSharp { public interface RequestHandler<TRequest, TResponse> : IRequestHandler { Task<TResponse> Handle(TRequest request); } public interface IAggregateResponse { IAggregateResponse Merge(IAggregateResponse response); } public interface IRequest { } public static class OmnisharpEndpoints { public const string GotoDefinition = "/gotodefinition"; public const string FindSymbols = "/findsymbols"; public const string UpdateBuffer = "/updatebuffer"; public const string ChangeBuffer = "/changebuffer"; public const string CodeCheck = "/codecheck"; public const string FilesChanged = "/filesChanged"; public const string FormatAfterKeystroke = "/formatAfterKeystroke"; public const string FormatRange = "/formatRange"; public const string CodeFormat = "/codeformat"; public const string Highlight = "/highlight"; public const string AutoComplete = "/autocomplete"; public const string FindImplementations = "/findimplementations"; public const string FindUsages = "/findusages"; public const string GotoFile = "/gotofile"; public const string GotoRegion = "/gotoregion"; public const string NavigateUp = "/navigateup"; public const string NavigateDown = "/navigatedown"; public const string TypeLookup = "/typelookup"; public const string GetCodeAction = "/getcodeactions"; public const string RunCodeAction = "/runcodeaction"; public const string Rename = "/rename"; public const string SignatureHelp = "/signatureHelp"; public const string MembersTree = "/currentfilemembersastree"; public const string MembersFlat = "/currentfilemembersasflat"; public const string TestCommand = "/gettestcontext"; public const string Metadata = "/metadata"; public const string PackageSource = "/packagesource"; public const string PackageSearch = "/packagesearch"; public const string PackageVersion = "/packageversion"; public const string WorkspaceInformation = "/projects"; public const string ProjectInformation = "/project"; public const string FixUsings = "/fixusings"; public const string CheckAliveStatus = "/checkalivestatus"; public const string CheckReadyStatus = "/checkreadystatus"; public const string StopServer = "/stopserver"; public static class V2 { public const string GetCodeActions = "/v2/getcodeactions"; public const string RunCodeAction = "/v2/runcodeaction"; } public const string GetTestStartInfo = "/v2/getteststartinfo"; public const string RunDotNetTest = "/v2/rundotnettest"; } }
mit
C#
14a52479a2d23cd94fb0e0556eb5889e57e4963c
Use LD_TRUST_TOKEN as Mercurial password (#129)
sillsdev/LfMerge,sillsdev/LfMerge,sillsdev/LfMerge
src/LfMerge.Core/Actions/Infrastructure/ChorusHelper.cs
src/LfMerge.Core/Actions/Infrastructure/ChorusHelper.cs
// Copyright (c) 2016-2018 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using Autofac; using SIL.Network; using LfMerge.Core.Settings; using SIL.LCModel; using System.Web; namespace LfMerge.Core.Actions.Infrastructure { public class ChorusHelper { static ChorusHelper() { Username = "x"; Password = System.Environment.GetEnvironmentVariable("LD_TRUST_TOKEN") ?? "x"; } public virtual string GetSyncUri(ILfProject project) { var settings = MainClass.Container.Resolve<LfMergeSettings>(); if (!string.IsNullOrEmpty(settings.LanguageDepotRepoUri)) return settings.LanguageDepotRepoUri; var uriBldr = new UriBuilder(project.LanguageDepotProjectUri) { UserName = Username, Password = Password, Path = HttpUtility.UrlEncode(project.LanguageDepotProject.Identifier) }; return uriBldr.Uri.ToString(); } public int ModelVersion { get; private set; } public static void SetModelVersion(int modelVersion) { var chorusHelper = MainClass.Container.Resolve<ChorusHelper>(); chorusHelper.ModelVersion = modelVersion; } public static bool RemoteDataIsForDifferentModelVersion { get { var chorusHelper = MainClass.Container.Resolve<ChorusHelper>(); return chorusHelper.ModelVersion > 0 && chorusHelper.ModelVersion != LcmCache.ModelVersion; } } public static string Username { get; set; } public static string Password { get; set; } } }
// Copyright (c) 2016-2018 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using Autofac; using SIL.Network; using LfMerge.Core.Settings; using SIL.LCModel; using System.Web; namespace LfMerge.Core.Actions.Infrastructure { public class ChorusHelper { static ChorusHelper() { Username = "x"; Password = "x"; } public virtual string GetSyncUri(ILfProject project) { var settings = MainClass.Container.Resolve<LfMergeSettings>(); if (!string.IsNullOrEmpty(settings.LanguageDepotRepoUri)) return settings.LanguageDepotRepoUri; var uriBldr = new UriBuilder(project.LanguageDepotProjectUri) { UserName = Username, Password = Password, Path = HttpUtility.UrlEncode(project.LanguageDepotProject.Identifier) }; var trustToken = System.Environment.GetEnvironmentVariable("LD_TRUST_TOKEN"); if (!string.IsNullOrEmpty(trustToken)) { uriBldr.Query = $"trust_token={trustToken}"; } return uriBldr.Uri.ToString(); } public int ModelVersion { get; private set; } public static void SetModelVersion(int modelVersion) { var chorusHelper = MainClass.Container.Resolve<ChorusHelper>(); chorusHelper.ModelVersion = modelVersion; } public static bool RemoteDataIsForDifferentModelVersion { get { var chorusHelper = MainClass.Container.Resolve<ChorusHelper>(); return chorusHelper.ModelVersion > 0 && chorusHelper.ModelVersion != LcmCache.ModelVersion; } } public static string Username { get; set; } public static string Password { get; set; } } }
mit
C#
4b17c3f40c7f9839573384dfcaab854412b1c09f
Set version to 0.7.
strayfatty/ShowFeed,strayfatty/ShowFeed
src/ShowFeed/Properties/AssemblyInfo.cs
src/ShowFeed/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("ShowFeed")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ShowFeed")] [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("3b3f205e-4800-4725-bfa1-a68a4b1527bd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("0.7.0.0")] [assembly: AssemblyFileVersion("0.7.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("ShowFeed")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ShowFeed")] [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("3b3f205e-4800-4725-bfa1-a68a4b1527bd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("0.6.1.0")] [assembly: AssemblyFileVersion("0.6.1.0")]
mit
C#
9b4ee980862313ecc7325b44dc3cb146a1cc22b0
build fix for ecng update
StockSharp/StockSharp
Algo/Storages/Binary/BoardStateBinarySerializer.cs
Algo/Storages/Binary/BoardStateBinarySerializer.cs
namespace StockSharp.Algo.Storages.Binary { using System; using System.Collections.Generic; using System.IO; using System.Linq; using Ecng.Common; using Ecng.Collections; using StockSharp.Localization; using StockSharp.Messages; class BoardStateMetaInfo : BinaryMetaInfo { public BoardStateMetaInfo(DateTime date) : base(date) { } public override void Read(Stream stream) { base.Read(stream); ServerOffset = stream.Read<TimeSpan>(); ReadOffsets(stream); } public override void Write(Stream stream) { base.Write(stream); stream.WriteEx(ServerOffset); WriteOffsets(stream); } } class BoardStateBinarySerializer : BinaryMarketDataSerializer<BoardStateMessage, BoardStateMetaInfo> { public BoardStateBinarySerializer(IExchangeInfoProvider exchangeInfoProvider) : base(default, null, 200, MarketDataVersions.Version31, exchangeInfoProvider) { } protected override void OnSave(BitArrayWriter writer, IEnumerable<BoardStateMessage> messages, BoardStateMetaInfo metaInfo) { var isMetaEmpty = metaInfo.IsEmpty(); writer.WriteInt(messages.Count()); foreach (var msg in messages) { if (isMetaEmpty) { metaInfo.ServerOffset = msg.ServerTime.Offset; isMetaEmpty = false; } var lastOffset = metaInfo.LastServerOffset; metaInfo.LastTime = writer.WriteTime(msg.ServerTime, metaInfo.LastTime, LocalizedStrings.BoardInfo, true, true, metaInfo.ServerOffset, true, true, ref lastOffset); metaInfo.LastServerOffset = lastOffset; writer.WriteStringEx(msg.BoardCode); writer.WriteInt((int)msg.State); } } public override BoardStateMessage MoveNext(MarketDataEnumerator enumerator) { var reader = enumerator.Reader; var metaInfo = enumerator.MetaInfo; var message = new BoardStateMessage(); var prevTime = metaInfo.FirstTime; var lastOffset = metaInfo.FirstServerOffset; message.ServerTime = reader.ReadTime(ref prevTime, true, true, metaInfo.ServerOffset, true, true, ref lastOffset); metaInfo.FirstTime = prevTime; metaInfo.FirstServerOffset = lastOffset; message.BoardCode = reader.ReadStringEx(); message.State = (SessionStates)reader.ReadInt(); return message; } } }
namespace StockSharp.Algo.Storages.Binary { using System; using System.Collections.Generic; using System.IO; using System.Linq; using Ecng.Collections; using Ecng.Serialization; using StockSharp.Localization; using StockSharp.Messages; class BoardStateMetaInfo : BinaryMetaInfo { public BoardStateMetaInfo(DateTime date) : base(date) { } public override void Read(Stream stream) { base.Read(stream); ServerOffset = stream.Read<TimeSpan>(); ReadOffsets(stream); } public override void Write(Stream stream) { base.Write(stream); stream.WriteEx(ServerOffset); WriteOffsets(stream); } } class BoardStateBinarySerializer : BinaryMarketDataSerializer<BoardStateMessage, BoardStateMetaInfo> { public BoardStateBinarySerializer(IExchangeInfoProvider exchangeInfoProvider) : base(default, null, 200, MarketDataVersions.Version31, exchangeInfoProvider) { } protected override void OnSave(BitArrayWriter writer, IEnumerable<BoardStateMessage> messages, BoardStateMetaInfo metaInfo) { var isMetaEmpty = metaInfo.IsEmpty(); writer.WriteInt(messages.Count()); foreach (var msg in messages) { if (isMetaEmpty) { metaInfo.ServerOffset = msg.ServerTime.Offset; isMetaEmpty = false; } var lastOffset = metaInfo.LastServerOffset; metaInfo.LastTime = writer.WriteTime(msg.ServerTime, metaInfo.LastTime, LocalizedStrings.BoardInfo, true, true, metaInfo.ServerOffset, true, true, ref lastOffset); metaInfo.LastServerOffset = lastOffset; writer.WriteStringEx(msg.BoardCode); writer.WriteInt((int)msg.State); } } public override BoardStateMessage MoveNext(MarketDataEnumerator enumerator) { var reader = enumerator.Reader; var metaInfo = enumerator.MetaInfo; var message = new BoardStateMessage(); var prevTime = metaInfo.FirstTime; var lastOffset = metaInfo.FirstServerOffset; message.ServerTime = reader.ReadTime(ref prevTime, true, true, metaInfo.ServerOffset, true, true, ref lastOffset); metaInfo.FirstTime = prevTime; metaInfo.FirstServerOffset = lastOffset; message.BoardCode = reader.ReadStringEx(); message.State = (SessionStates)reader.ReadInt(); return message; } } }
apache-2.0
C#
1627bd0c18b18cf1042116e327b44a6a99e9ac76
Fix null check oversight in getting localized text
uulltt/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,plrusek/NitoriWare,Barleytree/NitoriWare
Assets/Scripts/Localization/LocalizationManager.cs
Assets/Scripts/Localization/LocalizationManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; public class LocalizationManager : MonoBehaviour { private const string NotFoundString = "LOCALIZED TEXT NOT FOUND"; public static LocalizationManager instance; [SerializeField] private string forceLanguage; private string language; private SerializedNestedStrings localizedText; public void Awake () { if (instance != null) { if (instance != this) Destroy(gameObject); return; } else instance = this; if (transform.parent == null) DontDestroyOnLoad(gameObject); language = (forceLanguage == "" ? Application.systemLanguage.ToString() : forceLanguage); loadLocalizedText("Languages/" + language + ""); } public void loadLocalizedText(string filename) { string filePath = Path.Combine(Application.streamingAssetsPath, filename); if (!File.Exists(filePath)) { filePath = filePath.Replace(language, "English"); Debug.Log("Language " + language + " not found. Using English"); language = "English"; } if (File.Exists(filePath)) { System.DateTime started = System.DateTime.Now; localizedText = SerializedNestedStrings.deserialize(File.ReadAllText(filePath)); System.TimeSpan timeElapsed = System.DateTime.Now - started; Debug.Log("Language " + language + " loaded successfully. Deserialization time: " + timeElapsed.TotalMilliseconds + "ms"); } else Debug.LogError("No English json found!"); } public string getLanguage() { return language; } public void setLanguage(string language) { //TODO make loading async and revisit this } public string getLocalizedValue(string key) { return (localizedText == null) ? "No language set" : getLocalizedValue(key, NotFoundString); } public string getLocalizedValue(string key, string defaultString) { if (localizedText == null) return defaultString; string value = (string)localizedText[key]; if (string.IsNullOrEmpty(value)) { Debug.LogWarning("Language " + getLanguage() + " does not have a value for key " + key); return defaultString; } value = value.Replace("\\n", "\n"); return value; } public string getLocalizedValueNoWarnings(string key, string defaultString) { if (localizedText == null) return defaultString; string value = (string)localizedText[key]; if (string.IsNullOrEmpty(value)) return defaultString; if (key.Split('.')[0].Equals("multiline")) value = value.Replace("\\n", "\n"); return value; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; public class LocalizationManager : MonoBehaviour { private const string NotFoundString = "LOCALIZED TEXT NOT FOUND"; public static LocalizationManager instance; [SerializeField] private string forceLanguage; private string language; private SerializedNestedStrings localizedText; public void Awake () { if (instance != null) { if (instance != this) Destroy(gameObject); return; } else instance = this; if (transform.parent == null) DontDestroyOnLoad(gameObject); language = (forceLanguage == "" ? Application.systemLanguage.ToString() : forceLanguage); loadLocalizedText("Languages/" + language + ""); } public void loadLocalizedText(string filename) { string filePath = Path.Combine(Application.streamingAssetsPath, filename); if (!File.Exists(filePath)) { filePath = filePath.Replace(language, "English"); Debug.Log("Language " + language + " not found. Using English"); language = "English"; } if (File.Exists(filePath)) { System.DateTime started = System.DateTime.Now; localizedText = SerializedNestedStrings.deserialize(File.ReadAllText(filePath)); System.TimeSpan timeElapsed = System.DateTime.Now - started; Debug.Log("Language " + language + " loaded successfully. Deserialization time: " + timeElapsed.TotalMilliseconds + "ms"); } else Debug.LogError("No English json found!"); } public string getLanguage() { return language; } public void setLanguage(string language) { //TODO make loading async and revisit this } public string getLocalizedValue(string key) { return (localizedText == null) ? "No language set" : getLocalizedValue(key, NotFoundString); } public string getLocalizedValue(string key, string defaultString) { if (localizedText == null) return defaultString; string value = (string)localizedText[key]; value = value.Replace("\\n", "\n"); if (string.IsNullOrEmpty(value)) { Debug.LogWarning("Language " + getLanguage() + " does not have a value for key " + key); return defaultString; } return value; } public string getLocalizedValueNoWarnings(string key, string defaultString) { if (localizedText == null) return defaultString; string value = (string)localizedText[key]; if (key.Split('.')[0].Equals("multiline")) value = value.Replace("\\n", "\n"); return string.IsNullOrEmpty(value) ? defaultString : value; } }
mit
C#
469f6a2188382c41c5f8e8a8eac72546d10dc3a2
Fix compilation strategy
binore/linterhub-cli,repometric/linterhub-cli,repometric/linterhub-cli,binore/linterhub-cli,repometric/linterhub-cli,binore/linterhub-cli
src/cli/Strategy/CatalogStrategy.cs
src/cli/Strategy/CatalogStrategy.cs
namespace Linterhub.Cli.Strategy { using System; using System.Linq; using Runtime; using Engine; using Engine.Exceptions; using Engine.Extensions; public class CatalogStrategy : IStrategy { public object Run(RunContext context, LinterFactory factory, LogManager log) { var catalog = GetCatalog(context, factory); var result = from record in factory.GetRecords().OrderBy(x => x.Name) let item = catalog.linters.FirstOrDefault(y => y.name == record.Name) select new { name = record.Name, description = item?.description, languages = item?.languages }; return result; } private Linters GetCatalog(RunContext context, LinterFactory factory) { try { return context.InputAwailable ? context.Input.DeserializeAsJson<Linters>() : new LinterhubWrapper(context).Info().DeserializeAsJson<Linters>(); } catch (Exception exception) { throw new LinterParseException(exception); } } } }
namespace Linterhub.Cli.Strategy { using System; using System.Linq; using Runtime; using Engine; using Engine.Exceptions; using Engine.Extensions; public class CatalogStrategy : IStrategy { public object Run(RunContext context, LinterFactory factory, LogManager log) { var catalog = GetCatalog(context, factory); var result = from record in factory.GetRecords().OrderBy(x => x.Name) let item = catalog.linters.FirstOrDefault(y => y.name == record.Name) select new { name = record.Name, description = item?.description, languages = item?.languages }; return result; } private Linters GetCatalog(RunContext context, LinterFactory factory) { try { return context.InputAwailable ? context.Input.DeserializeAsJson<Linters>() : new LinterhubWrapper(context, factory).Info().DeserializeAsJson<Linters>(); } catch (Exception exception) { throw new LinterParseException(exception); } } } }
mit
C#
66fafb301bf72c15c39a1fc72678a4ba9556888d
Switch to version 1.2.5
AtwooTM/Zebus,biarne-a/Zebus,Abc-Arbitrage/Zebus,rbouallou/Zebus
src/SharedVersionInfo.cs
src/SharedVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.2.5")] [assembly: AssemblyFileVersion("1.2.5")] [assembly: AssemblyInformationalVersion("1.2.5")]
using System.Reflection; [assembly: AssemblyVersion("1.2.4")] [assembly: AssemblyFileVersion("1.2.4")] [assembly: AssemblyInformationalVersion("1.2.4")]
mit
C#
1d096c35d1cf8e8c25896e055c3f678fd9d1ed9d
Remove unused timer
pardahlman/RawRabbit,northspb/RawRabbit
src/RawRabbit/Operations/Publisher.cs
src/RawRabbit/Operations/Publisher.cs
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using RabbitMQ.Client; using RabbitMQ.Client.Framing; using RawRabbit.Common; using RawRabbit.Configuration.Publish; using RawRabbit.Context; using RawRabbit.Context.Provider; using RawRabbit.Logging; using RawRabbit.Operations.Contracts; using RawRabbit.Serialization; namespace RawRabbit.Operations { public class Publisher<TMessageContext> : OperatorBase, IPublisher where TMessageContext : IMessageContext { private readonly IMessageContextProvider<TMessageContext> _contextProvider; private readonly ILogger _logger = LogManager.GetLogger<Publisher<TMessageContext>>(); public Publisher(IChannelFactory channelFactory, IMessageSerializer serializer, IMessageContextProvider<TMessageContext> contextProvider) : base(channelFactory, serializer) { _contextProvider = contextProvider; } public Task PublishAsync<T>(T message, Guid globalMessageId, PublishConfiguration config) { return _contextProvider .GetMessageContextAsync(globalMessageId) .ContinueWith(ctxTask => { var channel = ChannelFactory.GetChannel(); DeclareQueue(config.Queue, channel); DeclareExchange(config.Exchange, channel); var properties = new BasicProperties { MessageId = Guid.NewGuid().ToString(), Headers = new Dictionary<string, object> { { _contextProvider.ContextHeaderName, ctxTask.Result }, {PropertyHeaders.Sent, DateTime.UtcNow.ToString("u") } } }; channel.BasicPublish( exchange: config.Exchange.ExchangeName, routingKey: config.RoutingKey, basicProperties: properties, body: Serializer.Serialize(message) ); channel.Dispose(); }); } public override void Dispose() { _logger.LogDebug("Disposing Publisher"); base.Dispose(); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using RabbitMQ.Client; using RabbitMQ.Client.Framing; using RawRabbit.Common; using RawRabbit.Configuration.Publish; using RawRabbit.Context; using RawRabbit.Context.Provider; using RawRabbit.Logging; using RawRabbit.Operations.Contracts; using RawRabbit.Serialization; namespace RawRabbit.Operations { public class Publisher<TMessageContext> : OperatorBase, IPublisher where TMessageContext : IMessageContext { private readonly IMessageContextProvider<TMessageContext> _contextProvider; private readonly ThreadLocal<Timer> _timer; private readonly ILogger _logger = LogManager.GetLogger<Publisher<TMessageContext>>(); public Publisher(IChannelFactory channelFactory, IMessageSerializer serializer, IMessageContextProvider<TMessageContext> contextProvider) : base(channelFactory, serializer) { _contextProvider = contextProvider; _timer = new ThreadLocal<Timer>(); } public Task PublishAsync<T>(T message, Guid globalMessageId, PublishConfiguration config) { return _contextProvider .GetMessageContextAsync(globalMessageId) .ContinueWith(ctxTask => { var channel = ChannelFactory.GetChannel(); DeclareQueue(config.Queue, channel); DeclareExchange(config.Exchange, channel); var properties = new BasicProperties { MessageId = Guid.NewGuid().ToString(), Headers = new Dictionary<string, object> { { _contextProvider.ContextHeaderName, ctxTask.Result }, {PropertyHeaders.Sent, DateTime.UtcNow.ToString("u") } } }; channel.BasicPublish( exchange: config.Exchange.ExchangeName, routingKey: config.RoutingKey, basicProperties: properties, body: Serializer.Serialize(message) ); channel.Dispose(); }); } public override void Dispose() { _logger.LogDebug("Disposing Publisher"); base.Dispose(); _timer.Dispose(); } } }
mit
C#
0485d51b6c740092c0e01fb30f16a84695d9e16b
Tidy up comments
VladMukhitdinovLic/i18n,sms1991/i18n
src/i18n/Abstract/ITextLocalizer.cs
src/i18n/Abstract/ITextLocalizer.cs
namespace i18n { using System.Collections.Concurrent; /// <summary> /// Defines a service for retrieving localized text from a data source. /// </summary> public interface ITextLocalizer { /// <summary> /// Obtains dictionary of language tags (key = langtag string, value = LanguageTag instance) /// describing the set of Po-valid languages (that is, the languages for which one or more /// resource are defined). /// </summary> ConcurrentDictionary<string, LanguageTag> GetAppLanguages(); /// <summary> /// Looks up and returns localized text for a resource. /// </summary> /// <param name="msgid"> /// Specifies the msgid of the subject resource. /// Null if we are not interested in a particular resource but wish to know /// the best matching language for which ANY resources are available (one or more). /// </param> /// <param name="msgcomment"> /// Specifies the optional message comment value of the subject resource, or null/empty. /// </param> /// <param name="languages"> /// A list of language preferences, sorted in order of preference (most preferred first). /// </param> /// <param name="o_langtag"> /// On success, outputs a description of the language from which the resource was selected. /// </param> /// <param name="maxPasses"> /// 0 - allow exact match only /// 1 - allow exact match or default-region match only /// 2 - allow exact match or default-region match or script match only /// 3 - allow exact match or default-region match or script match or language match only /// 4 - allow exact match or default-region match or script match or language match only, or failing return the default language. /// -1 to set to most tolerant (i.e. 4). /// </param> /// <returns> /// When <paramref name="msgid"/> is set to non-null, returns either the sucessully-looked up localized string, or /// null if the lookup failed. /// When <paramref name="msgid"/> is set to null, returns "" to indicate a match to a PO-valid language was made /// (PO-valid meaning that one or more messages/resources are defined for that language), /// or null if no match was made. /// </returns> string GetText( string msgid, string msgcomment, LanguageItem[] languages, out LanguageTag o_langtag, int maxPasses = -1); } }
namespace i18n { using System.Collections.Concurrent; /// <summary> /// Defines a service for retrieving localized text from a data source. /// </summary> public interface ITextLocalizer { /// <summary> /// Obtains dictionary of language tags (key = langtag string, value = LanguageTag instance) /// describing the set of Po-valid languages, that is the languages for which one or more /// resource are defined. /// </summary> ConcurrentDictionary<string, LanguageTag> GetAppLanguages(); /// <summary> /// Looks up and returns localized text for a resource. /// </summary> /// <param name="msgid"> /// Specifies the msgid of the subject resource. /// Null if we are not interested in a particular resource but wish to know /// the best matching language for which ANY resources are available (one or more). /// </param> /// <param name="msgcomment"> /// Specifies the optional message comment value of the subject resource, or null/empty. /// </param> /// <param name="languages"> /// A list of language preferences, sorted in order or preference (most preferred first). /// </param> /// <param name="o_langtag"> /// On success, outputs a description of the language from which the resource was selected. /// </param> /// <param name="maxPasses"> /// 0 - allow exact match only /// 1 - allow exact match or default-region match only /// 2 - allow exact match or default-region match or script match only /// 3 - allow exact match or default-region match or script match or language match only /// 4 - allow exact match or default-region match or script match or language match only, or failing return the default language. /// -1 to set to most tolerant (i.e. 4). /// </param> /// <returns> /// When key is set to non-null, returns either the sucessully-looked up localized string, or /// null if the lookup failed. /// When key is set to null, returns "" to indicate a match to a PO-valid language was made /// (PO-valid meaning that one or more messages/resources are defined for that language), /// or null if no match was made. /// </returns> string GetText( string msgid, string msgcomment, LanguageItem[] languages, out LanguageTag o_langtag, int maxPasses = -1); } }
mit
C#
86817f3a70bcaa002a9cbd8aef4c5e35fd9e3df1
Update Program.cs
medhajoshi27/GitTest1
ConsoleApplication1/ConsoleApplication1/Program.cs
ConsoleApplication1/ConsoleApplication1/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //Code was Edited in Git Hub } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { } } }
mit
C#
50f650c47e3f6f25a54a34e217b76e7c6908884e
Fix Travis CI / AppVeyor
lecaillon/Evolve
test/Evolve.Test.Utilities/PostgreSqlDockerContainer.cs
test/Evolve.Test.Utilities/PostgreSqlDockerContainer.cs
using System.Runtime.InteropServices; namespace Evolve.Test.Utilities { public class PostgreSqlDockerContainer : IDockerContainer { private DockerContainer _container; public string Id => _container.Id; public string ExposedPort => "5432"; public string HostPort => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "5432" : "5433"; // AppVeyor: 5432 Travis CI: 5433 public string DbName => "my_database"; public string DbPwd => "Password12!"; // AppVeyor public string DbUser => "postgres"; public bool Start() { _container = new DockerContainerBuilder(new DockerContainerBuilderOptions { FromImage = "postgres", Tag = "alpine", Name = "postgres-evolve", Env = new[] { $"POSTGRES_PASSWORD={DbPwd}", $"POSTGRES_DB={DbName}" }, ExposedPort = $"{ExposedPort}/tcp", HostPort = HostPort }).Build(); return _container.Start(); } public void Remove() => _container.Remove(); public bool Stop() => _container.Stop(); public void Dispose() => _container.Dispose(); } }
using System.Runtime.InteropServices; namespace Evolve.Test.Utilities { public class PostgreSqlDockerContainer : IDockerContainer { private DockerContainer _container; public string Id => _container.Id; public string ExposedPort => "5432"; public string HostPort => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "3306" : "3307"; // AppVeyor: 5432 Travis CI: 5433 public string DbName => "my_database"; public string DbPwd => "Password12!"; // AppVeyor public string DbUser => "postgres"; public bool Start() { _container = new DockerContainerBuilder(new DockerContainerBuilderOptions { FromImage = "postgres", Tag = "alpine", Name = "postgres-evolve", Env = new[] { $"POSTGRES_PASSWORD={DbPwd}", $"POSTGRES_DB={DbName}" }, ExposedPort = $"{ExposedPort}/tcp", HostPort = HostPort }).Build(); return _container.Start(); } public void Remove() => _container.Remove(); public bool Stop() => _container.Stop(); public void Dispose() => _container.Dispose(); } }
mit
C#
1b8b5f95376013b35a4931818fb0d5107609cbf6
test suite: modifiers + minor docs
stephenlautier/.netcore-labs
experimental/Slabs.Experimental.Console/TestSuite.cs
experimental/Slabs.Experimental.Console/TestSuite.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Slabs.Experimental.ConsoleClient { public class TestSuiteBuilder { private readonly string _name; private List<List<TestEntity>> TestGroups { get; } private List<TestEntity> _currentParallelGroup; public TestSuiteBuilder(string name) { TestGroups = new List<List<TestEntity>>(); _name = name; } public TestSuite Build() { return new TestSuite(_name, TestGroups); } internal TestSuiteBuilder Add<TTest>(string name) where TTest : ITest, new() { var group = new List<TestEntity> { ToTestEntity(name, typeof(TTest)) }; TestGroups.Add(group); _currentParallelGroup = null; return this; } public TestSuiteBuilder AddParallel<TTest>(string name) where TTest : ITest, new() { var testEntity = ToTestEntity(name, typeof(TTest)); if (_currentParallelGroup == null) { var group = new List<TestEntity> { testEntity }; TestGroups.Add(group); _currentParallelGroup = group; } else { _currentParallelGroup.Add(testEntity); } return this; } static TestEntity ToTestEntity(string key, Type type) { return new TestEntity { Name = key, Type = type }; } } public class TestSuite { public string Name { get; } private readonly List<List<TestEntity>> _tests; public TestSuite(string name, List<List<TestEntity>> tests) { Name = name; _tests = tests; } public async Task Run() { Console.WriteLine($"[TestSuite] Running test suite '{Name}'"); foreach (var testGroup in _tests) { IList<Task> promises = new List<Task>(); foreach (var testEntity in testGroup) { Console.WriteLine($"[TestSuite] Running '{testEntity.Name}'"); var test = (ITest)Activator.CreateInstance(testEntity.Type); var task = test.Execute(); promises.Add(task); } // parallized test groups await Task.WhenAll(promises); } } } /// <summary> /// Describe a test unit. /// </summary> public interface ITest { /// <summary> /// Method which gets executed by the runner. /// </summary> /// <returns></returns> Task Execute(); } internal class TestEntity { public string Name { get; set; } public Type Type { get; set; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Slabs.Experimental.ConsoleClient { internal class TestSuiteBuilder { private readonly string _name; private List<List<TestEntity>> TestGroups { get; } private List<TestEntity> _currentParallelGroup; public TestSuiteBuilder(string name) { TestGroups = new List<List<TestEntity>>(); _name = name; } public TestSuite Build() { return new TestSuite(_name, TestGroups); } internal TestSuiteBuilder Add<TTest>(string name) where TTest : ITest, new() { var group = new List<TestEntity> { ToTestEntity(name, typeof(TTest)) }; TestGroups.Add(group); _currentParallelGroup = null; return this; } public TestSuiteBuilder AddParallel<TTest>(string name) where TTest : ITest, new() { var testEntity = ToTestEntity(name, typeof(TTest)); if (_currentParallelGroup == null) { var group = new List<TestEntity> { testEntity }; TestGroups.Add(group); _currentParallelGroup = group; } else { _currentParallelGroup.Add(testEntity); } return this; } static TestEntity ToTestEntity(string key, Type type) { return new TestEntity { Name = key, Type = type }; } } internal class TestSuite { public string Name { get; } private readonly List<List<TestEntity>> _tests; public TestSuite(string name, List<List<TestEntity>> tests) { Name = name; _tests = tests; } public async Task Run() { Console.WriteLine($"[TestSuite] Running test suite '{Name}'"); foreach (var testGroup in _tests) { IList<Task> promises = new List<Task>(); foreach (var testEntity in testGroup) { Console.WriteLine($"[TestSuite] Running '{testEntity.Name}'"); var test = (ITest)Activator.CreateInstance(testEntity.Type); var task = test.Execute(); promises.Add(task); } // parallized test groups await Task.WhenAll(promises); } } } internal interface ITest { Task Execute(); } internal class TestEntity { public string Name { get; set; } public Type Type { get; set; } } }
mit
C#
d62a05ac10f21a4488bf051c51dcc956327b5abb
add performance log type (#10616)
valfirst/selenium,titusfortner/selenium,HtmlUnit/selenium,HtmlUnit/selenium,titusfortner/selenium,titusfortner/selenium,SeleniumHQ/selenium,SeleniumHQ/selenium,joshmgrant/selenium,valfirst/selenium,titusfortner/selenium,valfirst/selenium,joshmgrant/selenium,SeleniumHQ/selenium,valfirst/selenium,HtmlUnit/selenium,joshmgrant/selenium,joshmgrant/selenium,SeleniumHQ/selenium,joshmgrant/selenium,SeleniumHQ/selenium,valfirst/selenium,HtmlUnit/selenium,joshmgrant/selenium,joshmgrant/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,HtmlUnit/selenium,HtmlUnit/selenium,joshmgrant/selenium,titusfortner/selenium,valfirst/selenium,titusfortner/selenium,valfirst/selenium,joshmgrant/selenium,HtmlUnit/selenium,titusfortner/selenium,SeleniumHQ/selenium,titusfortner/selenium,HtmlUnit/selenium,joshmgrant/selenium,valfirst/selenium,HtmlUnit/selenium,valfirst/selenium,SeleniumHQ/selenium,joshmgrant/selenium,SeleniumHQ/selenium,titusfortner/selenium,valfirst/selenium,SeleniumHQ/selenium,titusfortner/selenium,titusfortner/selenium,valfirst/selenium,SeleniumHQ/selenium
dotnet/src/webdriver/LogType.cs
dotnet/src/webdriver/LogType.cs
// <copyright file="LogType.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> namespace OpenQA.Selenium { /// <summary> /// Class containing names of common log types. /// </summary> public static class LogType { /// <summary> /// Log messages from the client language bindings. /// </summary> public static readonly string Client = "client"; /// <summary> /// Logs from the current WebDriver instance. /// </summary> public static readonly string Driver = "driver"; /// <summary> /// Logs from the browser. /// </summary> public static readonly string Browser = "browser"; /// <summary> /// Logs from the server. /// </summary> public static readonly string Server = "server"; /// <summary> /// Profiling logs. /// </summary> public static readonly string Profiler = "profiler"; /// <summary> /// Performance logs. /// </summary> public static readonly string Performance = "performance"; } }
// <copyright file="LogType.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> namespace OpenQA.Selenium { /// <summary> /// Class containing names of common log types. /// </summary> public static class LogType { /// <summary> /// Log messages from the client language bindings. /// </summary> public static readonly string Client = "client"; /// <summary> /// Logs from the current WebDriver instance. /// </summary> public static readonly string Driver = "driver"; /// <summary> /// Logs from the browser. /// </summary> public static readonly string Browser = "browser"; /// <summary> /// Logs from the server. /// </summary> public static readonly string Server = "server"; /// <summary> /// Profiling logs. /// </summary> public static readonly string Profiler = "profiler"; } }
apache-2.0
C#
19ddd2ad3bbfe56635ab1579e941e05db7498145
Update style.csss
troke12/troke12.github.com,troke12/troke12.github.com,troke12/troke12.github.com
style.cs
style.cs
/*====================================================*/ /* Copyright by Troke */ /*====================================================*/ body { background-color: #FFFF00; background: url(https://github.com/troke12/trokewebsite/blob/master/images/The-Night-Sky-Wallpaper.jpg?raw=true) top center no-repeat; background-size: cover; color: #000000; font-size: 13px; margin: 0; padding: 0; } p { font-size:13px; position:center; font-style:normal; font-family:Verdana; color: #FFFFFF; } .html-marquee { height:200px; width:400px; font-family:Verdana; font-size:14px; color:#FFFFFF; } #Logo { border-width: 0; position:absolute; left:498px; top:243px; width:336px; height:44px; z-index:1; } #menu { border: 0px #9370DB solid; background-color: transparent; position:absolute; left:498px; top:320px; width:336px; height:100px; text-align:center; z-index:3; } #menu ul { list-style-type: none; margin: 0; padding: 0; } #menu li { float: left; margin: 0; padding: 0px 0px 0px 0px; width: 33.33%; } #menu a { display: block; float: left; color: #FFFFFF; border: 0px #000000 solid; background-color: #6A5ACD; background-image: none; font-family: Verdana; font-size: 13px; font-weight: bold; font-style: normal; text-decoration: none; width: 84.26%; height: 30px; padding: 0px 8px 0px 5px; vertical-align: middle; line-height: 30px; text-align: center; -moz-box-shadow: 2px 1px 9px #000000; -webkit-box-shadow: 2px 1px 9px #000000; box-shadow: 2px 1px 9px #000000; } #menu li:hover a, #menu a:hover { color: #D3D3D3; background-color: #7B68EE; background-image: none; border: 0px #000000 solid; } #menu li.firstmain { padding-left: 0px; } #menu li.lastmain { padding-right: 0px; } #menu br { clear: both; font-size: 1px; height: 0; line-height: 0; }
/*====================================================*/ /* Copyright by Troke */ /*====================================================*/ body { background-color: #FFFF00; background: url(images/The-Night-Sky-Wallpaper.jpg) top center no-repeat; background-size: cover; color: #000000; font-size: 13px; margin: 0; padding: 0; } p { font-size:13px; position:center; font-style:normal; font-family:Verdana; color: #FFFFFF; } .html-marquee { height:200px; width:400px; font-family:Verdana; font-size:14px; color:#FFFFFF; } #Logo { border-width: 0; position:absolute; left:498px; top:243px; width:336px; height:44px; z-index:1; } #menu { border: 0px #9370DB solid; background-color: transparent; position:absolute; left:498px; top:320px; width:336px; height:100px; text-align:center; z-index:3; } #menu ul { list-style-type: none; margin: 0; padding: 0; } #menu li { float: left; margin: 0; padding: 0px 0px 0px 0px; width: 33.33%; } #menu a { display: block; float: left; color: #FFFFFF; border: 0px #000000 solid; background-color: #6A5ACD; background-image: none; font-family: Verdana; font-size: 13px; font-weight: bold; font-style: normal; text-decoration: none; width: 84.26%; height: 30px; padding: 0px 8px 0px 5px; vertical-align: middle; line-height: 30px; text-align: center; -moz-box-shadow: 2px 1px 9px #000000; -webkit-box-shadow: 2px 1px 9px #000000; box-shadow: 2px 1px 9px #000000; } #menu li:hover a, #menu a:hover { color: #D3D3D3; background-color: #7B68EE; background-image: none; border: 0px #000000 solid; } #menu li.firstmain { padding-left: 0px; } #menu li.lastmain { padding-right: 0px; } #menu br { clear: both; font-size: 1px; height: 0; line-height: 0; }
mit
C#
7d03fb84169f9965387ec058e0d00d4e72cceaee
Add xmldoc to RomanisableString class
peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework
osu.Framework/Localisation/RomanisableString.cs
osu.Framework/Localisation/RomanisableString.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 osu.Framework.Configuration; #nullable enable namespace osu.Framework.Localisation { /// <summary> /// A string that has a romanised fallback to allow a better experience for users that potentially can't read the original script. /// See <see cref="FrameworkSetting.ShowUnicode"/>, which can toggle the display of romanised variants. /// </summary> public class RomanisableString { /// <summary> /// The string in its original script. May be null. /// </summary> public readonly string Original; /// <summary> /// The romanised version of the string. May be null. /// </summary> public readonly string Romanised; /// <summary> /// Construct a new romanisable string. /// </summary> /// <param name="original">The string in its original script. If null, the <paramref name="romanised"/> version will always be used.</param> /// <param name="romanised">The romanised version of the string. If null, the <paramref name="original"/> version will always be used.</param> public RomanisableString(string original, string romanised) { Romanised = romanised; Original = original; } /// <summary> /// Get the best match for this string based on a user preference for which should be displayed. /// </summary> /// <param name="preferUnicode">Whether to prefer the unicode (aka original) version where available.</param> /// <returns>The best match for the provided criteria.</returns> public string GetPreferred(bool preferUnicode) { if (string.IsNullOrEmpty(Romanised)) return Original; if (string.IsNullOrEmpty(Original)) return Romanised; return preferUnicode ? Original : Romanised; } public override string ToString() => GetPreferred(false); } }
// 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 namespace osu.Framework.Localisation { /// <summary> /// A string that has variations in Unicode and Romanised form. /// </summary> public class RomanisableString { public readonly string Romanised; public readonly string Unicode; public RomanisableString(string unicode, string romanised) { Romanised = romanised; Unicode = unicode; } public string GetPreferred(bool preferUnicode) { if (string.IsNullOrEmpty(Romanised)) return Unicode; if (string.IsNullOrEmpty(Unicode)) return Romanised; return preferUnicode ? Unicode : Romanised; } public override string ToString() => GetPreferred(false); } }
mit
C#
f23dba05d700493772903e93e5971b4e4a106b8c
Add Render to IRuntimeElement interface, useful for lower level engines that expect explicit draw calls
craigomatic/IMML
src/Imml.Runtime/IRuntimeElement.cs
src/Imml.Runtime/IRuntimeElement.cs
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Imml.Runtime { public interface IRuntimeElement<T> : IDisposable { /// <summary> /// Gets the parent of this element /// </summary> ImmlElement Parent { get; } T Node { get; } /// <summary> /// Calculate any layout changes that need to be applied to the <see cref="T"/> /// </summary> /// <returns></returns> void ApplyLayout(); /// <summary> /// Acquire any resources this element is dependent on for load /// </summary> /// <returns></returns> Task AcquireResourcesAsync(); /// <summary> /// Load the resource for this element, all resources required should have been already retrieved by <see cref="AcquireResourcesAsync"/> /// </summary> /// <param name="parentNode"></param> /// <returns></returns> T Load(T parentNode); /// <summary> /// Perform any tasks that need to occur to render the <see cref="T"/> /// </summary> void Render(); } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Imml.Runtime { public interface IRuntimeElement<T> : IDisposable { /// <summary> /// Gets the parent of this element /// </summary> ImmlElement Parent { get; } T Node { get; } /// <summary> /// Calculate any layout changes that need to be applied to the <see cref="T"/> /// </summary> /// <returns></returns> void ApplyLayout(); /// <summary> /// Acquire any resources this element is dependent on for load /// </summary> /// <returns></returns> Task AcquireResourcesAsync(); /// <summary> /// Load the resource for this element, all resources required should have been already retrieved by <see cref="AcquireResourcesAsync"/> /// </summary> /// <param name="parentNode"></param> /// <returns></returns> T Load(T parentNode); } }
mit
C#
134ac2dd369c6ce20bc02facb0ee6b2baf0daf27
Update Assembly Infos
Dexiom/Dexiom.EPPlusExporter
Dexiom.EPPlusExporter/Properties/AssemblyInfo.cs
Dexiom.EPPlusExporter/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("Dexiom.EPPlusExporter")] [assembly: AssemblyDescription("A very simple, yet incredibly powerfull library to generate Excel documents out of objects, arrays, lists, collections, etc.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Dexiom")] [assembly: AssemblyProduct("Dexiom.EPPlusExporter")] [assembly: AssemblyCopyright("© Consultation Dexiom inc.")] [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("9a52c50c-f868-4838-8a5e-562a5dda4707")] // 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")]
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("Dexiom.EPPlusExporter")] [assembly: AssemblyDescription("A very simple, yet incredibly powerfull library to generate Excel documents out of objects, arrays, lists, collections, etc.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Consultation Dexiom inc.")] [assembly: AssemblyProduct("Dexiom.EPPlusExporter")] [assembly: AssemblyCopyright("© Consultation Dexiom inc.")] [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("9a52c50c-f868-4838-8a5e-562a5dda4707")] // 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")]
mit
C#
11710d09fb74e6d863bcd13532ac77b90f48e9c2
Add an RS5 prerelease build
File-New-Project/EarTrumpet
EarTrumpet/Extensions/OperatingSystemExtensions.cs
EarTrumpet/Extensions/OperatingSystemExtensions.cs
using System; namespace EarTrumpet.Extensions { public enum OSVersions : int { RS3 = 16299, RS4 = 17134, RS5_Prerelease = 17723, } public static class OperatingSystemExtensions { public static bool IsAtLeast(this OperatingSystem os, OSVersions version) { return os.Version.Build >= (int)version; } } }
using System; namespace EarTrumpet.Extensions { public enum OSVersions : int { RS3 = 16299, RS4 = 17134, } public static class OperatingSystemExtensions { public static bool IsAtLeast(this OperatingSystem os, OSVersions version) { return os.Version.Build >= (int)version; } } }
mit
C#
b8e4573c134f70dae72015595cab4719755f1a8c
Add documentation
David-Desmaisons/EasyActor
EasyActor/DispatcherManagers/IDispatcherManager.cs
EasyActor/DispatcherManagers/IDispatcherManager.cs
using System; using Concurrent; using EasyActor.Options; namespace EasyActor.DispatcherManagers { /// <summary> /// Dispatcher manager /// </summary> public interface IDispatcherManager : IAsyncDisposable { /// <summary> /// true if the Dispatcher should be released /// </summary> bool DisposeDispatcher { get; } /// <summary> /// Actor factory typr /// </summary> ActorFactorType Type { get; } /// <summary> /// Returns a consumable Dispatcher /// </summary> /// <returns></returns> ICancellableDispatcher GetDispatcher(); } }
using System; using Concurrent; using EasyActor.Options; namespace EasyActor.DispatcherManagers { public interface IDispatcherManager : IAsyncDisposable { bool DisposeDispatcher { get; } ActorFactorType Type { get; } ICancellableDispatcher GetDispatcher(); } }
mit
C#
56b9acfd0daa405e872bda30adbbae1e51626a8e
Set domain on cookie to match ARR v3
envoyat/Envoy.ArrCookieRestorer
Envoy.ArrCookieRestorer/ArrCookieRestorerModule.cs
Envoy.ArrCookieRestorer/ArrCookieRestorerModule.cs
using System.Configuration; using System.Text.RegularExpressions; using System.Web; namespace Envoy.ArrCookieRestorer { // Concept based on http://improve.dk/blog/2009/12/09/fixing-flash-bugs-by-intercepting-iis-application-request-routing-cookies public sealed class ArrCookieRestorerModule : IHttpModule { readonly static string cookieName; readonly static string queryStringName; readonly static Regex regex; static ArrCookieRestorerModule() { var config = (ArrCookieRestorerSection)ConfigurationManager.GetSection("arrCookieRestorer"); cookieName = config.CookieName; queryStringName = config.QueryStringName; regex = new Regex(cookieName + "=[0-9a-f]+;?", RegexOptions.Compiled); } public void Dispose() { } public void Init(HttpApplication context) { context.BeginRequest += (sender, e) => { try { var application = sender as HttpApplication; if (application != null) { var request = application.Request; var response = application.Response; if (request != null && response != null) { Restore(new HttpRequestWrapper(request), new HttpResponseWrapper(response)); } } } catch { } }; } public static void Restore(HttpRequestBase request, HttpResponseBase response) { string serverHash = request.QueryString[queryStringName]; if (serverHash != null) { string cookieHeader = request.Headers["Cookie"]; string cookieValue = cookieName + "=" + serverHash; // Modifying request.Cookies doesn't work if (cookieHeader != null) { if (cookieHeader.Contains(cookieName + "=")) { cookieHeader = regex.Replace(cookieHeader, cookieValue + ";"); } else { cookieHeader += "; " + cookieValue; } request.Headers["Cookie"] = cookieHeader; } else { request.Headers.Add("Cookie", cookieValue); } // response.Cookies also updates request.Cookies, which may have other implications, so we set the raw cookie response.Headers.Add("Set-Cookie", cookieName + "=" + serverHash + ";Path=" + request.ApplicationPath + ";Domain=" + request.Url.Host); } } } }
using System.Configuration; using System.Text.RegularExpressions; using System.Web; namespace Envoy.ArrCookieRestorer { // Concept based on http://improve.dk/blog/2009/12/09/fixing-flash-bugs-by-intercepting-iis-application-request-routing-cookies public sealed class ArrCookieRestorerModule : IHttpModule { readonly static string cookieName; readonly static string queryStringName; readonly static Regex regex; static ArrCookieRestorerModule() { var config = (ArrCookieRestorerSection)ConfigurationManager.GetSection("arrCookieRestorer"); cookieName = config.CookieName; queryStringName = config.QueryStringName; regex = new Regex(cookieName + "=[0-9a-f]+;?", RegexOptions.Compiled); } public void Dispose() { } public void Init(HttpApplication context) { context.BeginRequest += (sender, e) => { try { var application = sender as HttpApplication; if (application != null) { var request = application.Request; var response = application.Response; if (request != null && response != null) { Restore(new HttpRequestWrapper(request), new HttpResponseWrapper(response)); } } } catch { } }; } public static void Restore(HttpRequestBase request, HttpResponseBase response) { string serverHash = request.QueryString[queryStringName]; if (serverHash != null) { string cookieHeader = request.Headers["Cookie"]; string cookieValue = cookieName + "=" + serverHash; // Modifying request.Cookies doesn't work if (cookieHeader != null) { if (cookieHeader.Contains(cookieName + "=")) { cookieHeader = regex.Replace(cookieHeader, cookieValue + ";"); } else { cookieHeader += "; " + cookieValue; } request.Headers["Cookie"] = cookieHeader; } else { request.Headers.Add("Cookie", cookieValue); } // response.Cookies also updates request.Cookies, which may have other implications, so we set the raw cookie response.Headers.Add("Set-Cookie", cookieName + "=" + serverHash + ";Path=" + request.ApplicationPath); } } } }
mit
C#
a89f16ab70c7d8129e7bebf28ca95a9bd31cde46
Add Unit tests for IEnumerable<BranchTree>.GetAllChildren()
WolfVR/git-tfs,allansson/git-tfs,kgybels/git-tfs,jeremy-sylvis-tmg/git-tfs,codemerlin/git-tfs,allansson/git-tfs,bleissem/git-tfs,TheoAndersen/git-tfs,kgybels/git-tfs,bleissem/git-tfs,hazzik/git-tfs,codemerlin/git-tfs,NathanLBCooper/git-tfs,git-tfs/git-tfs,modulexcite/git-tfs,pmiossec/git-tfs,NathanLBCooper/git-tfs,jeremy-sylvis-tmg/git-tfs,andyrooger/git-tfs,guyboltonking/git-tfs,modulexcite/git-tfs,guyboltonking/git-tfs,WolfVR/git-tfs,adbre/git-tfs,steveandpeggyb/Public,vzabavnov/git-tfs,PKRoma/git-tfs,TheoAndersen/git-tfs,hazzik/git-tfs,guyboltonking/git-tfs,jeremy-sylvis-tmg/git-tfs,NathanLBCooper/git-tfs,TheoAndersen/git-tfs,adbre/git-tfs,allansson/git-tfs,bleissem/git-tfs,adbre/git-tfs,modulexcite/git-tfs,hazzik/git-tfs,allansson/git-tfs,hazzik/git-tfs,steveandpeggyb/Public,kgybels/git-tfs,TheoAndersen/git-tfs,steveandpeggyb/Public,codemerlin/git-tfs,WolfVR/git-tfs
GitTfsTest/Core/TfsInterop/BranchExtensionsTest.cs
GitTfsTest/Core/TfsInterop/BranchExtensionsTest.cs
using System; using System.Collections.Generic; using System.Linq; using Rhino.Mocks; using Sep.Git.Tfs.Core.TfsInterop; using Xunit; namespace Sep.Git.Tfs.Test.Core.TfsInterop { public class BranchExtensionsTest { [Fact] public void AllChildrenAlwaysReturnsAnEnumerable() { IEnumerable<BranchTree> result = ((BranchTree) null).GetAllChildren(); Assert.NotNull(result); Assert.Empty(result); } private BranchTree CreateBranchTree(string tfsPath, BranchTree parent = null) { var branchObject = MockRepository.GenerateStub<IBranchObject>(); branchObject.Stub(m => m.Path).Return(tfsPath); var branchTree = new BranchTree(branchObject); if(parent != null) parent.ChildBranches.Add(branchTree); return branchTree; } [Fact] public void WhenGettingChildrenOfTopBranch_ThenReturnAllTheChildren() { var trunk = CreateBranchTree("$/Project/Trunk"); var branch1 = CreateBranchTree("$/Project/Branch1", trunk); var branch2 = CreateBranchTree("$/Project/Branch2", trunk); var branch3 = CreateBranchTree("$/Project/Branch3", trunk); IEnumerable<BranchTree> result = trunk.GetAllChildren(); Assert.NotNull(result); Assert.Equal(3, result.Count()); Assert.Equal(new List<BranchTree> { branch1, branch2, branch3 }, result); } [Fact] public void WhenGettingChildrenOfOneBranch_ThenReturnChildrenOfThisBranch() { var trunk = CreateBranchTree("$/Project/Trunk"); var branch1 = CreateBranchTree("$/Project/Branch1", trunk); var branch1_1 = CreateBranchTree("$/Project/Branch1.1", branch1); var branch1_2 = CreateBranchTree("$/Project/Branch1.2", branch1); var branch2 = CreateBranchTree("$/Project/Branch2", trunk); var branch3 = CreateBranchTree("$/Project/Branch3", trunk); IEnumerable<BranchTree> result = branch1.GetAllChildren(); Assert.NotNull(result); Assert.Equal(2, result.Count()); Assert.Equal(new List<BranchTree> { branch1_1, branch1_2 }, result); } } }
using System; using System.Collections.Generic; using Sep.Git.Tfs.Core.TfsInterop; using Xunit; namespace Sep.Git.Tfs.Test.Core.TfsInterop { public class BranchExtensionsTest { [Fact] public void AllChildrenAlwaysReturnsAnEnumerable() { IEnumerable<BranchTree> result = ((BranchTree) null).GetAllChildren(); Assert.NotNull(result); Assert.Empty(result); } } }
apache-2.0
C#