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 |
---|---|---|---|---|---|---|---|---|
e5d2885590b4a6143d9feaf0666ee1c516b0e099 | add one line of code | toannvqo/dnn_publish | Components/ProductController.cs | Components/ProductController.cs | using DotNetNuke.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Christoc.Modules.DNNModule1.Components
{
public class ProductController
{
public Product GetProduct(int productId)
{
Product p;
using (IDataContext ctx = DataContext.Instance())
{
Console.WriteLine("hello world");
Console.WriteLine("shshshshshs");
var rep = ctx.GetRepository<Product>();
p = rep.GetById(productId);
}
return p;
}
public IEnumerable<Product> getAll()
{
IEnumerable<Product> p;
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
p = rep.Get();
}
return p;
}
public void CreateProduct(Product p)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
rep.Insert(p);
}
}
public void DeleteProduct(int productId)
{
var p = GetProduct(productId);
DeleteProduct(p);
}
public void DeleteProduct(Product p)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
rep.Delete(p);
}
}
public void UpdateProduct(Product p)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
rep.Update(p);
}
}
}
} | using DotNetNuke.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Christoc.Modules.DNNModule1.Components
{
public class ProductController
{
public Product GetProduct(int productId)
{
Product p;
using (IDataContext ctx = DataContext.Instance())
{
Console.WriteLine("hello world");
var rep = ctx.GetRepository<Product>();
p = rep.GetById(productId);
}
return p;
}
public IEnumerable<Product> getAll()
{
IEnumerable<Product> p;
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
p = rep.Get();
}
return p;
}
public void CreateProduct(Product p)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
rep.Insert(p);
}
}
public void DeleteProduct(int productId)
{
var p = GetProduct(productId);
DeleteProduct(p);
}
public void DeleteProduct(Product p)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
rep.Delete(p);
}
}
public void UpdateProduct(Product p)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Product>();
rep.Update(p);
}
}
}
} | mit | C# |
8604aa165c1c23f58381a039ddbc3a83589719f1 | Add Value object with Id and Text | ktenman/netcore | Controllers/ValuesController.cs | Controllers/ValuesController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace netcore.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<Value> Get()
{
return new Value[] {
new Value { Id = 1, Text = "value1"},
new Value { Id = 2, Text = "value2"}
};
}
// GET api/values/5
[HttpGet("{id:int}")]
public Value Get(int id)
{
return new Value { Id = id, Text = "value" };
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
public class Value {
public int Id { get; set; }
public string Text { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace netcore.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
| apache-2.0 | C# |
a673cfd36003f893236c0bbbb836127b656aeef1 | Update SwitchStatementTemplateProvider.cs | controlflow/resharper-postfix | TemplateProviders/SwitchStatementTemplateProvider.cs | TemplateProviders/SwitchStatementTemplateProvider.cs | using System.Collections.Generic;
using JetBrains.Annotations;
using JetBrains.ReSharper.ControlFlow.PostfixCompletion.LookupItems;
using JetBrains.ReSharper.Feature.Services.Lookup;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Util;
namespace JetBrains.ReSharper.ControlFlow.PostfixCompletion.TemplateProviders
{
// TODO: make it work over everything in force mode (do not check type)
[PostfixTemplateProvider(
templateName: "switch",
description: "Produces switch over integral/string type",
example: "switch (expr)")]
public class SwitchStatementTemplateProvider : IPostfixTemplateProvider
{
public void CreateItems(PostfixTemplateAcceptanceContext context, ICollection<ILookupItem> consumer)
{
foreach (var exprContext in context.Expressions)
{
if (!exprContext.CanBeStatement) continue;
var type = exprContext.Type;
if (!type.IsResolved) continue;
if (type.IsPredefinedIntegral() || type.IsEnumType())
{
consumer.Add(new LookupItem(exprContext));
break;
}
}
}
private sealed class LookupItem : KeywordStatementPostfixLookupItem<ISwitchStatement>
{
public LookupItem([NotNull] PrefixExpressionContext context)
: base("switch", context) { }
protected override string Template
{
get { return "switch(expr)"; }
}
// switch statement can't be without braces
protected override ISwitchStatement CreateStatement(CSharpElementFactory factory)
{
var template = Template + "{" + CaretMarker + ";}";
return (ISwitchStatement) factory.CreateStatement(template);
}
protected override void PlaceExpression(
ISwitchStatement statement, ICSharpExpression expression, CSharpElementFactory factory)
{
statement.Condition.ReplaceBy(expression);
}
}
}
}
| using System.Collections.Generic;
using JetBrains.Annotations;
using JetBrains.ReSharper.ControlFlow.PostfixCompletion.LookupItems;
using JetBrains.ReSharper.Feature.Services.Lookup;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Util;
namespace JetBrains.ReSharper.ControlFlow.PostfixCompletion.TemplateProviders
{
[PostfixTemplateProvider(
templateName: "switch",
description: "Produces switch over integral/string type",
example: "switch (expr)")]
public class SwitchStatementTemplateProvider : IPostfixTemplateProvider
{
public void CreateItems(PostfixTemplateAcceptanceContext context, ICollection<ILookupItem> consumer)
{
foreach (var exprContext in context.Expressions)
{
if (!exprContext.CanBeStatement) continue;
var type = exprContext.Type;
if (!type.IsResolved) continue;
if (type.IsPredefinedIntegral() || type.IsEnumType())
{
consumer.Add(new LookupItem(exprContext));
break;
}
}
}
private sealed class LookupItem : KeywordStatementPostfixLookupItem<ISwitchStatement>
{
public LookupItem([NotNull] PrefixExpressionContext context)
: base("switch", context) { }
protected override string Template
{
get { return "switch(expr)"; }
}
// switch statement can't be without braces
protected override ISwitchStatement CreateStatement(CSharpElementFactory factory)
{
var template = Template + "{" + CaretMarker + ";}";
return (ISwitchStatement) factory.CreateStatement(template);
}
protected override void PlaceExpression(
ISwitchStatement statement, ICSharpExpression expression, CSharpElementFactory factory)
{
statement.Condition.ReplaceBy(expression);
}
}
}
} | mit | C# |
c3ed51c6fd819f9ae65a77dd288e2ecbfddb3215 | Revert log changes | madelson/MedallionShell | MedallionShell/Log.cs | MedallionShell/Log.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Medallion.Shell
{
internal static class Log
{
[Conditional("TESTING")]
public static void WriteLine(string format, params object[] args)
{
var text = string.Format("{0:h:m:ss.fff}: ", DateTime.Now) + string.Format(format, args);
using (var fs = new FileStream("log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (var writer = new StreamWriter(fs))
{
writer.WriteLine(text);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Medallion.Shell
{
internal static class Log
{
// TODO REVERT CHANGES
[Conditional("TESTING")]
public static void WriteLine(string format, params object[] args)
{
Console.WriteLine(format, args);
//var text = string.Format("{0:h:m:ss.fff}: ", DateTime.Now) + string.Format(format, args);
//using (var fs = new FileStream("log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
//using (var writer = new StreamWriter(fs))
//{
// writer.WriteLine(text);
//}
}
}
}
| mit | C# |
e615d283c909e97a6e9765cf231010f92a824692 | Fix name conflict | rockfordlhotka/csla,JasonBock/csla,jonnybee/csla,rockfordlhotka/csla,MarimerLLC/csla,MarimerLLC/csla,jonnybee/csla,jonnybee/csla,MarimerLLC/csla,JasonBock/csla,JasonBock/csla,rockfordlhotka/csla | Source/Csla.test/DataPortal/DataPortalExceptionTest.cs | Source/Csla.test/DataPortal/DataPortalExceptionTest.cs | using System;
using Csla;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Csla.Test.DataPortal
{
[TestClass]
public class DataPortalExceptionTests
{
[TestMethod]
[TestCategory("SkipWhenLiveUnitTesting")]
public void ChildInnerExceptionFlowsFromDataPortal()
{
try
{
var bo = EditableRoot1.New();
bo.Save();
}
catch (DataPortalException e)
{
Assert.IsInstanceOfType(e.BusinessException, typeof(InvalidOperationException));
}
}
}
[Serializable]
public class EditableRoot1 : BusinessBase<EditableRoot1>
{
public static readonly PropertyInfo<EditableChild1> ChildProperty =
RegisterProperty<EditableChild1>(c => c.Child);
private EditableRoot1()
{
/* Require use of factory methods */
}
public EditableChild1 Child
{
get { return GetProperty(ChildProperty); }
private set { LoadProperty(ChildProperty, value); }
}
public static EditableRoot1 New()
{
return Csla.DataPortal.Create<EditableRoot1>();
}
[RunLocal]
protected override void DataPortal_Create()
{
using (BypassPropertyChecks)
{
Child = EditableChild1.New();
}
base.DataPortal_Create();
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (BypassPropertyChecks)
{
FieldManager.UpdateChildren(this);
}
}
}
[Serializable]
public class EditableChild1 : BusinessBase<EditableChild1>
{
#region Factory Methods
internal static EditableChild1 New()
{
return Csla.DataPortal.CreateChild<EditableChild1>();
}
private EditableChild1()
{
/* Require use of factory methods */
}
#endregion
#region Data Access
protected override void Child_Create()
{
using (BypassPropertyChecks)
{
}
base.Child_Create();
}
private void Child_Insert(object parent)
{
using (BypassPropertyChecks)
{
throw new InvalidOperationException("Insert not allowed");
}
}
#endregion
}
} | using System;
using Csla;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Csla.Test.DataPortal
{
[TestClass]
public class DataPortalExceptionTests
{
[TestMethod]
[TestCategory("SkipWhenLiveUnitTesting")]
public void ChildInnerExceptionFlowsFromDataPortal()
{
try
{
var bo = EditableRoot1.New();
bo.Save();
}
catch (DataPortalException e)
{
Assert.IsInstanceOfType(e.BusinessException, typeof(InvalidOperationException));
}
}
}
[Serializable]
public class EditableRoot1 : BusinessBase<EditableRoot1>
{
public static readonly PropertyInfo<EditableChild1> ChildProperty =
RegisterProperty<EditableChild1>(c => c.Child);
private EditableRoot1()
{
/* Require use of factory methods */
}
public EditableChild1 Child
{
get { return GetProperty(ChildProperty); }
private set { LoadProperty(ChildProperty, value); }
}
public static EditableRoot1 New()
{
return DataPortal.Create<EditableRoot1>();
}
[RunLocal]
protected override void DataPortal_Create()
{
using (BypassPropertyChecks)
{
Child = EditableChild1.New();
}
base.DataPortal_Create();
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (BypassPropertyChecks)
{
FieldManager.UpdateChildren(this);
}
}
}
[Serializable]
public class EditableChild1 : BusinessBase<EditableChild1>
{
#region Factory Methods
internal static EditableChild1 New()
{
return DataPortal.CreateChild<EditableChild1>();
}
private EditableChild1()
{
/* Require use of factory methods */
}
#endregion
#region Data Access
protected override void Child_Create()
{
using (BypassPropertyChecks)
{
}
base.Child_Create();
}
private void Child_Insert(object parent)
{
using (BypassPropertyChecks)
{
throw new InvalidOperationException("Insert not allowed");
}
}
#endregion
}
} | mit | C# |
c23f604f3ef9e3fbe035e26c932fc4486c958baf | Set TTL for prefix to infinity rn | Daniele122898/SoraBot-v2,Daniele122898/SoraBot-v2 | SoraBot/SoraBot.Services/Guilds/PrefixService.cs | SoraBot/SoraBot.Services/Guilds/PrefixService.cs | using System;
using System.Threading.Tasks;
using SoraBot.Data.Repositories.Interfaces;
using SoraBot.Services.Cache;
namespace SoraBot.Services.Guilds
{
public class PrefixService : IPrefixService
{
public const string CACHE_PREFIX = "prfx:";
// public const short CACHE_TTL_MINS = 60;
private readonly ICacheService _cacheService;
private readonly IGuildRepository _guildRepo;
public PrefixService(ICacheService cacheService, IGuildRepository guildRepo)
{
_cacheService = cacheService;
_guildRepo = guildRepo;
}
public async Task<string> GetPrefix(ulong id)
{
string idStr = CACHE_PREFIX + id.ToString();
return await _cacheService.GetOrSetAndGetAsync(idStr,
async () => await _guildRepo.GetGuildPrefix(id).ConfigureAwait(false) ?? "$"
).ConfigureAwait(false);
}
public async Task<bool> SetPrefix(ulong id, string prefix)
{
// Let's set it in the DB. And if it succeeds we'll also add it to our cache
if (!await _guildRepo.SetGuildPrefix(id, prefix).ConfigureAwait(false))
return false;
// Update the Cache
string idStr = CACHE_PREFIX + id.ToString();
_cacheService.Set(idStr, prefix);
return true;
}
}
} | using System;
using System.Threading.Tasks;
using SoraBot.Data.Repositories.Interfaces;
using SoraBot.Services.Cache;
namespace SoraBot.Services.Guilds
{
public class PrefixService : IPrefixService
{
public const string CACHE_PREFIX = "prfx:";
public const short CACHE_TTL_MINS = 60;
private readonly ICacheService _cacheService;
private readonly IGuildRepository _guildRepo;
public PrefixService(ICacheService cacheService, IGuildRepository guildRepo)
{
_cacheService = cacheService;
_guildRepo = guildRepo;
}
public async Task<string> GetPrefix(ulong id)
{
string idStr = CACHE_PREFIX + id.ToString();
return await _cacheService.GetOrSetAndGetAsync(idStr,
async () => await _guildRepo.GetGuildPrefix(id).ConfigureAwait(false) ?? "$",
TimeSpan.FromMinutes(CACHE_TTL_MINS)).ConfigureAwait(false);
}
public async Task<bool> SetPrefix(ulong id, string prefix)
{
// Let's set it in the DB. And if it succeeds we'll also add it to our cache
if (!await _guildRepo.SetGuildPrefix(id, prefix).ConfigureAwait(false))
return false;
// Update the Cache
string idStr = CACHE_PREFIX + id.ToString();
_cacheService.Set(idStr, prefix, TimeSpan.FromMinutes(CACHE_TTL_MINS));
return true;
}
}
} | agpl-3.0 | C# |
9a04410f0a93866a7f0a88c80c368f9d1b427065 | Use case sensitive cache for Undefined result | rexm/Handlebars.Net,rexm/Handlebars.Net | source/Handlebars/UndefinedBindingResult.cs | source/Handlebars/UndefinedBindingResult.cs | using System;
using System.Diagnostics;
using HandlebarsDotNet.Collections;
using HandlebarsDotNet.EqualityComparers;
using HandlebarsDotNet.Runtime;
namespace HandlebarsDotNet
{
[DebuggerDisplay("undefined")]
public class UndefinedBindingResult : IEquatable<UndefinedBindingResult>
{
private static readonly LookupSlim<string, GcDeferredValue<string, UndefinedBindingResult>, StringEqualityComparer> Cache
= new LookupSlim<string, GcDeferredValue<string, UndefinedBindingResult>, StringEqualityComparer>(new StringEqualityComparer(StringComparison.Ordinal));
public static UndefinedBindingResult Create(string value) => Cache.GetOrAdd(value, ValueFactory).Value;
private static readonly Func<string, GcDeferredValue<string, UndefinedBindingResult>> ValueFactory = s =>
{
return new GcDeferredValue<string, UndefinedBindingResult>(s, v => new UndefinedBindingResult(v));
};
public readonly string Value;
private UndefinedBindingResult(string value) => Value = value;
public override string ToString() => Value;
public bool Equals(UndefinedBindingResult other) => Value == other?.Value;
public override bool Equals(object obj) => obj is UndefinedBindingResult other && Equals(other);
public override int GetHashCode() => Value != null ? Value.GetHashCode() : 0;
}
}
| using System;
using System.Diagnostics;
using HandlebarsDotNet.Collections;
using HandlebarsDotNet.EqualityComparers;
using HandlebarsDotNet.Runtime;
namespace HandlebarsDotNet
{
[DebuggerDisplay("undefined")]
public class UndefinedBindingResult : IEquatable<UndefinedBindingResult>
{
private static readonly LookupSlim<string, GcDeferredValue<string, UndefinedBindingResult>, StringEqualityComparer> Cache
= new LookupSlim<string, GcDeferredValue<string, UndefinedBindingResult>, StringEqualityComparer>(new StringEqualityComparer(StringComparison.OrdinalIgnoreCase));
public static UndefinedBindingResult Create(string value) => Cache.GetOrAdd(value, ValueFactory).Value;
private static readonly Func<string, GcDeferredValue<string, UndefinedBindingResult>> ValueFactory = s =>
{
return new GcDeferredValue<string, UndefinedBindingResult>(s, v => new UndefinedBindingResult(v));
};
public readonly string Value;
private UndefinedBindingResult(string value) => Value = value;
public override string ToString() => Value;
public bool Equals(UndefinedBindingResult other) => Value == other?.Value;
public override bool Equals(object obj) => obj is UndefinedBindingResult other && Equals(other);
public override int GetHashCode() => Value != null ? Value.GetHashCode() : 0;
}
}
| mit | C# |
4f05e4f33342a66762afa12db6b7b9539eaaffd2 | fix broken System.Threading.Interlocked | dot42/api | System/Threading/Interlocked.cs | System/Threading/Interlocked.cs | using System.Runtime.CompilerServices;
namespace System.Threading
{
/// <summary>
/// This class is here mainly because Fody.PropertyChanged needs an implementation.
///
/// A proper implementation would let the dot42 compiler detect all accesses to
/// Interlocked, and on-the-fly replace all usages of interlocked fields with their
/// AtomicXXX counterparts.
/// </summary>
[Obsolete("please try not to use this class, since the implementation makes use of a lock, which of course defeats the whole purpose of a lighweight Interlocked. Use javas AtomicXXX instead. Please note that the compiler will make use of this class to implement events.")]
internal static class Interlocked
{
// NOTE: all calls to this class are managed by the compiler,
// no explicit locking is needed here.
public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class
{
T ret = location1;
if (location1 == comparand)
location1 = value;
return ret;
}
public static int Increment(ref Int32 obj)
{
return obj++;
}
public static int Decrement(ref Int32 obj)
{
return obj--;
}
public static Int64 Increment(ref Int64 obj)
{
return obj++;
}
public static Int64 Decrement(ref Int64 obj)
{
return obj--;
}
}
}
| namespace System.Threading
{
/// <summary>
/// This class is here to provide compatibility with existing implementations.
/// best would be to let the dot42 compiler detect all accesses to Interlocked,
/// and on-the-fly replace all usages of interlocked fields with their AtomicXXX
/// counterparts.
/// </summary>
[Obsolete("please try not to use this class, since the implementation makes use of a global lock atm, which of course defeats the whole purpose of a lighweight Interlocked. please note that the compiler will make use of this class to implement events.")]
public static class Interlocked
{
private static readonly object _sync = new object();
//[Obsolete("please try not to use this class, since the implementation makes use of a global lock atm, which of course defeats the purpose of a lighweight Interlocked.")]
public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class
{
lock (_sync)
{
T ret = location1;
if (location1 == comparand)
location1 = value;
return ret;
}
}
//[Obsolete("please try not to use this class, since the implementation makes use of a global lock atm, which of course defeats the purpose of a lighweight Interlocked.")]
public static int Increment(ref Int32 obj)
{
lock (_sync)
{
return obj++;
}
}
//[Obsolete("please try not to use this class, since the implementation makes use of a global lock atm, which of course defeats the purpose of a lighweight Interlocked.")]
public static int Decrement(ref Int32 obj)
{
lock (_sync)
{
return obj--;
}
}
//[Obsolete("please try not to use this class, since the implementation makes use of a global lock atm, which of course defeats the purpose of a lighweight Interlocked.")]
public static Int64 Increment(ref Int64 obj)
{
lock (_sync)
{
return obj++;
}
}
[Obsolete("please try not to use this class, since the implementation makes use of a global lock atm, which of course defeats the purpose of a lighweight Interlocked.")]
public static Int64 Decrement(ref Int64 obj)
{
lock (_sync)
{
return obj--;
}
}
}
}
| apache-2.0 | C# |
70a0c1e23cfde4d229f8413c7de22910161b9b06 | Update LiteDbDatabaseProvider.cs | tiksn/TIKSN-Framework | TIKSN.Core/Data/LiteDB/LiteDbDatabaseProvider.cs | TIKSN.Core/Data/LiteDB/LiteDbDatabaseProvider.cs | using LiteDB;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
namespace TIKSN.Data.LiteDB
{
/// <summary>
/// Create LiteDB database
/// </summary>
public class LiteDbDatabaseProvider : ILiteDbDatabaseProvider
{
private readonly IConfigurationRoot _configuration;
private readonly string _connectionStringKey;
private readonly IFileProvider _fileProvider;
public LiteDbDatabaseProvider(IConfigurationRoot configuration, string connectionStringKey,
IFileProvider fileProvider = null)
{
this._configuration = configuration;
this._connectionStringKey = connectionStringKey;
this._fileProvider = fileProvider;
}
/// <summary>
/// Creates LiteDB database with mapper
/// </summary>
/// <param name="mapper">Mapper</param>
/// <returns></returns>
public LiteDatabase GetDatabase(BsonMapper mapper)
{
var connectionString =
new ConnectionString(this._configuration.GetConnectionString(this._connectionStringKey));
if (this._fileProvider != null)
{
connectionString.Filename = this._fileProvider.GetFileInfo(connectionString.Filename).PhysicalPath;
}
return new LiteDatabase(connectionString);
}
/// <summary>
/// Creates LiteDB database
/// </summary>
/// <returns></returns>
public LiteDatabase GetDatabase() => this.GetDatabase(null);
}
}
| using LiteDB;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
namespace TIKSN.Data.LiteDB
{
/// <summary>
/// Create LiteDB database
/// </summary>
public class LiteDbDatabaseProvider : ILiteDbDatabaseProvider
{
private readonly IConfigurationRoot _configuration;
private readonly string _connectionStringKey;
private readonly IFileProvider _fileProvider;
public LiteDbDatabaseProvider(IConfigurationRoot configuration, string connectionStringKey, IFileProvider fileProvider = null)
{
_configuration = configuration;
_connectionStringKey = connectionStringKey;
_fileProvider = fileProvider;
}
/// <summary>
/// Creates LiteDB database with mapper
/// </summary>
/// <param name="mapper">Mapper</param>
/// <returns></returns>
public LiteDatabase GetDatabase(BsonMapper mapper)
{
var connectionString = new ConnectionString(_configuration.GetConnectionString(_connectionStringKey));
if (_fileProvider != null)
connectionString.Filename = _fileProvider.GetFileInfo(connectionString.Filename).PhysicalPath;
return new LiteDatabase(connectionString);
}
/// <summary>
/// Creates LiteDB database
/// </summary>
/// <returns></returns>
public LiteDatabase GetDatabase()
{
return GetDatabase(null);
}
}
} | mit | C# |
5ac1114072c8c916cc9e18331a140b568ec96069 | Update version to 1.4.0 | TheOtherTimDuncan/TOTD-Mailer | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Other Tim Duncan")]
[assembly: AssemblyProduct("TOTD Mailer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
// 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.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
| using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Other Tim Duncan")]
[assembly: AssemblyProduct("TOTD Mailer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
// 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.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
| mit | C# |
fbd019222cec4b32238d3048ae132f9c4b565a8c | Increment Minor -> 0.5.0 | awseward/Bugsnag.NET,awseward/Bugsnag.NET | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("0.5.0.0")]
[assembly: AssemblyFileVersion("0.5.0.0")]
[assembly: AssemblyInformationalVersion("0.5.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("0.4.3.0")]
[assembly: AssemblyFileVersion("0.4.3.0")]
[assembly: AssemblyInformationalVersion("0.4.3")]
| mit | C# |
7c9bea719e0103feab08ac8e1f20de3f88854187 | Add XML comments to ILogConsumer | atata-framework/atata,atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata | src/Atata/Logging/ILogConsumer.cs | src/Atata/Logging/ILogConsumer.cs | namespace Atata
{
/// <summary>
/// Defines a method to log the event information.
/// </summary>
public interface ILogConsumer
{
/// <summary>
/// Logs the specified event information.
/// </summary>
/// <param name="eventInfo">The event information.</param>
void Log(LogEventInfo eventInfo);
}
}
| namespace Atata
{
public interface ILogConsumer
{
void Log(LogEventInfo eventInfo);
}
}
| apache-2.0 | C# |
740cec3782fa488b8a3cef1e0f3808ae89ad6e2d | Update JsonHelpers.cs | jordansjones/Cex.io-Api-Client | src/Cex.io/Helpers/JsonHelpers.cs | src/Cex.io/Helpers/JsonHelpers.cs | using System;
using System.Globalization;
using System.Linq;
namespace Nextmethod.Cex
{
internal static class JsonHelpers
{
internal static bool ContainsProperty(dynamic This, string name)
{
if (This == null || string.IsNullOrEmpty(name)) return false;
var jo = This as JsonObject;
if (jo != null)
{
return jo.ContainsKey(name);
}
var ja = This as JsonArray;
if (ja != null)
{
return false;
}
if ((This is bool) || Equals(This, bool.FalseString) || Equals(This, bool.TrueString)) return false;
return This.GetType().GetProperty(name);
}
internal static decimal ToDecimal(dynamic value)
{
if (value == null) return default(decimal);
var valueType = value.GetType();
if (valueType == typeof (decimal)) return value;
if (valueType == typeof (double)) return (decimal)value;
return Convert.ToDecimal(value);
}
}
}
| using System;
using System.Globalization;
using System.Linq;
namespace Nextmethod.Cex
{
internal static class JsonHelpers
{
internal static bool ContainsProperty(dynamic This, string name)
{
if (This == null || string.IsNullOrEmpty(name)) return false;
var jo = This as JsonObject;
if (jo != null)
{
return jo.ContainsKey(name);
}
var ja = This as JsonArray;
if (ja != null)
{
return false;
}
if ((This is bool) || Equals(This, bool.FalseString) || Equals(This, bool.TrueString)) return false;
return This.GetType().GetProperty(name);
}
internal static decimal ToDecimal(dynamic value)
{
if (value == null) return default(decimal);
var valueType = value.GetType();
if (valueType == typeof (decimal)) return value;
if (valueType == typeof (double)) return (decimal) value;
return decimal.Parse(value, CultureInfo.InvariantCulture);
}
}
}
| mit | C# |
11d0ca56de6c040b1b2f8223dfda54ffbe6bf99a | fix timespan in render demo. | jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,akrisiun/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex | samples/RenderDemo/Controls/LineBoundsDemoControl.cs | samples/RenderDemo/Controls/LineBoundsDemoControl.cs | using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Rendering.SceneGraph;
using Avalonia.Threading;
namespace RenderDemo.Controls
{
public class LineBoundsDemoControl : Control
{
static LineBoundsDemoControl()
{
AffectsRender<LineBoundsDemoControl>(AngleProperty);
}
public LineBoundsDemoControl()
{
var timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1 / 60.0);
timer.Tick += (sender, e) => Angle += Math.PI / 360;
timer.Start();
}
public static readonly StyledProperty<double> AngleProperty =
AvaloniaProperty.Register<LineBoundsDemoControl, double>(nameof(Angle));
public double Angle
{
get => GetValue(AngleProperty);
set => SetValue(AngleProperty, value);
}
public override void Render(DrawingContext drawingContext)
{
var lineLength = Math.Sqrt((100 * 100) + (100 * 100));
var diffX = LineBoundsHelper.CalculateAdjSide(Angle, lineLength);
var diffY = LineBoundsHelper.CalculateOppSide(Angle, lineLength);
var p1 = new Point(200, 200);
var p2 = new Point(p1.X + diffX, p1.Y + diffY);
var pen = new Pen(Brushes.Green, 20, lineCap: PenLineCap.Square);
var boundPen = new Pen(Brushes.Black);
drawingContext.DrawLine(pen, p1, p2);
drawingContext.DrawRectangle(boundPen, LineBoundsHelper.CalculateBounds(p1, p2, pen));
}
}
}
| using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Rendering.SceneGraph;
using Avalonia.Threading;
namespace RenderDemo.Controls
{
public class LineBoundsDemoControl : Control
{
static LineBoundsDemoControl()
{
AffectsRender<LineBoundsDemoControl>(AngleProperty);
}
public LineBoundsDemoControl()
{
var timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1 / 60);
timer.Tick += (sender, e) => Angle += Math.PI / 360;
timer.Start();
}
public static readonly StyledProperty<double> AngleProperty =
AvaloniaProperty.Register<LineBoundsDemoControl, double>(nameof(Angle));
public double Angle
{
get => GetValue(AngleProperty);
set => SetValue(AngleProperty, value);
}
public override void Render(DrawingContext drawingContext)
{
var lineLength = Math.Sqrt((100 * 100) + (100 * 100));
var diffX = LineBoundsHelper.CalculateAdjSide(Angle, lineLength);
var diffY = LineBoundsHelper.CalculateOppSide(Angle, lineLength);
var p1 = new Point(200, 200);
var p2 = new Point(p1.X + diffX, p1.Y + diffY);
var pen = new Pen(Brushes.Green, 20, lineCap: PenLineCap.Square);
var boundPen = new Pen(Brushes.Black);
drawingContext.DrawLine(pen, p1, p2);
drawingContext.DrawRectangle(boundPen, LineBoundsHelper.CalculateBounds(p1, p2, pen));
}
}
}
| mit | C# |
e2fa1670791ac311cf17822f0230eefa9e9f7e7b | Use SiteObject.Generate in main | lunet-io/lunet,lunet-io/lunet | src/LunetExe/Program.cs | src/LunetExe/Program.cs | using System;
using System.IO;
using System.IO.Compression;
using Lunet.Runtime;
using Microsoft.Extensions.Logging;
namespace Lunet
{
class Program
{
static void Main(string[] args)
{
var loggerFactory = new LoggerFactory().AddConsole(LogLevel.Trace);
var site = SiteFactory.FromFile(Path.Combine(Environment.CurrentDirectory, args[0]), loggerFactory);
//site.Initialize();
site.Generate();
site.Statistics.Dump((s => site.Info(s)));
}
}
}
| using System;
using System.IO;
using System.IO.Compression;
using Lunet.Runtime;
using Microsoft.Extensions.Logging;
namespace Lunet
{
class Program
{
static void Main(string[] args)
{
var loggerFactory = new LoggerFactory().AddConsole(LogLevel.Trace);
var site = SiteFactory.FromFile(Path.Combine(Environment.CurrentDirectory, args[0]), loggerFactory);
//site.Initialize();
site.Generator.Run();
site.Statistics.Dump((s => site.Info(s)));
}
}
}
| bsd-2-clause | C# |
3df3b1fc3010132a23ac447503f6592d32b745ee | Bump version number | timheuer/taglib-sharp-portable | src/TagLib.Shared/AssemblyInfo.cs | src/TagLib.Shared/AssemblyInfo.cs | //
// AssemblyInfo.cs.in: Contains flags to use for the assembly.
//
// Author:
// Brian Nickel ([email protected])
//
// Copyright (C) 2006-2007 Brian Nickel
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly:AssemblyVersion("2.2.0.0")]
[assembly:AssemblyTitle ("TagLib#")]
[assembly:AssemblyDescription ("A library for reading and writing audio metatags.")]
[assembly:AssemblyCopyright ("Copyright (c) 2006-2007 Brian Nickel. Copyright (c) 2009-2015 Other contributors")]
[assembly:AssemblyCompany ("")]
[assembly:AssemblyDelaySign(false)]
[assembly:CLSCompliant(false)]
| //
// AssemblyInfo.cs.in: Contains flags to use for the assembly.
//
// Author:
// Brian Nickel ([email protected])
//
// Copyright (C) 2006-2007 Brian Nickel
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly:AssemblyVersion("2.1.0.0")]
[assembly:AssemblyTitle ("TagLib#")]
[assembly:AssemblyDescription ("A library for reading and writing audio metatags.")]
[assembly:AssemblyCopyright ("Copyright (c) 2006-2007 Brian Nickel. Copyright (c) 2009-2010 Other contributors")]
[assembly:AssemblyCompany ("")]
[assembly:AssemblyDelaySign(false)]
[assembly:CLSCompliant(false)]
| lgpl-2.1 | C# |
5dcdda3ab33c2c0cf34283a194a1bb5a1b3df7e7 | Use generic host in sample | mrahhal/MR.AspNetCore.Jobs,mrahhal/MR.AspNetCore.Jobs | samples/Basic/Program.cs | samples/Basic/Program.cs | using System.Threading.Tasks;
using Basic.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MR.AspNetCore.Jobs;
namespace Basic
{
public class Program
{
public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
await host.StartJobsAsync();
using (var scope = host.Services.CreateScope())
{
var context = scope.ServiceProvider.GetService<AppDbContext>();
await context.Database.MigrateAsync();
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| using System.Threading.Tasks;
using Basic.Models;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MR.AspNetCore.Jobs;
namespace Basic
{
public class Program
{
public static async Task Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
await host.StartJobsAsync();
using (var scope = host.Services.CreateScope())
{
var context = scope.ServiceProvider.GetService<AppDbContext>();
await context.Database.MigrateAsync();
}
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| mit | C# |
c6a0fc322af5d758063bb77167f9a3a8f9cbcb1c | Fix TeamCity trace output | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/CI/TeamCity/TeamCityOutputSink.cs | source/Nuke.Common/CI/TeamCity/TeamCityOutputSink.cs | // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
using Nuke.Common.OutputSinks;
using Nuke.Common.Utilities;
namespace Nuke.Common.CI.TeamCity
{
[UsedImplicitly]
[ExcludeFromCodeCoverage]
internal class TeamCityOutputSink : AnsiColorOutputSink
{
private readonly TeamCity _teamCity;
public TeamCityOutputSink(TeamCity teamCity)
{
_teamCity = teamCity;
Console.OutputEncoding = Encoding.UTF8;
}
protected override string TraceCode => "90";
protected override string InformationCode => "36";
protected override string WarningCode => "33";
protected override string ErrorCode => "31";
protected override string SuccessCode => "32";
internal override IDisposable WriteBlock(string text)
{
var stopWatch = new Stopwatch();
return DelegateDisposable.CreateBracket(
() =>
{
_teamCity.OpenBlock(text);
stopWatch.Start();
},
() =>
{
_teamCity.CloseBlock(text);
_teamCity.AddStatisticValue(
$"NUKE_DURATION_{text.SplitCamelHumpsWithSeparator("_").ToUpper()}",
stopWatch.ElapsedMilliseconds.ToString());
stopWatch.Stop();
});
}
protected override bool EnableWriteErrors => false;
protected override void WriteWarning(string text, string details = null)
{
_teamCity.WriteWarning(text);
if (details != null)
_teamCity.WriteWarning(details);
}
protected override void ReportError(string text, string details = null)
{
_teamCity.WriteError(text);
if (details != null)
_teamCity.WriteError(details);
}
}
}
| // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
using Nuke.Common.OutputSinks;
using Nuke.Common.Utilities;
namespace Nuke.Common.CI.TeamCity
{
[UsedImplicitly]
[ExcludeFromCodeCoverage]
internal class TeamCityOutputSink : AnsiColorOutputSink
{
private readonly TeamCity _teamCity;
public TeamCityOutputSink(TeamCity teamCity)
{
_teamCity = teamCity;
Console.OutputEncoding = Encoding.UTF8;
}
protected override string TraceCode => "37";
protected override string InformationCode => "36";
protected override string WarningCode => "33";
protected override string ErrorCode => "31";
protected override string SuccessCode => "32";
internal override IDisposable WriteBlock(string text)
{
var stopWatch = new Stopwatch();
return DelegateDisposable.CreateBracket(
() =>
{
_teamCity.OpenBlock(text);
stopWatch.Start();
},
() =>
{
_teamCity.CloseBlock(text);
_teamCity.AddStatisticValue(
$"NUKE_DURATION_{text.SplitCamelHumpsWithSeparator("_").ToUpper()}",
stopWatch.ElapsedMilliseconds.ToString());
stopWatch.Stop();
});
}
protected override bool EnableWriteErrors => false;
protected override void WriteWarning(string text, string details = null)
{
_teamCity.WriteWarning(text);
if (details != null)
_teamCity.WriteWarning(details);
}
protected override void ReportError(string text, string details = null)
{
_teamCity.WriteError(text);
if (details != null)
_teamCity.WriteError(details);
}
}
}
| mit | C# |
238c998488c27f58c90a6c970feaaaeabde17c3e | change discount scope to price rule | vinhch/BizwebSharp | src/BizwebSharp/Enums/AuthorizationScope.cs | src/BizwebSharp/Enums/AuthorizationScope.cs | using System.Runtime.Serialization;
using BizwebSharp.Converters;
using Newtonsoft.Json;
namespace BizwebSharp.Enums
{
[JsonConverter(typeof(NullableEnumConverter<AuthorizationScope>))]
public enum AuthorizationScope
{
[EnumMember(Value = "read_content")] ReadContent,
[EnumMember(Value = "write_content")] WriteContent,
[EnumMember(Value = "read_themes")] ReadThemes,
[EnumMember(Value = "write_themes")] WriteThemes,
[EnumMember(Value = "read_products")] ReadProducts,
[EnumMember(Value = "write_products")] WriteProducts,
[EnumMember(Value = "read_customers")] ReadCustomers,
[EnumMember(Value = "write_customers")] WriteCustomers,
[EnumMember(Value = "read_orders")] ReadOrders,
[EnumMember(Value = "write_orders")] WriteOrders,
[EnumMember(Value = "read_script_tags")] ReadScriptTags,
[EnumMember(Value = "write_script_tags")] WriteScriptTags,
[EnumMember(Value = "read_fulfillments")] ReadFulfillments,
[EnumMember(Value = "write_fulfillments")] WriteFulfillments,
[EnumMember(Value = "read_shipping")] ReadShipping,
[EnumMember(Value = "write_shipping")] WriteShipping,
[EnumMember(Value = "read_analytics")] ReadAnalytics,
[EnumMember(Value = "read_users")] ReadUsers,
[EnumMember(Value = "write_users")] WriteUsers,
//[EnumMember(Value = "read_discounts")] ReadDiscounts,
//[EnumMember(Value = "write_discounts")] WriteDiscounts,
[EnumMember(Value = "read_price_rules")] ReadPriceRules,
[EnumMember(Value = "write_price_rules")] WritePriceRules
}
} | using System.Runtime.Serialization;
using BizwebSharp.Converters;
using Newtonsoft.Json;
namespace BizwebSharp.Enums
{
[JsonConverter(typeof(NullableEnumConverter<AuthorizationScope>))]
public enum AuthorizationScope
{
[EnumMember(Value = "read_content")] ReadContent,
[EnumMember(Value = "write_content")] WriteContent,
[EnumMember(Value = "read_themes")] ReadThemes,
[EnumMember(Value = "write_themes")] WriteThemes,
[EnumMember(Value = "read_products")] ReadProducts,
[EnumMember(Value = "write_products")] WriteProducts,
[EnumMember(Value = "read_customers")] ReadCustomers,
[EnumMember(Value = "write_customers")] WriteCustomers,
[EnumMember(Value = "read_orders")] ReadOrders,
[EnumMember(Value = "write_orders")] WriteOrders,
[EnumMember(Value = "read_script_tags")] ReadScriptTags,
[EnumMember(Value = "write_script_tags")] WriteScriptTags,
[EnumMember(Value = "read_fulfillments")] ReadFulfillments,
[EnumMember(Value = "write_fulfillments")] WriteFulfillments,
[EnumMember(Value = "read_shipping")] ReadShipping,
[EnumMember(Value = "write_shipping")] WriteShipping,
[EnumMember(Value = "read_analytics")] ReadAnalytics,
[EnumMember(Value = "read_users")] ReadUsers,
[EnumMember(Value = "write_users")] WriteUsers,
[EnumMember(Value = "read_discounts")] ReadDiscounts,
[EnumMember(Value = "write_discounts")] WriteDiscounts
}
} | mit | C# |
4e7c3e05e3222ff20e999d5407b082dcd535c1ef | Fix SideBar Ninject bindings. | alastairs/cgowebsite,alastairs/cgowebsite | src/CGO.Web/NinjectModules/SideBarModule.cs | src/CGO.Web/NinjectModules/SideBarModule.cs | using System.Web;
using System.Web.Mvc;
using CGO.Web.Controllers;
using Ninject.Modules;
using Ninject.Web.Common;
namespace CGO.Web.NinjectModules
{
public class SideBarModule : NinjectModule
{
public override void Load()
{
const string concertsControllerName = "Concerts";
Kernel.Bind<ISideBarFactory>()
.To<DefaultSideBarFactory>()
.InRequestScope();
Kernel.Rebind<ISideBarFactory>()
.To<ConcertsSideBarFactory>()
.When(_ => RequestedControllerIs(concertsControllerName))
.InRequestScope();
}
private static bool RequestedControllerIs(string controllerName)
{
const string controllerRouteKey = "controller";
var mvcHandler = (MvcHandler)HttpContext.Current.Handler;
var routeValues = mvcHandler.RequestContext.RouteData.Values;
object requestedControllerName;
if (routeValues.TryGetValue(controllerRouteKey, out requestedControllerName))
{
return requestedControllerName.ToString().ToUpper() == controllerName.ToUpper();
}
return false;
}
}
} | using CGO.Web.Controllers;
using Ninject.Modules;
using Ninject.Web.Common;
namespace CGO.Web.NinjectModules
{
public class SideBarModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<ISideBarFactory>()
.To<ConcertsSideBarFactory>()
.WhenInjectedInto<SideBarController>()
.InRequestScope();
Kernel.Bind<ISideBarFactory>().To<DefaultSideBarFactory>().InRequestScope();
}
}
} | mit | C# |
ed14f27456e02cfee34d3c29b450e72d9f90a691 | Check if the specified path is a physical or a virtual path | mono/nuget,indsoft/NuGet2,pratikkagda/nuget,jholovacs/NuGet,akrisiun/NuGet,oliver-feng/nuget,RichiCoder1/nuget-chocolatey,RichiCoder1/nuget-chocolatey,akrisiun/NuGet,oliver-feng/nuget,mrward/nuget,zskullz/nuget,ctaggart/nuget,GearedToWar/NuGet2,oliver-feng/nuget,jholovacs/NuGet,antiufo/NuGet2,jholovacs/NuGet,rikoe/nuget,chester89/nugetApi,rikoe/nuget,ctaggart/nuget,antiufo/NuGet2,mono/nuget,oliver-feng/nuget,dolkensp/node.net,chester89/nugetApi,OneGet/nuget,zskullz/nuget,indsoft/NuGet2,mrward/NuGet.V2,zskullz/nuget,dolkensp/node.net,jholovacs/NuGet,antiufo/NuGet2,mrward/nuget,oliver-feng/nuget,mrward/nuget,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,xoofx/NuGet,chocolatey/nuget-chocolatey,mrward/NuGet.V2,themotleyfool/NuGet,xoofx/NuGet,mrward/NuGet.V2,GearedToWar/NuGet2,mrward/nuget,jmezach/NuGet2,OneGet/nuget,rikoe/nuget,dolkensp/node.net,ctaggart/nuget,GearedToWar/NuGet2,chocolatey/nuget-chocolatey,kumavis/NuGet,indsoft/NuGet2,dolkensp/node.net,mrward/NuGet.V2,alluran/node.net,mrward/NuGet.V2,anurse/NuGet,pratikkagda/nuget,pratikkagda/nuget,ctaggart/nuget,indsoft/NuGet2,GearedToWar/NuGet2,xero-github/Nuget,kumavis/NuGet,chocolatey/nuget-chocolatey,alluran/node.net,atheken/nuget,mrward/nuget,jmezach/NuGet2,chocolatey/nuget-chocolatey,GearedToWar/NuGet2,jmezach/NuGet2,zskullz/nuget,alluran/node.net,mrward/NuGet.V2,pratikkagda/nuget,atheken/nuget,mrward/nuget,themotleyfool/NuGet,jholovacs/NuGet,alluran/node.net,mono/nuget,mono/nuget,antiufo/NuGet2,RichiCoder1/nuget-chocolatey,jmezach/NuGet2,GearedToWar/NuGet2,OneGet/nuget,antiufo/NuGet2,antiufo/NuGet2,pratikkagda/nuget,pratikkagda/nuget,oliver-feng/nuget,anurse/NuGet,chocolatey/nuget-chocolatey,RichiCoder1/nuget-chocolatey,indsoft/NuGet2,rikoe/nuget,xoofx/NuGet,xoofx/NuGet,jholovacs/NuGet,xoofx/NuGet,xoofx/NuGet,themotleyfool/NuGet,RichiCoder1/nuget-chocolatey,jmezach/NuGet2,indsoft/NuGet2,jmezach/NuGet2,OneGet/nuget | src/Server/Infrastructure/PackageUtility.cs | src/Server/Infrastructure/PackageUtility.cs | using System;
using System.Web;
using System.Web.Hosting;
using System.Configuration;
using System.IO;
namespace NuGet.Server.Infrastructure
{
public class PackageUtility
{
internal static string PackagePhysicalPath;
private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages");
static PackageUtility()
{
string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"];
if (string.IsNullOrEmpty(packagePath))
{
PackagePhysicalPath = DefaultPackagePhysicalPath;
}
else
{
if (Path.IsPathRooted(packagePath))
{
PackagePhysicalPath = packagePath;
}
else
{
PackagePhysicalPath = HostingEnvironment.MapPath(packagePath);
}
}
}
public static Uri GetPackageUrl(string path, Uri baseUri)
{
return new Uri(baseUri, GetPackageDownloadUrl(path));
}
private static string GetPackageDownloadUrl(string path)
{
return VirtualPathUtility.ToAbsolute("~/Packages/" + path);
}
}
}
| using System;
using System.Web;
using System.Web.Hosting;
using System.Configuration;
namespace NuGet.Server.Infrastructure
{
public class PackageUtility
{
internal static string PackagePhysicalPath;
private static string DefaultPackagePhysicalPath = HostingEnvironment.MapPath("~/Packages");
static PackageUtility()
{
string packagePath = ConfigurationManager.AppSettings["NuGetPackagePath"];
if (string.IsNullOrEmpty(packagePath))
{
PackagePhysicalPath = DefaultPackagePhysicalPath;
}
else
{
PackagePhysicalPath = packagePath;
}
}
public static Uri GetPackageUrl(string path, Uri baseUri)
{
return new Uri(baseUri, GetPackageDownloadUrl(path));
}
private static string GetPackageDownloadUrl(string path)
{
return VirtualPathUtility.ToAbsolute("~/Packages/" + path);
}
}
}
| apache-2.0 | C# |
ada26c5ccd7ffe1b4709310bc62f16fd3cb13ddb | Change id type from uint to ulong | Aux/NTwitch,Aux/NTwitch | src/NTwitch.Core/Entities/IEntity.cs | src/NTwitch.Core/Entities/IEntity.cs | namespace NTwitch
{
public interface IEntity
{
ITwitchClient Client { get; }
ulong Id { get; }
}
}
| namespace NTwitch
{
public interface IEntity
{
ITwitchClient Client { get; }
uint Id { get; }
}
}
| mit | C# |
c02a6f7235c780644ac1aa841d85d1ae1dcd1e81 | Comment updates | AtaS/SectionJS.NET | SectionJS.NET/SectionJSModel.cs | SectionJS.NET/SectionJSModel.cs | using System.Collections;
using System.Collections.Generic;
namespace SectionJS.NET
{
public class SectionJSModel : IEnumerable<SectionJSModel.Section>
{
/// <summary>
/// Sections List
/// </summary>
public List<Section> Sections = new List<Section>();
/// <summary>
/// Add a new section into the Sections List
/// </summary>
/// <param name="viewName"></param>
/// <param name="model"></param>
public void Add(string viewName, object model = null)
{
Sections.Add(new Section { ViewName = viewName, Model = model });
}
/// <summary>
/// Child class to wrap ViewName and Model. More readable than Dictionary<string, objec>
/// </summary>
public class Section
{
public string ViewName { get; set; }
public object Model { get; set; }
}
/// <summary>
/// For being able to use SectionsJSModel with Foreach loop
/// </summary>
/// <returns></returns>
public IEnumerator<Section> GetEnumerator()
{
return Sections.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| using System.Collections;
using System.Collections.Generic;
namespace SectionJS.NET
{
public class SectionJSModel : IEnumerable<SectionJSModel.Section>
{
/// <summary>
/// Sections
/// </summary>
public List<Section> Sections = new List<Section>();
public void Add(string viewName, object model = null)
{
Sections.Add(new Section { ViewName = viewName, Model = model });
}
public class Section
{
public string ViewName { get; set; }
public object Model { get; set; }
}
public IEnumerator<Section> GetEnumerator()
{
return Sections.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| mit | C# |
995b5b24a25ef949261ec81be829a443488222e8 | Change private Url setter to protected | TurnerSoftware/MongoFramework | src/MongoFramework/MongoDbConnection.cs | src/MongoFramework/MongoDbConnection.cs | using System;
using System.Collections.Concurrent;
using MongoDB.Driver;
using MongoFramework.Infrastructure;
using MongoFramework.Infrastructure.Diagnostics;
using MongoFramework.Utilities;
namespace MongoFramework
{
public class MongoDbConnection : IMongoDbConnection
{
public MongoUrl Url { get; protected set; }
private bool IsDisposed { get; set; }
private IMongoClient InternalClient;
public IMongoClient Client
{
get
{
if (IsDisposed)
{
throw new ObjectDisposedException(nameof(MongoDbConnection));
}
if (InternalClient == null)
{
InternalClient = new MongoClient(Url);
}
return InternalClient;
}
}
public IDiagnosticListener DiagnosticListener { get; set; } = new NoOpDiagnosticListener();
public static MongoDbConnection FromUrl(MongoUrl mongoUrl)
{
Check.NotNull(mongoUrl, nameof(mongoUrl));
return new MongoDbConnection
{
Url = mongoUrl
};
}
public static MongoDbConnection FromConnectionString(string connectionString)
{
return FromUrl(new MongoUrl(connectionString));
}
public IMongoDatabase GetDatabase()
{
if (IsDisposed)
{
throw new ObjectDisposedException(nameof(MongoDbConnection));
}
return Client.GetDatabase(Url.DatabaseName);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (IsDisposed)
{
return;
}
if (disposing)
{
InternalClient = null;
IsDisposed = true;
}
}
~MongoDbConnection()
{
Dispose(false);
}
}
}
| using System;
using System.Collections.Concurrent;
using MongoDB.Driver;
using MongoFramework.Infrastructure;
using MongoFramework.Infrastructure.Diagnostics;
using MongoFramework.Utilities;
namespace MongoFramework
{
public class MongoDbConnection : IMongoDbConnection
{
public MongoUrl Url { get; private set; }
private bool IsDisposed { get; set; }
private IMongoClient InternalClient;
public IMongoClient Client
{
get
{
if (IsDisposed)
{
throw new ObjectDisposedException(nameof(MongoDbConnection));
}
if (InternalClient == null)
{
InternalClient = new MongoClient(Url);
}
return InternalClient;
}
}
public IDiagnosticListener DiagnosticListener { get; set; } = new NoOpDiagnosticListener();
public static MongoDbConnection FromUrl(MongoUrl mongoUrl)
{
Check.NotNull(mongoUrl, nameof(mongoUrl));
return new MongoDbConnection
{
Url = mongoUrl
};
}
public static MongoDbConnection FromConnectionString(string connectionString)
{
return FromUrl(new MongoUrl(connectionString));
}
public IMongoDatabase GetDatabase()
{
if (IsDisposed)
{
throw new ObjectDisposedException(nameof(MongoDbConnection));
}
return Client.GetDatabase(Url.DatabaseName);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (IsDisposed)
{
return;
}
if (disposing)
{
InternalClient = null;
IsDisposed = true;
}
}
~MongoDbConnection()
{
Dispose(false);
}
}
}
| mit | C# |
843f2263fe1741a932391c08e06c1ba1bfc65e8c | add doc | nerai/CMenu | src/ExampleMenu/Util.cs | src/ExampleMenu/Util.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsoleMenu;
namespace ExampleMenu
{
public class Util
{
/// <summary>
/// Loose string comparison. Returns the best match using increasingly inaccurate comparisons.
/// Also makes sure there is a sole match at that level of accuracy.
///
/// Spaces in the select string are ignored.
///
/// The levels are:
/// <list>
/// <item>Perfect match (abcd in abcd)</item>
/// <item>Prefix match (ab in abcd)</item>
/// <item>Containing match (bc in abcd)</item>
/// <item>Matching ordered sequence of characters (bd in abcd)</item>
/// </list>
/// </summary>
public static string LooseSelect (IEnumerable<string> source, string select, StringComparison sc)
{
select = select.Replace (" ", "");
var ec = sc.GetCorrespondingComparer ();
var matches = new List<string> ();
int bestQuality = -1;
foreach (var s in source) {
int quality = -1;
if (s.Equals (select, sc)) {
quality = 10;
}
else if (s.StartsWith (select, sc)) {
quality = 8;
}
else if (s.Contains (select, sc)) {
quality = 6;
}
else if (StringContainsSequence (s, select)) {
quality = 3;
}
else {
quality = 0;
}
if (quality >= bestQuality) {
if (quality > bestQuality) {
bestQuality = quality;
matches.Clear ();
}
matches.Add (s);
}
}
if (matches.Count == 1) {
return matches[0];
}
if (matches.Count > 1) {
Console.WriteLine ("Identifier not unique: " + select);
}
else {
Console.WriteLine ("Could not find identifier: " + select);
}
return null;
}
private static bool StringContainsSequence (string str, string sequence)
{
int i = 0;
foreach (var c in sequence) {
i = str.IndexOf (c, i) + 1;
if (i == 0) {
return false;
}
}
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsoleMenu;
namespace ExampleMenu
{
class Util
{
public static string LooseSelect (IEnumerable<string> source, string select, StringComparison sc)
{
select = select.Replace (" ", "");
var ec = sc.GetCorrespondingComparer ();
var matches = new List<string> ();
int bestQuality = -1;
foreach (var s in source) {
int quality = -1;
if (s.Equals (select, sc)) {
quality = 10;
}
else if (s.StartsWith (select, sc)) {
quality = 8;
}
else if (s.Contains (select, sc)) {
quality = 6;
}
else if (StringContainsSequence (s, select)) {
quality = 3;
}
else {
quality = 0;
}
if (quality >= bestQuality) {
if (quality > bestQuality) {
bestQuality = quality;
matches.Clear ();
}
matches.Add (s);
}
}
if (matches.Count == 1) {
return matches[0];
}
if (matches.Count > 1) {
Console.WriteLine ("Identifier not unique: " + select);
}
else {
Console.WriteLine ("Could not find identifier: " + select);
}
return null;
}
private static bool StringContainsSequence (string str, string sequence)
{
int i = 0;
foreach (var c in sequence) {
i = str.IndexOf (c, i) + 1;
if (i == 0) {
return false;
}
}
return true;
}
}
}
| mit | C# |
b625822b92c3bc033304eab9730412202a3080f9 | Use C#7 is operator to remove additional cast (#32131) | ericstj/corefx,ericstj/corefx,wtgodbe/corefx,wtgodbe/corefx,ptoonen/corefx,shimingsg/corefx,ptoonen/corefx,ViktorHofer/corefx,shimingsg/corefx,ViktorHofer/corefx,ptoonen/corefx,shimingsg/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ericstj/corefx,ericstj/corefx,wtgodbe/corefx,BrennanConroy/corefx,ViktorHofer/corefx,ptoonen/corefx,wtgodbe/corefx,wtgodbe/corefx,ViktorHofer/corefx,shimingsg/corefx,ptoonen/corefx,shimingsg/corefx,wtgodbe/corefx,ViktorHofer/corefx,ericstj/corefx,shimingsg/corefx,ptoonen/corefx,ericstj/corefx,ericstj/corefx,BrennanConroy/corefx,shimingsg/corefx,ptoonen/corefx,BrennanConroy/corefx,wtgodbe/corefx | src/System.Linq/src/System/Linq/Cast.cs | src/System.Linq/src/System/Linq/Cast.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
namespace System.Linq
{
public static partial class Enumerable
{
public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source)
{
if (source == null)
{
throw Error.ArgumentNull(nameof(source));
}
return OfTypeIterator<TResult>(source);
}
private static IEnumerable<TResult> OfTypeIterator<TResult>(IEnumerable source)
{
foreach (object obj in source)
{
if (obj is TResult result)
{
yield return result;
}
}
}
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source)
{
IEnumerable<TResult> typedSource = source as IEnumerable<TResult>;
if (typedSource != null)
{
return typedSource;
}
if (source == null)
{
throw Error.ArgumentNull(nameof(source));
}
return CastIterator<TResult>(source);
}
private static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source)
{
foreach (object obj in source)
{
yield return (TResult)obj;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
namespace System.Linq
{
public static partial class Enumerable
{
public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source)
{
if (source == null)
{
throw Error.ArgumentNull(nameof(source));
}
return OfTypeIterator<TResult>(source);
}
private static IEnumerable<TResult> OfTypeIterator<TResult>(IEnumerable source)
{
foreach (object obj in source)
{
if (obj is TResult)
{
yield return (TResult)obj;
}
}
}
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source)
{
IEnumerable<TResult> typedSource = source as IEnumerable<TResult>;
if (typedSource != null)
{
return typedSource;
}
if (source == null)
{
throw Error.ArgumentNull(nameof(source));
}
return CastIterator<TResult>(source);
}
private static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source)
{
foreach (object obj in source)
{
yield return (TResult)obj;
}
}
}
}
| mit | C# |
0244edcb02ae5ea665f03dd5b2ae0c75ba754ce7 | Update NumberFormatting.cs | keith-hall/Extensions,keith-hall/Extensions | src/NumberFormatting.cs | src/NumberFormatting.cs | using System.Text.RegularExpressions;
using System;
namespace HallLibrary.Extensions
{
public static class NumberFormatting
{
private static readonly Regex _number = new Regex(@"^-?\d+(?:" + _defaultDecimalSeparatorForRegex + @"\d+)?$"); // TODO: replace dot with decimal separator from current culture
private static readonly Regex _thousands = new Regex(@"(?<=\d)(?<!" + _defaultDecimalSeparatorForRegex + @"\d*)(?=(?:\d{3})+($|" + _defaultDecimalSeparatorForRegex + @"))"); // TODO: replace dot with decimal separator from current culture
private const char _defaultThousandsSeparator = ',';
private const string _defaultDecimalSeparatorForRegex = @"\.";
public static bool IsValidNumber (string value)
{
return _number.IsMatch(value);
}
public static string AddThousandsSeparators (string number, string thousandsSeparator = null)
{
if (!IsValidNumber(number))
throw new ArgumentException(nameof(number), "String does not contain a valid number");
return _thousands.Replace(number, thousandsSeparator ?? _defaultThousandsSeparator.ToString()); // TODO: replace comma with thousands separator from current culture
/*
// alternative implementation, without regex
if (thousandsSeparator == null)
thousandsSeparator = _defaultThousandsSeparator.ToString();
var digits = number.IndexOf(".", StringComparison.InvariantCultureIgnoreCase);
if (digits == -1)
digits = number.Length;
for (var pos = digits - 3; pos > 0; pos -= 3)
{
number = number.Substring(0, pos) + thousandsSeparator + number.Substring(pos);
}
*/
}
/*
// Store integer 182
int decValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = decValue.ToString("X"); // doesn't add 0x prefix
// Convert the hex string back to the number
int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); // doesn't cope with 0x prefix
*/
}
}
| using System.Text.RegularExpressions;
using System;
namespace HallLibrary.Extensions
{
public static class NumberFormatting
{
private static readonly Regex _number = new Regex(@"^-?\d+(?:" + _defaultDecimalSeparatorForRegex + @"\d+)?$"); // TODO: replace dot with decimal separator from current culture
private static readonly Regex _thousands = new Regex(@"(?<=\d)(?<!" + _defaultDecimalSeparatorForRegex + @"\d*)(?=(?:\d{3})+($|" + _defaultDecimalSeparatorForRegex + @"))"); // TODO: replace dot with decimal separator from current culture
private const char _defaultThousandsSeparator = ',';
private const string _defaultDecimalSeparatorForRegex = @"\.";
public static bool IsValidNumber (string value)
{
return _number.IsMatch(value);
}
public static string AddThousandsSeparators (string number, string thousandsSeparator = null)
{
if (!IsValidNumber(number))
throw new ArgumentException(nameof(number), "String does not contain a valid number");
return _thousands.Replace(number, thousandsSeparator ?? _defaultThousandsSeparator.ToString()); // TODO: replace comma with thousands separator from current culture
/*
// alternative implementation, without regex
var digits = write.IndexOf(".", StringComparison.InvariantCultureIgnoreCase);
if (digits == -1)
digits = write.Length;
for (var pos = digits - 3; pos > 0; pos -= 3)
{
write = write.Substring(0, pos) + thousandsSeparator + write.Substring(pos);
}
*/
}
/*
// Store integer 182
int decValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = decValue.ToString("X"); // doesn't add 0x prefix
// Convert the hex string back to the number
int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); // doesn't cope with 0x prefix
*/
}
}
| apache-2.0 | C# |
bd3ce36e2390cd5287c27bbcd108fcaf62a284a9 | Support BSON responses | obsoleted/PyriteServer,PyriteServer/PyriteServer,obsoleted/PyriteServer,PyriteServer/PyriteServer | PyriteServer/Global.asax.cs | PyriteServer/Global.asax.cs | // // //-------------------------------------------------------------------------------------------------
// // // <copyright file="Global.asax.cs" company="Microsoft Corporation">
// // // Copyright (c) Microsoft Corporation. All rights reserved.
// // // </copyright>
// // //-------------------------------------------------------------------------------------------------
namespace PyriteServer
{
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http;
using PyriteServer.Contracts;
using PyriteServer.DataAccess;
public class WebApiApplication : HttpApplication
{
private bool disposed = false;
private AzureUriStorage storage = null;
public override void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected void Application_Start()
{
string dataPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, ".\\Data");
dataPath = Path.GetFullPath(dataPath);
Trace.WriteLine(String.Format("Data path: {0}", dataPath));
string connSecretsPath = Path.Combine(dataPath, "accountkey.txt");
ISecretsProvider connProvider = new FileSecretsProvider(connSecretsPath);
string setRootUrl = ConfigurationManager.AppSettings["SetRootUrl"];
if (string.IsNullOrWhiteSpace(setRootUrl))
{
throw new ConfigurationErrorsException("SetRootUrl not specified");
}
this.storage = new AzureUriStorage(connProvider.Value, setRootUrl);
Dependency.Storage = this.storage;
// wait reasonable amount of time for first load
this.storage.WaitLoadCompleted.WaitOne(30000);
GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
GlobalConfiguration.Configuration.Formatters.Add(new BsonMediaTypeFormatter());
GlobalConfiguration.Configuration.EnsureInitialized();
}
private void Dispose(bool disposing)
{
if (!disposing || this.disposed)
{
return;
}
if (this.storage != null)
{
this.storage.Dispose();
}
this.disposed = true;
base.Dispose();
}
}
} | // // //-------------------------------------------------------------------------------------------------
// // // <copyright file="Global.asax.cs" company="Microsoft Corporation">
// // // Copyright (c) Microsoft Corporation. All rights reserved.
// // // </copyright>
// // //-------------------------------------------------------------------------------------------------
namespace PyriteServer
{
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http;
using PyriteServer.Contracts;
using PyriteServer.DataAccess;
public class WebApiApplication : HttpApplication
{
private bool disposed = false;
private AzureUriStorage storage = null;
public override void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected void Application_Start()
{
string dataPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, ".\\Data");
dataPath = Path.GetFullPath(dataPath);
Trace.WriteLine(String.Format("Data path: {0}", dataPath));
string connSecretsPath = Path.Combine(dataPath, "accountkey.txt");
ISecretsProvider connProvider = new FileSecretsProvider(connSecretsPath);
string setRootUrl = ConfigurationManager.AppSettings["SetRootUrl"];
if (string.IsNullOrWhiteSpace(setRootUrl))
{
throw new ConfigurationErrorsException("SetRootUrl not specified");
}
this.storage = new AzureUriStorage(connProvider.Value, setRootUrl);
Dependency.Storage = this.storage;
// wait reasonable amount of time for first load
this.storage.WaitLoadCompleted.WaitOne(30000);
GlobalConfiguration.Configuration.MapHttpAttributeRoutes();
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
GlobalConfiguration.Configuration.EnsureInitialized();
}
private void Dispose(bool disposing)
{
if (!disposing || this.disposed)
{
return;
}
if (this.storage != null)
{
this.storage.Dispose();
}
this.disposed = true;
base.Dispose();
}
}
} | mit | C# |
10f92a2599083b2b485a5bba9c2b14c3d58f43c0 | Update demo | sunkaixuan/SqlSugar | Src/Asp.Net/PgSqlTest/Config.cs | Src/Asp.Net/PgSqlTest/Config.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
/// <summary>
/// Setting up the database name does not require you to create the database
/// 设置好数据库名不需要你去手动建库
/// </summary>
public class Config
{
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString = "PORT=5432;DATABASE=SqlSugar4xTest;HOST=localhost;PASSWORD=haosql;USER ID=postgres";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString2 = "PORT=5432;DATABASE=SqlSugar4xTest2;HOST=localhost;PASSWORD=haosql;USER ID=postgres";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString3 = "PORT=5432;DATABASE=SqlSugar4xTest3;HOST=localhost;PASSWORD=haosql;USER ID=postgres";
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
/// <summary>
/// Setting up the database name does not require you to create the database
/// 设置好数据库名不需要你去手动建库
/// </summary>
public class Config
{
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString = "PORT=5433;DATABASE=SqlSugar4xTest;HOST=localhost;PASSWORD=haosql;USER ID=postgres";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString2 = "PORT=5433;DATABASE=SqlSugar4xTest2;HOST=localhost;PASSWORD=haosql;USER ID=postgres";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString3 = "PORT=5433;DATABASE=SqlSugar4xTest3;HOST=localhost;PASSWORD=haosql;USER ID=postgres";
}
}
| apache-2.0 | C# |
2435b8b5942dadd4efc6e74b11dbc2ae71adf7ed | Support also external members with email and CN in iCloud groups. Will be used by Open-Xchange for DistributionList mapping. | aluxnimm/outlookcaldavsynchronizer | CalDavSynchronizer/Implementation/DistributionLists/VCard/UidDistListEntityMapper.cs | CalDavSynchronizer/Implementation/DistributionLists/VCard/UidDistListEntityMapper.cs | // This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
// Copyright (c) 2015 Alexander Nimmervoll
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using CalDavSynchronizer.Implementation.ComWrappers;
using CalDavSynchronizer.Implementation.DistributionLists.Sogo;
using GenSync.Logging;
using log4net;
using Microsoft.Office.Interop.Outlook;
using Thought.vCards;
namespace CalDavSynchronizer.Implementation.DistributionLists.VCard
{
public class UidDistListEntityMapper : DistListEntityMapperBase
{
protected override vCardMember CreateVCardMemberOrNull(GenericComObjectWrapper<Recipient> recipientWrapper, string nameWithoutEmail, DistributionListSychronizationContext context, IEntitySynchronizationLogger synchronizationLogger, ILog logger)
{
var uid = context.GetUidByEmailAddress(recipientWrapper.Inner.Address);
var targetMember = new vCardMember();
if (uid != null)
{
targetMember.Uid = uid;
}
else
{
targetMember.EmailAddress = recipientWrapper.Inner.Address;
targetMember.DisplayName = nameWithoutEmail;
}
return targetMember;
}
protected override IEnumerable<DistributionListMember> GetMembers(vCard source, DistributionListSychronizationContext context, IEntitySynchronizationLogger synchronizationLogger, ILog logger)
{
foreach(var member in source.Members)
{
DistributionListMember distributionListMember;
if (!string.IsNullOrEmpty(member.Uid))
{
(var contactWrapper, var emailAddress) = context.GetContactByUidOrNull(member.Uid, synchronizationLogger, logger);
if (contactWrapper != null)
{
using (contactWrapper)
{
distributionListMember = new DistributionListMember(emailAddress, contactWrapper.Inner.FullName);
yield return distributionListMember;
}
}
}
else
{
distributionListMember = new DistributionListMember(member.EmailAddress, member.DisplayName);
yield return distributionListMember;
}
}
}
}
} | // This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
// Copyright (c) 2015 Alexander Nimmervoll
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using CalDavSynchronizer.Implementation.ComWrappers;
using CalDavSynchronizer.Implementation.DistributionLists.Sogo;
using GenSync.Logging;
using log4net;
using Microsoft.Office.Interop.Outlook;
using Thought.vCards;
namespace CalDavSynchronizer.Implementation.DistributionLists.VCard
{
public class UidDistListEntityMapper : DistListEntityMapperBase
{
protected override vCardMember CreateVCardMemberOrNull(GenericComObjectWrapper<Recipient> recipientWrapper, string nameWithoutEmail, DistributionListSychronizationContext context, IEntitySynchronizationLogger synchronizationLogger, ILog logger)
{
var uid = context.GetUidByEmailAddress(recipientWrapper.Inner.Address);
if (uid == null)
{
var logMessage = $"Did not find Uid of EmailAddress '{recipientWrapper.Inner.Address}'. Member won't be added to contact group";
logger.WarnFormat(logMessage);
synchronizationLogger.LogWarning(logMessage);
}
var targetMember = new vCardMember();
targetMember.Uid = uid;
return targetMember;
}
protected override IEnumerable<DistributionListMember> GetMembers(vCard source, DistributionListSychronizationContext context, IEntitySynchronizationLogger synchronizationLogger, ILog logger)
{
foreach(var member in source.Members)
{
(var contactWrapper, var emailAddress) = context.GetContactByUidOrNull(member.Uid, synchronizationLogger, logger);
if (contactWrapper != null)
{
DistributionListMember distributionListMember;
using (contactWrapper)
{
distributionListMember = new DistributionListMember(emailAddress, contactWrapper.Inner.FullName);
}
yield return distributionListMember;
}
}
}
}
} | agpl-3.0 | C# |
616353e3abcd32042ee852c907daa23a9db1bbc3 | watermark for add tag. | hfoffani/WinFormTagsEditor | WinFormTagsEditor/NewTagForm.cs | WinFormTagsEditor/NewTagForm.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WFTE
{
internal partial class NewTagForm : Form
{
string waterMarkText = "<Enter> to add. <Esc> to close.";
Font prototype;
public NewTagForm()
{
InitializeComponent();
prototype = this.textBox1.Font;
this.textBox1.Font = new Font(prototype.FontFamily, prototype.Size-2, prototype.Style);
this.btnok.Width = 0;
this.btncancel.Width = 0;
this.textBox1.TextChanged += textBox1_TextChanged;
SendMessage(this.textBox1.Handle, 0x1501, 1, waterMarkText);
}
void textBox1_TextChanged(object sender, EventArgs e)
{
this.Value = this.textBox1.Text;
if (this.textBox1.Text != "") {
this.textBox1.Font = prototype;
} else {
this.textBox1.Font = new Font(prototype.FontFamily, prototype.Size - 2, prototype.Style);
}
}
public string Value { get; set; }
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WFTE
{
internal partial class NewTagForm : Form
{
public NewTagForm()
{
InitializeComponent();
this.btnok.Width = 0;
this.btncancel.Width = 0;
this.textBox1.TextChanged += textBox1_TextChanged;
}
void textBox1_TextChanged(object sender, EventArgs e)
{
this.Value = this.textBox1.Text;
}
public string Value { get; set; }
}
}
| apache-2.0 | C# |
d5e37fe9a1fa97a810e0e6e2905a51a8d7d1243e | Fix Register.cshtml | Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training | src/ChessVariantsTraining/Views/User/Register.cshtml | src/ChessVariantsTraining/Views/User/Register.cshtml | @section Title {Register}
@if (ViewBag.Error != null)
{
@foreach (string err in ViewBag.Error)
{
<div class="error">@err</div>
}
}
@{ Html.BeginForm("New", "User", FormMethod.Post); }
<input type="text" placeholder="Username" name="username">
<input type="password" name="password">
<input type="text" placeholder="Email" name="email">
<input type="submit" value="Submit">
@{ Html.EndForm(); }
| @section Title {Register}
@using System.Web.Routing
@if (ViewBag.Error != null)
{
@foreach (string err in ViewBag.Error)
{
<div class="error">@err</div>
}
}
@{ Html.BeginForm("New", "User", FormMethod.Post); }
<input type="text" placeholder="Username" name="username">
<input type="password" name="password">
<input type="text" placeholder="Email" name="email">
<input type="submit" value="Submit">
@{ Html.EndForm(); }
| agpl-3.0 | C# |
0257831945ccf76f2cc38fe46170c021ea39dcaf | Add new methods to StartupExtensions to use Institutes and Specialitites | denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs | src/Diploms.WebUI/Configuration/StartupExtensions.cs | src/Diploms.WebUI/Configuration/StartupExtensions.cs | using Diploms.Core;
using Diploms.DataLayer;
using Diploms.Services.Departments;
using Diploms.Services.Specialities;
using Diploms.Services.Institutes;
using Microsoft.Extensions.DependencyInjection;
namespace Diploms.WebUI.Configuration
{
public static class StartupExtensions
{
public static IServiceCollection AddInstitutes(this IServiceCollection services)
{
services.AddScoped<IRepository<Institute>, RepositoryBase<Institute>>();
services.AddScoped<InstitutesService>();
return services;
}
public static IServiceCollection AddSpecialities(this IServiceCollection services)
{
services.AddScoped<IRepository<Speciality>, RepositoryBase<Speciality>>();
services.AddScoped<SpecialitiesService>();
return services;
}
public static IServiceCollection AddDepartments(this IServiceCollection services)
{
services.AddScoped<IRepository<Department>, RepositoryBase<Department>>();
services.AddScoped<DepartmentsService>();
return services;
}
}
} | using Diploms.Core;
using Diploms.DataLayer;
using Diploms.Services.Departments;
using Microsoft.Extensions.DependencyInjection;
namespace Diploms.WebUI.Configuration
{
public static class StartupExtensions
{
public static IServiceCollection AddDepartments(this IServiceCollection services)
{
services.AddScoped<IRepository<Department>, RepositoryBase<Department>>();
services.AddScoped<DepartmentsService>();
return services;
}
}
} | mit | C# |
54c40afcc5a31941402f2b18f1ad90c6b4a52789 | Format Date Naissance | webSportENIProject/webSport,webSportENIProject/webSport | WUI/Models/PersonneModel.cs | WUI/Models/PersonneModel.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WUI.Models
{
public class PersonneModel
{
public int Id { get; set; }
public string Nom { get; set; }
public string Prenom { get; set; }
public string Email { get; set; }
[RegularExpression("^0[1-68][0-9]{8}$", ErrorMessage="La saisie ne correspond pas à un numéro de téléphone")]
public string Phone { get; set; }
public int UserTable { get; set; }
public string distance { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? DateNaissance { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WUI.Models
{
public class PersonneModel
{
public int Id { get; set; }
public string Nom { get; set; }
public string Prenom { get; set; }
public string Email { get; set; }
[RegularExpression("^0[1-68][0-9]{8}$", ErrorMessage="La saisie ne correspond pas à un numéro de téléphone")]
public string Phone { get; set; }
public int UserTable { get; set; }
public string distance { get; set; }
public DateTime? DateNaissance { get; set; }
}
}
| apache-2.0 | C# |
9a32b8eaba7dc6370937757e2d1efc97b65c0eb8 | Define command line options | a-ctor/roslyn,Hosch250/roslyn,sharadagrawal/Roslyn,yeaicc/roslyn,genlu/roslyn,SeriaWei/roslyn,mattwar/roslyn,basoundr/roslyn,jhendrixMSFT/roslyn,dotnet/roslyn,CaptainHayashi/roslyn,xasx/roslyn,davkean/roslyn,dotnet/roslyn,TyOverby/roslyn,basoundr/roslyn,akrisiun/roslyn,jcouv/roslyn,jeffanders/roslyn,CaptainHayashi/roslyn,tvand7093/roslyn,jasonmalinowski/roslyn,MatthieuMEZIL/roslyn,orthoxerox/roslyn,bartdesmet/roslyn,gafter/roslyn,davkean/roslyn,mavasani/roslyn,xoofx/roslyn,Giftednewt/roslyn,rgani/roslyn,kelltrick/roslyn,paulvanbrenk/roslyn,akrisiun/roslyn,robinsedlaczek/roslyn,pdelvo/roslyn,Giftednewt/roslyn,tmeschter/roslyn,mattscheffer/roslyn,agocke/roslyn,sharwell/roslyn,nguerrera/roslyn,TyOverby/roslyn,robinsedlaczek/roslyn,michalhosala/roslyn,tmat/roslyn,amcasey/roslyn,abock/roslyn,SeriaWei/roslyn,paulvanbrenk/roslyn,MattWindsor91/roslyn,orthoxerox/roslyn,CyrusNajmabadi/roslyn,khyperia/roslyn,MichalStrehovsky/roslyn,amcasey/roslyn,ljw1004/roslyn,swaroop-sridhar/roslyn,dpoeschl/roslyn,jaredpar/roslyn,stephentoub/roslyn,jkotas/roslyn,heejaechang/roslyn,KevinRansom/roslyn,Shiney/roslyn,balajikris/roslyn,MichalStrehovsky/roslyn,khyperia/roslyn,budcribar/roslyn,nguerrera/roslyn,KevinRansom/roslyn,sharadagrawal/Roslyn,ValentinRueda/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,mmitche/roslyn,agocke/roslyn,AnthonyDGreen/roslyn,rgani/roslyn,ericfe-ms/roslyn,Hosch250/roslyn,genlu/roslyn,vslsnap/roslyn,bbarry/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,panopticoncentral/roslyn,khellang/roslyn,Hosch250/roslyn,sharadagrawal/Roslyn,natgla/roslyn,jeffanders/roslyn,srivatsn/roslyn,abock/roslyn,shyamnamboodiripad/roslyn,rgani/roslyn,tvand7093/roslyn,bbarry/roslyn,eriawan/roslyn,natidea/roslyn,sharwell/roslyn,KevinH-MS/roslyn,eriawan/roslyn,a-ctor/roslyn,DustinCampbell/roslyn,robinsedlaczek/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,budcribar/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,basoundr/roslyn,KevinH-MS/roslyn,zooba/roslyn,srivatsn/roslyn,Shiney/roslyn,jaredpar/roslyn,KevinRansom/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,vslsnap/roslyn,balajikris/roslyn,cston/roslyn,KirillOsenkov/roslyn,DustinCampbell/roslyn,tannergooding/roslyn,mattwar/roslyn,xasx/roslyn,yeaicc/roslyn,paulvanbrenk/roslyn,xoofx/roslyn,jasonmalinowski/roslyn,MattWindsor91/roslyn,ValentinRueda/roslyn,pdelvo/roslyn,davkean/roslyn,jeffanders/roslyn,leppie/roslyn,wvdd007/roslyn,Pvlerick/roslyn,OmarTawfik/roslyn,jhendrixMSFT/roslyn,stephentoub/roslyn,Pvlerick/roslyn,diryboy/roslyn,cston/roslyn,khellang/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,swaroop-sridhar/roslyn,AnthonyDGreen/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,zooba/roslyn,jmarolf/roslyn,amcasey/roslyn,natidea/roslyn,KirillOsenkov/roslyn,KirillOsenkov/roslyn,mattwar/roslyn,mmitche/roslyn,brettfo/roslyn,balajikris/roslyn,kelltrick/roslyn,a-ctor/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,AlekseyTs/roslyn,SeriaWei/roslyn,KiloBravoLima/roslyn,CyrusNajmabadi/roslyn,MatthieuMEZIL/roslyn,aelij/roslyn,vslsnap/roslyn,wvdd007/roslyn,tannergooding/roslyn,VSadov/roslyn,sharwell/roslyn,jcouv/roslyn,khyperia/roslyn,xoofx/roslyn,tmat/roslyn,jamesqo/roslyn,lorcanmooney/roslyn,leppie/roslyn,swaroop-sridhar/roslyn,jkotas/roslyn,MatthieuMEZIL/roslyn,tmat/roslyn,MichalStrehovsky/roslyn,Pvlerick/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,Giftednewt/roslyn,ericfe-ms/roslyn,nguerrera/roslyn,jhendrixMSFT/roslyn,AmadeusW/roslyn,KevinH-MS/roslyn,mattscheffer/roslyn,bkoelman/roslyn,tmeschter/roslyn,vcsjones/roslyn,ErikSchierboom/roslyn,tmeschter/roslyn,panopticoncentral/roslyn,jaredpar/roslyn,ljw1004/roslyn,dpoeschl/roslyn,zooba/roslyn,natidea/roslyn,AArnott/roslyn,OmarTawfik/roslyn,leppie/roslyn,wvdd007/roslyn,mgoertz-msft/roslyn,physhi/roslyn,genlu/roslyn,mmitche/roslyn,AArnott/roslyn,jkotas/roslyn,shyamnamboodiripad/roslyn,drognanar/roslyn,diryboy/roslyn,gafter/roslyn,ErikSchierboom/roslyn,cston/roslyn,TyOverby/roslyn,jmarolf/roslyn,ericfe-ms/roslyn,yeaicc/roslyn,weltkante/roslyn,bartdesmet/roslyn,VSadov/roslyn,agocke/roslyn,budcribar/roslyn,ValentinRueda/roslyn,bkoelman/roslyn,srivatsn/roslyn,ErikSchierboom/roslyn,CaptainHayashi/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mavasani/roslyn,orthoxerox/roslyn,KiloBravoLima/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,bkoelman/roslyn,natgla/roslyn,physhi/roslyn,mattscheffer/roslyn,AmadeusW/roslyn,dotnet/roslyn,Shiney/roslyn,gafter/roslyn,michalhosala/roslyn,tvand7093/roslyn,drognanar/roslyn,vcsjones/roslyn,ljw1004/roslyn,khellang/roslyn,pdelvo/roslyn,MattWindsor91/roslyn,reaction1989/roslyn,KiloBravoLima/roslyn,brettfo/roslyn,xasx/roslyn,aelij/roslyn,VSadov/roslyn,reaction1989/roslyn,abock/roslyn,akrisiun/roslyn,DustinCampbell/roslyn,vcsjones/roslyn,lorcanmooney/roslyn,michalhosala/roslyn,kelltrick/roslyn,aelij/roslyn,jmarolf/roslyn,dpoeschl/roslyn,MattWindsor91/roslyn,physhi/roslyn,jamesqo/roslyn,OmarTawfik/roslyn,AArnott/roslyn,jcouv/roslyn,mavasani/roslyn,reaction1989/roslyn,drognanar/roslyn,weltkante/roslyn,jamesqo/roslyn,tannergooding/roslyn,natgla/roslyn,AnthonyDGreen/roslyn,lorcanmooney/roslyn,bbarry/roslyn | src/Tools/ProcessWatchdog/Options.cs | src/Tools/ProcessWatchdog/Options.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using CommandLine;
namespace ProcessWatchdog
{
/// <summary>
/// Command line options for the ProcessWatchdog tool.
/// </summary>
internal class Options
{
[Option(
't',
"timeout",
HelpText = "Timeout value in the form hh:mm[:ss].",
Required = true)]
public string Timeout { get; set; }
[Option(
'c',
"command-line",
HelpText = "Command line for the executable to be run.",
Required = true)]
public string CommandLine { get; set; }
}
} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace ProcessWatchdog
{
internal class Options
{
}
} | apache-2.0 | C# |
efb992477cd244a0d50a5cc5e3a2d7142baa6b80 | add add addrange and find in University, not tested yet | Mooophy/158212 | as5/Lib/University.cs | as5/Lib/University.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lib
{
public class University
{
public List<Student> Students { get; private set; }
public List<Paper> Papers { get; private set; }
public Dictionary<Paper, SortedSet<Student>> Enrollment { get; private set; }
public University() { }
public void Add(Student student)
{
Students.Add(student);
}
public void Add(Paper paper)
{
Papers.Add(paper);
}
public void AddRange(IEnumerable<Student> collection)
{
Students.AddRange(collection);
}
public void AddRange(IEnumerable<Paper> collection)
{
Papers.AddRange(collection);
}
public IEnumerable<Student> find(Paper paper)
{
return Enrollment.ContainsKey(paper) ? Enrollment[paper].ToArray() : new Student[0];
}
public IEnumerable<Paper> find(Student student)
{
return from entry in Enrollment where entry.Value.Contains(student) select entry.Key;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lib
{
public class University
{
public List<Student> Students { get; private set; }
public List<Paper> Papers { get; private set; }
public Dictionary<Paper, SortedSet<Student>> Enrollment { get; private set; }
public University() { }
}
}
| mit | C# |
6cf1bc7b3c3f7b7bd61232ba2f776c825671f5b6 | Add another unit test | LambdaSix/Capsicum | Capsicum.Test/EntityTests.cs | Capsicum.Test/EntityTests.cs | using System.Linq;
using Capsicum.Exceptions;
using NUnit.Framework;
namespace Capsicum.Test {
[TestFixture]
public class EntityTests {
/* Initial State Tests */
[TestFixture]
public class InitialState {
private Entity e;
[SetUp]
public void Setup() => e = new Entity();
[Test]
public void ThrowsWhenAttemptingToRetrieveUnregisteredComponent() {
Assert.Throws<ComponentNotRegisteredException>(() => e.GetComponent<FakeComponent>());
}
[Test]
public void NoComponentsWhenNoComponentsRegistered()
{
Assert.That(!e.GetComponents().Any());
}
}
}
} | using System.Linq;
using Capsicum.Exceptions;
using NUnit.Framework;
namespace Capsicum.Test {
[TestFixture]
public class EntityTests {
/* Initial State Tests */
[TestFixture]
public class InitialState {
private Entity e;
[SetUp]
public void Setup() => e = new Entity();
[Test]
public void ThrowsWhenAttemptingToRetrieveUnregisteredComponent() {
Assert.Throws<ComponentNotRegisteredException>(() => e.GetComponent<FakeComponent>());
}
}
}
} | mit | C# |
c6e3a91eb28fa6679b6150916c9b33c6a228c495 | fix UTF | KotlyarovV/testing,kontur-csharper/testing,KotlyarovV/testing,kontur-csharper/testing,kontur-csharper/testing | Challenge/WordsStatistics.cs | Challenge/WordsStatistics.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Challenge
{
public class WordsStatistics : IWordsStatistics
{
protected readonly IDictionary<string, int> stats
= new Dictionary<string, int>();
public virtual void AddWord(string word)
{
if (word == null) throw new ArgumentNullException(nameof(word));
if (string.IsNullOrWhiteSpace(word)) return;
if (word.Length > 10)
word = word.Substring(0, 10);
int count;
stats[word.ToLower()] = stats.TryGetValue(word.ToLower(), out count) ? count + 1 : 1;
}
/**
<summary>
Частотный словарь добавленных слов.
Слова сравниваются без учета регистра символов.
Порядок — по убыванию частоты слова.
При одинаковой частоте — в лексикографическом порядке.
</summary>
*/
public virtual IEnumerable<Tuple<int, string>> GetStatistics()
{
return stats.OrderByDescending(kv => kv.Value)
.ThenBy(kv => kv.Key)
.Select(kv => Tuple.Create(kv.Value, kv.Key));
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace Challenge
{
public class WordsStatistics : IWordsStatistics
{
protected readonly IDictionary<string, int> stats
= new Dictionary<string, int>();
public virtual void AddWord(string word)
{
if (word == null) throw new ArgumentNullException(nameof(word));
if (string.IsNullOrWhiteSpace(word)) return;
if (word.Length > 10)
word = word.Substring(0, 10);
int count;
stats[word.ToLower()] = stats.TryGetValue(word.ToLower(), out count) ? count + 1 : 1;
}
/**
<summary>
.
.
.
.
</summary>
*/
public virtual IEnumerable<Tuple<int, string>> GetStatistics()
{
return stats.OrderByDescending(kv => kv.Value)
.ThenBy(kv => kv.Key)
.Select(kv => Tuple.Create(kv.Value, kv.Key));
}
}
} | mit | C# |
0276c39e9c2fd955a34c923c765d5f3dc7138d87 | Send Message to chat and stuff | joel076/Va-,joel076/Va-,joel076/Va-,joel076/Va- | DeltaBot/DeltaBot/Program.cs | DeltaBot/DeltaBot/Program.cs | using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace MyBot
{
public class Program
{
public static void Main(string[] args)
=> new Program().MainAsync().GetAwaiter().GetResult();
public async Task MainAsync()
{
var client = new DiscordSocketClient(new DiscordSocketConfig {
WebSocketProvider = Discord.Net.Providers.WS4Net.WS4NetProvider.Instance,
LogLevel = LogSeverity.Info
});
client.Log += Log;
client.MessageReceived += MessageReceived;
string token = "MzA3NTQyMjQxMDQyNDk3NTM2.C-T0kw.26UU8gZRrfcMRUkjSsIhlGKbI6w";
await client.LoginAsync(TokenType.Bot, token);
await client.StartAsync();
var cmdthread = new Thread(() => adco(client));
cmdthread.Start();
// Block this task until the program is closed.
await Task.Delay(-1);
}
private async Task MessageReceived(SocketMessage message)
{
Thread msgthread = new Thread(() => MessageHandler(message));
msgthread.Start();
}
private void MessageHandler(SocketMessage message)
{
if (message.Author.Id != 307542241042497536)
{
if (message.Channel.Id == 274987790914027520)
{
//code here
if (message.Content.Equals("!time"))
{
var time = new DateTime();
time = DateTime.Now;
time.ToLocalTime();
message.Channel.SendMessageAsync(time.Year + "-" + time.Month + "-" + time.Day + " | " + time.Hour + ":" + time.Minute);
}
}
}
}
private void adco(DiscordSocketClient client)
{
string c = "";
for (;;)
{
c = Console.ReadLine();
(client.GetChannel(274987790914027520) as IMessageChannel).SendMessageAsync(c);
}
}
private Task Log(LogMessage msg)
{
Console.WriteLine(msg.ToString());
return Task.CompletedTask;
}
}
} | using Discord;
using Discord.WebSocket;
using System;
using System.Threading.Tasks;
namespace MyBot
{
public class Program
{
public static void Main(string[] args)
=> new Program().MainAsync().GetAwaiter().GetResult();
public async Task MainAsync()
{
var client = new DiscordSocketClient(new DiscordSocketConfig {
WebSocketProvider = Discord.Net.Providers.WS4Net.WS4NetProvider.Instance
});
client.Log += Log;
client.MessageReceived += MessageReceived;
string token = "MzA3NTQyMjQxMDQyNDk3NTM2.C-T0kw.26UU8gZRrfcMRUkjSsIhlGKbI6w";
await client.LoginAsync(TokenType.Bot, token);
await client.StartAsync();
// Block this task until the program is closed.
await Task.Delay(-1);
}
private async Task MessageReceived(SocketMessage message)
{
if (message.Author.Id != 307542241042497536)
{
if (message.Channel.Id == 274987790914027520)
{
//code here
if (message.Content.Equals("!time"))
{
var time = new DateTime();
time = DateTime.Now;
time.ToLocalTime();
await message.Channel.SendMessageAsync(time.Year + "-" + time.Month + "-" + time.Day + " | " + time.Hour + ":" + time.Minute);
}
}
}
}
private Task Log(LogMessage msg)
{
Console.WriteLine(msg.ToString());
return Task.CompletedTask;
}
}
} | mit | C# |
cb35db55410c22fa7bd408cc29a55e15fa3fb4dd | Add ew to DbTemplate.Add(ID, string) method to a void hiding method from the base class | hermanussen/Sitecore.FakeDb,sergeyshushlyapin/Sitecore.FakeDb,pveller/Sitecore.FakeDb | src/Sitecore.FakeDb/DbTemplate.cs | src/Sitecore.FakeDb/DbTemplate.cs | namespace Sitecore.FakeDb
{
using System.Collections;
using Sitecore.Data;
public class DbTemplate : DbItem
{
public ID[] BaseIDs { get; set; }
internal DbFieldCollection StandardValues { get; private set; }
public DbTemplate()
: this((string)null)
{
}
public DbTemplate(ID id)
: this(null, id)
{
}
public DbTemplate(string name)
: this(name, ID.NewID)
{
}
public DbTemplate(string name, ID id)
: base(name, ID.IsNullOrEmpty(id) ? ID.NewID : id, TemplateIDs.Template)
{
this.StandardValues = new DbFieldCollection();
this.Add(new DbField(FieldIDs.BaseTemplate) { Shared = true });
// TODO:[High] Move these out into the standard template. we have tempalte inheritance now
this.Add(new DbField(FieldIDs.Lock) { Shared = true });
this.Add(new DbField(FieldIDs.Security) { Shared = true });
this.Add(new DbField(FieldIDs.Created));
this.Add(new DbField(FieldIDs.CreatedBy));
this.Add(new DbField(FieldIDs.Updated));
this.Add(new DbField(FieldIDs.UpdatedBy));
this.Add(new DbField(FieldIDs.Revision));
this.Add(new DbField(FieldIDs.DisplayName));
this.Add(new DbField(FieldIDs.Hidden));
this.Add(new DbField(FieldIDs.ReadOnly));
}
public void Add(string fieldName)
{
this.Add(fieldName, string.Empty);
}
public void Add(ID id)
{
this.Add(id, string.Empty);
}
public new void Add(string fieldName, string standardValue)
{
var field = new DbField(fieldName);
this.Add(field, standardValue);
}
public new void Add(ID id, string standardValue)
{
var field = new DbField(id);
this.Add(field, standardValue);
}
public IEnumerator GetEnumerator()
{
return this.Fields.GetEnumerator();
}
protected void Add(DbField field, string standardValue)
{
this.Fields.Add(field);
var standardValueField = new DbField(field.Name, field.ID) { Value = standardValue };
this.StandardValues.Add(standardValueField);
}
}
} | namespace Sitecore.FakeDb
{
using System.Collections;
using Sitecore.Data;
public class DbTemplate : DbItem
{
public ID[] BaseIDs { get; set; }
internal DbFieldCollection StandardValues { get; private set; }
public DbTemplate()
: this((string)null)
{
}
public DbTemplate(ID id)
: this(null, id)
{
}
public DbTemplate(string name)
: this(name, ID.NewID)
{
}
public DbTemplate(string name, ID id)
: base(name, ID.IsNullOrEmpty(id) ? ID.NewID : id, TemplateIDs.Template)
{
this.StandardValues = new DbFieldCollection();
this.Add(new DbField(FieldIDs.BaseTemplate) { Shared = true });
// TODO:[High] Move these out into the standard template. we have tempalte inheritance now
this.Add(new DbField(FieldIDs.Lock) { Shared = true });
this.Add(new DbField(FieldIDs.Security) { Shared = true });
this.Add(new DbField(FieldIDs.Created));
this.Add(new DbField(FieldIDs.CreatedBy));
this.Add(new DbField(FieldIDs.Updated));
this.Add(new DbField(FieldIDs.UpdatedBy));
this.Add(new DbField(FieldIDs.Revision));
this.Add(new DbField(FieldIDs.DisplayName));
this.Add(new DbField(FieldIDs.Hidden));
this.Add(new DbField(FieldIDs.ReadOnly));
}
public void Add(string fieldName)
{
this.Add(fieldName, string.Empty);
}
public void Add(ID id)
{
this.Add(id, string.Empty);
}
public new void Add(string fieldName, string standardValue)
{
var field = new DbField(fieldName);
this.Add(field, standardValue);
}
public void Add(ID id, string standardValue)
{
var field = new DbField(id);
this.Add(field, standardValue);
}
public IEnumerator GetEnumerator()
{
return this.Fields.GetEnumerator();
}
protected void Add(DbField field, string standardValue)
{
this.Fields.Add(field);
var standardValueField = new DbField(field.Name, field.ID) { Value = standardValue };
this.StandardValues.Add(standardValueField);
}
}
} | mit | C# |
13a4d0c42d33cb8e0d577d30d21a65350266076b | Make ValidationResult serializable | regisbsb/FluentValidation,olcayseker/FluentValidation,glorylee/FluentValidation,mgmoody42/FluentValidation,pacificIT/FluentValidation,robv8r/FluentValidation,GDoronin/FluentValidation,IRlyDontKnow/FluentValidation,roend83/FluentValidation,deluxetiky/FluentValidation,cecilphillip/FluentValidation,ruisebastiao/FluentValidation,roend83/FluentValidation | src/FluentValidation/Results/ValidationResult.cs | src/FluentValidation/Results/ValidationResult.cs | #region License
// Copyright 2008-2009 Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation.Results {
using System;
using System.Collections.Generic;
using System.Linq;
#if !SILVERLIGHT
[Serializable]
#endif
public class ValidationResult {
private readonly List<ValidationFailure> errors = new List<ValidationFailure>();
public bool IsValid {
get { return Errors.Count == 0; }
}
public IList<ValidationFailure> Errors {
get { return errors; }
}
public ValidationResult() {
}
public ValidationResult(IEnumerable<ValidationFailure> failures) {
errors.AddRange(failures.Where(failure => failure != null));
}
}
} | #region License
// Copyright 2008-2009 Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation.Results {
using System.Collections.Generic;
using System.Linq;
public class ValidationResult {
private readonly List<ValidationFailure> errors = new List<ValidationFailure>();
public bool IsValid {
get { return Errors.Count == 0; }
}
public IList<ValidationFailure> Errors {
get { return errors; }
}
public ValidationResult() {
}
public ValidationResult(IEnumerable<ValidationFailure> failures) {
errors.AddRange(failures.Where(failure => failure != null));
}
}
} | apache-2.0 | C# |
bbd24ab21d2f9147b1d59a99dedfb07e49a42295 | 修改 HelloWorldController. | NemoChenTW/MvcMovie,NemoChenTW/MvcMovie,NemoChenTW/MvcMovie | src/MvcMovie/Controllers/HelloWorldController.cs | src/MvcMovie/Controllers/HelloWorldController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/
public string Index()
{
return "This is my default action...";
}
//
// GET: /HelloWorld/Welcome/
public string Welcome()
{
return "This is the Welcome action method...";
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
}
}
| apache-2.0 | C# |
ef173f78cbedddc85bcb04b1e20e7f22b7623af5 | Write current packaging progress | appharbor/appharbor-cli | src/AppHarbor/CompressionExtensions.cs | src/AppHarbor/CompressionExtensions.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Tar;
namespace AppHarbor
{
public static class CompressionExtensions
{
public static void ToTar(this DirectoryInfo sourceDirectory, Stream output, string[] excludedDirectoryNames)
{
var archive = TarArchive.CreateOutputTarArchive(output);
archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/');
var entries = GetFiles(sourceDirectory, excludedDirectoryNames)
.Select(x => TarEntry.CreateEntryFromFile(x.FullName))
.ToList();
var entriesCount = entries.Count();
for (var i = 0; i < entriesCount; i++)
{
archive.WriteEntry(entries[i], true);
ConsoleProgressBar.Render(i * 100 / (double)entriesCount, ConsoleColor.Green,
string.Format("Packing files ({0} of {1})", i, entriesCount));
}
Console.CursorTop++;
Console.WriteLine();
archive.Close();
}
private static IEnumerable<FileInfo> GetFiles(DirectoryInfo directory, string[] excludedDirectories)
{
return directory.GetFiles("*", SearchOption.TopDirectoryOnly)
.Concat(directory.GetDirectories()
.Where(x => !excludedDirectories.Contains(x.Name))
.SelectMany(x => GetFiles(x, excludedDirectories)));
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Tar;
namespace AppHarbor
{
public static class CompressionExtensions
{
public static void ToTar(this DirectoryInfo sourceDirectory, Stream output, string[] excludedDirectoryNames)
{
var archive = TarArchive.CreateOutputTarArchive(output);
archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/');
var entries = GetFiles(sourceDirectory, excludedDirectoryNames)
.Select(x => TarEntry.CreateEntryFromFile(x.FullName));
foreach (var entry in entries)
{
archive.WriteEntry(entry, true);
}
archive.Close();
}
private static IEnumerable<FileInfo> GetFiles(DirectoryInfo directory, string[] excludedDirectories)
{
return directory.GetFiles("*", SearchOption.TopDirectoryOnly)
.Concat(directory.GetDirectories()
.Where(x => !excludedDirectories.Contains(x.Name))
.SelectMany(x => GetFiles(x, excludedDirectories)));
}
}
}
| mit | C# |
c16c9de605dfb03c71a7fe997529ddadb5c7e8ea | Fix LoanTest call | jzebedee/lcapi | LCAPI/LcapiTests/LoanTest.cs | LCAPI/LcapiTests/LoanTest.cs | using System.Collections.Generic;
using System.IO;
using System.Linq;
using LendingClub;
using Xunit;
namespace LcapiTests
{
public class LoanTest
{
private KeyValuePair<string, string> GetTestCredentials()
{
var lines = File.ReadLines(@"C:\Dropbox\Data\LocalRepos\lcapi\LCAPI\testCredentials.txt").ToList();
return new KeyValuePair<string, string>(lines.First(), lines.Last());
}
private Loan CreateApiObject()
{
var cred = GetTestCredentials();
var apiKey = cred.Value;
return new Loan(apiKey);
}
[Fact]
public void ListingTest()
{
var api = CreateApiObject();
var listing = api.GetListingAsync().Result;
Assert.NotNull(listing);
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Linq;
using LendingClub;
using Xunit;
namespace LcapiTests
{
public class LoanTest
{
private KeyValuePair<string, string> GetTestCredentials()
{
var lines = File.ReadLines(@"C:\Dropbox\Data\LocalRepos\lcapi\LCAPI\testCredentials.txt").ToList();
return new KeyValuePair<string, string>(lines.First(), lines.Last());
}
private Loan CreateApiObject()
{
var cred = GetTestCredentials();
var apiKey = cred.Value;
return new Loan(apiKey);
}
[Fact]
public void ListingTest()
{
var api = CreateApiObject();
var listing = api.GetListing();
Assert.NotNull(listing);
}
}
}
| agpl-3.0 | C# |
a94975b6e6925a52f67731f3dd134ff14760d230 | Remove uneeded player collection methods | HelloKitty/Booma.Proxy | src/Booma.Proxy.Client.Unity.Ship/Services/Entity/Player/INetworkPlayerCollection.cs | src/Booma.Proxy.Client.Unity.Ship/Services/Entity/Player/INetworkPlayerCollection.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Booma.Proxy
{
/// <summary>
/// The collection of network players that are known about.
/// </summary>
public interface INetworkPlayerCollection : IEnumerable<INetworkPlayer>
{
/// <summary>
/// The networked players.
/// </summary>
IEnumerable<INetworkPlayer> Players { get; }
/// <summary>
/// Returns the <see cref="INetworkPlayer"/> with the id.
/// Or null if the player doesn't exist.
/// </summary>
/// <param name="id">The id to check for.</param>
/// <returns>The <see cref="INetworkPlayer"/> with the id or null.</returns>
INetworkPlayer this[int id] { get; }
/// <summary>
/// Indicates if it contains the <see cref="id"/> key value.
/// </summary>
/// <param name="id">The id to check for.</param>
/// <returns>True if the collection contains the ID.</returns>
bool ContainsId(int id);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Booma.Proxy
{
/// <summary>
/// The collection of network players that are known about.
/// </summary>
public interface INetworkPlayerCollection : IEnumerable<INetworkPlayer>
{
/// <summary>
/// The local player.
/// </summary>
INetworkPlayer Local { get; }
/// <summary>
/// The networked players.
/// </summary>
IEnumerable<INetworkPlayer> Players { get; }
/// <summary>
/// The networked player's excluding the <see cref="Local"/> player.
/// </summary>
IEnumerable<INetworkPlayer> ExcludingLocal { get; }
/// <summary>
/// Returns the <see cref="INetworkPlayer"/> with the id.
/// Or null if the player doesn't exist.
/// </summary>
/// <param name="id">The id to check for.</param>
/// <returns>The <see cref="INetworkPlayer"/> with the id or null.</returns>
INetworkPlayer this[int id] { get; }
/// <summary>
/// Indicates if it contains the <see cref="id"/> key value.
/// </summary>
/// <param name="id">The id to check for.</param>
/// <returns>True if the collection contains the ID.</returns>
bool ContainsId(int id);
}
}
| agpl-3.0 | C# |
8153c5dcd856e9968287bc1a73f33061e164f8be | Fix #10 - Relocate default value for base URL | mailosaurapp/mailosaur-dotnet | Mailosaur/MailosaurClient.cs | Mailosaur/MailosaurClient.cs | namespace Mailosaur
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Mailosaur.Operations;
public class MailosaurClient
{
public Servers Servers { get; private set; }
public Messages Messages { get; private set; }
public Files Files { get; private set; }
public Analysis Analysis { get; private set; }
private readonly HttpClient _client;
/// <summary>
/// Initializes a new instance of the MailosaurClient class.
/// </summary>
/// <param name='apiKey'>
/// Your Mailosaur API key.
/// </param>
public MailosaurClient(string apiKey) : this(apiKey, "https://mailosaur.com/") {}
/// <summary>
/// Initializes a new instance of the MailosaurClient class.
/// </summary>
/// <param name='apiKey'>
/// Your Mailosaur API key.
/// </param>
/// <param name='baseUrl'>
/// Optional. Override the base URL for the mailosaur server.
/// </param>
public MailosaurClient(string apiKey, string baseUrl)
{
_client = new HttpClient();
_client.BaseAddress = new Uri(baseUrl);
_client.DefaultRequestHeaders.Add("Accept", "application/json");
_client.DefaultRequestHeaders.Add("User-Agent", "mailosaur-dotnet/6.0.0");
var apiKeyBytes = ASCIIEncoding.ASCII.GetBytes($"{apiKey}:");
var apiKeyBase64 = Convert.ToBase64String(apiKeyBytes);
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", apiKeyBase64);
Servers = new Servers(_client);
Messages = new Messages(_client);
Files = new Files(_client);
Analysis = new Analysis(_client);
}
}
}
| namespace Mailosaur
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Mailosaur.Operations;
public class MailosaurClient
{
public Servers Servers { get; private set; }
public Messages Messages { get; private set; }
public Files Files { get; private set; }
public Analysis Analysis { get; private set; }
private readonly HttpClient _client;
/// <summary>
/// Initializes a new instance of the MailosaurClient class.
/// </summary>
/// <param name='apiKey'>
/// Your Mailosaur API key.
/// </param>
public MailosaurClient(string apiKey) : this(apiKey, null) {}
/// <summary>
/// Initializes a new instance of the MailosaurClient class.
/// </summary>
/// <param name='apiKey'>
/// Your Mailosaur API key.
/// </param>
/// <param name='baseUrl'>
/// Optional. Override the base URL for the mailosaur server.
/// </param>
public MailosaurClient(string apiKey, string baseUrl = "https://mailosaur.com/")
{
_client = new HttpClient();
_client.BaseAddress = new Uri(baseUrl);
_client.DefaultRequestHeaders.Add("Accept", "application/json");
_client.DefaultRequestHeaders.Add("User-Agent", "mailosaur-dotnet/6.0.0");
var apiKeyBytes = ASCIIEncoding.ASCII.GetBytes($"{apiKey}:");
var apiKeyBase64 = Convert.ToBase64String(apiKeyBytes);
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", apiKeyBase64);
Servers = new Servers(_client);
Messages = new Messages(_client);
Files = new Files(_client);
Analysis = new Analysis(_client);
}
}
}
| mit | C# |
2f6c0cf40919173c04d74899cd3f9aab39adb17d | Revert "Made testmethods static." | RobThree/NUlid | NUlid.Performance/Program.cs | NUlid.Performance/Program.cs | using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using NUlid.Rng;
using System;
namespace NUlid.Performance;
[MemoryDiagnoser]
public class Program
{
private static readonly SimpleUlidRng _simplerng = new();
private static readonly CSUlidRng _csrng = new();
private static readonly MonotonicUlidRng _simplemonotonicrng = new(_simplerng);
private static readonly MonotonicUlidRng _csmonotonicrng = new(_csrng);
private static readonly Random _plainrng = new();
public static void Main()
=> BenchmarkRunner.Run(typeof(Program).Assembly);
private static byte[] GetRandomBytes(int amount)
{
var b = new byte[amount];
_plainrng.NextBytes(b);
return b;
}
[Benchmark(Description = "Guid.NewGuid()")]
public Guid Guid_NewGuid() => Guid.NewGuid();
[Benchmark(Description = "Ulid.NewUlid(SimpleUlidRng)")]
public Ulid Ulid_NewUlid_SimpleUlidRng() => Ulid.NewUlid(_simplerng);
[Benchmark(Description = "Ulid.NewUlid(CSUlidRng)")]
public Ulid Ulid_NewUlid_CSUlidRng() => Ulid.NewUlid(_csrng);
[Benchmark(Description = "Ulid.NewUlid(SimpleMonotonicUlidRng)")]
public Ulid Ulid_NewUlid_SimpleMonotonicUlidRng() => Ulid.NewUlid(_simplemonotonicrng);
[Benchmark(Description = "Ulid.NewUlid(CSMonotonicUlidRng)")]
public Ulid Ulid_NewUlid_CSMonotonicUlidRng() => Ulid.NewUlid(_csmonotonicrng);
[Benchmark(Description = "Guid.Parse(string)")]
public Guid Guid_Parse() => Guid.Parse(Guid.NewGuid().ToString());
[Benchmark(Description = "Ulid.Parse(string)")]
public Ulid Ulid_Parse() => Ulid.Parse(Ulid.NewUlid().ToString());
[Benchmark(Description = "Guid.ToString()")]
public string Guid_ToString() => Guid.NewGuid().ToString();
[Benchmark(Description = "Ulid.ToString()")]
public string Ulid_ToString() => Ulid.NewUlid().ToString();
[Benchmark(Description = "new Guid(byte[])")]
public Guid New_Guid_Byte() => new(GetRandomBytes(16));
[Benchmark(Description = "new Ulid(byte[])")]
public Ulid New_Ulid_Byte() => new(GetRandomBytes(16));
[Benchmark(Description = "Guid.ToByteArray()")]
public byte[] Guid_ToByteArray() => Guid.NewGuid().ToByteArray();
[Benchmark(Description = "Ulid.ToByteArray()")]
public byte[] Ulid_ToByteArray() => Ulid.NewUlid().ToByteArray();
[Benchmark(Description = "Ulid.ToGuid()")]
public Guid Ulid_ToGuid() => Ulid.NewUlid().ToGuid();
[Benchmark(Description = "new Ulid(Guid)")]
public Ulid New_Ulid_Guid() => new(Guid.NewGuid());
} | using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using NUlid.Rng;
using System;
namespace NUlid.Performance;
[MemoryDiagnoser]
public class Program
{
private static readonly SimpleUlidRng _simplerng = new();
private static readonly CSUlidRng _csrng = new();
private static readonly MonotonicUlidRng _simplemonotonicrng = new(_simplerng);
private static readonly MonotonicUlidRng _csmonotonicrng = new(_csrng);
private static readonly Random _plainrng = new();
public static void Main()
=> BenchmarkRunner.Run(typeof(Program).Assembly);
private static byte[] GetRandomBytes(int amount)
{
var b = new byte[amount];
_plainrng.NextBytes(b);
return b;
}
[Benchmark(Description = "Guid.NewGuid()")]
public static Guid Guid_NewGuid() => Guid.NewGuid();
[Benchmark(Description = "Ulid.NewUlid(SimpleUlidRng)")]
public static Ulid Ulid_NewUlid_SimpleUlidRng() => Ulid.NewUlid(_simplerng);
[Benchmark(Description = "Ulid.NewUlid(CSUlidRng)")]
public static Ulid Ulid_NewUlid_CSUlidRng() => Ulid.NewUlid(_csrng);
[Benchmark(Description = "Ulid.NewUlid(SimpleMonotonicUlidRng)")]
public static Ulid Ulid_NewUlid_SimpleMonotonicUlidRng() => Ulid.NewUlid(_simplemonotonicrng);
[Benchmark(Description = "Ulid.NewUlid(CSMonotonicUlidRng)")]
public static Ulid Ulid_NewUlid_CSMonotonicUlidRng() => Ulid.NewUlid(_csmonotonicrng);
[Benchmark(Description = "Guid.Parse(string)")]
public static Guid Guid_Parse() => Guid.Parse(Guid.NewGuid().ToString());
[Benchmark(Description = "Ulid.Parse(string)")]
public static Ulid Ulid_Parse() => Ulid.Parse(Ulid.NewUlid().ToString());
[Benchmark(Description = "Guid.ToString()")]
public static string Guid_ToString() => Guid.NewGuid().ToString();
[Benchmark(Description = "Ulid.ToString()")]
public static string Ulid_ToString() => Ulid.NewUlid().ToString();
[Benchmark(Description = "new Guid(byte[])")]
public static Guid New_Guid_Byte() => new(GetRandomBytes(16));
[Benchmark(Description = "new Ulid(byte[])")]
public static Ulid New_Ulid_Byte() => new(GetRandomBytes(16));
[Benchmark(Description = "Guid.ToByteArray()")]
public static byte[] Guid_ToByteArray() => Guid.NewGuid().ToByteArray();
[Benchmark(Description = "Ulid.ToByteArray()")]
public static byte[] Ulid_ToByteArray() => Ulid.NewUlid().ToByteArray();
[Benchmark(Description = "Ulid.ToGuid()")]
public static Guid Ulid_ToGuid() => Ulid.NewUlid().ToGuid();
[Benchmark(Description = "new Ulid(Guid)")]
public static Ulid New_Ulid_Guid() => new(Guid.NewGuid());
} | mit | C# |
5c605ec5d12a6c17c111f8875982ab01512bf4cb | Remove redundant namespace in UITest | ProgTrade/nUpdate,ProgTrade/nUpdate | nUpdate.UserInterfaceTest/Properties/AssemblyInfo.cs | nUpdate.UserInterfaceTest/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
using nUpdate.Core;
// 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("nUpdate.UserInterfaceTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("nUpdate.UserInterfaceTest")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1c11588b-06fc-4502-a7c1-00c75e9e551f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: nUpdateVersion("1.0")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using nUpdate.Core;
// 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("nUpdate.UserInterfaceTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("nUpdate.UserInterfaceTest")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1c11588b-06fc-4502-a7c1-00c75e9e551f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: nUpdateVersion("1.0")] | mit | C# |
679cb32a3277d363e701ea55d86e369cf7b80bee | Disable test that is too slow for CI | martincostello/project-euler | src/ProjectEuler.Tests/Puzzles/Puzzle035Tests.cs | src/ProjectEuler.Tests/Puzzles/Puzzle035Tests.cs | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System.Collections.Generic;
using Xunit;
/// <summary>
/// A class containing tests for the <see cref="Puzzle035"/> class. This class cannot be inherited.
/// </summary>
public static class Puzzle035Tests
{
[Theory]
[InlineData(100, 13)]
public static void Puzzle035_Returns_Correct_Solution(string maximum, int expected)
{
// Arrange
var args = new[] { maximum };
// Act and Assert
Puzzles.AssertSolution<Puzzle035>(args, expected);
}
[NotCITheory]
[InlineData(1000000, 55)]
public static void Puzzle035_Returns_Correct_Solution_Slow(string maximum, int expected)
{
// Arrange
var args = new[] { maximum };
// Act and Assert
Puzzles.AssertSolution<Puzzle035>(args, expected);
}
[Theory]
[InlineData(197, new[] { 197, 971, 719 })]
public static void Puzzle035_GetRotations_Returns_Correct_Values(int value, IEnumerable<int> expected)
{
// Act
IEnumerable<int> actual = Puzzle035.GetRotations(value);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public static void Puzzle035_Returns_Minus_One_If_Maximum_Is_Invalid()
{
// Arrange
string[] args = new[] { "a" };
// Act and Assert
Puzzles.AssertInvalid<Puzzle035>(args);
}
[Fact]
public static void Puzzle035_Returns_Minus_One_If_Maximum_Is_Too_Small()
{
// Arrange
string[] args = new[] { "1" };
// Act and Assert
Puzzles.AssertInvalid<Puzzle035>(args);
}
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System.Collections.Generic;
using Xunit;
/// <summary>
/// A class containing tests for the <see cref="Puzzle035"/> class. This class cannot be inherited.
/// </summary>
public static class Puzzle035Tests
{
[Theory]
[InlineData(100, 13)]
[InlineData(1000000, 55)]
public static void Puzzle035_Returns_Correct_Solution(string maximum, int expected)
{
// Arrange
var args = new[] { maximum };
// Act and Assert
Puzzles.AssertSolution<Puzzle035>(args, expected);
}
[Theory]
[InlineData(197, new[] { 197, 971, 719 })]
public static void Puzzle035_GetRotations_Returns_Correct_Values(int value, IEnumerable<int> expected)
{
// Act
IEnumerable<int> actual = Puzzle035.GetRotations(value);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public static void Puzzle035_Returns_Minus_One_If_Maximum_Is_Invalid()
{
// Arrange
string[] args = new[] { "a" };
// Act and Assert
Puzzles.AssertInvalid<Puzzle035>(args);
}
[Fact]
public static void Puzzle035_Returns_Minus_One_If_Maximum_Is_Too_Small()
{
// Arrange
string[] args = new[] { "1" };
// Act and Assert
Puzzles.AssertInvalid<Puzzle035>(args);
}
}
}
| apache-2.0 | C# |
3fa5d710fd2a726e189a1c9987bb6605c723a58a | Update IPathGeometry.cs | Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | src/Core2D/Model/Path/IPathGeometry.cs | src/Core2D/Model/Path/IPathGeometry.cs | using System.Collections.Immutable;
namespace Core2D.Path
{
/// <summary>
/// Defines path geometry contract.
/// </summary>
public interface IPathGeometry : IObservableObject, IStringExporter
{
/// <summary>
/// Gets or sets figures collection.
/// </summary>
ImmutableArray<IPathFigure> Figures { get; set; }
/// <summary>
/// Gets or sets fill rule.
/// </summary>
FillRule FillRule { get; set; }
}
}
| using System.Collections.Immutable;
namespace Core2D.Path
{
/// <summary>
/// Defines path geometry contract.
/// </summary>
public interface IPathGeometry : IObservableObject
{
/// <summary>
/// Gets or sets figures collection.
/// </summary>
ImmutableArray<IPathFigure> Figures { get; set; }
/// <summary>
/// Gets or sets fill rule.
/// </summary>
FillRule FillRule { get; set; }
}
}
| mit | C# |
6c578f3cc79500a2e50942014ce7c59c2af73a4c | Comment out non-compiling test while we don't flatten ListGroups | evildour/google-cloud-dotnet,jskeet/google-cloud-dotnet,iantalarico/google-cloud-dotnet,googleapis/google-cloud-dotnet,benwulfe/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,benwulfe/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,iantalarico/google-cloud-dotnet,jskeet/google-cloud-dotnet,ctaggart/google-cloud-dotnet,benwulfe/google-cloud-dotnet,jskeet/google-cloud-dotnet,ctaggart/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,iantalarico/google-cloud-dotnet,chrisdunelm/gcloud-dotnet,chrisdunelm/google-cloud-dotnet,evildour/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/gcloud-dotnet,evildour/google-cloud-dotnet,ctaggart/google-cloud-dotnet | apis/Google.Monitoring.V3/Google.Monitoring.V3.Snippets/GroupServiceClientSnippets.cs | apis/Google.Monitoring.V3/Google.Monitoring.V3.Snippets/GroupServiceClientSnippets.cs | // Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax;
using System;
using System.Linq;
using Xunit;
namespace Google.Monitoring.V3
{
[Collection(nameof(MonitoringFixture))]
public class GroupServiceClientSnippets
{
private readonly MonitoringFixture _fixture;
public GroupServiceClientSnippets(MonitoringFixture fixture)
{
_fixture = fixture;
}
/* TODO: Reinstate when ListGroups is present again.
[Fact]
public void ListGroups()
{
string projectId = _fixture.ProjectId;
// Snippet: ListGroups
GroupServiceClient client = GroupServiceClient.Create();
string projectName = MetricServiceClient.FormatProjectName(projectId);
IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", "");
foreach (Group group in groups.Take(10))
{
Console.WriteLine($"{group.Name}: {group.DisplayName}");
}
// End snippet
}
*/
}
}
| // Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax;
using System;
using System.Linq;
using Xunit;
namespace Google.Monitoring.V3
{
[Collection(nameof(MonitoringFixture))]
public class GroupServiceClientSnippets
{
private readonly MonitoringFixture _fixture;
public GroupServiceClientSnippets(MonitoringFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void ListGroups()
{
string projectId = _fixture.ProjectId;
// Snippet: ListGroups
GroupServiceClient client = GroupServiceClient.Create();
string projectName = MetricServiceClient.FormatProjectName(projectId);
IPagedEnumerable<ListGroupsResponse, Group> groups = client.ListGroups(projectName, "", "", "");
foreach (Group group in groups.Take(10))
{
Console.WriteLine($"{group.Name}: {group.DisplayName}");
}
// End snippet
}
}
}
| apache-2.0 | C# |
2e62317fcef41082ea9c989dc8b659e3daaadd3f | Add semicolon | octoblu/meshblu-connector-skype,octoblu/meshblu-connector-skype | src/csharp/get-state.cs | src/csharp/get-state.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using Microsoft.Lync.Model.Conversation.AudioVideo;
using Microsoft.Lync.Model.Extensibility;
public class Startup
{
public async Task<object> Invoke(string conversationId)
{
var Client = LyncClient.GetClient();
Thread.Sleep(3000);
Conversation conversation = Client.ConversationManager.Conversations.FirstOrDefault();
var participant = conversation.Participants.Where(p => p.IsSelf).FirstOrDefault();
var videoChannel = ((AVModality)conversation.Modalities[ModalityTypes.AudioVideo]).VideoChannel;
return new {
conversationId = conversation.Properties[ConversationProperty.Id].ToString(),
meetingUrl = conversation.Properties[ConversationProperty.ConferencingUri].ToString(),
audioEnabled = participant.IsMuted,
videoEnabled = videoChannel.IsContributing,
};
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using Microsoft.Lync.Model.Conversation.AudioVideo;
using Microsoft.Lync.Model.Extensibility;
public class Startup
{
public async Task<object> Invoke(string conversationId)
{
var Client = LyncClient.GetClient();
Thread.Sleep(3000);
Conversation conversation = Client.ConversationManager.Conversations.FirstOrDefault();
var participant = conversation.Participants.Where(p => p.IsSelf).FirstOrDefault();
var videoChannel = ((AVModality)conversation.Modalities[ModalityTypes.AudioVideo]).VideoChannel;
return new {
conversationId = conversation.Properties[ConversationProperty.Id].ToString(),
meetingUrl = conversation.Properties[ConversationProperty.ConferencingUri].ToString(),
audioEnabled = participant.IsMuted,
videoEnabled = videoChannel.IsContributing,
}
}
}
| mit | C# |
f8be6d789921454fac673ea4d4f15f6b9c4f70e4 | Fix build | NicolasDorier/NBitcoin,MetacoSA/NBitcoin,MetacoSA/NBitcoin | NBitcoin.Tests/sample_tests.cs | NBitcoin.Tests/sample_tests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace NBitcoin.Tests
{
public class sample_tests
{
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanBuildSegwitP2SHMultisigTransactions()
{
using(var nodeBuilder = NodeBuilderEx.Create())
{
var rpc = nodeBuilder.CreateNode().CreateRPCClient();
nodeBuilder.StartAll();
rpc.Generate(102);
// Build the keys and addresses
var masterKeys = Enumerable.Range(0, 3).Select(_ => new ExtKey()).ToArray();
var keyRedeemAddresses = Enumerable.Range(0, 4)
.Select(i => masterKeys.Select(m => m.Derive(i, false)).ToArray())
.Select(keys =>
(
Keys: keys.Select(k => k.PrivateKey).ToArray(),
Redeem: PayToMultiSigTemplate.Instance.GenerateScriptPubKey(keys.Length, keys.Select(k => k.PrivateKey.PubKey).ToArray()))
).Select(_ =>
(
Keys: _.Keys,
Redeem: _.Redeem,
Address: _.Redeem.WitHash.ScriptPubKey.Hash.ScriptPubKey.GetDestinationAddress(nodeBuilder.Network)
));
// Fund the addresses
var scriptCoins = keyRedeemAddresses.Select(async kra =>
{
var id = await rpc.SendToAddressAsync(kra.Address, Money.Coins(1));
var tx = await rpc.GetRawTransactionAsync(id);
return tx.Outputs.AsCoins().Where(o => o.ScriptPubKey == kra.Address.ScriptPubKey)
.Select(c => c.ToScriptCoin(kra.Redeem)).Single();
}).Select(t => t.Result).ToArray();
var destination = new Key().ScriptPubKey;
var amount = new Money(1, MoneyUnit.BTC);
var redeemScripts = keyRedeemAddresses.Select(kra => kra.Redeem).ToArray();
var privateKeys = keyRedeemAddresses.SelectMany(kra => kra.Keys).ToArray();
var builder = Network.Main.CreateTransactionBuilder();
var rate = new FeeRate(Money.Satoshis(1), 1);
var signedTx = builder
.AddCoins(scriptCoins)
.AddKeys(privateKeys)
.Send(destination, amount)
.SubtractFees()
.SetChange(new Key().ScriptPubKey)
.SendEstimatedFees(rate)
.BuildTransaction(true);
rpc.SendRawTransaction(signedTx);
var errors = builder.Check(signedTx);
Assert.Empty(errors);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace NBitcoin.Tests
{
public class sample_tests
{
[Fact]
[Trait("UnitTest", "UnitTest")]
public void CanBuildSegwitP2SHMultisigTransactions()
{
using(var nodeBuilder = NodeBuilderEx.Create())
{
var rpc = nodeBuilder.CreateNode().CreateRPCClient();
nodeBuilder.StartAll();
rpc.Generate(102);
// Build the keys and addresses
var masterKeys = Enumerable.Range(0, 3).Select(_ => new ExtKey()).ToArray();
var keyRedeemAddresses = Enumerable.Range(0, 4)
.Select(i => masterKeys.Select(m => m.Derive(i, false)).ToArray())
.Select(keys =>
(
Keys: keys.Select(k => k.PrivateKey).ToArray(),
Redeem: PayToMultiSigTemplate.Instance.GenerateScriptPubKey(keys.Length, keys.Select(k => k.PrivateKey.PubKey).ToArray()))
).Select(_ =>
(
Keys: _.Keys,
Redeem: _.Redeem,
Address: _.Redeem.WitHash.ScriptPubKey.Hash.ScriptPubKey.GetDestinationAddress(nodeBuilder.Network)
));
// Fund the addresses
var scriptCoins = keyRedeemAddresses.Select(async kra =>
{
var id = await rpc.SendToAddressAsync(kra.Address, Money.Coins(1));
var tx = await rpc.GetRawTransactionAsync(id);
return tx.Outputs.AsCoins().Where(o => o.ScriptPubKey == kra.Address.ScriptPubKey)
.Select(c => c.ToScriptCoin(kra.Redeem)).Single();
}).Select(t => t.Result).ToArray();
var destination = new Key().ScriptPubKey;
var amount = new Money(1, MoneyUnit.BTC);
var redeemScripts = keyRedeemAddresses.Select(kra => kra.Redeem).ToArray();
var privateKeys = keyRedeemAddresses.SelectMany(kra => kra.Keys).ToArray();
var builder = Network.CreateTransactionBuilder();
var rate = new FeeRate(Money.Satoshis(1), 1);
var signedTx = builder
.AddCoins(scriptCoins)
.AddKeys(privateKeys)
.Send(destination, amount)
.SubtractFees()
.SetChange(new Key().ScriptPubKey)
.SendEstimatedFees(rate)
.BuildTransaction(true);
rpc.SendRawTransaction(signedTx);
var errors = builder.Check(signedTx);
Assert.Empty(errors);
}
}
}
}
| mit | C# |
0aecb6e6c6ea49a9f939ec968abbbbed177346e3 | Rearrange vms | nigel-sampson/talks,nigel-sampson/talks | ndc-sydney/Hubb.Core/ViewModels/ShellViewModel.cs | ndc-sydney/Hubb.Core/ViewModels/ShellViewModel.cs | using System;
using Caliburn.Micro;
using Hubb.Core.Services;
using Octokit;
namespace Hubb.Core.ViewModels
{
public class ShellViewModel : Screen
{
public ShellViewModel(IHubbClient hubbClient, IEventAggregator eventAggregator)
{
Issues = new IssuesViewModel(hubbClient, eventAggregator);
Menu = new MenuViewModel(hubbClient, eventAggregator);
Issues.ConductWith(this);
Menu.ConductWith(this);
}
public MenuViewModel Menu { get; }
public IssuesViewModel Issues { get; }
}
}
| using System;
using Caliburn.Micro;
using Hubb.Core.Services;
using Octokit;
namespace Hubb.Core.ViewModels
{
public class ShellViewModel : Screen
{
public ShellViewModel(IHubbClient hubbClient, IEventAggregator eventAggregator)
{
Menu = new MenuViewModel(hubbClient, eventAggregator);
Issues = new IssuesViewModel(hubbClient, eventAggregator);
Menu.ConductWith(this);
Issues.ConductWith(this);
}
public MenuViewModel Menu { get; }
public IssuesViewModel Issues { get; }
}
}
| mit | C# |
896a87e62921bfef2281a822eb20c784e3612fd2 | Replace accidental tab with spaces | smoogipooo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,ppy/osu,ppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu | osu.Game.Rulesets.Osu/Skinning/OsuSkinConfiguration.cs | osu.Game.Rulesets.Osu/Skinning/OsuSkinConfiguration.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Rulesets.Osu.Skinning
{
public enum OsuSkinConfiguration
{
HitCirclePrefix,
HitCircleOverlap,
SliderBorderSize,
SliderPathRadius,
AllowSliderBallTint,
CursorExpand,
CursorRotate,
HitCircleOverlayAboveNumber,
HitCircleOverlayAboveNumer, // Some old skins will have this typo
SpinnerFrequencyModulate
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Rulesets.Osu.Skinning
{
public enum OsuSkinConfiguration
{
HitCirclePrefix,
HitCircleOverlap,
SliderBorderSize,
SliderPathRadius,
AllowSliderBallTint,
CursorExpand,
CursorRotate,
HitCircleOverlayAboveNumber,
HitCircleOverlayAboveNumer, // Some old skins will have this typo
SpinnerFrequencyModulate
}
}
| mit | C# |
af6f2e54fd6f1bbba5f1627eafc8e7bdffb8fef1 | Add execute method overload with ordering | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University/Queries/Query.cs | R7.University/Queries/Query.cs | //
// Query.cs
//
// Author:
// Roman M. Yagodin <[email protected]>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using R7.University.Models;
namespace R7.University.Queries
{
public class Query<TEntity> where TEntity: class
{
private readonly IModelContext modelContext;
public Query (IModelContext modelContext)
{
this.modelContext = modelContext;
}
public IList<TEntity> Execute ()
{
return modelContext.Query<TEntity> ().ToList ();
}
public IList<TEntity> Execute<TKey> (Func<TEntity,TKey> keySelector)
{
return modelContext.Query<TEntity> ().OrderBy (keySelector).ToList ();
}
}
}
| //
// Query.cs
//
// Author:
// Roman M. Yagodin <[email protected]>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using R7.University.Models;
namespace R7.University.Queries
{
public class Query<TEntity> where TEntity: class
{
private readonly IModelContext modelContext;
public Query (IModelContext modelContext)
{
this.modelContext = modelContext;
}
public IEnumerable<TEntity> Execute ()
{
return modelContext.Query<TEntity> ().ToList ();
}
}
}
| agpl-3.0 | C# |
88b2a12c0942e6296f453456a42e8a7958a92488 | Reduce footer height to match back button | peppy/osu,ppy/osu,UselessToucan/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu | osu.Game/Screens/Multi/Match/Components/Footer.cs | osu.Game/Screens/Multi/Match/Components/Footer.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Game.Online.Multiplayer;
using osuTK;
namespace osu.Game.Screens.Multi.Match.Components
{
public class Footer : CompositeDrawable
{
public const float HEIGHT = 50;
public Action OnStart;
public readonly Bindable<PlaylistItem> SelectedItem = new Bindable<PlaylistItem>();
private readonly Drawable background;
public Footer()
{
RelativeSizeAxes = Axes.X;
Height = HEIGHT;
InternalChildren = new[]
{
background = new Box { RelativeSizeAxes = Axes.Both },
new ReadyButton
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(600, 50),
SelectedItem = { BindTarget = SelectedItem },
Action = () => OnStart?.Invoke()
}
};
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
background.Colour = Color4Extensions.FromHex(@"28242d");
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Game.Online.Multiplayer;
using osuTK;
namespace osu.Game.Screens.Multi.Match.Components
{
public class Footer : CompositeDrawable
{
public const float HEIGHT = 100;
public Action OnStart;
public readonly Bindable<PlaylistItem> SelectedItem = new Bindable<PlaylistItem>();
private readonly Drawable background;
public Footer()
{
RelativeSizeAxes = Axes.X;
Height = HEIGHT;
InternalChildren = new[]
{
background = new Box { RelativeSizeAxes = Axes.Both },
new ReadyButton
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(600, 50),
SelectedItem = { BindTarget = SelectedItem },
Action = () => OnStart?.Invoke()
}
};
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
background.Colour = Color4Extensions.FromHex(@"28242d");
}
}
}
| mit | C# |
1ac8cfa0852aff9f5c8c8e7eb3c017c2fb8c4a4e | fix #14; UnmaskRaycastFilter is not reliable | mob-sakai/UnmaskForUGUI | Scripts/UnmaskRaycastFilter.cs | Scripts/UnmaskRaycastFilter.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Coffee.UIExtensions
{
/// <summary>
/// Unmask Raycast Filter.
/// The ray passes through the unmasked rectangle.
/// </summary>
[AddComponentMenu("UI/Unmask/UnmaskRaycastFilter", 2)]
public class UnmaskRaycastFilter : MonoBehaviour, ICanvasRaycastFilter
{
//################################
// Serialize Members.
//################################
[Tooltip("Target unmask component. The ray passes through the unmasked rectangle.")]
[SerializeField] Unmask m_TargetUnmask;
//################################
// Public Members.
//################################
/// <summary>
/// Target unmask component. Ray through the unmasked rectangle.
/// </summary>
public Unmask targetUnmask{ get { return m_TargetUnmask; } set { m_TargetUnmask = value; } }
/// <summary>
/// Given a point and a camera is the raycast valid.
/// </summary>
/// <returns>Valid.</returns>
/// <param name="sp">Screen position.</param>
/// <param name="eventCamera">Raycast camera.</param>
public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
{
// Skip if deactived.
if (!isActiveAndEnabled || !m_TargetUnmask || !m_TargetUnmask.isActiveAndEnabled)
{
return true;
}
// check inside
return !RectTransformUtility.RectangleContainsScreenPoint ((m_TargetUnmask.transform as RectTransform), sp);
}
//################################
// Private Members.
//################################
/// <summary>
/// This function is called when the object becomes enabled and active.
/// </summary>
void OnEnable()
{
}
}
} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Coffee.UIExtensions
{
/// <summary>
/// Unmask Raycast Filter.
/// The ray passes through the unmasked rectangle.
/// </summary>
[AddComponentMenu("UI/Unmask/UnmaskRaycastFilter", 2)]
public class UnmaskRaycastFilter : MonoBehaviour, ICanvasRaycastFilter
{
//################################
// Constant or Static Members.
//################################
Vector3[] s_WorldCorners = new Vector3[4];
//################################
// Serialize Members.
//################################
[Tooltip("Target unmask component. The ray passes through the unmasked rectangle.")]
[SerializeField] Unmask m_TargetUnmask;
//################################
// Public Members.
//################################
/// <summary>
/// Target unmask component. Ray through the unmasked rectangle.
/// </summary>
public Unmask targetUnmask{ get { return m_TargetUnmask; } set { m_TargetUnmask = value; } }
/// <summary>
/// Given a point and a camera is the raycast valid.
/// </summary>
/// <returns>Valid.</returns>
/// <param name="sp">Screen position.</param>
/// <param name="eventCamera">Raycast camera.</param>
public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
{
// Skip if deactived.
if (!isActiveAndEnabled || !m_TargetUnmask || !m_TargetUnmask.isActiveAndEnabled)
{
return true;
}
// Get world corners for the target.
(m_TargetUnmask.transform as RectTransform).GetWorldCorners(s_WorldCorners);
// Convert to screen positions.
var cam = eventCamera ?? Camera.main;
var p = cam.WorldToScreenPoint(sp);
var a = cam.WorldToScreenPoint(s_WorldCorners[0]);
var b = cam.WorldToScreenPoint(s_WorldCorners[1]);
var c = cam.WorldToScreenPoint(s_WorldCorners[2]);
var d = cam.WorldToScreenPoint(s_WorldCorners[3]);
// check left/right side
var ab = Cross(p - a, b - a) < 0.0;
var bc = Cross(p - b, c - b) < 0.0;
var cd = Cross(p - c, d - c) < 0.0;
var da = Cross(p - d, a - d) < 0.0;
// check inside
return ab ^ bc ||bc ^ cd ||cd ^ da;
}
//################################
// Private Members.
//################################
/// <summary>
/// This function is called when the object becomes enabled and active.
/// </summary>
void OnEnable()
{
}
/// <summary>
/// Cross for Vector2.
/// </summary>
float Cross(Vector2 a, Vector2 b)
{
return a.x * b.y - a.y * b.x;
}
}
} | mit | C# |
2dd163b0acc8c62b0f5467f936f1635e2797497c | Use int | martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode | tests/AdventOfCode.Tests/Puzzles/Y2021/Day16Tests.cs | tests/AdventOfCode.Tests/Puzzles/Y2021/Day16Tests.cs | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.AdventOfCode.Puzzles.Y2021;
public sealed class Day16Tests : PuzzleTest
{
public Day16Tests(ITestOutputHelper outputHelper)
: base(outputHelper)
{
}
[Theory]
[InlineData("D2FE28", 6)]
[InlineData("38006F45291200", 9)]
[InlineData("EE00D40C823060", 14)]
[InlineData("8A004A801A8002F478", 16)]
[InlineData("620080001611562C8802118E34", 12)]
[InlineData("C0015000016115A2E0802F182340", 23)]
[InlineData("A0016C880162017C3686B18A3D4780", 31)]
public void Y2021_Day16_Decode_Returns_Correct_Value(string transmission, int expected)
{
// Act
int actual = Day16.Decode(transmission);
// Assert
actual.ShouldBe(expected);
}
[Fact]
public async Task Y2021_Day16_Solve_Returns_Correct_Solution()
{
// Act
var puzzle = await SolvePuzzleAsync<Day16>();
// Assert
puzzle.VersionNumberSum.ShouldBe(974);
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.AdventOfCode.Puzzles.Y2021;
public sealed class Day16Tests : PuzzleTest
{
public Day16Tests(ITestOutputHelper outputHelper)
: base(outputHelper)
{
}
[Theory]
[InlineData("D2FE28", 6)]
[InlineData("38006F45291200", 9)]
[InlineData("EE00D40C823060", 14)]
[InlineData("8A004A801A8002F478", 16)]
[InlineData("620080001611562C8802118E34", 12)]
[InlineData("C0015000016115A2E0802F182340", 23)]
[InlineData("A0016C880162017C3686B18A3D4780", 31)]
public void Y2021_Day16_Decode_Returns_Correct_Value(string transmission, long expected)
{
// Act
long actual = Day16.Decode(transmission);
// Assert
actual.ShouldBe(expected);
}
[Fact]
public async Task Y2021_Day16_Solve_Returns_Correct_Solution()
{
// Act
var puzzle = await SolvePuzzleAsync<Day16>();
// Assert
puzzle.VersionNumberSum.ShouldBe(974);
}
}
| apache-2.0 | C# |
b33501dd00bbb4b39a0f3a56f3f70eb19fd81720 | fix for fakeiteasy issue | wikibus/Argolis | src/Lernaean.Hydra.Tests/ApiDocumentation/DefaultPropertyRangeRetrievalPolicyTests.cs | src/Lernaean.Hydra.Tests/ApiDocumentation/DefaultPropertyRangeRetrievalPolicyTests.cs | using System;
using System.Collections.Generic;
using FakeItEasy;
using FluentAssertions;
using Hydra.Discovery.SupportedProperties;
using JsonLD.Entities;
using TestHydraApi;
using Vocab;
using Xunit;
namespace Lernaean.Hydra.Tests.ApiDocumentation
{
public class DefaultPropertyRangeRetrievalPolicyTests
{
private readonly DefaultPropertyRangeRetrievalPolicy _rangePolicy;
private readonly IPropertyRangeMappingPolicy _propertyType;
public DefaultPropertyRangeRetrievalPolicyTests()
{
_propertyType = A.Fake<IPropertyRangeMappingPolicy>();
var mappings = new[]
{
_propertyType
};
_rangePolicy = new DefaultPropertyRangeRetrievalPolicy(mappings);
}
[Fact]
public void Should_use_RangAttribute_if_present()
{
// when
var iriRef = _rangePolicy.GetRange(typeof (Issue).GetProperty("ProjectId"), new Dictionary<Type, Uri>());
// then
iriRef.Should().Be((IriRef)"http://example.api/o#project");
}
[Fact]
public void Should_map_property_range_to_RDF_type()
{
// given
var propertyInfo = typeof(Issue).GetProperty("Content");
var mappedPredicate = new Uri(Xsd.@string);
var classIds = new Dictionary<Type, Uri>
{
{ typeof(Issue), new Uri("http://example.com/issue") }
};
A.CallTo(() => _propertyType.MapType(propertyInfo, classIds)).Returns(mappedPredicate);
// when
var range = _rangePolicy.GetRange(propertyInfo, classIds);
// then
range.Should().Be((IriRef)mappedPredicate);
}
}
} | using System;
using System.Collections.Generic;
using System.Reflection;
using FakeItEasy;
using FluentAssertions;
using Hydra.Discovery.SupportedProperties;
using JsonLD.Entities;
using TestHydraApi;
using Vocab;
using Xunit;
namespace Lernaean.Hydra.Tests.ApiDocumentation
{
public class DefaultPropertyRangeRetrievalPolicyTests
{
private readonly DefaultPropertyRangeRetrievalPolicy _rangePolicy;
private readonly IPropertyRangeMappingPolicy _propertyType;
public DefaultPropertyRangeRetrievalPolicyTests()
{
_propertyType = A.Fake<IPropertyRangeMappingPolicy>();
var mappings = new[]
{
_propertyType
};
_rangePolicy = new DefaultPropertyRangeRetrievalPolicy(mappings);
}
[Fact]
public void Should_use_RangAttribute_if_present()
{
// when
var iriRef = _rangePolicy.GetRange(typeof (Issue).GetProperty("ProjectId"), new Dictionary<Type, Uri>());
// then
iriRef.Should().Be((IriRef)"http://example.api/o#project");
}
[Fact]
public void Should_map_property_range_to_RDF_type()
{
// given
var mappedPredicate = new Uri(Xsd.@string);
var classIds = new Dictionary<Type, Uri>
{
{ typeof(Issue), new Uri("http://example.com/issue") }
};
A.CallTo(() => _propertyType.MapType(A<PropertyInfo>._, A<IReadOnlyDictionary<Type, Uri>>._)).Returns(mappedPredicate);
// when
var range = _rangePolicy.GetRange(typeof(Issue).GetProperty("Content"), classIds);
// then
range.Should().Be((IriRef)mappedPredicate);
}
}
} | mit | C# |
d81e662364763b4014782cbd04fb53600c5cc938 | Switch to version 1.5.1-beta | Abc-Arbitrage/Zebus,biarne-a/Zebus | src/SharedVersionInfo.cs | src/SharedVersionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.5.1-beta")]
[assembly: AssemblyFileVersion("1.5.1-beta")]
[assembly: AssemblyInformationalVersion("1.5.1-beta")]
| using System.Reflection;
[assembly: AssemblyVersion("1.5.0")]
[assembly: AssemblyFileVersion("1.5.0")]
[assembly: AssemblyInformationalVersion("1.5.0")]
| mit | C# |
654d121051a16b4d9e93bb2ea2c3937dced8e06b | change scope | pedroreys/docs.particular.net,WojcikMike/docs.particular.net,pashute/docs.particular.net,SzymonPobiega/docs.particular.net,eclaus/docs.particular.net,yuxuac/docs.particular.net | Snippets/Snippets_5/Logging/BuiltInConfig.cs | Snippets/Snippets_5/Logging/BuiltInConfig.cs | using NServiceBus.Logging;
public class BuiltInConfig
{
string pathToLoggingDirectory = "";
public void ChangingDefaults()
{
#region OverrideLoggingDefaultsInCode
var defaultFactory = LogManager.Use<DefaultFactory>();
defaultFactory.Directory(pathToLoggingDirectory);
defaultFactory.Level(LogLevel.Debug);
#endregion
}
} | using NServiceBus.Logging;
public class BuiltInConfig
{
public void ChangingDefaults()
{
var pathToLoggingDirectory = "";
#region OverrideLoggingDefaultsInCode
var defaultFactory = LogManager.Use<DefaultFactory>();
defaultFactory.Directory(pathToLoggingDirectory);
defaultFactory.Level(LogLevel.Debug);
#endregion
}
} | apache-2.0 | C# |
4f1e661878ed5ccadb7a30f7db0cb094127458eb | Fix lab details page as I now use it... | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Views/Lab/Details.cshtml | Anlab.Mvc/Views/Lab/Details.cshtml | @using Humanizer
@model AnlabMvc.Models.Order.OrderReviewModel
@{
ViewData["Title"] = "Details";
}
<div class="col">
@Html.Partial("_OrderDetails")
</div>
@section AdditionalStyles
{
@{ await Html.RenderPartialAsync("_DataTableStylePartial"); }
}
@section Scripts
{
@{ await Html.RenderPartialAsync("_DataTableScriptsPartial"); }
<script type="text/javascript">
$(function () {
$("#table").dataTable();
});
</script>
@{ await Html.RenderPartialAsync("_ShowdownScriptsPartial"); }
}
| @using Humanizer
@model AnlabMvc.Models.Order.OrderReviewModel
@{
ViewData["Title"] = "Details";
}
@Html.Partial("_OrderDetails")
@section AdditionalStyles
{
@{ await Html.RenderPartialAsync("_DataTableStylePartial"); }
}
@section Scripts
{
@{ await Html.RenderPartialAsync("_DataTableScriptsPartial"); }
<script type="text/javascript">
$(function() {
$("#table").dataTable();
});
</script>
@{ await Html.RenderPartialAsync("_ShowdownScriptsPartial"); }
} | mit | C# |
4250dc58c460b1109a394dd6e3036c9c66236565 | Revert "Formatting comments." | mario-loza/Z.ExtensionMethods,huoxudong125/Z.ExtensionMethods,zzzprojects/Z.ExtensionMethods | test/Z.Core.Test/String.IsAnagram.cs | test/Z.Core.Test/String.IsAnagram.cs | // Copyright (c) 2015 ZZZ Projects. All rights reserved
// Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
// Website: http://www.zzzprojects.com/
// Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
// All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Z.Core.Test
{
[TestClass]
public class System_String_IsAnagram
{
[TestMethod]
public void IsAnagram()
{
// Type
string @this = "abba";
// Examples
bool value1 = @this.IsAnagram("abba"); // return true;
bool value2 = @this.IsAnagram("abab"); // return false;
bool value3 = @this.IsAnagram("aba"); // return false;
bool value4 = @this.IsAnagram(""); // return false;
bool value5 = @this.IsAnagram("aba b"); // return false;
// Unit Test
Assert.IsTrue(value1);
Assert.IsFalse(value2);
Assert.IsFalse(value3);
Assert.IsFalse(value4);
Assert.IsFalse(value5);
}
}
}
| // Copyright (c) 2015 ZZZ Projects. All rights reserved
// Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
// Website: http://www.zzzprojects.com/
// Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
// All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Z.Core.Test
{
[TestClass]
public class System_String_IsAnagram
{
[TestMethod]
public void IsAnagram()
{
// Type
string @this = "abba";
// Examples
bool value1 = @this.IsAnagram("abba"); // return true;
bool value2 = @this.IsAnagram("abab"); // return false;
bool value3 = @this.IsAnagram("aba"); // return false;
bool value4 = @this.IsAnagram(""); // return false;
bool value5 = @this.IsAnagram("aba b"); // return false;
// Unit Test
Assert.IsTrue(value1);
Assert.IsFalse(value2);
Assert.IsFalse(value3);
Assert.IsFalse(value4);
Assert.IsFalse(value5);
}
}
}
| mit | C# |
f8922624fd09d3f2f5ad0df0e6a7803117274de4 | Fix comment parameter | ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework | osu.Framework/Graphics/Animations/IAnimation.cs | osu.Framework/Graphics/Animations/IAnimation.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Graphics.Animations
{
/// <summary>
/// An animation / playback sequence.
/// </summary>
public interface IAnimation
{
/// <summary>
/// The duration of the animation.
/// </summary>
public double Duration { get; }
/// <summary>
/// True if the animation has finished playing, false otherwise.
/// </summary>
public bool FinishedPlaying => !Loop && PlaybackPosition > Duration;
/// <summary>
/// True if the animation is playing, false otherwise. <c>true</c> by default.
/// </summary>
bool IsPlaying { get; set; }
/// <summary>
/// True if the animation should start over from the first frame after finishing. False if it should stop playing and keep displaying the last frame when finishing.
/// </summary>
bool Loop { get; set; }
/// <summary>
/// Seek the animation to a specific time value.
/// </summary>
/// <param name="time">The time value to seek to.</param>
void Seek(double time);
/// <summary>
/// The current position of playback.
/// </summary>
public double PlaybackPosition { get; set; }
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Graphics.Animations
{
/// <summary>
/// An animation / playback sequence.
/// </summary>
public interface IAnimation
{
/// <summary>
/// The duration of the animation.
/// </summary>
public double Duration { get; }
/// <summary>
/// True if the animation has finished playing, false otherwise.
/// </summary>
public bool FinishedPlaying => !Loop && PlaybackPosition > Duration;
/// <summary>
/// True if the animation is playing, false otherwise. Starts true.
/// </summary>
bool IsPlaying { get; set; }
/// <summary>
/// True if the animation should start over from the first frame after finishing. False if it should stop playing and keep displaying the last frame when finishing.
/// </summary>
bool Loop { get; set; }
/// <summary>
/// Seek the animation to a specific time value.
/// </summary>
/// <param name="time">The time value to seek to.</param>
void Seek(double time);
/// <summary>
/// The current position of playback.
/// </summary>
public double PlaybackPosition { get; set; }
}
}
| mit | C# |
693d777f7b99e104a73c8b1be437723e43956759 | Update Program.cs | jacobrossandersen/GitTest1 | ConsoleApp1/ConsoleApp1/Program.cs | ConsoleApp1/ConsoleApp1/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//Code was edited in GitHub
//Code was added in VS
//Code to call Feature1
//Code to call Feature3
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//Code was edited in GitHub
//Code was added in VS
//Code to call Feature1
}
}
}
| mit | C# |
6e5381cc755440289899b4c6e309e0fe14adc206 | Make Wildcard class public | lukyad/Eco | Eco/Wildcard.cs | Eco/Wildcard.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Eco
{
// Slightly modified version of Wildcard class from here: http://www.codeproject.com/Articles/11556/Converting-Wildcards-to-Regexes
//
/// <summary>
/// Represents a wildcard running on the
/// <see cref="System.Text.RegularExpressions"/> engine.
/// </summary>
public class Wildcard : Regex
{
/// <summary>
/// Initializes a wildcard with the given search pattern.
/// </summary>
/// <param name="pattern">The wildcard pattern to match.</param>
public Wildcard(string pattern)
: base(ToRegex(pattern))
{
}
/// <summary>
/// Initializes a wildcard with the given search pattern and options.
/// </summary>
/// <param name="pattern">The wildcard pattern to match.</param>
/// <param name="options">A combination of one or more
/// <see cref="System.Text.RegexOptions"/>.</param>
public Wildcard(string pattern, RegexOptions options)
: base(ToRegex(pattern), options)
{
}
/// <summary>
/// Converts a wildcard to a regex.
/// </summary>
/// <param name="pattern">The wildcard pattern to convert.</param>
/// <returns>A regex equivalent of the given wildcard.</returns>
static string ToRegex(string pattern)
{
return "^" + Regex.Escape(pattern).
Replace("\\*", ".*").
Replace("\\?", ".") + "$";
}
public static readonly string Everything = "*";
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Eco
{
// Slightly modified version of Wildcard class from here: http://www.codeproject.com/Articles/11556/Converting-Wildcards-to-Regexes
//
/// <summary>
/// Represents a wildcard running on the
/// <see cref="System.Text.RegularExpressions"/> engine.
/// </summary>
class Wildcard : Regex
{
/// <summary>
/// Initializes a wildcard with the given search pattern.
/// </summary>
/// <param name="pattern">The wildcard pattern to match.</param>
public Wildcard(string pattern)
: base(ToRegex(pattern))
{
}
/// <summary>
/// Initializes a wildcard with the given search pattern and options.
/// </summary>
/// <param name="pattern">The wildcard pattern to match.</param>
/// <param name="options">A combination of one or more
/// <see cref="System.Text.RegexOptions"/>.</param>
public Wildcard(string pattern, RegexOptions options)
: base(ToRegex(pattern), options)
{
}
/// <summary>
/// Converts a wildcard to a regex.
/// </summary>
/// <param name="pattern">The wildcard pattern to convert.</param>
/// <returns>A regex equivalent of the given wildcard.</returns>
static string ToRegex(string pattern)
{
return "^" + Regex.Escape(pattern).
Replace("\\*", ".*").
Replace("\\?", ".") + "$";
}
public static readonly string Everything = "*";
}
}
| apache-2.0 | C# |
3624ac77052fa5fa34c199de9f426a8262e8ea69 | Implement WebClientIPHeader telemetry initializer | Microsoft/ApplicationInsights-aspnetcore,hackathonvixion/ApplicationInsights-aspnet5,Microsoft/ApplicationInsights-aspnet5,gzepeda/ApplicationInsights-aspnetcore,gzepeda/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnet5,hackathonvixion/ApplicationInsights-aspnet5,Microsoft/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnet5,hackathonvixion/ApplicationInsights-aspnet5,gzepeda/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnetcore | src/ApplicationInsights.AspNet/DataCollection/WebClientIpHeaderTelemetryInitializer.cs | src/ApplicationInsights.AspNet/DataCollection/WebClientIpHeaderTelemetryInitializer.cs |
namespace Microsoft.ApplicationInsights.AspNet.DataCollection
{
using Microsoft.ApplicationInsights.Extensibility;
using System;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.Framework.DependencyInjection;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Interfaces;
using Microsoft.ApplicationInsights.AspNet.Implementation;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
/// <summary>
/// This telemetry initializer extracts client IP address and populates telemetry.Context.Location.Ip property.
/// Lot's of code reuse from Microsoft.ApplicationInsights.Extensibility.Web.TelemetryInitializers.WebClientIpHeaderTelemetryInitializer
/// </summary>
public class WebClientIpHeaderTelemetryInitializer : ITelemetryInitializer
{
private IServiceProvider serviceProvider;
private readonly char[] HeaderValuesSeparatorDefault = new char[] { ',' };
private const string HeaderNameDefault = "X-Forwarded-For";
private char[] headerValueSeparators;
private readonly ICollection<string> headerNames;
public WebClientIpHeaderTelemetryInitializer(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
this.headerNames = new List<string>();
this.HeaderNames.Add(HeaderNameDefault);
this.UseFirstIp = true;
this.headerValueSeparators = HeaderValuesSeparatorDefault;
}
/// <summary>
/// Gets or sets comma separated list of request header names that is used to check client id.
/// </summary>
public ICollection<string> HeaderNames
{
get
{
return this.headerNames;
}
}
/// <summary>
/// Gets or sets a header values separator.
/// </summary>
public string HeaderValueSeparators
{
get
{
return string.Concat(this.headerValueSeparators);
}
set
{
if (!string.IsNullOrEmpty(value))
{
this.headerValueSeparators = value.ToCharArray();
}
}
}
/// <summary>
/// Gets or sets a value indicating whether the first or the last IP should be used from the lists of IPs in the header.
/// </summary>
public bool UseFirstIp { get; set; }
public void Initialize(ITelemetry telemetry)
{
var request = this.serviceProvider.GetService<RequestTelemetry>();
if (!string.IsNullOrEmpty(request.Context.Location.Ip))
{
telemetry.Context.Location.Ip = request.Context.Location.Ip;
}
else
{
var context = this.serviceProvider.GetService<HttpContextHolder>().Context;
string resultIp = null;
foreach (var name in this.HeaderNames)
{
var headerValue = context.Request.Headers[name];
if (!string.IsNullOrEmpty(headerValue))
{
var ip = GetIpFromHeader(headerValue);
ip = CutPort(ip);
if (IsCorrectIpAddress(ip))
{
resultIp = ip;
break;
}
}
}
if (string.IsNullOrEmpty(resultIp))
{
var connectionFeature = context.GetFeature<IHttpConnectionFeature>();
if (connectionFeature != null)
{
resultIp = connectionFeature.RemoteIpAddress.ToString();
}
}
request.Context.Location.Ip = resultIp;
telemetry.Context.Location.Ip = resultIp;
}
}
private static string CutPort(string address)
{
// For Web sites in Azure header contains ip address with port e.g. 50.47.87.223:54464
int portSeparatorIndex = address.IndexOf(":", StringComparison.OrdinalIgnoreCase);
if (portSeparatorIndex > 0)
{
return address.Substring(0, portSeparatorIndex);
}
return address;
}
private static bool IsCorrectIpAddress(string address)
{
IPAddress outParameter;
address = address.Trim();
// Core SDK does not support setting Location.Ip to malformed ip address
if (IPAddress.TryParse(address, out outParameter))
{
// Also SDK supports only ipv4!
if (outParameter.AddressFamily == AddressFamily.InterNetwork)
{
return true;
}
}
return false;
}
private string GetIpFromHeader(string clientIpsFromHeader)
{
var ips = clientIpsFromHeader.Split(this.headerValueSeparators, StringSplitOptions.RemoveEmptyEntries);
return this.UseFirstIp ? ips[0].Trim() : ips[ips.Length - 1].Trim();
}
}
} |
namespace Microsoft.ApplicationInsights.AspNet.DataCollection
{
using Microsoft.ApplicationInsights.Extensibility;
using System;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.Framework.DependencyInjection;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Interfaces;
using Microsoft.ApplicationInsights.AspNet.Implementation;
public class WebClientIpHeaderTelemetryInitializer : ITelemetryInitializer
{
private IServiceProvider serviceProvider;
public WebClientIpHeaderTelemetryInitializer(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public void Initialize(ITelemetry telemetry)
{
var request = this.serviceProvider.GetService<RequestTelemetry>();
if (!string.IsNullOrEmpty(request.Context.Location.Ip))
{
telemetry.Context.Location.Ip = request.Context.Location.Ip;
}
else
{
var context = this.serviceProvider.GetService<HttpContextHolder>().Context;
var connectionFeature = context.GetFeature<IHttpConnectionFeature>();
if (connectionFeature != null)
{
string ip = connectionFeature.RemoteIpAddress.ToString();
request.Context.Location.Ip = ip;
if (request != telemetry)
{
telemetry.Context.Location.Ip = ip;
}
}
}
}
}
} | mit | C# |
2c1793ddebee36f63d64ebf4c0aff323cb332b0f | Change hello world implementation to using the | tiesmaster/DCC,tiesmaster/DCC | Dcc/Startup.cs | Dcc/Startup.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
namespace Tiesmaster.Dcc
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.RunProxy(new ProxyOptions { Host = "jsonplaceholder.typicode.com" });
}
}
} | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Tiesmaster.Dcc
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello from DCC ;)");
});
}
}
} | mit | C# |
2daa520ef6a36f4bebaa3913974f26290034938b | add GetEnumUnderlyingType helper | fnajera-rac-de/cecil,furesoft/cecil,joj/cecil,kzu/cecil,cgourlay/cecil,sailro/cecil,gluck/cecil,saynomoo/cecil,xen2/cecil,mono/cecil,ttRevan/cecil,jbevain/cecil,SiliconStudio/Mono.Cecil | rocks/Mono.Cecil.Rocks/TypeDefinitionRocks.cs | rocks/Mono.Cecil.Rocks/TypeDefinitionRocks.cs | //
// TypeDefinitionRocks.cs
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace Mono.Cecil.Rocks {
public static class TypeDefinitionRocks {
public static IEnumerable<MethodDefinition> GetConstructors (this TypeDefinition self)
{
if (self == null)
throw new ArgumentNullException ("self");
if (!self.HasMethods)
return Empty<MethodDefinition>.Array;
return self.Methods.Where (method => method.IsConstructor);
}
public static MethodDefinition GetStaticConstructor (this TypeDefinition self)
{
if (self == null)
throw new ArgumentNullException ("self");
if (!self.HasMethods)
return null;
return self.GetConstructors ().FirstOrDefault (ctor => ctor.IsStatic);
}
public static IEnumerable<MethodDefinition> GetMethods (this TypeDefinition self)
{
if (self == null)
throw new ArgumentNullException ("self");
if (!self.HasMethods)
return Empty<MethodDefinition>.Array;
return self.Methods.Where (method => !method.IsConstructor);
}
public static TypeReference GetEnumUnderlyingType (this TypeDefinition self)
{
if (self == null)
throw new ArgumentNullException ("self");
if (!self.IsEnum)
throw new ArgumentException ();
return Mixin.GetEnumUnderlyingType (self);
}
}
}
| //
// TypeDefinitionRocks.cs
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace Mono.Cecil.Rocks {
public static class TypeDefinitionRocks {
public static IEnumerable<MethodDefinition> GetConstructors (this TypeDefinition self)
{
if (self == null)
throw new ArgumentNullException ("self");
if (!self.HasMethods)
return Empty<MethodDefinition>.Array;
return self.Methods.Where (method => method.IsConstructor);
}
public static MethodDefinition GetStaticConstructor (this TypeDefinition self)
{
if (self == null)
throw new ArgumentNullException ("self");
if (!self.HasMethods)
return null;
return self.GetConstructors ().FirstOrDefault (ctor => ctor.IsStatic);
}
public static IEnumerable<MethodDefinition> GetMethods (this TypeDefinition self)
{
if (self == null)
throw new ArgumentNullException ("self");
if (!self.HasMethods)
return Empty<MethodDefinition>.Array;
return self.Methods.Where (method => !method.IsConstructor);
}
}
}
| mit | C# |
628a30193ff7b94c10815d1c8d8be7db7b1e4187 | Remove incorrect `TrackLoaded` override from `TestWorkingBeatmap` | peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu | osu.Game/Tests/Beatmaps/TestWorkingBeatmap.cs | osu.Game/Tests/Beatmaps/TestWorkingBeatmap.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.IO;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Graphics.Textures;
using osu.Game.Beatmaps;
using osu.Game.Skinning;
using osu.Game.Storyboards;
namespace osu.Game.Tests.Beatmaps
{
public class TestWorkingBeatmap : WorkingBeatmap
{
private readonly IBeatmap beatmap;
private readonly Storyboard storyboard;
/// <summary>
/// Create an instance which provides the <see cref="IBeatmap"/> when requested.
/// </summary>
/// <param name="beatmap">The beatmap.</param>
/// <param name="storyboard">An optional storyboard.</param>
/// <param name="audioManager">The <see cref="AudioManager"/>.</param>
public TestWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null, AudioManager audioManager = null)
: base(beatmap.BeatmapInfo, audioManager)
{
this.beatmap = beatmap;
this.storyboard = storyboard;
}
public override bool BeatmapLoaded => true;
protected override IBeatmap GetBeatmap() => beatmap;
protected override Storyboard GetStoryboard() => storyboard ?? base.GetStoryboard();
protected internal override ISkin GetSkin() => null;
public override Stream GetStream(string storagePath) => null;
protected override Texture GetBackground() => null;
protected override Track GetBeatmapTrack() => null;
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.IO;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Graphics.Textures;
using osu.Game.Beatmaps;
using osu.Game.Skinning;
using osu.Game.Storyboards;
namespace osu.Game.Tests.Beatmaps
{
public class TestWorkingBeatmap : WorkingBeatmap
{
private readonly IBeatmap beatmap;
private readonly Storyboard storyboard;
/// <summary>
/// Create an instance which provides the <see cref="IBeatmap"/> when requested.
/// </summary>
/// <param name="beatmap">The beatmap.</param>
/// <param name="storyboard">An optional storyboard.</param>
/// <param name="audioManager">The <see cref="AudioManager"/>.</param>
public TestWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null, AudioManager audioManager = null)
: base(beatmap.BeatmapInfo, audioManager)
{
this.beatmap = beatmap;
this.storyboard = storyboard;
}
public override bool TrackLoaded => true;
public override bool BeatmapLoaded => true;
protected override IBeatmap GetBeatmap() => beatmap;
protected override Storyboard GetStoryboard() => storyboard ?? base.GetStoryboard();
protected internal override ISkin GetSkin() => null;
public override Stream GetStream(string storagePath) => null;
protected override Texture GetBackground() => null;
protected override Track GetBeatmapTrack() => null;
}
}
| mit | C# |
9b356ce75420384fca938c9e8f06114bf4a16583 | Add comments for F.True | farity/farity | Farity/True.cs | Farity/True.cs | namespace Farity
{
public static partial class F
{
/// <summary>
/// A function that takes any arguments and returns true.
/// </summary>
/// <param name="args">Any arguments passed to the function.</param>
/// <returns>true</returns>
public static bool True(params object[] args) => true;
}
} | namespace Farity
{
public static partial class F
{
public static bool True(params object[] args) => true;
}
} | mit | C# |
274f1b7b065a4ca149a95174605e5e6d825de560 | Add multi-exit discriminator (MED) support | mstrother/BmpListener | src/BmpListener/Bgp/PathAttributeMultiExitDisc.cs | src/BmpListener/Bgp/PathAttributeMultiExitDisc.cs | using BmpListener.Utilities;
namespace BmpListener.Bgp
{
internal class PathAttributeMultiExitDisc : PathAttribute
{
public uint Metric { get; private set; }
public override void Decode(byte[] data, int offset)
{
Metric = EndianBitConverter.Big.ToUInt32(data, offset);
}
}
} | namespace BmpListener.Bgp
{
internal class PathAttributeMultiExitDisc : PathAttribute
{
public int? Metric { get; private set; }
public override void Decode(byte[] data, int offset)
{
//Array.Reverse(data, offset, 0);
//Metric = BitConverter.ToInt32(data, 0);
}
}
} | mit | C# |
ea47b849492f7c16e378a5ce44e484da23c17002 | Update assembly metadata. | dougludlow/umbraco-navbuilder,dougludlow/umbraco-navbuilder | src/Cob.Umb.NavBuilder/Properties/AssemblyInfo.cs | src/Cob.Umb.NavBuilder/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("Cob.Umb.NavBuilder")]
[assembly: AssemblyDescription("NavBuilder for Umbraco 7.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("City of Boise")]
[assembly: AssemblyProduct("Cob.Umb.NavBuilder")]
[assembly: AssemblyCopyright("Copyright © City of Boise 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("a2ec16c7-5dbf-4758-8e15-15b42ec8dc5b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.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("Cob.Umb.NavBuilder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Cob.Umb.NavBuilder")]
[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("a2ec16c7-5dbf-4758-8e15-15b42ec8dc5b")]
// 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# |
73365efd1765ec70fbf6423398b31ef8eaca348b | Add implementation details to MySQLScheamAggregator.cs | Ackara/Daterpillar | src/Daterpillar.NET/Data/MySQLSchemaAggregator.cs | src/Daterpillar.NET/Data/MySQLSchemaAggregator.cs | using System;
using System.Data;
namespace Gigobyte.Daterpillar.Data
{
public class MySQLSchemaAggregator : SchemaAggregatorBase
{
public MySQLSchemaAggregator(IDbConnection connection) : base(connection)
{
}
protected override string GetColumnInfoQuery(string tableName)
{
return $"SELECT c.`COLUMN_NAME` AS `Name`, c.DATA_TYPE AS `Type`, if(c.CHARACTER_MAXIMUM_LENGTH IS NULL, if(c.NUMERIC_PRECISION IS NULL, 0, c.NUMERIC_PRECISION), c.CHARACTER_MAXIMUM_LENGTH) AS `Scale`, if(c.NUMERIC_SCALE IS NULL, 0, c.NUMERIC_SCALE) AS `Precision`, c.IS_NULLABLE AS `Nullable`, c.COLUMN_DEFAULT AS `Default`, if(c.EXTRA = 'auto_increment', 1, 0) AS `Auto`, c.COLUMN_COMMENT AS `Comment` FROM information_schema.`COLUMNS` c WHERE c.TABLE_SCHEMA = '{Schema.Name}' AND c.`TABLE_NAME` = '{tableName}';";
}
protected override string GetForeignKeyInfoQuery(string tableName)
{
return $"SELECT rc.`CONSTRAINT_NAME` AS `Name`, fc.FOR_COL_NAME AS `Column`, rc.REFERENCED_TABLE_NAME AS `Referecne_Table`, fc.REF_COL_NAME AS `Reference_Column`, rc.UPDATE_RULE AS `On_Update`, rc.DELETE_RULE AS `On_Delete`, rc.MATCH_OPTION AS `On_Match` FROM information_schema.REFERENTIAL_CONSTRAINTS rc JOIN information_schema.INNODB_SYS_FOREIGN_COLS fc ON fc.ID = concat(rc.`CONSTRAINT_SCHEMA`, '/', rc.`CONSTRAINT_NAME`) WHERE rc.`CONSTRAINT_SCHEMA` = '{Schema.Name}' AND rc.`TABLE_NAME` = '{tableName}';";
}
protected override string GetIndexColumnsQuery(string indexIdentifier)
{
throw new NotImplementedException();
}
protected override string GetIndexInfoQuery(string tableName)
{
throw new NotImplementedException();
}
protected override string GetTableInfoQuery()
{
return $"SELECT t.TABLE_NAME AS `Name`, t.TABLE_COMMENT AS `Comment` FROM information_schema.TABLES t WHERE t.TABLE_SCHEMA = '{Schema.Name}';";
}
}
} | using System;
using System.Data;
namespace Gigobyte.Daterpillar.Data
{
public class MySQLSchemaAggregator : SchemaAggregatorBase
{
public MySQLSchemaAggregator(IDbConnection connection) : base(connection)
{
}
protected override string GetColumnInfoQuery(string tableName)
{
throw new NotImplementedException();
}
protected override string GetForeignKeyInfoQuery(string tableName)
{
throw new NotImplementedException();
}
protected override string GetIndexColumnsQuery(string indexIdentifier)
{
throw new NotImplementedException();
}
protected override string GetIndexInfoQuery(string tableName)
{
throw new NotImplementedException();
}
protected override string GetTableInfoQuery()
{
throw new NotImplementedException();
}
}
} | mit | C# |
5914b10c2f3133c1a5126c2b5e5952ddfa6a8f63 | fix issue with datetime converter | lurch83/RfsForChromeService | src/RfsForChrome.Service/Extensions/Extensions.cs | src/RfsForChrome.Service/Extensions/Extensions.cs | using System;
using System.Globalization;
namespace RfsForChrome.Service.Extensions
{
public static class Extensions
{
public static DateTime MyToDateTime(this string value)
{
DateTime converted;
DateTime.TryParseExact(value, "dd MMM yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out converted);
if(converted == DateTime.MinValue)
DateTime.TryParseExact(value, "d MMM yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out converted);
return converted;
}
}
} | using System;
using System.Globalization;
namespace RfsForChrome.Service.Extensions
{
public static class Extensions
{
public static DateTime MyToDateTime(this string value)
{
DateTime converted;
DateTime.TryParseExact(value, "dd MMM yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out converted);
return converted;
}
}
} | mit | C# |
b658efe04621625fcb028c7db0adea9404b31dbb | Add image and description to playlist location | scooper91/SevenDigital.Api.Schema,7digital/SevenDigital.Api.Schema | src/Schema/Playlists/Response/PlaylistLocation.cs | src/Schema/Playlists/Response/PlaylistLocation.cs | using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace SevenDigital.Api.Schema.Playlists.Response
{
[Serializable]
public class PlaylistLocation : UserBasedUpdatableItem
{
[XmlAttribute("id")]
public string Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("links")]
[XmlArrayItem("link")]
public List<Link> Links { get; set; }
[XmlElement("trackCount")]
public int TrackCount { get; set; }
[XmlElement("visibility")]
public PlaylistVisibilityType Visibility { get; set; }
[XmlElement("description")]
public string Description { get; set; }
[XmlElement("image")]
public string Image { get; set; }
[XmlElement("status")]
public PlaylistStatusType Status { get; set; }
[XmlArray("tags")]
[XmlArrayItem("tag")]
public List<Tag> Tags { get; set; }
public override string ToString()
{
return string.Format("{0}: {1}", Id, Name);
}
}
} | using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace SevenDigital.Api.Schema.Playlists.Response
{
[Serializable]
public class PlaylistLocation : UserBasedUpdatableItem
{
[XmlAttribute("id")]
public string Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("links")]
[XmlArrayItem("link")]
public List<Link> Links { get; set; }
[XmlElement("trackCount")]
public int TrackCount { get; set; }
[XmlElement("visibility")]
public PlaylistVisibilityType Visibility { get; set; }
[XmlElement("status")]
public PlaylistStatusType Status { get; set; }
[XmlArray("tags")]
[XmlArrayItem("tag")]
public List<Tag> Tags { get; set; }
public override string ToString()
{
return string.Format("{0}: {1}", Id, Name);
}
}
} | mit | C# |
10cef1cff7684e3e8e7425848f0f73d61f89ca4d | remove failing unit test as it requires network access | aloneguid/storage | src/Storage.Net.Tests/StorageInstantiationTest.cs | src/Storage.Net.Tests/StorageInstantiationTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Storage.Net.Blob;
using Storage.Net.Blob.Files;
using Storage.Net.Microsoft.Azure.Storage.Blob;
using Storage.Net.Tests.Integration;
using Xunit;
namespace Storage.Net.Tests
{
public class StorageInstantiationTest : AbstractTestFixture
{
public StorageInstantiationTest()
{
StorageFactory.Modules.UseAzureStorage();
}
[Fact]
public void Disk_storage_creates_from_connection_string()
{
IBlobStorage disk = StorageFactory.Blobs.FromConnectionString("disk://path=" + TestDir.FullName);
Assert.IsType<DiskDirectoryBlobStorage>(disk);
DiskDirectoryBlobStorage ddbs = (DiskDirectoryBlobStorage)disk;
Assert.Equal(TestDir.FullName, ddbs.RootDirectory.FullName);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Storage.Net.Blob;
using Storage.Net.Blob.Files;
using Storage.Net.Microsoft.Azure.Storage.Blob;
using Storage.Net.Tests.Integration;
using Xunit;
namespace Storage.Net.Tests
{
public class StorageInstantiationTest : AbstractTestFixture
{
public StorageInstantiationTest()
{
StorageFactory.Modules.UseAzureStorage();
}
[Fact]
public void Disk_storage_creates_from_connection_string()
{
IBlobStorage disk = StorageFactory.Blobs.FromConnectionString("disk://path=" + TestDir.FullName);
Assert.IsType<DiskDirectoryBlobStorage>(disk);
DiskDirectoryBlobStorage ddbs = (DiskDirectoryBlobStorage)disk;
Assert.Equal(TestDir.FullName, ddbs.RootDirectory.FullName);
}
[Fact]
public void External_module_storage_created_with_connection_string()
{
IBlobStorage storage = StorageFactory.Blobs.FromConnectionString("azure.blob://account=test;container=rrr;key=0RlOLDEu8Zn0HmfQ3hnODdAUqEwLOOKq0njK/TaKuYM4LTpyBDozq2LgmD/O9i/0yVP3S/7+sKNYJqmN9+ME9A==;createIfNotExists=false");
Assert.IsType<AzureUniversalBlobStorageProvider>(storage);
}
}
}
| mit | C# |
53c5ae9d48de2aaa47d5f4e6bfc1b05536a102fc | Rename Wallets group to Managers group | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Shell/MainMenu/ToolsMainMenuItems.cs | WalletWasabi.Gui/Shell/MainMenu/ToolsMainMenuItems.cs | using AvalonStudio.MainMenu;
using AvalonStudio.Menus;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Text;
namespace WalletWasabi.Gui.Shell.MainMenu
{
internal class ToolsMainMenuItems
{
private IMenuItemFactory _menuItemFactory;
[ImportingConstructor]
public ToolsMainMenuItems(IMenuItemFactory menuItemFactory)
{
_menuItemFactory = menuItemFactory;
}
#region MainMenu
[ExportMainMenuItem("Tools")]
[DefaultOrder(1)]
public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null);
#endregion MainMenu
#region Group
[ExportMainMenuDefaultGroup("Tools", "Managers")]
[DefaultOrder(0)]
public object ManagersGroup => null;
[ExportMainMenuDefaultGroup("Tools", "Settings")]
[DefaultOrder(1)]
public object SettingsGroup => null;
#endregion Group
#region MenuItem
[ExportMainMenuItem("Tools", "Wallet Manager")]
[DefaultOrder(0)]
[DefaultGroup("Managers")]
public IMenuItem GenerateWallet => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager");
[ExportMainMenuItem("Tools", "Settings")]
[DefaultOrder(1)]
[DefaultGroup("Settings")]
public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings");
#endregion MenuItem
}
}
| using AvalonStudio.MainMenu;
using AvalonStudio.Menus;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Text;
namespace WalletWasabi.Gui.Shell.MainMenu
{
internal class ToolsMainMenuItems
{
private IMenuItemFactory _menuItemFactory;
[ImportingConstructor]
public ToolsMainMenuItems(IMenuItemFactory menuItemFactory)
{
_menuItemFactory = menuItemFactory;
}
#region MainMenu
[ExportMainMenuItem("Tools")]
[DefaultOrder(1)]
public IMenuItem Tools => _menuItemFactory.CreateHeaderMenuItem("Tools", null);
#endregion MainMenu
#region Group
[ExportMainMenuDefaultGroup("Tools", "Wallet")]
[DefaultOrder(0)]
public object WalletGroup => null;
[ExportMainMenuDefaultGroup("Tools", "Settings")]
[DefaultOrder(1)]
public object SettingsGroup => null;
#endregion Group
#region MenuItem
[ExportMainMenuItem("Tools", "Wallet")]
[DefaultOrder(0)]
[DefaultGroup("Wallet")]
public IMenuItem GenerateWallet => _menuItemFactory.CreateCommandMenuItem("Tools.WalletManager");
[ExportMainMenuItem("Tools", "Settings")]
[DefaultOrder(1)]
[DefaultGroup("Settings")]
public IMenuItem Settings => _menuItemFactory.CreateCommandMenuItem("Tools.Settings");
#endregion MenuItem
}
}
| mit | C# |
3436843a0ad293669050bac5f8717c300211b5d1 | Reorder tray menu | zr40/kyru-dotnet,zr40/kyru-dotnet | Kyru/Program.cs | Kyru/Program.cs | using System;
using System.Drawing;
using System.Windows.Forms;
using Kyru.Core;
using Kyru.Utilities;
namespace Kyru
{
internal static class Program
{
private static KyruApplication app;
private static NotifyIcon trayIcon;
private static ContextMenu trayMenu;
[STAThread]
private static void Main()
{
Console.WriteLine("Kyru debug console");
Console.WriteLine();
KyruTimer.Start();
app = new KyruApplication();
app.Start();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
CreateSystemTray();
Application.Run();
trayIcon.Visible = false;
}
private static void CreateSystemTray()
{
trayMenu = new ContextMenu();
trayMenu.MenuItems.Add("Log in", OnLogin);
trayMenu.MenuItems.Add("Add node", OnRegisterNode);
trayMenu.MenuItems.Add("-");
trayMenu.MenuItems.Add("Exit", OnExit);
trayIcon = new NotifyIcon();
trayIcon.Text = "Kyru";
trayIcon.Icon = new Icon("kyru.ico");
trayIcon.MouseDoubleClick += OnLogin;
trayIcon.ContextMenu = trayMenu;
trayIcon.Visible = true;
}
private static void OnExit(object sender, EventArgs e)
{
Application.Exit();
}
private static void OnLogin(object sender, EventArgs e)
{
Form f = new LoginForm(app.LocalObjectStorage);
f.Show();
}
private static void OnRegisterNode(object sender, EventArgs e)
{
Form f = new AddNodeForm(app.Node.Kademlia);
f.Show();
}
}
}
| using System;
using System.Drawing;
using System.Windows.Forms;
using Kyru.Core;
using Kyru.Utilities;
namespace Kyru
{
internal static class Program
{
private static KyruApplication app;
private static NotifyIcon trayIcon;
private static ContextMenu trayMenu;
[STAThread]
private static void Main()
{
Console.WriteLine("Kyru debug console");
Console.WriteLine();
KyruTimer.Start();
app = new KyruApplication();
app.Start();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
CreateSystemTray();
Application.Run();
trayIcon.Visible = false;
}
private static void CreateSystemTray()
{
trayMenu = new ContextMenu();
trayMenu.MenuItems.Add("Exit", OnExit);
trayMenu.MenuItems.Add("Login", OnLogin);
trayMenu.MenuItems.Add("Add Node", OnRegisterNode);
trayIcon = new NotifyIcon();
trayIcon.Text = "Kyru";
trayIcon.Icon = new Icon("kyru.ico");
trayIcon.MouseDoubleClick += OnLogin;
trayIcon.ContextMenu = trayMenu;
trayIcon.Visible = true;
}
private static void OnExit(object sender, EventArgs e)
{
Application.Exit();
}
private static void OnLogin(object sender, EventArgs e)
{
Form f = new LoginForm(app.LocalObjectStorage);
f.Show();
}
private static void OnRegisterNode(object sender, EventArgs e)
{
Form f = new AddNodeForm(app.Node.Kademlia);
f.Show();
}
}
} | bsd-3-clause | C# |
26cb77e8885cbdfea65bdf946eeed7401a7dde71 | Fix a crash opening the text tool. | PintaProject/Pinta,PintaProject/Pinta,PintaProject/Pinta | Pinta.Core/Managers/FontManager.cs | Pinta.Core/Managers/FontManager.cs | //
// FontManager.cs
//
// Authors:
// Olivier Dufour <[email protected]>
// Jonathan Pobst <[email protected]>
//
// Copyright (c) 2010 Jonathan Pobst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using Gdk;
using Pango;
namespace Pinta.Core
{
public class FontManager
{
private List<FontFamily> families;
private List<int> default_font_sizes = new List<int> (new int[] { 6, 7, 8, 9, 10, 11, 12, 14, 16,
18, 20, 22, 24, 26, 28, 32, 36, 40, 44,
48, 54, 60, 66, 72, 80, 88, 96 });
public FontManager ()
{
families = new List<FontFamily> ();
using (Pango.Context c = PangoHelper.ContextGet ())
families.AddRange (c.Families);
}
public List<string> GetInstalledFonts ()
{
return families.Select (f => f.Name).ToList ();
}
public FontFamily GetFamily (string fontname)
{
return families.Find (f => f.Name == fontname);
}
public List<int> GetSizes (FontFamily family)
{
var face = family.Faces[0];
// It seems possible for this to be null if there were issues loading the font.
if (face == null)
return default_font_sizes;
else
return GetSizes (face);
}
unsafe private List<int> GetSizes (FontFace fontFace)
{
int sizes;
int nsizes;
// Query for supported sizes for this font
fontFace.ListSizes (out sizes, out nsizes);
if (nsizes == 0)
return default_font_sizes;
List<int> result = new List<int> ();
for (int i = 0; i < nsizes; i++)
result.Add (*(&sizes + 4 * i));
return result;
}
}
}
| //
// FontManager.cs
//
// Authors:
// Olivier Dufour <[email protected]>
// Jonathan Pobst <[email protected]>
//
// Copyright (c) 2010 Jonathan Pobst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using Gdk;
using Pango;
namespace Pinta.Core
{
public class FontManager
{
private List<FontFamily> families;
private List<int> default_font_sizes = new List<int> (new int[] { 6, 7, 8, 9, 10, 11, 12, 14, 16,
18, 20, 22, 24, 26, 28, 32, 36, 40, 44,
48, 54, 60, 66, 72, 80, 88, 96 });
public FontManager ()
{
families = new List<FontFamily> ();
using (Pango.Context c = PangoHelper.ContextGet ())
families.AddRange (c.Families);
}
public List<string> GetInstalledFonts ()
{
return families.Select (f => f.Name).ToList ();
}
public FontFamily GetFamily (string fontname)
{
return families.Find (f => f.Name == fontname);
}
public List<int> GetSizes (FontFamily family)
{
return GetSizes (family.Faces[0]);
}
unsafe public List<int> GetSizes (FontFace fontFace)
{
int sizes;
int nsizes;
// Query for supported sizes for this font
fontFace.ListSizes (out sizes, out nsizes);
if (nsizes == 0)
return default_font_sizes;
List<int> result = new List<int> ();
for (int i = 0; i < nsizes; i++)
result.Add (*(&sizes + 4 * i));
return result;
}
}
}
| mit | C# |
4fdddd8c79fc11313eaa9335bdb765dd584723b0 | Delete file in setup | Azure/azure-sdk-for-java,selvasingh/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,selvasingh/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,selvasingh/azure-sdk-for-java | net/Azure.Storage.Blobs.PerfStress/UploadTest.cs | net/Azure.Storage.Blobs.PerfStress/UploadTest.cs | using Azure.Storage.Blobs.PerfStress.Core;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.Storage.Blobs.PerfStress
{
public class UploadTest : ParallelTransferTest<ParallelTransferOptionsOptions>
{
public UploadTest(ParallelTransferOptionsOptions options) : base(options)
{
try
{
BlobClient.Delete();
}
catch (StorageRequestFailedException)
{
}
}
public override void Run(CancellationToken cancellationToken)
{
BlobClient.Upload(RandomStream, parallelTransferOptions: ParallelTransferOptions, cancellationToken: cancellationToken);
}
public override Task RunAsync(CancellationToken cancellationToken)
{
return BlobClient.UploadAsync(RandomStream, parallelTransferOptions: ParallelTransferOptions, cancellationToken: cancellationToken);
}
public override void Dispose()
{
BlobClient.Delete();
base.Dispose();
}
}
}
| using Azure.Storage.Blobs.PerfStress.Core;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.Storage.Blobs.PerfStress
{
public class UploadTest : ParallelTransferTest<ParallelTransferOptionsOptions>
{
public UploadTest(ParallelTransferOptionsOptions options) : base(options)
{
}
public override void Run(CancellationToken cancellationToken)
{
BlobClient.Upload(RandomStream, parallelTransferOptions: ParallelTransferOptions, cancellationToken: cancellationToken);
}
public override Task RunAsync(CancellationToken cancellationToken)
{
return BlobClient.UploadAsync(RandomStream, parallelTransferOptions: ParallelTransferOptions, cancellationToken: cancellationToken);
}
public override void Dispose()
{
BlobClient.Delete();
base.Dispose();
}
}
}
| mit | C# |
e6f91d858cd8def9b38967bcb308edb0a3353dba | Update tests | vivet/GoogleApi | GoogleApi.Test/BaseTest.cs | GoogleApi.Test/BaseTest.cs | namespace GoogleApi.Test
{
public abstract class BaseTest
{
public string _apiKey = ""; // your API key goes here...
}
} | namespace GoogleApi.Test
{
public abstract class BaseTest
{
public string _apiKey = "AIzaSyCh-Kr-9s7LSJPLflpk8k2BvLjEetm0laE"; // your API key goes here...
}
} | mit | C# |
806e531d5cd3843463df23efe9e43f0d5a5f55f9 | Update in line with merge | EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework | osu.Framework/IO/Stores/TimedExpiryGlyphStore.cs | osu.Framework/IO/Stores/TimedExpiryGlyphStore.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics.Textures;
namespace osu.Framework.IO.Stores
{
/// <summary>
/// A glyph store which caches font sprite sheets in memory temporary, to allow for more efficient retrieval.
/// </summary>
/// <remarks>
/// This store has a higher memory overhead than <see cref="RawCachingGlyphStore"/>, but better performance and zero disk footprint.
/// </remarks>
public class TimedExpiryGlyphStore : GlyphStore
{
private readonly TimedExpiryCache<int, TextureUpload> texturePages = new TimedExpiryCache<int, TextureUpload>();
public TimedExpiryGlyphStore(ResourceStore<byte[]> store, string assetName = null)
: base(store, assetName)
{
}
protected override TextureUpload GetPageImage(int page)
{
if (!texturePages.TryGetValue(page, out var image))
{
loadedPageCount++;
texturePages.Add(page, image = base.GetPageImage(page));
}
return image;
}
private int loadedPageCount;
public override string ToString() => $@"GlyphStore({AssetName}) LoadedPages:{loadedPageCount} LoadedGlyphs:{LoadedGlyphCount}";
protected override void Dispose(bool disposing)
{
texturePages.Dispose();
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.IO.Stores
{
/// <summary>
/// A glyph store which caches font sprite sheets in memory temporary, to allow for more efficient retrieval.
/// </summary>
/// <remarks>
/// This store has a higher memory overhead than <see cref="RawCachingGlyphStore"/>, but better performance and zero disk footprint.
/// </remarks>
public class TimedExpiryGlyphStore : GlyphStore
{
private readonly TimedExpiryCache<int, Image<Rgba32>> texturePages = new TimedExpiryCache<int, Image<Rgba32>>();
public TimedExpiryGlyphStore(ResourceStore<byte[]> store, string assetName = null)
: base(store, assetName)
{
}
protected override Image<Rgba32> GetPageImage(int page)
{
if (!texturePages.TryGetValue(page, out var image))
{
loadedPageCount++;
texturePages.Add(page, image = base.GetPageImage(page));
}
return image;
}
private int loadedPageCount;
public override string ToString() => $@"GlyphStore({AssetName}) LoadedPages:{loadedPageCount} LoadedGlyphs:{LoadedGlyphCount}";
protected override void Dispose(bool disposing)
{
texturePages.Dispose();
}
}
}
| mit | C# |
00493127eaf3c958a9163c414980b508bcff8100 | Fix nullref when no Icon is supplied | denxorz/HotChocolatey | HotChocolatey/ChocoItem.cs | HotChocolatey/ChocoItem.cs |
using System;
using System.ComponentModel;
using NuGet;
using System.IO;
namespace HotChocolatey
{
[Magic]
public class ChocoItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public IPackage Package { get; }
public string Name => Package.Id;
public string InstalledVersion { get; private set; }
public string LatestVersion { get; private set; }
public bool IsInstalledUpgradable { get; private set; }
public bool IsMarkedForInstallation { get; set; }
public bool IsMarkedForUpgrade { get; set; }
public bool IsMarkedForUninstall { get; set; }
public string Title => Package.Title;
public Uri Ico => Package.IconUrl == null || Path.GetExtension(Package.IconUrl.ToString()) == ".svg" ? noIconUri : Package.IconUrl;
public bool IsPreRelease => !Package.IsReleaseVersion();
public string Summary => Package.Summary;
public string Description => Package.Description;
public bool IsInstalled => InstalledVersion != null;
private readonly Uri noIconUri = new Uri("/HotChocolatey;component/Images/chocolateyicon.gif", UriKind.Relative);
public ChocoItem(IPackage package)
{
Package = package;
}
public static ChocoItem FromInstalledString(IPackage package, string version)
{
return new ChocoItem(package) { InstalledVersion = version };
}
public static ChocoItem FromPackage(IPackage package)
{
return new ChocoItem(package);
}
public static ChocoItem FromUpdatableString(IPackage package, string installedVersion, string latestVersion)
{
return new ChocoItem(package) { InstalledVersion = installedVersion, LatestVersion = latestVersion, IsInstalledUpgradable = installedVersion != latestVersion };
}
internal void Update(ChocoItem item)
{
if (item.InstalledVersion != null && InstalledVersion != item.InstalledVersion)
{
InstalledVersion = item.InstalledVersion;
}
if (item.LatestVersion != null && LatestVersion != item.LatestVersion)
{
LatestVersion = item.LatestVersion;
}
IsInstalledUpgradable = item.IsInstalledUpgradable;
}
private void RaisePropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
|
using System;
using System.ComponentModel;
using NuGet;
using System.IO;
namespace HotChocolatey
{
[Magic]
public class ChocoItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public IPackage Package { get; }
public string Name => Package.Id;
public string InstalledVersion { get; private set; }
public string LatestVersion { get; private set; }
public bool IsInstalledUpgradable { get; private set; }
public bool IsMarkedForInstallation { get; set; }
public bool IsMarkedForUpgrade { get; set; }
public bool IsMarkedForUninstall { get; set; }
public string Title => Package.Title;
public Uri Ico => Path.GetExtension(Package.IconUrl.ToString()) == ".svg" ? new Uri("/HotChocolatey;component/Images/chocolateyicon.gif", UriKind.Relative) : Package.IconUrl;
public bool IsPreRelease => !Package.IsReleaseVersion();
public string Summary => Package.Summary;
public string Description => Package.Description;
public bool IsInstalled => InstalledVersion != null;
public ChocoItem(IPackage package)
{
Package = package;
}
public static ChocoItem FromInstalledString(IPackage package, string version)
{
return new ChocoItem(package) { InstalledVersion = version };
}
public static ChocoItem FromPackage(IPackage package)
{
return new ChocoItem(package);
}
public static ChocoItem FromUpdatableString(IPackage package, string installedVersion, string latestVersion)
{
return new ChocoItem(package) { InstalledVersion = installedVersion, LatestVersion = latestVersion, IsInstalledUpgradable = installedVersion != latestVersion };
}
internal void Update(ChocoItem item)
{
if (item.InstalledVersion != null && InstalledVersion != item.InstalledVersion)
{
InstalledVersion = item.InstalledVersion;
}
if (item.LatestVersion != null && LatestVersion != item.LatestVersion)
{
LatestVersion = item.LatestVersion;
}
IsInstalledUpgradable = item.IsInstalledUpgradable;
}
private void RaisePropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
| mit | C# |
f9c72c764604fb11f8cf828422eb60558b723f81 | Remove the label as you can not see it when running the app | ZLima12/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework | SampleGame.Android/MainActivity.cs | SampleGame.Android/MainActivity.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using Android.App;
using Android.OS;
using Android.Content.PM;
using Android.Views;
namespace SampleGame.Android
{
[Activity(ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.Fullscreen);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
SetContentView(new SampleGameView(this));
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using Android.App;
using Android.OS;
using Android.Content.PM;
using Android.Views;
namespace SampleGame.Android
{
[Activity(Label = "SampleGame", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, MainLauncher = true, Theme = "@android:style/Theme.NoTitleBar")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.Fullscreen);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
SetContentView(new SampleGameView(this));
}
}
}
| mit | C# |
d8ba4a257df26dafd2f8c9e4734d1351d017148f | Use SystemTime in logging | D3-LucaPiombino/NEventStore,chris-evans/NEventStore,marcoaoteixeira/NEventStore,adamfur/NEventStore,paritoshmmmec/NEventStore,AGiorgetti/NEventStore,NEventStore/NEventStore,nerdamigo/NEventStore,gael-ltd/NEventStore,jamiegaines/NEventStore,deltatre-webplu/NEventStore | src/proj/EventStore.Core/Logging/ExtensionMethods.cs | src/proj/EventStore.Core/Logging/ExtensionMethods.cs | namespace EventStore.Logging
{
using System;
using System.Globalization;
using System.Threading;
internal static class ExtensionMethods
{
private const string MessageFormat = "{0:yyyy/MM/dd HH:mm:ss.ff} - {1} - {2} - {3}";
public static string FormatMessage(this string message, Type typeToLog, params object[] values)
{
return string.Format(
CultureInfo.InvariantCulture,
MessageFormat,
SystemTime.UtcNow,
Thread.CurrentThread.GetName(),
typeToLog.FullName,
string.Format(CultureInfo.InvariantCulture, message, values));
}
private static string GetName(this Thread thread)
{
return !string.IsNullOrEmpty(thread.Name)
? thread.Name
: thread.ManagedThreadId.ToString(CultureInfo.InvariantCulture);
}
}
} | namespace EventStore.Logging
{
using System;
using System.Globalization;
using System.Threading;
internal static class ExtensionMethods
{
private const string MessageFormat = "{0:yyyy/MM/dd HH:mm:ss.ff} - {1} - {2} - {3}";
public static string FormatMessage(this string message, Type typeToLog, params object[] values)
{
return string.Format(
CultureInfo.InvariantCulture,
MessageFormat,
DateTime.UtcNow,
Thread.CurrentThread.GetName(),
typeToLog.FullName,
string.Format(CultureInfo.InvariantCulture, message, values));
}
private static string GetName(this Thread thread)
{
return !string.IsNullOrEmpty(thread.Name)
? thread.Name
: thread.ManagedThreadId.ToString(CultureInfo.InvariantCulture);
}
}
} | mit | C# |
7a123c6079d1febb8372c7773bf6ee8b108496fe | Fix whitespace | rdingwall/MondoUniversalWindowsSample | SchedulerService.cs | SchedulerService.cs | using System.Reactive.Concurrency;
namespace MondoUniversalWindowsSample
{
public interface ISchedulerService
{
IScheduler Dispatcher { get; }
IScheduler TaskPool { get; }
}
public sealed class SchedulerService : ISchedulerService
{
public IScheduler Dispatcher { get; } = CoreDispatcherScheduler.Current;
public IScheduler TaskPool { get; } = TaskPoolScheduler.Default;
}
} | using System.Reactive.Concurrency;
namespace MondoUniversalWindowsSample
{
public interface ISchedulerService
{
IScheduler Dispatcher { get; }
IScheduler TaskPool { get; }
}
public sealed class SchedulerService : ISchedulerService
{
public IScheduler Dispatcher { get; } = CoreDispatcherScheduler.Current;
public IScheduler TaskPool { get; } = TaskPoolScheduler.Default;
}
} | mit | C# |
1eefb245881f284d78313876f34470c525c6876f | Create docs for ProxySettings | extremecodetv/SocksSharp | src/SocksSharp/Proxy/ProxySettings.cs | src/SocksSharp/Proxy/ProxySettings.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace SocksSharp.Proxy
{
/// <summary>
/// Represents the settings for <see cref="ProxyClient{T}"/>
/// </summary>
public class ProxySettings : IProxySettings, IProxySettingsFluent
{
/// <summary>
/// Gets or sets the credentials to submit to the proxy server for authentication.
/// </summary>
public NetworkCredential Credentials { get; set; }
/// <summary>
/// Gets or sets a value of host or IP address for the proxy server
/// </summary>
public string Host { get; set; }
/// <summary>
/// Gets or sets a value of Port for the proxy server
/// </summary>
public int Port { get; set; }
/// <summary>
/// Gets or sets the amount of time a <see cref="ProxyClient{T}"/>
/// will wait to connect to the proxy server
/// </summary>
public int ConnectTimeout { get; set; } = 5000;
/// <summary>
/// Gets or sets the amount of time a <see cref="ProxyClient{T}"/>
/// will wait for read or wait data from the proxy server
/// </summary>
public int ReadWriteTimeOut { get; set; } = 10000;
#region Fluent
public IProxySettingsFluent SetConnectionTimeout(int connectionTimeout)
{
throw new NotImplementedException();
}
public IProxySettingsFluent SetCredential(NetworkCredential credential)
{
throw new NotImplementedException();
}
public IProxySettingsFluent SetCredential(string username, string password)
{
throw new NotImplementedException();
}
public IProxySettingsFluent SetHost(string host)
{
throw new NotImplementedException();
}
public IProxySettingsFluent SetPort(int port)
{
throw new NotImplementedException();
}
public IProxySettingsFluent SetReadWriteTimeout(int readwriteTimeout)
{
throw new NotImplementedException();
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace SocksSharp.Proxy
{
public class ProxySettings : IProxySettings, IProxySettingsFluent
{
public NetworkCredential Credentials { get; set; }
public string Host { get; set; }
public int Port { get; set; }
public int ConnectTimeout { get; set; } = 5000;
public int ReadWriteTimeOut { get; set; } = 10000;
#region Fluent
public IProxySettingsFluent SetConnectionTimeout(int connectionTimeout)
{
throw new NotImplementedException();
}
public IProxySettingsFluent SetCredential(NetworkCredential credential)
{
throw new NotImplementedException();
}
public IProxySettingsFluent SetCredential(string username, string password)
{
throw new NotImplementedException();
}
public IProxySettingsFluent SetHost(string host)
{
throw new NotImplementedException();
}
public IProxySettingsFluent SetPort(int port)
{
throw new NotImplementedException();
}
public IProxySettingsFluent SetReadWriteTimeout(int readwriteTimeout)
{
throw new NotImplementedException();
}
#endregion
}
}
| mit | C# |
b046301486d6c15ad4fcfc3e5e20621d75984343 | Fix map roundtrip issues | feliwir/openSage,feliwir/openSage | src/OpenSage.Game/Data/Map/ScriptCondition.cs | src/OpenSage.Game/Data/Map/ScriptCondition.cs | using System.IO;
using OpenSage.Data.Utilities.Extensions;
namespace OpenSage.Data.Map
{
public sealed class ScriptCondition : ScriptContent<ScriptCondition, ScriptConditionType>
{
public const string AssetName = "Condition";
private const ushort MinimumVersionThatHasInternalName = 4;
private const ushort MinimumVersionThatHasEnabledFlag = 5;
public bool IsInverted { get; private set; }
internal static ScriptCondition Parse(BinaryReader reader, MapParseContext context)
{
return Parse(
reader,
context,
MinimumVersionThatHasInternalName,
MinimumVersionThatHasEnabledFlag,
(version, x) =>
{
if (version >= MinimumVersionThatHasEnabledFlag)
{
x.IsInverted = reader.ReadBooleanUInt32Checked();
}
});
}
internal void WriteTo(BinaryWriter writer, AssetNameCollection assetNames)
{
WriteTo(
writer,
assetNames,
MinimumVersionThatHasInternalName,
MinimumVersionThatHasEnabledFlag,
() =>
{
if (Version >= MinimumVersionThatHasEnabledFlag)
{
writer.WriteBooleanUInt32(IsInverted);
}
});
}
}
}
| using System.IO;
using OpenSage.Data.Utilities.Extensions;
namespace OpenSage.Data.Map
{
public sealed class ScriptCondition : ScriptContent<ScriptCondition, ScriptConditionType>
{
public const string AssetName = "Condition";
private const ushort MinimumVersionThatHasInternalName = 4;
private const ushort MinimumVersionThatHasEnabledFlag = 5;
public bool IsInverted { get; private set; }
internal static ScriptCondition Parse(BinaryReader reader, MapParseContext context)
{
return Parse(
reader,
context,
MinimumVersionThatHasInternalName,
MinimumVersionThatHasEnabledFlag,
(version, x) =>
{
if (version >= MinimumVersionThatHasEnabledFlag)
{
x.IsInverted = reader.ReadBooleanUInt32Checked();
}
});
}
internal void WriteTo(BinaryWriter writer, AssetNameCollection assetNames)
{
WriteTo(
writer,
assetNames,
MinimumVersionThatHasInternalName,
MinimumVersionThatHasEnabledFlag,
() => writer.WriteBooleanUInt32(IsInverted));
}
}
}
| mit | C# |
156de9f8c449f34f7ff032115edd3d0a90053adb | Remove unused variable. | eylvisaker/AgateLib | AgateLib/UserInterface/Content/Commands/SetTextScale.cs | AgateLib/UserInterface/Content/Commands/SetTextScale.cs | //
// Copyright (c) 2006-2018 Erik Ylvisaker
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
using Microsoft.Xna.Framework;
namespace AgateLib.UserInterface.Content.Commands
{
public class SetTextScale : IContentCommand
{
public void Execute(LayoutContext context, string arg)
{
if (float.TryParse(arg, out float scale))
{
context.Font.Size = (int)(context.Options.DefaultFont.Size * scale);
}
else
{
context.Font.Size = context.Options.DefaultFont.Size;
}
}
}
}
| //
// Copyright (c) 2006-2018 Erik Ylvisaker
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
using Microsoft.Xna.Framework;
namespace AgateLib.UserInterface.Content.Commands
{
public class SetTextScale : IContentCommand
{
public void Execute(LayoutContext context, string arg)
{
Color newColor;
if (float.TryParse(arg, out float scale))
{
context.Font.Size = (int)(context.Options.DefaultFont.Size * scale);
}
else
{
context.Font.Size = context.Options.DefaultFont.Size;
}
}
}
}
| mit | C# |
1f0efdb310bb5afe621d237089e754578ab80dad | comment about PR fixed | xamarin/Xamarin.Auth,xamarin/Xamarin.Auth,xamarin/Xamarin.Auth | source/Xamarin.Auth.LinkSource/AccountResult.cs | source/Xamarin.Auth.LinkSource/AccountResult.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Xamarin.Auth
{
// Pull Request - manually added/fixed
// Added IsAuthenticated check #88
// https://github.com/xamarin/Xamarin.Auth/pull/88
public partial class AccountResult
{
public string Name { get; set; }
public string AccountType { get; set; }
public string Token { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Xamarin.Auth
{
// Pull Request - manually added/fixed
// Marshalled NavigationService.GoBack to UI Thread #94
// https://github.com/xamarin/Xamarin.Auth/pull/88
public partial class AccountResult
{
public string Name { get; set; }
public string AccountType { get; set; }
public string Token { get; set; }
}
}
| apache-2.0 | C# |
31e96e46c4a291c6e888748d57f9eda782a6494c | 同步调整版本号。 :rabbit: | Zongsoft/Zongsoft.Terminals.Launcher | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Zongsoft.Terminals.Launcher")]
[assembly: AssemblyDescription("Zongsoft Terminals Launcher")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Zongsoft Corporation")]
[assembly: AssemblyProduct("Zongsoft.Terminals Launcher")]
[assembly: AssemblyCopyright("Copyright(C) Zongsoft Corporation 2010-2016. All rights reserved.")]
[assembly: AssemblyTrademark("Zongsoft is registered trademarks of Zongsoft Corporation in the P.R.C. and/or other countries.")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("4.1.1602.*")]
[assembly: AssemblyFileVersion("4.1.1602.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Zongsoft.Terminals.Launcher")]
[assembly: AssemblyDescription("Zongsoft Terminals Launcher")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Zongsoft Corporation")]
[assembly: AssemblyProduct("Zongsoft.Terminals Launcher")]
[assembly: AssemblyCopyright("Copyright(C) Zongsoft Corporation 2010-2013. All rights reserved.")]
[assembly: AssemblyTrademark("Zongsoft is registered trademarks of Zongsoft Corporation in the P.R.C. and/or other countries.")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("3.2.1407.*")]
[assembly: AssemblyFileVersion("3.2.1407.0")]
| mit | C# |
b24c875ad019cf321d9b18e7e8bfd49e858af95a | Bump the protocol version to 0x1343 | IceYGO/ygosharp | YGOSharp/Program.cs | YGOSharp/Program.cs | #if !DEBUG
using System;
using System.IO;
#endif
using System.Threading;
using YGOSharp.OCGWrapper;
namespace YGOSharp
{
public class Program
{
public static uint ClientVersion = 0x1343;
public static void Main(string[] args)
{
#if !DEBUG
try
{
#endif
Config.Load(args);
BanlistManager.Init(Config.GetString("BanlistFile", "lflist.conf"));
Api.Init(Config.GetString("RootPath", "."), Config.GetString("ScriptDirectory", "script"), Config.GetString("DatabaseFile", "cards.cdb"));
ClientVersion = Config.GetUInt("ClientVersion", ClientVersion);
CoreServer server = new CoreServer();
server.Start();
while (server.IsRunning)
{
server.Tick();
Thread.Sleep(1);
}
#if !DEBUG
}
catch (Exception ex)
{
File.WriteAllText("crash_" + DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss") + ".txt", ex.ToString());
}
#endif
}
}
}
| #if !DEBUG
using System;
using System.IO;
#endif
using System.Threading;
using YGOSharp.OCGWrapper;
namespace YGOSharp
{
public class Program
{
public static uint ClientVersion = 0x133D;
public static void Main(string[] args)
{
#if !DEBUG
try
{
#endif
Config.Load(args);
BanlistManager.Init(Config.GetString("BanlistFile", "lflist.conf"));
Api.Init(Config.GetString("RootPath", "."), Config.GetString("ScriptDirectory", "script"), Config.GetString("DatabaseFile", "cards.cdb"));
ClientVersion = Config.GetUInt("ClientVersion", ClientVersion);
CoreServer server = new CoreServer();
server.Start();
while (server.IsRunning)
{
server.Tick();
Thread.Sleep(1);
}
#if !DEBUG
}
catch (Exception ex)
{
File.WriteAllText("crash_" + DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss") + ".txt", ex.ToString());
}
#endif
}
}
}
| mit | C# |
b1557fcd517db7b1809be8ceecdc68db9ae65937 | Extend RelayCommand | stadub/WinClipboardApi,stadub/WinClipboardApi,stadub/WinClipboardApi | Utils.Wpf/MvvmBase/RelayCommand.cs | Utils.Wpf/MvvmBase/RelayCommand.cs | using System;
using System.Windows.Input;
namespace Utils.Wpf.MvvmBase
{
public class RelayCommand : IRelayCommand
{
private readonly Action execute;
private readonly Func<bool> canExecute;
private bool status;
public RelayCommand(Action execute, Func<bool> canExecute = null)
{
this.execute = execute;
if (canExecute != null)
this.canExecute = canExecute;
else
this.canExecute = () => true;
status = true;
}
public bool CanExecute()
{
var newStatus = canExecute();
if (newStatus == status)
return newStatus;
status = newStatus;
OnCanExecuteChanged();
return newStatus;
}
public void RefreshCanExecute()
{
CanExecute();
}
public void Execute()
{
if (!CanExecute())
return;
execute();
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute();
}
void ICommand.Execute(object parameter)
{
Execute();
}
public event EventHandler CanExecuteChanged;
protected virtual void OnCanExecuteChanged()
{
EventHandler handler = CanExecuteChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
}
public interface IRelayCommand : ICommand
{
bool CanExecute();
void RefreshCanExecute();
void Execute();
}
} | using System;
using System.Windows.Input;
namespace Utils.Wpf.MvvmBase
{
public class RelayCommand : ICommand
{
private readonly Action execute;
private readonly Func<bool> canExecute;
private bool status;
public RelayCommand(Action execute, Func<bool> canExecute = null)
{
this.execute = execute;
if (canExecute != null)
this.canExecute = canExecute;
else
this.canExecute = () => true;
status = true;
}
public bool CanExecute(object parameter)
{
var newStatus = canExecute();
if (newStatus == status)
return newStatus;
status = newStatus;
OnCanExecuteChanged();
return newStatus;
}
public void Execute(object parameter)
{
if (!CanExecute(parameter))
return;
execute();
}
public event EventHandler CanExecuteChanged;
protected virtual void OnCanExecuteChanged()
{
EventHandler handler = CanExecuteChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
}
} | bsd-3-clause | C# |
97e106dc7fa32e772d5edc324a2766fb5b64611a | Optimize jQuery code. | Dissolving-in-Eternity/Vidly,Dissolving-in-Eternity/Vidly,Dissolving-in-Eternity/Vidly | Vidly/Views/Customers/Index.cshtml | Vidly/Views/Customers/Index.cshtml | @model IEnumerable<Vidly.Models.Customer>
@{
ViewBag.Title = "Customers";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Customers</h2>
@if (!Model.Any())
{
<p>We don't have any customers yet.</p>
}
else
{
<table id="customers" class="table table-bordered table-hover">
<thead>
<tr>
<th>Customer</th>
<th>Membership Type</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
@foreach (var customer in Model)
{
<tr>
<td>@Html.ActionLink(customer.Name, "Edit", "Customers", new { id = customer.Id }, null)</td>
<td>@customer.MembershipType.Name</td>
<td>
<button data-customer-id="@customer.Id" class="btn-link js-delete">Delete</button>
</td>
</tr>
}
</tbody>
</table>
}
@section scripts
{
<script>
$(document).ready(function () {
$("#customers").on("click", ".js-delete", function () {
var button = $(this);
bootbox.confirm("Are you sure you want to delete this customer?", function (result) {
if (result) {
$.ajax({
url: "/api/customers/" + button.attr("data-customer-id"),
method: "DELETE",
success: function () {
button.parents("tr").remove();
}
});
}
});
});
});
</script>
} | @model IEnumerable<Vidly.Models.Customer>
@{
ViewBag.Title = "Customers";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Customers</h2>
@if (!Model.Any())
{
<p>We don't have any customers yet.</p>
}
else
{
<table id="customers" class="table table-bordered table-hover">
<thead>
<tr>
<th>Customer</th>
<th>Membership Type</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
@foreach (var customer in Model)
{
<tr>
<td>@Html.ActionLink(customer.Name, "Edit", "Customers", new { id = customer.Id }, null)</td>
<td>@customer.MembershipType.Name</td>
<td>
<button data-customer-id="@customer.Id" class="btn-link js-delete">Delete</button>
</td>
</tr>
}
</tbody>
</table>
}
@section scripts
{
<script>
$(document).ready(function () {
$("#customers .js-delete").on("click", function () {
var button = $(this);
bootbox.confirm("Are you sure you want to delete this customer?", function (result) {
if (result) {
$.ajax({
url: "/api/customers/" + button.attr("data-customer-id"),
method: "DELETE",
success: function () {
button.parents("tr").remove();
}
});
}
});
});
});
</script>
} | mit | C# |
8056f4834b49353ac4e3f6085817d2a5de4b34b4 | Add apply extension method to CollectionExtensions | hossmi/qtfk | QTFK.Core/Extensions/Collections/CollectionExtension.cs | QTFK.Core/Extensions/Collections/CollectionExtension.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QTFK.Extensions.Collections
{
public static class CollectionExtension
{
public static ICollection<T> Push<T>(this ICollection<T> items, T item)
{
items.Add(item);
return items;
}
public static IEnumerable<T> apply<T>(this IEnumerable<T> items, Action<T> actionDelegate) where T : class
{
foreach (T item in items)
{
actionDelegate(item);
yield return item;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QTFK.Extensions.Collections
{
public static class CollectionExtension
{
public static ICollection<T> Push<T>(this ICollection<T> items, T item)
{
items.Add(item);
return items;
}
}
}
| mit | C# |
b0953c7924977b1d0561a5aa264579710d26f1e5 | Update version message | zumicts/Audiotica | Apps/Audiotica.WindowsPhone/View/HomePage.xaml.cs | Apps/Audiotica.WindowsPhone/View/HomePage.xaml.cs | #region
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
using IF.Lastfm.Core.Objects;
#endregion
namespace Audiotica.View
{
public sealed partial class HomePage
{
public HomePage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var justUpdated = true;
var firstRun = !ApplicationData.Current.LocalSettings.Values.ContainsKey("CurrentBuild");
if (!firstRun)
justUpdated = (string) ApplicationData.Current.LocalSettings.Values["CurrentBuild"]
!= "1409-beta3-patch1";
else
{
ApplicationData.Current.LocalSettings.Values.Add("CurrentBuild", "1410-beta4-patch0");
new MessageDialog(
"Test out saving downloading using the new metadate provider (last.fm)",
"v1410 (BETA4)").ShowAsync();
}
if (!justUpdated || firstRun) return;
new MessageDialog(
"-switch from xbox music to last.fm\n-now playing page is everywhere!\n-subtle changes in ui",
"Beta4 - Patch #0")
.ShowAsync();
ApplicationData.Current.LocalSettings.Values["CurrentBuild"] = "1410-beta4-patch0";
}
//TODO [Harry,20140908] move this to view model with RelayCommand
private void ListView_ItemClick(object sender, ItemClickEventArgs e)
{
var album = e.ClickedItem as LastAlbum;
if (album != null) Frame.Navigate(typeof (AlbumPage), album);
}
private void Grid_Tapped(object sender, TappedRoutedEventArgs e)
{
var artist = ((Grid) sender).DataContext as LastArtist;
if (artist != null) Frame.Navigate(typeof (ArtistPage), artist.Name);
}
}
} | #region
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
using IF.Lastfm.Core.Objects;
#endregion
namespace Audiotica.View
{
public sealed partial class HomePage
{
public HomePage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var justUpdated = true;
var firstRun = !ApplicationData.Current.LocalSettings.Values.ContainsKey("CurrentBuild");
if (!firstRun)
justUpdated = (string) ApplicationData.Current.LocalSettings.Values["CurrentBuild"]
!= "1409-beta3-patch1";
else
{
ApplicationData.Current.LocalSettings.Values.Add("CurrentBuild", "1409-beta3-patch1");
new MessageDialog(
"Test out saving, deleting and playing songs",
"v1409 (BETA3)").ShowAsync();
}
if (!justUpdated || firstRun) return;
new MessageDialog(
"-switch from xbox music to last.fm\n-now playing page is everywhere!\n-subtle changes in ui",
"Beta3 - Patch #1")
.ShowAsync();
ApplicationData.Current.LocalSettings.Values["CurrentBuild"] = "1409-beta3-patch1";
}
//TODO [Harry,20140908] move this to view model with RelayCommand
private void ListView_ItemClick(object sender, ItemClickEventArgs e)
{
var album = e.ClickedItem as LastAlbum;
if (album != null) Frame.Navigate(typeof (AlbumPage), album);
}
private void Grid_Tapped(object sender, TappedRoutedEventArgs e)
{
var artist = ((Grid) sender).DataContext as LastArtist;
if (artist != null) Frame.Navigate(typeof (ArtistPage), artist.Name);
}
}
} | apache-2.0 | C# |
01d81fc388cf425e3164a4643896acfa8ff95911 | Update MetricsEndpointHandler.cs | toolhouse/monitoring-dotnet | Toolhouse.Monitoring/Handlers/MetricsEndpointHandler.cs | Toolhouse.Monitoring/Handlers/MetricsEndpointHandler.cs | using System;
using System.Web;
using Prometheus;
using Prometheus.Advanced;
namespace Toolhouse.Monitoring.Handlers
{
/// <summary>
/// IHttpHandler implementation that provides a Prometheus metrics scraping endpoint.
/// </summary>
public class MetricsEndpointHandler : AbstractHttpHandler
{
public override void ProcessRequest(HttpContext context)
{
if (!CheckAuthentication(context))
{
return;
}
var request = context.Request;
var response = context.Response;
// This adapts prometheus-net's internal HTTP serving code
// Cribbed from http://www.erikojebo.se/Code/Details/792
var acceptHeader = request.Headers.Get("Accept");
var acceptHeaders = (acceptHeader ?? "").Split(',');
response.ContentType = ScrapeHandler.GetContentType(acceptHeaders);
response.ContentEncoding = System.Text.Encoding.UTF8;
ScrapeHandler.ProcessScrapeRequest(
DefaultCollectorRegistry.Instance.CollectAll(),
response.ContentType,
response.OutputStream
);
}
}
}
| using System;
using System.Web;
using Prometheus;
using Prometheus.Advanced;
namespace Toolhouse.Monitoring.Handlers
{
/// <summary>
/// IHttpHandler implementation that provides a Prometheus metrics scraping endpoint.
/// </summary>
class MetricsEndpointHandler : AbstractHttpHandler
{
public override void ProcessRequest(HttpContext context)
{
if (!CheckAuthentication(context))
{
return;
}
var request = context.Request;
var response = context.Response;
// This adapts prometheus-net's internal HTTP serving code
// Cribbed from http://www.erikojebo.se/Code/Details/792
var acceptHeader = request.Headers.Get("Accept");
var acceptHeaders = (acceptHeader ?? "").Split(',');
response.ContentType = ScrapeHandler.GetContentType(acceptHeaders);
response.ContentEncoding = System.Text.Encoding.UTF8;
ScrapeHandler.ProcessScrapeRequest(
DefaultCollectorRegistry.Instance.CollectAll(),
response.ContentType,
response.OutputStream
);
}
}
}
| apache-2.0 | C# |
f991a040545f4730f4785fa3599d7bf628fe5205 | disable parallel tests | SamuelDebruyn/MugenMvvmToolkit.DryIoc,SamuelDebruyn/MugenMvvmToolkit.DryIoc | MugenMvvmToolkit.DryIoc.Tests/ContainerFixture.cs | MugenMvvmToolkit.DryIoc.Tests/ContainerFixture.cs | using System;
using Xunit;
[assembly: CollectionBehavior(DisableTestParallelization = true)]
namespace MugenMvvmToolkit.DryIoc.Tests
{
public class ContainerFixture : IDisposable
{
public DryIocContainer DryIocContainer { get; private set; }
public ContainerFixture()
{
Reset();
}
public void Reset()
{
DryIocContainer?.Dispose();
DryIocContainer = new DryIocContainer.Builder().Build();
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
DryIocContainer?.Dispose();
DryIocContainer = null;
}
}
public void Dispose()
{
Dispose(true);
}
}
} | using System;
namespace MugenMvvmToolkit.DryIoc.Tests
{
public class ContainerFixture : IDisposable
{
public DryIocContainer DryIocContainer { get; private set; }
public ContainerFixture()
{
Reset();
}
public void Reset()
{
DryIocContainer?.Dispose();
DryIocContainer = new DryIocContainer.Builder().Build();
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
DryIocContainer?.Dispose();
DryIocContainer = null;
}
}
public void Dispose()
{
Dispose(true);
}
}
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.