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 |
|---|---|---|---|---|---|---|---|---|
cf42ff92ec282d0cc467f90f24921fa5eb14718c | Fix is null | avifatal/framework,signumsoftware/framework,avifatal/framework,signumsoftware/framework,AlejandroCano/framework,AlejandroCano/framework | Signum.Engine/Linq/ExpressionVisitor/DbQueryUtils.cs | Signum.Engine/Linq/ExpressionVisitor/DbQueryUtils.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using Signum.Utilities.ExpressionTrees;
using Signum.Engine.Maps;
using Signum.Entities;
using Signum.Utilities;
namespace Signum.Engine.Linq
{
internal static class DbQueryUtils
{
internal static bool IsNull(this Expression e)
{
switch (e.NodeType)
{
case ExpressionType.Convert: return ((UnaryExpression)e).Operand.IsNull();
case ExpressionType.Constant: return ((ConstantExpression)e).Value == null;
case (ExpressionType)DbExpressionType.SqlConstant: return ((SqlConstantExpression)e).Value == null;
}
return false;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using Signum.Utilities.ExpressionTrees;
using Signum.Engine.Maps;
using Signum.Entities;
using Signum.Utilities;
namespace Signum.Engine.Linq
{
internal static class DbQueryUtils
{
internal static bool IsNull(this Expression e)
{
ConstantExpression ce = e as ConstantExpression;
SqlConstantExpression sce = e as SqlConstantExpression;
return ce != null && ce.Value == null ||
sce != null && sce.Value == null;
}
}
}
| mit | C# |
6209d6ec82fd425573724464a75d12bc40b666f9 | remove editor usings (#23) | bengreenier/Unity-MenuStack | Assets/Scripts/Navigation/BaseMenuNavigator.cs | Assets/Scripts/Navigation/BaseMenuNavigator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
namespace MenuStack.Navigation
{
/// <summary>
/// Base for a control capable of navigating to a different <see cref="Menu"/> within a <see cref="MenuRoot"/>
/// </summary>
public abstract class BaseMenuNavigator : MonoBehaviour, INavigator
{
/// <summary>
/// Provides a location to navigate to, when navigation occurs
/// </summary>
/// <returns><see cref="Menu"/> to navigate to</returns>
protected abstract Menu GetNavigationLocation();
/// <summary>
/// Triggers navigation
/// </summary>
public virtual void Navigate()
{
this.GetComponentInParent<MenuRoot>().OpenAsync(this.GetNavigationLocation());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor.Events;
using UnityEngine;
using UnityEngine.UI;
namespace MenuStack.Navigation
{
/// <summary>
/// Base for a control capable of navigating to a different <see cref="Menu"/> within a <see cref="MenuRoot"/>
/// </summary>
public abstract class BaseMenuNavigator : MonoBehaviour, INavigator
{
/// <summary>
/// Provides a location to navigate to, when navigation occurs
/// </summary>
/// <returns><see cref="Menu"/> to navigate to</returns>
protected abstract Menu GetNavigationLocation();
/// <summary>
/// Triggers navigation
/// </summary>
public virtual void Navigate()
{
this.GetComponentInParent<MenuRoot>().OpenAsync(this.GetNavigationLocation());
}
}
}
| mit | C# |
c73cec6b1ee407e85dbc1f0d2c9ed23316b321a9 | Remove empty line in name spaces | tvanfosson/dapper-integration-testing | DapperTesting/Core/Data/MsSqlConnectionFactory.cs | DapperTesting/Core/Data/MsSqlConnectionFactory.cs | using System.Data.Common;
using System.Data.SqlClient;
using DapperTesting.Core.Configuration;
namespace DapperTesting.Core.Data
{
public class MsSqlConnectionFactory : IConnectionFactory
{
private readonly IConfiguration _configuration;
public MsSqlConnectionFactory(IConfiguration configuration)
{
_configuration = configuration;
}
public DbConnection Create(string connectionStringName)
{
return new SqlConnection(_configuration.GetConnectionString(connectionStringName));
}
}
}
| using System.Data.Common;
using System.Data.SqlClient;
using DapperTesting.Core.Configuration;
namespace DapperTesting.Core.Data
{
public class MsSqlConnectionFactory : IConnectionFactory
{
private readonly IConfiguration _configuration;
public MsSqlConnectionFactory(IConfiguration configuration)
{
_configuration = configuration;
}
public DbConnection Create(string connectionStringName)
{
return new SqlConnection(_configuration.GetConnectionString(connectionStringName));
}
}
}
| mit | C# |
bb2451515914d98fe0249f58b7cdb8c062d5078a | refactor repository | eriklieben/ErikLieben.Data | ErikLieben.Data/Repository/IRepository.cs | ErikLieben.Data/Repository/IRepository.cs | namespace ErikLieben.Data.Repository
{
using System.Collections.Generic;
public interface IRepository<T>
where T : class
{
/// <summary>
/// Adds the specified item.
/// </summary>
/// <param name="item">The item to add.</param>
void Add(T item);
/// <summary>
/// Deletes the specified item.
/// </summary>
/// <param name="item">The item to delete.</param>
void Delete(T item);
/// <summary>
/// Updates the specified item.
/// </summary>
/// <param name="item">The item to update.</param>
void Update(T item);
IEnumerable<T> Find(ISpecification<T> specification, IFetchingStrategy<T> fetchingStrategy);
}
}
| namespace ErikLieben.Data.Repository
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
public interface IRepository<T>
where T : class
{
/// <summary>
/// Adds the specified item.
/// </summary>
/// <param name="item">The item to add.</param>
void Add(T item);
/// <summary>
/// Deletes the specified item.
/// </summary>
/// <param name="item">The item to delete.</param>
void Delete(T item);
/// <summary>
/// Updates the specified item.
/// </summary>
/// <param name="item">The item to update.</param>
void Update(T item);
Task<int> SubmitChangesAsync();
Task<int> SubmitChangesAsync(CancellationToken token);
IEnumerable<T> FindAll();
IEnumerable<T> Find(ISpecification<T> specification);
[SuppressMessage(
"Microsoft.Design",
"CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "Async method")]
Task<IEnumerable<T>> FindAsync(ISpecification<T> specification, CancellationToken token);
}
}
| mit | C# |
2b9c24142bb7d8f5389f1872ff85e8855fe07b8b | fix namespace | feedhenry-templates/blank-xamarin,feedhenry-templates/blank-xamarin | blank-xamarin-android/MainActivity.cs | blank-xamarin-android/MainActivity.cs | using Android.App;
using Android.Widget;
using Android.OS;
using FHSDK;
namespace fhxamarinandroidblank
{
[Activity (Label = "fh-xamarin-android-blank", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
// Set our view from the "main" layout resource
//SetContentView (Resource.Layout.Main);
var initTask = FHClient.Init();
initTask.ContinueWith(task =>
{RunOnUiThread(()=>{
if (!task.IsFaulted)
{
Toast.MakeText(this, "Init complete", ToastLength.Long).Show();
}
else
{
Toast.MakeText(this, "Init failed " + task.Exception, ToastLength.Long).Show();
}
});
});
}
}
}
| using Android.App;
using Android.Widget;
using Android.OS;
using FHSDK.Droid;
namespace fhxamarinandroidblank
{
[Activity (Label = "fh-xamarin-android-blank", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
// Set our view from the "main" layout resource
//SetContentView (Resource.Layout.Main);
var initTask = FHClient.Init();
initTask.ContinueWith(task =>
{RunOnUiThread(()=>{
if (!task.IsFaulted)
{
Toast.MakeText(this, "Init complete", ToastLength.Long).Show();
}
else
{
Toast.MakeText(this, "Init failed " + task.Exception, ToastLength.Long).Show();
}
});
});
}
}
}
| apache-2.0 | C# |
822c760888a1f6f8f06519a033d988cd60292186 | clean up | dkataskin/bstrkr | bstrkr.mobile/bstrkr.android/Setup.cs | bstrkr.mobile/bstrkr.android/Setup.cs | using Android.Content;
using Cirrious.CrossCore;
using Cirrious.CrossCore.Platform;
using Cirrious.MvvmCross.Binding.Bindings.Target.Construction;
using Cirrious.MvvmCross.Droid.Platform;
using Cirrious.MvvmCross.Droid.Views;
using Cirrious.MvvmCross.ViewModels;
using Xamarin;
using bstrkr.core.android.config;
using bstrkr.core.android.presenters;
using bstrkr.core.android.services;
using bstrkr.core.android.services.location;
using bstrkr.core.android.services.resources;
using bstrkr.core.config;
using bstrkr.core.services.location;
using bstrkr.core.services.resources;
using bstrkr.mvvm;
using bstrkr.mvvm.views;
using bstrkr.android.views;
namespace bstrkr.android
{
public class Setup : MvxAndroidSetup
{
public Setup(Context applicationContext) : base(applicationContext)
{
Insights.Initialize("<your_key_here>", applicationContext);
}
protected override void InitializeFirstChance()
{
Mvx.LazyConstructAndRegisterSingleton<IConfigManager, ConfigManager>();
Mvx.LazyConstructAndRegisterSingleton<ILocationService, SuperLocationService>();
Mvx.LazyConstructAndRegisterSingleton<IResourceManager, ResourceManager>();
Mvx.RegisterSingleton<ICustomPresenter>(new CustomPresenter());
base.InitializeFirstChance();
}
protected override IMvxApplication CreateApp()
{
return new BusTrackerApp();
}
protected override IMvxTrace CreateDebugTrace()
{
return new DebugTrace();
}
protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
registry.RegisterCustomBindingFactory<MonoDroidGoogleMapsView>(
"Zoom",
mapView => new MapViewZoomTargetBinding(mapView));
base.FillTargetFactories(registry);
}
protected override IMvxAndroidViewPresenter CreateViewPresenter()
{
return Mvx.Resolve<ICustomPresenter>();
}
}
} | using Android.Content;
using Cirrious.CrossCore;
using Cirrious.CrossCore.Platform;
using Cirrious.MvvmCross.Binding.Bindings.Target.Construction;
using Cirrious.MvvmCross.Droid.Platform;
using Cirrious.MvvmCross.ViewModels;
using bstrkr.core.android.config;
using bstrkr.core.android.services;
using bstrkr.core.android.services.location;
using bstrkr.core.android.services.resources;
using bstrkr.core.config;
using bstrkr.core.services.location;
using bstrkr.core.services.resources;
using bstrkr.mvvm;
using bstrkr.mvvm.views;
using bstrkr.android.views;
using Xamarin;
using Cirrious.MvvmCross.Droid.Views;
using bstrkr.core.android.presenters;
namespace bstrkr.android
{
public class Setup : MvxAndroidSetup
{
public Setup(Context applicationContext) : base(applicationContext)
{
Insights.Initialize("<your_key_here>", applicationContext);
}
protected override void InitializeFirstChance()
{
Mvx.LazyConstructAndRegisterSingleton<IConfigManager, ConfigManager>();
Mvx.LazyConstructAndRegisterSingleton<ILocationService, SuperLocationService>();
Mvx.LazyConstructAndRegisterSingleton<IResourceManager, ResourceManager>();
Mvx.RegisterSingleton<ICustomPresenter>(new CustomPresenter());
base.InitializeFirstChance();
}
protected override IMvxApplication CreateApp()
{
return new BusTrackerApp();
}
protected override IMvxTrace CreateDebugTrace()
{
return new DebugTrace();
}
protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
registry.RegisterCustomBindingFactory<MonoDroidGoogleMapsView>(
"Zoom",
mapView => new MapViewZoomTargetBinding(mapView));
base.FillTargetFactories(registry);
}
protected override IMvxAndroidViewPresenter CreateViewPresenter()
{
return Mvx.Resolve<ICustomPresenter>();
}
}
} | bsd-2-clause | C# |
799e91446fa3625afea6b4d3bb28fa0bc5ded147 | fix bug all fun | dzhenko/FunBook,dzhenko/FunBook | FunBook/FunBook.WebForms/FunAreaPages/All.aspx.cs | FunBook/FunBook.WebForms/FunAreaPages/All.aspx.cs | using System;
using System.Linq;
using System.Web.ModelBinding;
using System.Web.UI;
using FunBook.Data;
using FunBook.WebForms.DataModels;
namespace FunBook.WebForms.FunAreaPages
{
public partial class All : Page
{
private FunBookData db = FunBookData.Create();
public IQueryable<HomeItemDataModel> GridViewAll_GetData([QueryString]
string search)
{
if (search == null)
{
search = string.Empty;
}
else
{
search = search.ToLower();
}
var allJoke = this.db.Jokes.All()
.Where(j => j.Text.ToLower().Contains(search) || j.Title.ToLower().Contains(search))
.Select(HomeItemDataModel.FromJoke);
var allLink = this.db.Links.All()
.Where(l => l.URL.ToLower().Contains(search) || l.Title.ToLower().Contains(search))
.Select(HomeItemDataModel.FromLink);
var allPicture = this.db.Pictures.All()
.Where(p => p.UrlPath.ToLower().Contains(search) || p.Title.ToLower().Contains(search))
.Select(HomeItemDataModel.FromPicture);
return allJoke.Union(allLink).Union(allPicture);
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using FunBook.Data;
using FunBook.WebForms.DataModels;
using System.Web.ModelBinding;
namespace FunBook.WebForms.FunAreaPages
{
public partial class All : Page
{
private FunBookData db = FunBookData.Create();
public IQueryable<HomeItemDataModel> GridViewAll_GetData()
{
var allJoke = this.db.Jokes.All().Select(HomeItemDataModel.FromJoke);
var allLink = this.db.Links.All().Select(HomeItemDataModel.FromLink);
var allPicture = this.db.Pictures.All().Select(HomeItemDataModel.FromPicture);
return allJoke.Union(allLink).Union(allPicture);
}
public IQueryable<HomeItemDataModel> GridViewAll_GetData([QueryString] string search)
{
var allJoke = this.db.Jokes.All()
.Where(j => j.Text.Contains(search) || j.Title.Contains(search))
.Select(HomeItemDataModel.FromJoke);
var allLink = this.db.Links.All()
.Where(l => l.URL.Contains(search) || l.Title.Contains(search))
.Select(HomeItemDataModel.FromLink);
var allPicture = this.db.Pictures.All()
.Where(p => p.UrlPath.Contains(search) || p.Title.Contains(search))
.Select(HomeItemDataModel.FromPicture);
return allJoke.Union(allLink).Union(allPicture);
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | mit | C# |
f39b1105cf76720911c8b7d6ed40a96f509ae25e | Fix for Prelude.random can throw an OverflowException | StanJav/language-ext,louthy/language-ext | LanguageExt.Core/Prelude/Random/Prelude_Random.cs | LanguageExt.Core/Prelude/Random/Prelude_Random.cs | using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Threading;
namespace LanguageExt
{
public static partial class Prelude
{
// There is no documentation that specifies whether the underlying RNG is thread-safe.
// It is assumed that the implementation is `RNGCryptoServiceProvider`, which under the
// hood calls `CryptGenRandom` from `advapi32` (i.e. a built-in Windows RNG). There is
// no mention of thread-safety issues in any documentation, so we assume this must be
// thread-safe.
//
// Documentation of `CrypGenRandom`
//
// https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptgenrandom
//
// There is some discussion here:
//
// https://stackoverflow.com/questions/46147805/is-cryptgenrandom-thread-safe
//
static readonly RandomNumberGenerator rnd = RandomNumberGenerator.Create();
static readonly int wordTop = BitConverter.IsLittleEndian ? 3 : 0;
/// <summary>
/// Thread-safe cryptographically strong random number generator
/// </summary>
/// <param name="max">Maximum value to return + 1</param>
/// <returns>A non-negative random number, less than the value specified.</returns>
public static int random(int max)
{
var bytes = ArrayPool<byte>.Shared.Rent(4);
rnd.GetBytes(bytes);
bytes[wordTop] &= 0x7f;
var value = BitConverter.ToInt32(bytes, 0) % max;
return value;
}
/// <summary>
/// Thread-safe cryptographically strong random base-64 string generator
/// </summary>
/// <param name="bytesCount">number of bytes generated that are then
/// returned Base64 encoded</param>
/// <returns>Base64 encoded random string</returns>
public static string randomBase64(int bytesCount)
{
if (bytesCount < 1) throw new ArgumentException($"The minimum value for {nameof(bytesCount)} is 1");
var bytes = ArrayPool<byte>.Shared.Rent(bytesCount);
rnd.GetBytes(bytes);
var r = Convert.ToBase64String(bytes);
ArrayPool<byte>.Shared.Return(bytes);
return r;
}
}
}
| using System;
using System.Security.Cryptography;
namespace LanguageExt
{
public static partial class Prelude
{
readonly static RandomNumberGenerator rnd = RandomNumberGenerator.Create();
readonly static byte[] inttarget = new byte[4];
/// <summary>
/// Thread-safe cryptographically strong random number generator
/// </summary>
/// <param name="max">Maximum value to return + 1</param>
/// <returns>A non-negative random number, less than the value specified.</returns>
public static int random(int max)
{
lock (rnd)
{
rnd.GetBytes(inttarget);
return Math.Abs(BitConverter.ToInt32(inttarget, 0)) % max;
}
}
/// <summary>
/// Thread-safe cryptographically strong random base-64 string generator
/// </summary>
/// <param name="bytesCount">number of bytes generated that are then
/// returned Base64 encoded</param>
/// <returns>Base64 encoded random string</returns>
public static string randomBase64(int bytesCount)
{
if (bytesCount < 1) throw new ArgumentException($"The minimum value for {nameof(bytesCount)} is 1");
var bytes = new byte[bytesCount];
lock (rnd) {
rnd.GetBytes(bytes);
}
return Convert.ToBase64String(bytes);
}
}
}
| mit | C# |
cfd25082c68feef1dbb78af33980fe8929243801 | return ok or error from insert | pako1337/Content_Man,pako1337/Content_Man | Content_Man.Web/api/ContentElementApiModule.cs | Content_Man.Web/api/ContentElementApiModule.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ContentDomain;
using ContentDomain.Dto;
using ContentDomain.Repositories;
using Nancy;
using Nancy.ModelBinding;
namespace Content_Man.Web.Api
{
public class ContentElementApiModule : Nancy.NancyModule
{
public ContentElementApiModule()
: base("api/ContentElement")
{
Get["/"] = _ =>
{
var list = new ContentElementRepository().All().AsDto();
return Response.AsJson<IEnumerable<ContentElementDto>>(list);
};
Get["/{elementId}"] = arg =>
{
var jsonModel = new ContentElementRepository().Get((int)arg.elementId).AsDto();
return Response.AsJson<ContentElementDto>(jsonModel);
};
Post["/"] = _ =>
{
var contentElement = this.Bind<ContentElementDto>();
var service = new ContentDomain.ApplicationServices.ContentElementService();
try
{
service.InsertNewContentElement(contentElement);
return HttpStatusCode.OK;
}
catch (Exception ex)
{
if (ex is ArgumentException || ex is ArgumentNullException)
return new Response()
{
StatusCode = HttpStatusCode.BadRequest,
ContentType = "text/plain",
Contents = s => (new System.IO.StreamWriter(s) { AutoFlush = true }).Write(ex.Message)
};
throw;
}
};
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ContentDomain;
using ContentDomain.Dto;
using ContentDomain.Repositories;
using Nancy;
using Nancy.ModelBinding;
namespace Content_Man.Web.Api
{
public class ContentElementApiModule : Nancy.NancyModule
{
public ContentElementApiModule()
: base("api/ContentElement")
{
Get["/"] = _ =>
{
var list = new ContentElementRepository().All().AsDto();
return Response.AsJson<IEnumerable<ContentElementDto>>(list, HttpStatusCode.OK);
};
Get["/{elementId}"] = arg =>
{
var jsonModel = new ContentElementRepository().Get((int)arg.elementId).AsDto();
return Response.AsJson<ContentElementDto>(jsonModel, HttpStatusCode.OK);
};
Post["/"] = _ =>
{
var repo = new ContentElementRepository();
var contentElement = this.Bind<ContentElementDto>();
repo.Insert(new ContentDomain.Factories.ContentElementFactory().Create(contentElement));
return HttpStatusCode.OK;
};
}
}
} | mit | C# |
a1af9b181ddf272a6ac438aaf2d012e99159ee49 | Add overload to Console.WriteLine for string formatting | x335/WootzJs,kswoll/WootzJs,kswoll/WootzJs,x335/WootzJs,x335/WootzJs,kswoll/WootzJs | WootzJs.Runtime/Console.cs | WootzJs.Runtime/Console.cs | #region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
#endregion
using System.Runtime.WootzJs;
namespace System
{
/// <summary>
///
/// </summary>
public class Console
{
/// <summary>
/// Writes the specified string value, followed by the current line terminator, to the standard output stream.
/// </summary>
/// <param name="value">The value to write. </param><exception cref="T:System.IO.IOException">An I/O error occurred. </exception><filterpriority>1</filterpriority>
public static void WriteLine(string value)
{
Jsni.invoke(Jsni.member(Jsni.reference("console"), "log"), value.As<JsString>());
}
/// <summary>
/// Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream.
/// </summary>
/// <param name="value">The value to write. </param><exception cref="T:System.IO.IOException">An I/O error occurred. </exception><filterpriority>1</filterpriority>
public static void WriteLine(object value)
{
WriteLine(value.ToString());
}
/// <summary>
/// Writes the text representation of the specified array of objects, followed by the current line terminator, to the standard output stream using the specified format information.
/// </summary>
/// <param name="format">A composite format string (see Remarks).</param>
/// <param name="arg">An array of objects to write using <paramref name="format"/>. </param>
/// <exception cref="T:System.IO.IOException">An I/O error occurred. </exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="format"/> or <paramref name="arg"/> is null. </exception><exception cref="T:System.FormatException">The format specification in <paramref name="format"/> is invalid. </exception>
public static void WriteLine(string format, params object[] arg)
{
if (arg == null)
WriteLine(format);
else
WriteLine(string.Format(format, arg));
}
}
} | #region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
#endregion
using System.Runtime.WootzJs;
namespace System
{
/// <summary>
///
/// </summary>
public class Console
{
public static void WriteLine(string s)
{
Jsni.invoke(Jsni.member(Jsni.reference("console"), "log"), s.As<JsString>());
}
public static void WriteLine(object o)
{
WriteLine(o.ToString());
}
}
}
| mit | C# |
77a80f6a56806d4ef1a22319793496fd9f1d11da | Update index.cshtml | LeedsSharp/AppVeyorDemo | src/AppVeyorDemo/AppVeyorDemo/Views/index.cshtml | src/AppVeyorDemo/AppVeyorDemo/Views/index.cshtml | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>AppVeyor - Leeds#</title>
<style type="text/css">
body {
text-align: center;
}
h1 {
font-family: 'Segoe UI Light', 'Helvetica Neue', Helvetica, Helvetica, Arial, sans-serif;
}
</style>
</head>
<body>
<img src="https://pbs.twimg.com/profile_images/2269442372/5s66pnbt5v8tw6most5e.png" alt="AppVeyor logo" />
<h1>Hello AppVeyor</h1>
<img src="https://ci.appveyor.com/api/projects/status/mvcbc69n47vl5rvx" title="Build status"/>
</body>
</html>
| <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>AppVeyor - Leeds#</title>
<style type="text/css">
body {
text-align: center;
}
h1 {
font-family: 'Segoe UI Light', 'Helvetica Neue', Helvetica, Helvetica, Arial, sans-serif;
}
</style>
</head>
<body>
<img src="https://pbs.twimg.com/profile_images/2269442372/5s66pnbt5v8tw6most5e.png" alt="AppVeyor logo" />
<h1>Hello Leeds#</h1>
<img src="https://ci.appveyor.com/api/projects/status/mvcbc69n47vl5rvx" title="Build status"/>
</body>
</html>
| apache-2.0 | C# |
9fced67880cd6d9136770864c0ccc55ad433fcf6 | Initialise before enumerating, so can enumerate multiple times | ceddlyburge/canoe-polo-league-organiser-backend | CanoePoloLeagueOrganiser/PragmatisePermutations.cs | CanoePoloLeagueOrganiser/PragmatisePermutations.cs | using System;
using System.Collections.Generic;
using static System.Diagnostics.Contracts.Contract;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanoePoloLeagueOrganiser
{
public class PragmatisePermutations
{
IEnumerable<Game[]> Permutations { get; }
IPragmatiser Pragmatiser { get; }
DateTime TimeStartedCalculation { get; set; }
RunningOptimalGameOrder RunningOptimalGameOrder { get; }
uint permutationCount;
public PragmatisePermutations(
IPragmatiser pragmatiser,
IEnumerable<Game[]> permutations,
RunningOptimalGameOrder runningOptimalGameOrder)
{
Requires(pragmatiser != null);
Requires(permutations != null);
Requires(runningOptimalGameOrder != null);
Permutations = permutations;
Pragmatiser = pragmatiser;
RunningOptimalGameOrder = runningOptimalGameOrder;
}
public IEnumerable<PlayList> PragmatisedPermutations()
{
Initialise();
return Pragmatise();
}
IEnumerable<PlayList> Pragmatise()
{
foreach (var gameOrder in Permutations)
{
if (AcceptableSolutionExists())
yield break;
yield return new PlayList(gameOrder);
}
}
void Initialise()
{
TimeStartedCalculation = DateTime.Now;
permutationCount = 0;
}
bool AcceptableSolutionExists()
{
return
(permutationCount++ % 1000 == 0)
&& Pragmatiser.AcceptableSolution(
DateTime.Now.Subtract(TimeStartedCalculation),
RunningOptimalGameOrder.CurrentMaxOccurencesOfTeamsPlayingConsecutiveMatches);
}
}
}
| using System;
using System.Collections.Generic;
using static System.Diagnostics.Contracts.Contract;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanoePoloLeagueOrganiser
{
public class PragmatisePermutations
{
IEnumerable<Game[]> Permutations { get; }
IPragmatiser Pragmatiser { get; }
DateTime TimeStartedCalculation { get; }
RunningOptimalGameOrder RunningOptimalGameOrder { get; }
uint permutationCount;
public PragmatisePermutations(
IPragmatiser pragmatiser,
IEnumerable<Game[]> permutations,
RunningOptimalGameOrder runningOptimalGameOrder)
{
Requires(pragmatiser != null);
Requires(permutations != null);
Requires(runningOptimalGameOrder != null);
Permutations = permutations;
Pragmatiser = pragmatiser;
RunningOptimalGameOrder = runningOptimalGameOrder;
TimeStartedCalculation = DateTime.Now;
permutationCount = 0;
}
public IEnumerable<PlayList> PragmatisedPermutations()
{
foreach (var gameOrder in Permutations)
{
if (AcceptableSolutionExists())
yield break;
yield return new PlayList(gameOrder);
}
}
bool AcceptableSolutionExists()
{
return
(permutationCount++ % 1000 == 0)
&& Pragmatiser.AcceptableSolution(
DateTime.Now.Subtract(TimeStartedCalculation),
RunningOptimalGameOrder.CurrentMaxOccurencesOfTeamsPlayingConsecutiveMatches);
}
}
}
| mit | C# |
69b6fea587f77429aeb52e26b3bab38fca670afd | make sortSequence nullable | Team-LemonDrop/NBA-Statistics | NBAStatistics.Data.FillMongoDB/Models/Coach.cs | NBAStatistics.Data.FillMongoDB/Models/Coach.cs | using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace NBAStatistics.Data.FillMongoDB.Models
{
public class Coach : IEntity
{
public Coach(
int teamId,
string season,
string coachId,
string firstName,
string lastName,
string coachName,
string coachCode,
int isAssistant,
string coachType,
string school,
int? sortSequence
)
{
this.TeamId = teamId;
this.Season = season;
this.CoachId = coachId;
this.FirstName = firstName;
this.LastName = lastName;
this.CoachName = coachName;
this.CoachCode = coachCode;
this.IsAssistant = isAssistant;
this.CoachType = coachType;
this.School = school;
this.SortSequence = sortSequence;
}
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
[BsonIgnoreIfDefault]
public string Id { get; set; }
[BsonRepresentation(BsonType.Int32)]
public int TeamId { get; private set; }
public string Season { get; private set; }
public string CoachId { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string CoachName { get; private set; }
public string CoachCode { get; private set; }
[BsonRepresentation(BsonType.Int32)]
public int IsAssistant { get; private set; }
public string CoachType { get; private set; }
public string School { get; private set; }
public int? SortSequence { get; private set; }
}
}
| using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace NBAStatistics.Data.FillMongoDB.Models
{
public class Coach : IEntity
{
public Coach(
int teamId,
string season,
string coachId,
string firstName,
string lastName,
string coachName,
string coachCode,
int isAssistant,
string coachType,
string school,
int sortSequence
)
{
this.TeamId = teamId;
this.Season = season;
this.CoachId = coachId;
this.FirstName = firstName;
this.LastName = lastName;
this.CoachName = coachName;
this.CoachCode = coachCode;
this.IsAssistant = isAssistant;
this.CoachType = coachType;
this.School = school;
this.SortSequence = sortSequence;
}
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
[BsonIgnoreIfDefault]
public string Id { get; set; }
[BsonRepresentation(BsonType.Int32)]
public int TeamId { get; private set; }
public string Season { get; private set; }
public string CoachId { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string CoachName { get; private set; }
public string CoachCode { get; private set; }
[BsonRepresentation(BsonType.Int32)]
public int IsAssistant { get; private set; }
public string CoachType { get; private set; }
public string School { get; private set; }
[BsonRepresentation(BsonType.Int32)]
public int SortSequence { get; private set; }
}
}
| mit | C# |
b3bcd1687bc583fe286ccdab22456e4c975db9b9 | Fix SA1518 File may not end with a newline character | Vodurden/Http-Multipart-Data-Parser | Source/HttpMultipartParser/MultipartStreamPart.cs | Source/HttpMultipartParser/MultipartStreamPart.cs | namespace HttpMultipartParser
{
internal class MultipartStreamPart
{
}
} | namespace HttpMultipartParser
{
internal class MultipartStreamPart
{
}
}
| mit | C# |
380f0a9b57148c8ccd863977436916cbea0cef5b | Check for network | AngleSharp/AngleSharp.Scripting,AngleSharp/AngleSharp.Scripting | AngleSharp.Scripting.JavaScript.Tests/PageTests.cs | AngleSharp.Scripting.JavaScript.Tests/PageTests.cs | namespace AngleSharp.Scripting.JavaScript.Tests
{
using AngleSharp.Dom;
using NUnit.Framework;
using System;
using System.Threading.Tasks;
[TestFixture]
public class PageTests
{
static Task<IDocument> LoadPage(String url)
{
var configuration = Configuration.Default.WithJavaScript().WithCss().WithDefaultLoader(setup => setup.IsResourceLoadingEnabled = true);
var context = BrowsingContext.New(configuration);
return context.OpenAsync(url);
}
//[Test]
public async Task RunHtml5Test()
{
if (Helper.IsNetworkAvailable())
{
var target = "http://html5test.com";
var document = await LoadPage(target);
var points = document.QuerySelector("#score > .pointsPanel > h2 > strong").TextContent;
Assert.AreNotEqual("0", points);
}
}
//[Test]
public async Task RunTaobao()
{
if (Helper.IsNetworkAvailable())
{
var target = "https://meadjohnson.world.tmall.com/search.htm?search=y&orderType=defaultSort&scene=taobao_shop";
var document = await LoadPage(target);
var prices = document.QuerySelectorAll("span.c-price");
Assert.AreNotEqual(0, prices.Length);
}
}
}
}
| namespace AngleSharp.Scripting.JavaScript.Tests
{
using NUnit.Framework;
using System.Threading.Tasks;
[TestFixture]
public class PageTests
{
//[Test]
public async Task RunHtml5Test()
{
var target = "http://html5test.com";
var config = Configuration.Default.WithJavaScript().WithCss().WithDefaultLoader(setup => setup.IsResourceLoadingEnabled = true);
var context = BrowsingContext.New(config);
var document = await context.OpenAsync(target);
var points = document.QuerySelector("#score > .pointsPanel > h2 > strong").TextContent;
Assert.AreNotEqual("0", points);
}
//[Test]
public async Task RunTaobao()
{
var target = "https://meadjohnson.world.tmall.com/search.htm?search=y&orderType=defaultSort&scene=taobao_shop";
var config = Configuration.Default.WithJavaScript().WithCss().WithDefaultLoader(setup => setup.IsResourceLoadingEnabled = true);
var context = BrowsingContext.New(config);
var document = await context.OpenAsync(target);
var prices = document.QuerySelectorAll("span.c-price");
Assert.AreNotEqual(0, prices.Length);
}
}
}
| mit | C# |
2f717a36d71ecd447693e227c1751af3e5677c08 | Add Restart to CompositeTask | marcotmp/BehaviorTree | Assets/Scripts/BehaviorTree/Tasks/CompositeTask.cs | Assets/Scripts/BehaviorTree/Tasks/CompositeTask.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CompositeTask : Task {
public List<Task> tasks;
public CompositeTask(string name) : base(name) {
tasks = new List<Task>();
}
public void AddTask(Task task)
{
tasks.Add(task);
}
public override void Restart()
{
foreach (Task task in tasks)
{
task.Restart();
}
base.Restart();
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CompositeTask : Task {
public List<Task> tasks;
public CompositeTask(string name) : base(name) {
tasks = new List<Task>();
}
public void AddTask(Task task)
{
tasks.Add(task);
}
}
| unlicense | C# |
ba9ef473ff32da32b7baa010ff712a39a63c26a9 | fix sample client | DigDes/SoapCore | samples/Client/Program.cs | samples/Client/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Models;
namespace Client
{
public class Program
{
public static void Main(string[] args)
{
Newtonsoft.Json.JsonConvert.DefaultSettings = (() =>
{
var settings = new Newtonsoft.Json.JsonSerializerSettings();
settings.Formatting = Newtonsoft.Json.Formatting.Indented;
settings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = true });
return settings;
});
var binding = new BasicHttpBinding();
// todo: why DataContractSerializer not working?
var endpoint = new EndpointAddress(new Uri(string.Format("http://{0}:5050/Service.svc", Environment.MachineName)));
var channelFactory = new ChannelFactory<ISampleService>(binding, endpoint);
var serviceClient = channelFactory.CreateChannel();
var result = serviceClient.Ping("hey");
Console.WriteLine("Ping method result: {0}", result);
var complexModel = new ComplexModelInput
{
StringProperty = Guid.NewGuid().ToString(),
IntProperty = int.MaxValue / 2,
ListProperty = new List<string> { "test", "list", "of", "strings" },
//DateTimeOffsetProperty = new DateTimeOffset(2018, 12, 31, 13, 59, 59, TimeSpan.FromHours(1))
};
var pingComplexModelResult = serviceClient.PingComplexModel(complexModel);
Console.WriteLine($"{nameof(pingComplexModelResult)}:\n{Newtonsoft.Json.JsonConvert.SerializeObject(pingComplexModelResult)}\n");
serviceClient.EnumMethod(out var enumValue);
Console.WriteLine("Enum method result: {0}", enumValue);
var responseModelRef1 = ComplexModelResponse.CreateSample1();
var responseModelRef2 = ComplexModelResponse.CreateSample2();
var pingComplexModelOutAndRefResult =
serviceClient.PingComplexModelOutAndRef(
ComplexModelInput.CreateSample1(),
ref responseModelRef1,
ComplexObject.CreateSample1(),
ref responseModelRef2,
ComplexObject.CreateSample2(),
out var responseModelOut1,
out var responseModelOut2);
Console.WriteLine($"{nameof(pingComplexModelOutAndRefResult)}: {pingComplexModelOutAndRefResult}\n");
Console.WriteLine($"{nameof(responseModelRef1)}:\n{Newtonsoft.Json.JsonConvert.SerializeObject(responseModelRef1)}\n");
Console.WriteLine($"{nameof(responseModelRef2)}:\n{Newtonsoft.Json.JsonConvert.SerializeObject(responseModelRef2)}\n");
Console.WriteLine($"{nameof(responseModelOut1)}:\n{Newtonsoft.Json.JsonConvert.SerializeObject(responseModelOut1)}\n");
Console.WriteLine($"{nameof(responseModelOut2)}:\n{Newtonsoft.Json.JsonConvert.SerializeObject(responseModelOut2)}\n");
serviceClient.VoidMethod(out var stringValue);
Console.WriteLine("Void method result: {0}", stringValue);
var asyncMethodResult = serviceClient.AsyncMethod().Result;
Console.WriteLine("Async method result: {0}", asyncMethodResult);
Console.ReadKey();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Models;
namespace Client
{
public class Program
{
public static void Main(string[] args)
{
Newtonsoft.Json.JsonConvert.DefaultSettings = (() =>
{
var settings = new Newtonsoft.Json.JsonSerializerSettings();
settings.Formatting = Newtonsoft.Json.Formatting.Indented;
settings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = true });
return settings;
});
var binding = new BasicHttpBinding();
var endpoint = new EndpointAddress(new Uri(string.Format("http://{0}:5050/Service.svc", Environment.MachineName)));
var channelFactory = new ChannelFactory<ISampleService>(binding, endpoint);
var serviceClient = channelFactory.CreateChannel();
var result = serviceClient.Ping("hey");
Console.WriteLine("Ping method result: {0}", result);
var complexModel = new ComplexModelInput
{
StringProperty = Guid.NewGuid().ToString(),
IntProperty = int.MaxValue / 2,
ListProperty = new List<string> { "test", "list", "of", "strings" },
//DateTimeOffsetProperty = new DateTimeOffset(2018, 12, 31, 13, 59, 59, TimeSpan.FromHours(1))
};
var complexResult = serviceClient.PingComplexModel(complexModel);
Console.WriteLine("PingComplexModel result. FloatProperty: {0}, StringProperty: {1}, ListProperty: {2}",
complexResult.FloatProperty, complexResult.StringProperty, string.Join(", ", complexResult.ListProperty));
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(complexResult));
serviceClient.EnumMethod(out var enumValue);
Console.WriteLine("Enum method result: {0}", enumValue);
var responseModelRef = new ComplexModelResponse { };
var pingComplexModelOutAndRefResult =
serviceClient.PingComplexModelOutAndRef(
complexModel,
ref responseModelRef,
new ComplexObject(),
out var responseModelOut,
new ComplexObject());
Console.WriteLine($"{nameof(pingComplexModelOutAndRefResult)}:{pingComplexModelOutAndRefResult}");
Console.WriteLine($"{nameof(responseModelRef)}:");
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(responseModelRef));
Console.WriteLine($"{nameof(responseModelOut)}:");
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(responseModelOut));
serviceClient.VoidMethod(out var stringValue);
Console.WriteLine("Void method result: {0}", stringValue);
var asyncMethodResult = serviceClient.AsyncMethod().Result;
Console.WriteLine("Async method result: {0}", asyncMethodResult);
Console.ReadKey();
}
}
}
| mit | C# |
84c2ffca08546fec91a153d23309f97f643a2075 | change the amount we can randomly walk away from the start price from 10% to 3% | AdaptiveConsulting/ReactiveTrader,mrClapham/ReactiveTrader,jorik041/ReactiveTrader,jorik041/ReactiveTrader,LeeCampbell/ReactiveTrader,akrisiun/ReactiveTrader,HalidCisse/ReactiveTrader,abbasmhd/ReactiveTrader,LeeCampbell/ReactiveTrader,akrisiun/ReactiveTrader,rikoe/ReactiveTrader,HalidCisse/ReactiveTrader,mrClapham/ReactiveTrader,akrisiun/ReactiveTrader,mrClapham/ReactiveTrader,akrisiun/ReactiveTrader,mrClapham/ReactiveTrader,AdaptiveConsulting/ReactiveTrader,LeeCampbell/ReactiveTrader,abbasmhd/ReactiveTrader,jorik041/ReactiveTrader,HalidCisse/ReactiveTrader,jorik041/ReactiveTrader,abbasmhd/ReactiveTrader,LeeCampbell/ReactiveTrader,HalidCisse/ReactiveTrader,abbasmhd/ReactiveTrader,rikoe/ReactiveTrader,rikoe/ReactiveTrader,rikoe/ReactiveTrader | src/Adaptive.ReactiveTrader.Server.Domain/ReferenceData/RandomWalkCurrencyPairInfo.cs | src/Adaptive.ReactiveTrader.Server.Domain/ReferenceData/RandomWalkCurrencyPairInfo.cs | using System;
using System.Diagnostics;
using Adaptive.ReactiveTrader.Shared.DTO.Pricing;
using Adaptive.ReactiveTrader.Shared.DTO.ReferenceData;
namespace Adaptive.ReactiveTrader.Server.ReferenceData
{
public sealed class RandomWalkCurrencyPairInfo : CurrencyPairInfo
{
private static readonly Random Random = new Random();
private readonly int _halfSpread;
public RandomWalkCurrencyPairInfo(CurrencyPairDto currencyPair, decimal sampleRate, bool enabled, string comment)
: base(currencyPair, sampleRate, enabled, comment)
{
_halfSpread = Random.Next(2, 10);
}
public override PriceDto GenerateNextQuote(PriceDto previousPrice)
{
var pow = (decimal)Math.Pow(10, CurrencyPair.RatePrecision);
var newMid = previousPrice.Mid + Random.Next(-5, 5) / pow;
// check that the new mid does not drift too far from sampleRate (3%)
if (Math.Abs(newMid - SampleRate)/SampleRate > .03m)
{
newMid = SampleRate;
}
return new PriceDto
{
Symbol = previousPrice.Symbol,
SpotDate = DateTime.UtcNow.AddDays(2).Date,
Mid = newMid,
Ask = newMid + _halfSpread / pow,
Bid = newMid - _halfSpread / pow,
CreationTimestamp = Stopwatch.GetTimestamp()
};
}
}
} | using System;
using System.Diagnostics;
using Adaptive.ReactiveTrader.Shared.DTO.Pricing;
using Adaptive.ReactiveTrader.Shared.DTO.ReferenceData;
namespace Adaptive.ReactiveTrader.Server.ReferenceData
{
public sealed class RandomWalkCurrencyPairInfo : CurrencyPairInfo
{
private static readonly Random Random = new Random();
private readonly int _halfSpread;
public RandomWalkCurrencyPairInfo(CurrencyPairDto currencyPair, decimal sampleRate, bool enabled, string comment)
: base(currencyPair, sampleRate, enabled, comment)
{
_halfSpread = Random.Next(2, 10);
}
public override PriceDto GenerateNextQuote(PriceDto previousPrice)
{
var pow = (decimal)Math.Pow(10, CurrencyPair.RatePrecision);
var newMid = previousPrice.Mid + Random.Next(-5, 5) / pow;
// check that the new mid does not drift too far from sampleRate (10%)
if (Math.Abs(newMid - SampleRate)/SampleRate > .1m)
{
newMid = SampleRate;
}
return new PriceDto
{
Symbol = previousPrice.Symbol,
SpotDate = DateTime.UtcNow.AddDays(2).Date,
Mid = newMid,
Ask = newMid + _halfSpread / pow,
Bid = newMid - _halfSpread / pow,
CreationTimestamp = Stopwatch.GetTimestamp()
};
}
}
} | apache-2.0 | C# |
8cf4d534563b1831a5b0b016b0ad0763c4ad061b | Refactor `IUIComponentExtensions.WaitForCssTransitionEnd` method | atata-framework/atata-kendoui,atata-framework/atata-kendoui | src/Atata.KendoUI/Extensions/IUIComponentExtensions.cs | src/Atata.KendoUI/Extensions/IUIComponentExtensions.cs | using System;
using OpenQA.Selenium;
namespace Atata.KendoUI
{
internal static class IUIComponentExtensions
{
internal static TOwner WaitForCssTransitionEnd<TOwner>(this IUIComponent<TOwner> component, string transitionName, RetryOptions waitingOptions, SearchOptions searchOptions = null)
where TOwner : PageObject<TOwner>
{
if (waitingOptions?.Timeout > TimeSpan.Zero)
{
component.Context.Log.ExecuteSection(
new LogSection($"Wait for {component.ComponentFullName} \"{transitionName}\" CSS transition completion", LogLevel.Trace),
() =>
{
IWebElement element = searchOptions == null ? component.Scope : component.GetScope(searchOptions);
element?.Try().Until(HasNoCssTransition, waitingOptions);
});
}
return component.Owner;
}
private static bool HasNoCssTransition(IWebElement element)
{
string transitionDuration;
try
{
transitionDuration = element.GetCssValue("transitionDuration");
}
catch (StaleElementReferenceException)
{
return true;
}
return transitionDuration == null
|| !decimal.TryParse(transitionDuration.TrimEnd('m', 's'), out decimal transitionTime)
|| transitionTime == 0;
}
}
}
| using System;
using OpenQA.Selenium;
namespace Atata.KendoUI
{
internal static class IUIComponentExtensions
{
internal static TOwner WaitForCssTransitionEnd<TOwner>(this IUIComponent<TOwner> component, string transitionName, RetryOptions waitingOptions, SearchOptions searchOptions = null)
where TOwner : PageObject<TOwner>
{
if (waitingOptions?.Timeout > TimeSpan.Zero)
{
AtataContext.Current.Log.ExecuteSection(
new LogSection($"Wait for {component.ComponentFullName} \"{transitionName}\" CSS transition completion", LogLevel.Trace),
() =>
{
IWebElement element = searchOptions == null ? component.Scope : component.GetScope(searchOptions);
element?.Try().Until(HasNoCssTransition, waitingOptions);
});
}
return component.Owner;
}
private static bool HasNoCssTransition(IWebElement element)
{
string transitionDuration;
try
{
transitionDuration = element.GetCssValue("transitionDuration");
}
catch (StaleElementReferenceException)
{
return true;
}
return transitionDuration == null
|| !decimal.TryParse(transitionDuration.TrimEnd('m', 's'), out decimal transitionTime)
|| transitionTime == 0;
}
}
}
| apache-2.0 | C# |
970863ecb68a40cf25cfd32dc31e2dec909998ea | Remove CaseState now that it is no longer used. | fixie/fixie | src/Fixie/Internal/Case.cs | src/Fixie/Internal/Case.cs | namespace Fixie.Internal
{
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
/// <summary>
/// A test case being executed, representing a single call to a test method.
/// </summary>
class Case
{
readonly object?[] parameters;
public Case(MethodInfo testMethod, object?[] parameters)
{
this.parameters = parameters;
Test = new Test(testMethod);
Method = testMethod.TryResolveTypeArguments(parameters);
Name = CaseNameBuilder.GetName(Method, parameters);
}
/// <summary>
/// Gets the test for which this case describes a single execution.
/// </summary>
public Test Test { get; }
/// <summary>
/// Gets the input parameters for this single execution of the test.
/// </summary>
public IReadOnlyList<object?> Parameters => parameters;
/// <summary>
/// Gets the name of the test case, including any input parameters.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the method that defines this test case.
/// </summary>
public MethodInfo Method { get; }
public async Task RunAsync(object? instance)
=> await Method.RunTestMethodAsync(instance, parameters);
}
} | namespace Fixie.Internal
{
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
/// <summary>
/// A test case being executed, representing a single call to a test method.
/// </summary>
class Case
{
readonly object?[] parameters;
public Case(MethodInfo testMethod, object?[] parameters)
{
this.parameters = parameters;
Test = new Test(testMethod);
Method = testMethod.TryResolveTypeArguments(parameters);
Name = CaseNameBuilder.GetName(Method, parameters);
}
/// <summary>
/// Gets the test for which this case describes a single execution.
/// </summary>
public Test Test { get; }
/// <summary>
/// Gets the input parameters for this single execution of the test.
/// </summary>
public IReadOnlyList<object?> Parameters => parameters;
/// <summary>
/// Gets the name of the test case, including any input parameters.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the method that defines this test case.
/// </summary>
public MethodInfo Method { get; }
public async Task RunAsync(object? instance)
=> await Method.RunTestMethodAsync(instance, parameters);
}
enum CaseState
{
Skipped,
Passed,
Failed
}
}
| mit | C# |
86307b9f99ccc504dd51d8573ac6690bf4ed5705 | Add support for file uploading #4 - add support for Edge | cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium | Src/MvcPages/SeleniumUtils/FileUploading/Robot.cs | Src/MvcPages/SeleniumUtils/FileUploading/Robot.cs | using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Tellurium.MvcPages.SeleniumUtils.FileUploading.WindowsInternals;
namespace Tellurium.MvcPages.SeleniumUtils.FileUploading
{
internal static class Robot
{
internal static ControlHandle GetUploadWindow(string browserName)
{
var leftTries = 30;
do
{
var uploadWindow = TryGetUploadWindow(browserName);
if (uploadWindow != null)
{
return uploadWindow;
}
Thread.Sleep(1000);
} while (leftTries-- > 0);
throw new FileUploadException("Cannot find upload window");
}
internal static ControlHandle TryGetUploadWindow(string browserName)
{
var processName = GetBrowserProcessName(browserName);
var browserWindow = WindowLocator.GetWindows(processName);
return browserWindow.SelectMany(w => w.GetChildrenWindows()).FirstOrDefault();
}
private static string GetBrowserProcessName(string browserName)
{
switch (browserName)
{
case "Firefox":
return "firefox";
case "Chrome":
return "chrome";
case "InternetExplorer":
return "iexplore";
case "Opera":
return "opera";
case "Edge":
return "MicrosoftEdge";
default:
throw new FileUploadException("Not supported browser");
}
}
}
} | using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Tellurium.MvcPages.SeleniumUtils.FileUploading.WindowsInternals;
namespace Tellurium.MvcPages.SeleniumUtils.FileUploading
{
internal static class Robot
{
internal static ControlHandle GetUploadWindow(string browserName)
{
var leftTries = 30;
do
{
var uploadWindow = TryGetUploadWindow(browserName);
if (uploadWindow != null)
{
return uploadWindow;
}
Thread.Sleep(1000);
} while (leftTries-- > 0);
throw new FileUploadException("Cannot find upload window");
}
internal static ControlHandle TryGetUploadWindow(string browserName)
{
var processName = GetBrowserProcessName(browserName);
var browserWindow = WindowLocator.GetWindows(processName);
return browserWindow.SelectMany(w => w.GetChildrenWindows()).FirstOrDefault();
}
private static string GetBrowserProcessName(string browserName)
{
switch (browserName)
{
case "Firefox":
return "firefox";
case "Chrome":
return "chrome";
case "InternetExplorer":
return "iexplore";
case "Opera":
return "opera";
default:
throw new FileUploadException("Not supported browser");
}
}
}
} | mit | C# |
4fb09adb96bcf44b171a58673272c17eb6dd7ea4 | Comment fixed. | orbital7/orbital7.extensions,orbital7/orbital7.extensions | src/Orbital7.Extensions.WebAPIClient/AccountAPIBase.cs | src/Orbital7.Extensions.WebAPIClient/AccountAPIBase.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
// TODO: This library needs Microsoft.AspNet.WebApi.Client, which isn't yet available in .NET Standard 2.0. See:
//
// https://github.com/aspnet/Mvc/issues/5822
// https://github.com/aspnet/Home/issues/1558
namespace Orbital7.Extensions.WebAPIClient
{
public abstract class AccountAPIBase : AuthenticatedAPIBase
{
public AccountAPIBase(string serviceUri, string authenticationToken)
: base(serviceUri, authenticationToken) { }
public async Task<TokenResponse> GetAuthenticationTokenAsync(string username, string password)
{
// Obtain the response.
Stream jsonResponse = await base.RetrieveJsonPostResponseStreamAsync("Token", new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
}, false);
// Parse the response.
var serializer = new DataContractJsonSerializer(typeof(TokenResponse));
TokenResponse response = serializer.ReadObject(jsonResponse) as TokenResponse;
// Set the authentication token for this service.
this.AuthenticationToken = response.Token;
return response;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
// TODO: This library needs Microsoft.AspNet.WebApi.Client, which isn't yet available in .NET Standard 2.0 Preview 2,
// but is planned for inclusion in Preview 3. See:
//
// https://github.com/aspnet/Mvc/issues/5822
// https://github.com/aspnet/Home/issues/1558
namespace Orbital7.Extensions.WebAPIClient
{
public abstract class AccountAPIBase : AuthenticatedAPIBase
{
public AccountAPIBase(string serviceUri, string authenticationToken)
: base(serviceUri, authenticationToken) { }
public async Task<TokenResponse> GetAuthenticationTokenAsync(string username, string password)
{
// Obtain the response.
Stream jsonResponse = await base.RetrieveJsonPostResponseStreamAsync("Token", new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
}, false);
// Parse the response.
var serializer = new DataContractJsonSerializer(typeof(TokenResponse));
TokenResponse response = serializer.ReadObject(jsonResponse) as TokenResponse;
// Set the authentication token for this service.
this.AuthenticationToken = response.Token;
return response;
}
}
}
| mit | C# |
7d497ac7ae95dbb67fcee82ab2f4da8f5189ec7b | Update /Home/Basic.cshtml | aliencube/ReCaptcha.NET,aliencube/ReCaptcha.NET,aliencube/ReCaptcha.NET | SourceCodes/02_Apps/ReCaptcha.Wrapper.WebApp/Views/Home/Basic.cshtml | SourceCodes/02_Apps/ReCaptcha.Wrapper.WebApp/Views/Home/Basic.cshtml | @using Aliencube.ReCaptcha.Wrapper.Mvc
@using Aliencube.ReCaptcha.Wrapper.Mvc.Parameters
@model Aliencube.ReCaptcha.Wrapper.WebApp.Models.HomeBasicViewModel
@{
ViewBag.Title = "Basic";
}
<h2>@ViewBag.Title</h2>
@if (!IsPost)
{
using (Html.BeginForm(MVC.Home.ActionNames.Basic, MVC.Home.Name, FormMethod.Post))
{
<div class="form-group">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new Dictionary<string, object>() { { "class", "form-control" } })
</div>
@Html.ReCaptcha(new Dictionary<string, object>() { { "class", "form-group" } }, new RenderParameters() { SiteKey = Model.SiteKey })
<input class="btn btn-default" type="submit" name="Submit" />
}
}
else
{
<div>
<ul>
<li>Name: @Model.Name</li>
<li>Success: @Model.Success</li>
@if (@Model.ErrorCodes != null && @Model.ErrorCodes.Any())
{
<li>
ErrorCodes:
<ul>
@foreach (var errorCode in Model.ErrorCodes)
{
<li>@errorCode</li>
}
</ul>
</li>
}
</ul>
</div>
}
@section Scripts
{
@if (!IsPost)
{
@Html.ReCaptchaApiJs(Model.ApiUrl, ApiJsRenderingOptions.Async | ApiJsRenderingOptions.Defer)
}
}
| @using Aliencube.ReCaptcha.Wrapper.Mvc
@using Aliencube.ReCaptcha.Wrapper.Mvc.Parameters
@model Aliencube.ReCaptcha.Wrapper.WebApp.Models.HomeBasicViewModel
@{
ViewBag.Title = "Basic";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm(MVC.Home.ActionNames.Basic, MVC.Home.Name, FormMethod.Post))
{
<div class="form-group">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new Dictionary<string, object>() {{"class", "form-control"}})
</div>
@Html.ReCaptcha(new Dictionary<string, object>() { { "class", "form-group" } }, new RenderParameters() { SiteKey = Model.SiteKey })
<input class="btn btn-default" type="submit" name="Submit" />
}
@if (IsPost)
{
<div>
<ul>
<li>Success: @Model.Success</li>
@if (@Model.ErrorCodes != null && @Model.ErrorCodes.Any())
{
<li>
ErrorCodes:
<ul>
@foreach (var errorCode in Model.ErrorCodes)
{
<li>@errorCode</li>
}
</ul>
</li>
}
<li>ErorCodes: @Model.ErrorCodes</li>
</ul>
</div>
}
@section Scripts
{
@Html.ReCaptchaApiJs(Model.ApiUrl, ApiJsRenderingOptions.Async | ApiJsRenderingOptions.Defer)
}
| mit | C# |
ae4eb8aaf3f6f24f7f9ee8cab847751145b4fc3a | Fix global options for Integration test | aluxnimm/outlookcaldavsynchronizer | CalDavSynchronizer.IntegrationTests/Infrastructure/InMemoryGeneralOptionsDataAccess.cs | CalDavSynchronizer.IntegrationTests/Infrastructure/InMemoryGeneralOptionsDataAccess.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CalDavSynchronizer.Contracts;
using CalDavSynchronizer.DataAccess;
namespace CalDavSynchronizer.IntegrationTests.Infrastructure
{
class InMemoryGeneralOptionsDataAccess : IGeneralOptionsDataAccess
{
private GeneralOptions _options;
public GeneralOptions LoadOptions()
{
return (_options ??
(_options = new GeneralOptions
{
CalDavConnectTimeout = TimeSpan.FromSeconds(10),
MaxReportAgeInDays = 100,
QueryFoldersJustByGetTable = true,
CultureName = System.Threading.Thread.CurrentThread.CurrentUICulture.Name,
EnableTls12 = true
}))
.Clone();
}
public void SaveOptions(GeneralOptions options)
{
_options = options.Clone();
}
public Version IgnoreUpdatesTilVersion { get; set; }
public int EntityCacheVersion
{
get { return ComponentContainerTestExtension.GetRequiredEntityCacheVersion(); }
set { }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CalDavSynchronizer.Contracts;
using CalDavSynchronizer.DataAccess;
namespace CalDavSynchronizer.IntegrationTests.Infrastructure
{
class InMemoryGeneralOptionsDataAccess : IGeneralOptionsDataAccess
{
private GeneralOptions _options;
public GeneralOptions LoadOptions()
{
return (_options ??
(_options = new GeneralOptions
{
CalDavConnectTimeout = TimeSpan.FromSeconds(10),
MaxReportAgeInDays = 100,
QueryFoldersJustByGetTable = true,
CultureName = System.Threading.Thread.CurrentThread.CurrentUICulture.Name
}))
.Clone();
}
public void SaveOptions(GeneralOptions options)
{
_options = options.Clone();
}
public Version IgnoreUpdatesTilVersion { get; set; }
public int EntityCacheVersion
{
get { return ComponentContainerTestExtension.GetRequiredEntityCacheVersion(); }
set { }
}
}
}
| agpl-3.0 | C# |
bd4b2f4192382d211fe61608252ab739c770e447 | load multiple factories | jefking/King.Service | Demos/King.Service.CloudService.Role/WorkerRole.cs | Demos/King.Service.CloudService.Role/WorkerRole.cs | namespace King.Service.CloudService.Role
{
using Microsoft.WindowsAzure.ServiceRuntime;
public class WorkerRole : RoleEntryPoint
{
/// <summary>
/// Role Service Manager
/// </summary>
private readonly IRoleTaskManager<Configuration> manager = new RoleTaskManager<Configuration>(new ITaskFactory<Configuration>[] { new Factory(), new DataGenerationFactory() });
/// <summary>
/// Overloaded Role Entry Point Method
/// </summary>
public override void Run()
{
this.manager.Run();
base.Run();
}
/// <summary>
/// Overloaded Role Entry Point Method
/// </summary>
public override bool OnStart()
{
var config = new Configuration()
{
ConnectionString = "UseDevelopmentStorage=true;",
TableName = "table",
GenericQueueName = "queue",
ContainerName = "container",
FastQueueName = "fast",
ModerateQueueName = "moderate",
SlowQueueName = "slow",
};
return this.manager.OnStart(config);
}
/// <summary>
/// Overloaded Role Entry Point Method
/// </summary>
public override void OnStop()
{
this.manager.OnStop();
base.OnStop();
}
}
}
| namespace King.Service.CloudService.Role
{
using Microsoft.WindowsAzure.ServiceRuntime;
public class WorkerRole : RoleEntryPoint
{
/// <summary>
/// Role Service Manager
/// </summary>
private readonly IRoleTaskManager<Configuration> manager = new RoleTaskManager<Configuration>(new Factory());
/// <summary>
/// Overloaded Role Entry Point Method
/// </summary>
public override void Run()
{
this.manager.Run();
base.Run();
}
/// <summary>
/// Overloaded Role Entry Point Method
/// </summary>
public override bool OnStart()
{
var config = new Configuration()
{
ConnectionString = "UseDevelopmentStorage=true;",
TableName = "table",
GenericQueueName = "queue",
ContainerName = "container",
FastQueueName = "fast",
ModerateQueueName = "moderate",
SlowQueueName = "slow",
};
return this.manager.OnStart(config);
}
/// <summary>
/// Overloaded Role Entry Point Method
/// </summary>
public override void OnStop()
{
this.manager.OnStop();
base.OnStop();
}
}
}
| mit | C# |
e6eac428542c7f7490482ef44c7a79fff2753e76 | Update AdUnitSelector.cs | tiksn/TIKSN-Framework | TIKSN.Framework.UWP/Advertising/AdUnitSelector.cs | TIKSN.Framework.UWP/Advertising/AdUnitSelector.cs | using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Diagnostics;
namespace TIKSN.Advertising
{
public class AdUnitSelector : IAdUnitSelector
{
private readonly ILogger<AdUnitSelector> _logger;
private readonly IOptions<AdUnitSelectorOptions> _options;
public AdUnitSelector(IOptions<AdUnitSelectorOptions> options, ILogger<AdUnitSelector> logger)
{
_options = options;
_logger = logger;
}
public AdUnit Select(AdUnitBundle adUnitBundle)
{
if (_options.Value.IsDebug || _options.Value.IsDebuggerSensitive && Debugger.IsAttached)
{
return adUnitBundle.DesignTime;
}
return adUnitBundle.Production;
}
}
} | using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Diagnostics;
namespace TIKSN.Advertising
{
public class AdUnitSelector : IAdUnitSelector
{
private readonly ILogger<AdUnitSelector> _logger;
private readonly IOptions<AdUnitSelectorOptions> _options;
public AdUnitSelector(IOptions<AdUnitSelectorOptions> options, ILogger<AdUnitSelector> logger)
{
_options = options;
_logger = logger;
}
public AdUnit Select(AdUnitBundle adUnitBundle)
{
if (_options.Value.IsDebuggerSensitive && Debugger.IsAttached)
{
return adUnitBundle.DesignTime;
}
return adUnitBundle.Production;
}
}
} | mit | C# |
549ddee4ace6003202d4818e2fb1a6364ce18505 | Update Mobile.cs | jkanchelov/Telerik-OOP-Team-StarFruit | TeamworkStarFruit/CatalogueLib/Products/Mobile.cs | TeamworkStarFruit/CatalogueLib/Products/Mobile.cs | namespace CatalogueLib
{
using CatalogueLib.Products.Enumerations;
using CatalogueLib.Products.Struct;
using System.Text;
public abstract class Mobile : Product
{
public Mobile()
{
}
public Mobile(int ID, decimal price, bool isAvailable, Brand brand, int Memory, string CPU, int RAM, string Model, string battery, string connectivity, bool ExpandableMemory, double ScreenSize)
: base(ID, price, isAvailable, brand)
{
this.Memory = Memory;
this.CPU = CPU;
this.RAM = RAM;
this.Model = Model;
this.battery = battery;
this.Connectivity = Connectivity;
this.ExpandableMemory = ExpandableMemory;
this.ScreenSize = ScreenSize;
}
public int Memory { get; private set; }
public string CPU { get; private set; }
public int RAM { get; private set; }
public string Model { get; private set; }
public string battery { get; private set; }
public string Connectivity { get; private set; }
public bool ExpandableMemory { get; private set; }
public double ScreenSize { get; private set; }
public override string ToString()
{StringBuilder outline = new StringBuilder();
outline = outline.Append(string.Format("{0}", base.ToString()));
outline = outline.Append(string.Format(" Model: {0}",this.Model));
outline = outline.AppendLine();
outline = outline.Append(string.Format(" Screen size: {0}",this.ScreenSize));
outline = outline.AppendLine();
outline = outline.Append(string.Format(" Memory: {0}",this.Memory));
outline = outline.AppendLine();
outline = outline.Append(string.Format(" CPU: {0}",this.CPU));
outline = outline.AppendLine();
outline = outline.Append(string.Format(" RAM: {0}",this.RAM));
outline = outline.AppendLine();
outline = outline.Append(string.Format(" Expandable memory: {0}",this.Memory));
outline = outline.AppendLine();
outline = outline.Append(string.Format(" Battery: {0}",this.battery));
return outline.AppendLine().ToString();
}
}
}
| namespace CatalogueLib
{
using CatalogueLib.Products.Enumerations;
using CatalogueLib.Products.Struct;
using System.Text;
public abstract class Mobile : Product
{
public Mobile()
{
}
public Mobile(int ID, decimal price, bool isAvailable, Brand brand, int Memory, string CPU, int RAM, string Model, string battery, string connectivity, bool ExpandableMemory, double ScreenSize)
: base(ID, price, isAvailable, brand)
{
this.Memory = Memory;
this.CPU = CPU;
this.RAM = RAM;
this.Model = Model;
this.battery = battery;
this.Connectivity = Connectivity;
this.ExpandableMemory = ExpandableMemory;
this.ScreenSize = ScreenSize;
}
public int Memory { get; private set; }
public string CPU { get; private set; }
public int RAM { get; private set; }
public string Model { get; private set; }
public string battery { get; private set; }
public string Connectivity { get; private set; }
public bool ExpandableMemory { get; private set; }
public double ScreenSize { get; private set; }
public override string ToString()
{
StringBuilder stroitel = new StringBuilder();
stroitel = stroitel.Append(string.Format("{0}", base.ToString()));
stroitel = stroitel.Append(string.Format(" Model: {0}\n Screen size: {1}\n Memory: {2}\n CPU: {3}\n RAM: {4}\n Expandable memory: {5}\n Battery: {6}",this.Model,this.ScreenSize,this.Memory,this.CPU,this.RAM, this.ExpandableMemory,this.battery));
return stroitel.AppendLine().ToString();
}
}
}
| mit | C# |
81e4d59b4017f9d1da38514557824466a71fc78c | return request scope values | beginor/owin-samples | Owin04_OAuthResource/Controllers/UserController.cs | Owin04_OAuthResource/Controllers/UserController.cs | using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web.Http;
namespace Owin04_OAuthResource.Controllers {
[Authorize]
public class UserController : ApiController {
public object Get() {
var identity = User.Identity as ClaimsIdentity;
var infos = identity.Claims.Where(claim => claim.Type == "urn:oauth:scope")
.Select(claim => claim.Value)
.ToDictionary(s => s, s => s + " value is xxx.");
return new { name = identity.Name, infos };
}
}
} | using System.Web.Http;
namespace Owin04_OAuthResource.Controllers {
[Authorize]
public class UserController : ApiController {
public string Get() {
return User.Identity.Name;
}
}
} | mit | C# |
5f24d4350aa512d7d436ad5fa858292ee1d8c4ea | mark ModuleRoot as tag class | invisibledrygoods/RequireUnity | RequireUnity/Assets/Scripts/ModuleRoot.cs | RequireUnity/Assets/Scripts/ModuleRoot.cs | using UnityEngine;
public class ModuleRoot : MonoBehaviour
{
// tag class
}
| using UnityEngine;
public class ModuleRoot : MonoBehaviour
{
}
| bsd-2-clause | C# |
63b7730f1021eb613c81202ed5b9d7ecf4046ae3 | use correct name for game mode in logs | fomalsd/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation | UnityProject/Assets/Scripts/GameModes/Cargonia.cs | UnityProject/Assets/Scripts/GameModes/Cargonia.cs | using UnityEngine;
using Antagonists;
using System.Collections;
using System.Collections.Generic;
using System;
[CreateAssetMenu(menuName="ScriptableObjects/GameModes/Cargonia")]
public class Cargonia : GameMode
{
/// <summary>
/// Set up the station for the game mode
/// </summary>
private List<JobType> RebelJob;
public override void SetupRound()
{
Logger.Log("Setting up Rebel round!", Category.GameMode);
//Select a random department
var rnd = new System.Random();
var RebelDep = (Departments) rnd.Next(Enum.GetNames(typeof(Departments)).Length);
RebelJob = RebelJobs[RebelDep];
GameManager.Instance.Rebels = RebelJob;
}
/// <summary>
/// Begin the round
/// </summary>
public override void StartRound()
{
Logger.Log("Starting Rebel round!", Category.GameMode);
base.StartRound();
}
// /// <summary>
// /// Check if the round should end yet
// /// </summary>
// public override void CheckEndCondition()
// {
// Logger.Log("Check end round conditions!", Category.GameMode);
// }
// /// <summary>
// /// End the round and display any relevant reports
// /// </summary>
// public override void EndRound()
// {
// }
// TODO switch this for the Department ScriptableObjects
private enum Departments
{
Engineering,
Science,
Medical,
Service,
Supply
}
private readonly Dictionary<Departments, List<JobType>> RebelJobs = new Dictionary<Departments, List<JobType>>() {
{Departments.Engineering,
new List<JobType>{JobType.CHIEF_ENGINEER, JobType.ENGINEER, JobType.ATMOSTECH}},
{Departments.Science,
new List<JobType>{JobType.RD, JobType.GENETICIST, JobType.SCIENTIST, JobType.ROBOTICIST}},
{Departments.Medical,
new List<JobType>{JobType.CMO, JobType.DOCTOR, JobType.CHEMIST, JobType.VIROLOGIST}},
{Departments.Service,
new List<JobType>{JobType.CLOWN, JobType.JANITOR, JobType.BARTENDER, JobType.COOK, JobType.BOTANIST, JobType.MIME, JobType.CHAPLAIN, JobType.CURATOR}},
{Departments.Supply,
new List<JobType>{JobType.QUARTERMASTER, JobType.CARGOTECH, JobType.MINER}}
};
protected override bool ShouldSpawnAntag(PlayerSpawnRequest spawnRequest)
{
return RebelJob.Contains(spawnRequest.RequestedOccupation.JobType);
}
} | using UnityEngine;
using Antagonists;
using System.Collections;
using System.Collections.Generic;
using System;
[CreateAssetMenu(menuName="ScriptableObjects/GameModes/Cargonia")]
public class Cargonia : GameMode
{
/// <summary>
/// Set up the station for the game mode
/// </summary>
private List<JobType> RebelJob;
public override void SetupRound()
{
Logger.Log("Setting up traitor round!", Category.GameMode);
//Select a random department
var rnd = new System.Random();
var RebelDep = (Departments) rnd.Next(Enum.GetNames(typeof(Departments)).Length);
RebelJob = RebelJobs[RebelDep];
GameManager.Instance.Rebels = RebelJob;
}
/// <summary>
/// Begin the round
/// </summary>
public override void StartRound()
{
Logger.Log("Starting traitor round!", Category.GameMode);
base.StartRound();
}
// /// <summary>
// /// Check if the round should end yet
// /// </summary>
// public override void CheckEndCondition()
// {
// Logger.Log("Check end round conditions!", Category.GameMode);
// }
// /// <summary>
// /// End the round and display any relevant reports
// /// </summary>
// public override void EndRound()
// {
// }
private enum Departments
{
Engineering,
Science,
Medical,
Service,
Supply
}
private readonly Dictionary<Departments, List<JobType>> RebelJobs = new Dictionary<Departments, List<JobType>>() {
{Departments.Engineering,
new List<JobType>{JobType.CHIEF_ENGINEER, JobType.ENGINEER, JobType.ATMOSTECH}},
{Departments.Science,
new List<JobType>{JobType.RD, JobType.GENETICIST, JobType.SCIENTIST, JobType.ROBOTICIST}},
{Departments.Medical,
new List<JobType>{JobType.CMO, JobType.DOCTOR, JobType.CHEMIST, JobType.VIROLOGIST}},
{Departments.Service,
new List<JobType>{JobType.CLOWN, JobType.JANITOR, JobType.BARTENDER, JobType.COOK, JobType.BOTANIST, JobType.MIME, JobType.CHAPLAIN, JobType.CURATOR}},
{Departments.Supply,
new List<JobType>{JobType.QUARTERMASTER, JobType.CARGOTECH, JobType.MINER}}
};
protected override bool ShouldSpawnAntag(PlayerSpawnRequest spawnRequest)
{
return RebelJob.Contains(spawnRequest.RequestedOccupation.JobType);
}
} | agpl-3.0 | C# |
0b947ecf2494a5e3f2dbd0a9d4c52224cf294928 | Add sanity test for 600 (DC) and 700 (DCC). | pvasys/PillarRomanNumeralKata | VasysRomanNumeralsKataTest/ToRomanNumeralsTest.cs | VasysRomanNumeralsKataTest/ToRomanNumeralsTest.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VasysRomanNumeralsKata;
namespace VasysRomanNumeralsKataTest
{
[TestClass]
public class ToRomanNumeralsTest
{
[TestMethod]
public void WhenRomanNumeralExtensionIsPassedTenItReturnsX()
{
int ten = 10;
Assert.IsTrue(ten.ToRomanNumeral() == "X");
}
[TestMethod]
public void WhenRomanNumeralExtensionIsPassedNumbersDivisibleByOneHundredItReturnsARomanNumeral()
{
int oneThousand = 1000;
Assert.IsTrue(oneThousand.ToRomanNumeral() == "M");
int nineHundred = 900;
Assert.IsTrue(nineHundred.ToRomanNumeral() == "CM");
int fiveHundred = 500;
Assert.IsTrue(fiveHundred.ToRomanNumeral() == "D");
int fourHundred = 400;
Assert.IsTrue(fourHundred.ToRomanNumeral() == "CD");
int oneHundred = 100;
Assert.IsTrue(oneHundred.ToRomanNumeral() == "C");
int twoHundred = 200;
Assert.IsTrue(twoHundred.ToRomanNumeral() == "CC");
int threeHundred = 300;
Assert.IsTrue(threeHundred.ToRomanNumeral() == "CCC");
int twoThousand = 2000;
Assert.IsTrue(twoThousand.ToRomanNumeral() == "MM");
int sixHundred = 600;
Assert.IsTrue(sixHundred.ToRomanNumeral() == "DC");
int sevenHundred = 700;
Assert.IsTrue(sevenHundred.ToRomanNumeral() == "DCC");
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VasysRomanNumeralsKata;
namespace VasysRomanNumeralsKataTest
{
[TestClass]
public class ToRomanNumeralsTest
{
[TestMethod]
public void WhenRomanNumeralExtensionIsPassedTenItReturnsX()
{
int ten = 10;
Assert.IsTrue(ten.ToRomanNumeral() == "X");
}
[TestMethod]
public void WhenRomanNumeralExtensionIsPassedNumbersDivisibleByOneHundredItReturnsARomanNumeral()
{
int oneThousand = 1000;
Assert.IsTrue(oneThousand.ToRomanNumeral() == "M");
int nineHundred = 900;
Assert.IsTrue(nineHundred.ToRomanNumeral() == "CM");
int fiveHundred = 500;
Assert.IsTrue(fiveHundred.ToRomanNumeral() == "D");
int fourHundred = 400;
Assert.IsTrue(fourHundred.ToRomanNumeral() == "CD");
int oneHundred = 100;
Assert.IsTrue(oneHundred.ToRomanNumeral() == "C");
int twoHundred = 200;
Assert.IsTrue(twoHundred.ToRomanNumeral() == "CC");
int threeHundred = 300;
Assert.IsTrue(threeHundred.ToRomanNumeral() == "CCC");
int twoThousand = 2000;
Assert.IsTrue(twoThousand.ToRomanNumeral() == "MM");
}
}
}
| mit | C# |
7be05dc96b23377a17fb1228e208a418427c17c7 | add graphite to samples | Recognos/Metrics.NET,cvent/Metrics.NET,huoxudong125/Metrics.NET,Liwoj/Metrics.NET,ntent-ad/Metrics.NET,mnadel/Metrics.NET,etishor/Metrics.NET,DeonHeyns/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,huoxudong125/Metrics.NET,alhardy/Metrics.NET,cvent/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,mnadel/Metrics.NET,Liwoj/Metrics.NET,ntent-ad/Metrics.NET,MetaG8/Metrics.NET,etishor/Metrics.NET,alhardy/Metrics.NET | Samples/Metrics.SamplesConsole/Program.cs | Samples/Metrics.SamplesConsole/Program.cs | using System;
using Metrics.Samples;
using Metrics.Utils;
namespace Metrics.SamplesConsole
{
class Program
{
static void Main(string[] args)
{
//Metric.CompletelyDisableMetrics();
Metric.Config
.WithHttpEndpoint("http://localhost:1234/metrics/")
.WithAllCounters()
.WithInternalMetrics()
.WithReporting(config => config
.WithConsoleReport(TimeSpan.FromSeconds(30))
//.WithCSVReports(@"c:\temp\reports\", TimeSpan.FromSeconds(10))
//.WithTextFileReport(@"C:\temp\reports\metrics.txt", TimeSpan.FromSeconds(10))
//.WithGraphite(new Uri("net.udp://localhost:2003"), TimeSpan.FromSeconds(1))
);
using (var scheduler = new ActionScheduler())
{
SampleMetrics.RunSomeRequests();
scheduler.Start(TimeSpan.FromMilliseconds(500), () =>
{
SetCounterSample.RunSomeRequests();
SetMeterSample.RunSomeRequests();
UserValueHistogramSample.RunSomeRequests();
UserValueTimerSample.RunSomeRequests();
SampleMetrics.RunSomeRequests();
});
Metric.Gauge("Errors", () => 1, Unit.None);
Metric.Gauge("% Percent/Gauge|test", () => 1, Unit.None);
Metric.Gauge("& AmpGauge", () => 1, Unit.None);
Metric.Gauge("()[]{} ParantesisGauge", () => 1, Unit.None);
Metric.Gauge("Gauge With No Value", () => double.NaN, Unit.None);
//Metric.Gauge("Gauge Resulting in division by zero", () => 5 / 0.0, Unit.None);
////Metrics.Samples.FSharp.SampleMetrics.RunSomeRequests();
HealthChecksSample.RegisterHealthChecks();
//Metrics.Samples.FSharp.HealthChecksSample.RegisterHealthChecks();
Console.WriteLine("done setting things up");
Console.ReadKey();
}
}
}
}
| using System;
using Metrics.Samples;
using Metrics.Utils;
namespace Metrics.SamplesConsole
{
class Program
{
static void Main(string[] args)
{
//Metric.CompletelyDisableMetrics();
Metric.Config
.WithHttpEndpoint("http://localhost:1234/metrics/")
.WithAllCounters()
.WithInternalMetrics()
.WithReporting(config => config
.WithConsoleReport(TimeSpan.FromSeconds(30))
//.WithCSVReports(@"c:\temp\reports\", TimeSpan.FromSeconds(10))
//.WithTextFileReport(@"C:\temp\reports\metrics.txt", TimeSpan.FromSeconds(10))
);
using (var scheduler = new ActionScheduler())
{
SampleMetrics.RunSomeRequests();
scheduler.Start(TimeSpan.FromMilliseconds(500), () =>
{
SetCounterSample.RunSomeRequests();
SetMeterSample.RunSomeRequests();
UserValueHistogramSample.RunSomeRequests();
UserValueTimerSample.RunSomeRequests();
SampleMetrics.RunSomeRequests();
});
Metric.Gauge("Gauge With No Value", () => double.NaN, Unit.None);
Metric.Gauge("Gauge Resulting in division by zero", () => 5 / 0.0, Unit.None);
////Metrics.Samples.FSharp.SampleMetrics.RunSomeRequests();
HealthChecksSample.RegisterHealthChecks();
//Metrics.Samples.FSharp.HealthChecksSample.RegisterHealthChecks();
Console.WriteLine("done setting things up");
Console.ReadKey();
}
}
}
}
| apache-2.0 | C# |
accaa3edc5dcb88e0e9b09131f59489dd1a65350 | Bump System.Contrib version | Smartrak/Smartrak.Library | System.Contrib/Properties/AssemblyInfo.cs | System.Contrib/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("System.Contrib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Smartrak")]
[assembly: AssemblyProduct("System.Contrib")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ac97934a-bbbc-488b-b337-a11bf4c98e97")]
// 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.9.1")]
[assembly: AssemblyFileVersion("1.9.1")]
[assembly: AssemblyInformationalVersion("1.9.1")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("System.Contrib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Smartrak")]
[assembly: AssemblyProduct("System.Contrib")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ac97934a-bbbc-488b-b337-a11bf4c98e97")]
// 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.8.1")]
[assembly: AssemblyFileVersion("1.8.1")]
[assembly: AssemblyInformationalVersion("1.8.1")]
| mit | C# |
988d3627f811c400e9536492f1dbff3ada55939d | Fix inventory trying to update on every frame | Bering/TetriNET-RL | Assets/Scripts/Inventory.cs | Assets/Scripts/Inventory.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Events;
public class Inventory : MonoBehaviour {
public int[] inventorySlots;
public UnityEvent InventoryChangedEvent;
protected bool isDirty;
void Awake()
{
inventorySlots = new int[18];
}
void Start()
{
for (int i = 0; i < inventorySlots.Length; i++) {
inventorySlots[i]= Random.Range (PlayArea.normalBlocksCount+1, PlayArea.totalBlocksCount); // +1 because of the empty block
}
isDirty = true;
}
void Update()
{
if (isDirty) {
InventoryChangedEvent.Invoke ();
isDirty = false;
}
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Events;
public class Inventory : MonoBehaviour {
public int[] inventorySlots;
public UnityEvent InventoryChangedEvent;
void Awake()
{
inventorySlots = new int[18];
}
void Start()
{
for (int i = 0; i < inventorySlots.Length; i++) {
inventorySlots[i]= Random.Range (PlayArea.normalBlocksCount+1, PlayArea.totalBlocksCount); // +1 because of the empty block
}
InventoryChangedEvent.Invoke ();
}
}
| mit | C# |
9126edca7003c698f4f8a60e0ee10cd5c54605ec | Add documentation | SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,grokys/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia | src/Avalonia.Base/Metadata/TemplateDataTypeAttribute.cs | src/Avalonia.Base/Metadata/TemplateDataTypeAttribute.cs | using System;
namespace Avalonia.Metadata;
/// <summary>
/// Defines the property that contains type of the data passed to the <see cref="IDataTemplate"/> implementation.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class TemplateDataTypeAttribute : Attribute
{
}
| using System;
namespace Avalonia.Metadata;
[AttributeUsage(AttributeTargets.Property)]
public class TemplateDataTypeAttribute : Attribute
{
}
| mit | C# |
767ecb4422e9cdef40551d4c9b9aa56805080f63 | Fix rank status | smoogipoo/osu,UselessToucan/osu,naoey/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,EVAST9919/osu,DrabWeb/osu,Nabile-Rahmani/osu,johnneijzen/osu,peppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,naoey/osu,peppy/osu-new,johnneijzen/osu,ZLima12/osu,EVAST9919/osu,peppy/osu,2yangk23/osu,ZLima12/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,naoey/osu,DrabWeb/osu,DrabWeb/osu,peppy/osu | osu.Game/Beatmaps/RankStatus.cs | osu.Game/Beatmaps/RankStatus.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
namespace osu.Game.Beatmaps
{
public enum RankStatus
{
Any = 7,
[Description("Ranked & Approved")]
RankedApproved = 0,
Approved = 1,
Loved = 8,
Favourites = 2,
Qualified = 3,
Pending = 4,
Graveyard = 5,
[Description("My Maps")]
MyMaps = 6,
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
namespace osu.Game.Beatmaps
{
public enum RankStatus
{
Any = 7,
[Description("Ranked & Approved")]
RankedApproved = 0,
Approved = 1,
Loved = 8,
Favourites = 2,
[Description("Mod Requests")]
ModRequests = 3,
Pending = 4,
Graveyard = 5,
[Description("My Maps")]
MyMaps = 6,
}
}
| mit | C# |
32f34182a763a12234e1fa06b58239e07524f122 | Add documentation | rickyah/ini-parser,rickyah/ini-parser,davidgrupp/ini-parser | src/IniFileParser/Model/Formatting/IIniDataFormatter.cs | src/IniFileParser/Model/Formatting/IIniDataFormatter.cs | using IniParser.Model.Configuration;
namespace IniParser.Model.Formatting
{
/// <summary>
/// Formats a IniData structure to an string
/// </summary>
public interface IIniDataFormatter
{
/// <summary>
/// Produces an string given
/// </summary>
/// <returns>The data to string.</returns>
/// <param name="iniData">Ini data.</param>
string IniDataToString(IniData iniData);
/// <summary>
/// Configuration used by this formatter when converting IniData
/// to an string
/// </summary>
IIniParserConfiguration Configuration {get;set;}
}
} | using IniParser.Model.Configuration;
namespace IniParser.Model.Formatting
{
/// <summary>
/// Formats a IniData structure to an string
/// </summary>
public interface IIniDataFormatter
{
/// <summary>
/// Produces an string given
/// </summary>
/// <returns>The data to string.</returns>
/// <param name="iniData">Ini data.</param>
string IniDataToString(IniData iniData);
IIniParserConfiguration Configuration {get;set;}
}
} | mit | C# |
cb4b17504e1e2e807023563698bcb9ed9b40e566 | Remove `[SuppressMessage]` - build break | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.StaticFiles/DefaultFilesOptions.cs | src/Microsoft.AspNet.StaticFiles/DefaultFilesOptions.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.AspNet.StaticFiles.Infrastructure;
namespace Microsoft.AspNet.StaticFiles
{
/// <summary>
/// Options for selecting default file names.
/// </summary>
public class DefaultFilesOptions : SharedOptionsBase<DefaultFilesOptions>
{
/// <summary>
/// Configuration for the DefaultFilesMiddleware.
/// </summary>
public DefaultFilesOptions()
: this(new SharedOptions())
{
}
/// <summary>
/// Configuration for the DefaultFilesMiddleware.
/// </summary>
/// <param name="sharedOptions"></param>
public DefaultFilesOptions(SharedOptions sharedOptions)
: base(sharedOptions)
{
// Prioritized list
DefaultFileNames = new List<string>()
{
"default.htm",
"default.html",
"index.htm",
"index.html",
};
}
/// <summary>
/// An ordered list of file names to select by default. List length and ordering may affect performance.
/// </summary>
public IList<string> DefaultFileNames { get; set; }
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNet.StaticFiles.Infrastructure;
namespace Microsoft.AspNet.StaticFiles
{
/// <summary>
/// Options for selecting default file names.
/// </summary>
public class DefaultFilesOptions : SharedOptionsBase<DefaultFilesOptions>
{
/// <summary>
/// Configuration for the DefaultFilesMiddleware.
/// </summary>
public DefaultFilesOptions()
: this(new SharedOptions())
{
}
/// <summary>
/// Configuration for the DefaultFilesMiddleware.
/// </summary>
/// <param name="sharedOptions"></param>
public DefaultFilesOptions(SharedOptions sharedOptions)
: base(sharedOptions)
{
// Prioritized list
DefaultFileNames = new List<string>()
{
"default.htm",
"default.html",
"index.htm",
"index.html",
};
}
/// <summary>
/// An ordered list of file names to select by default. List length and ordering may affect performance.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Improves usability")]
public IList<string> DefaultFileNames { get; set; }
}
}
| apache-2.0 | C# |
f435f859b7ed8adc536c61452ffa665dda7f14f8 | Remove struct constraint from Box | sharper-library/Sharper.C.Box | Sharper.C.Box/Box.cs | Sharper.C.Box/Box.cs | namespace Sharper.C.Data
{
public sealed class Box<A>
{
internal Box(A a)
{
Unbox = a;
}
public A Unbox { get; }
public bool Equals(Box<A> ba)
=> ReferenceEquals(this, ba) || Unbox.Equals(ba.Unbox);
public override bool Equals(object o)
=> !ReferenceEquals(null, o)
&& o is Box<A>
&& Equals((Box<A>) o);
public override int GetHashCode()
{
return Unbox.GetHashCode();
}
public override string ToString() => $"{nameof(Box<A>)}({Unbox})";
}
public static class Box
{
public static Box<A> Mk<A>(A a)
=> new Box<A>(a);
}
}
| namespace Sharper.C.Data
{
public sealed class Box<A>
{
internal Box(A a)
{
Unbox = a;
}
public A Unbox { get; }
public bool Equals(Box<A> ba)
=> ReferenceEquals(this, ba) || Unbox.Equals(ba.Unbox);
public override bool Equals(object o)
=> !ReferenceEquals(null, o)
&& o is Box<A>
&& Equals((Box<A>) o);
public override int GetHashCode()
{
return Unbox.GetHashCode();
}
public override string ToString() => $"{nameof(Box<A>)}({Unbox})";
}
public static class Box
{
public static Box<A> Mk<A>(A a)
where A : struct
=> new Box<A>(a);
}
}
| mit | C# |
5faa54a14dabd7e5e8a6737469753da3dc8145d3 | add XML doc | OlegKleyman/Omego.Extensions | core/Omego.Extensions/NullExtensions/SmartCheck.cs | core/Omego.Extensions/NullExtensions/SmartCheck.cs | namespace Omego.Extensions.NullExtensions
{
using System;
using System.Linq.Expressions;
using Omego.Extensions.Poco;
public static partial class ObjectExtensions
{
/// <summary>
/// Throws an exception if part of any of the <paramref name="qualifierPath" /> is null.
/// </summary>
/// <typeparam name="TTarget">The type check qualifying path on.</typeparam>
/// <param name="target">The target object or value to check qualifying path on.</param>
/// <param name="exception">
/// The exception to throw when the qualifying path contains null.
/// </param>
/// <param name="qualifierPath">The qualifying elements path to check.</param>
/// <exception cref="ArgumentNullException">
/// Occurs when <paramref name="exception" /> or <paramref name="qualifierPath" /> is null.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Occurs when <paramref name="exception" /> returns null.
/// </exception>
public static void SmartCheck<TTarget>(
this TTarget target,
Func<string, Exception> exception,
params Expression<Func<TTarget, object>>[] qualifierPath)
{
if (qualifierPath == null) throw new ArgumentNullException(nameof(qualifierPath));
var visitor = new SmartGetVisitor(target);
foreach (var expression in qualifierPath)
{
visitor.OnNull(
expression,
s =>
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
var toThrow = exception(s);
if (toThrow == null) throw new InvalidOperationException("Exception to throw returned null.");
throw toThrow;
});
visitor.ResetWith(target);
}
}
}
} | namespace Omego.Extensions.NullExtensions
{
using System;
using System.Linq.Expressions;
using Omego.Extensions.Poco;
public static partial class ObjectExtensions
{
public static void SmartCheck<TTarget>(
this TTarget target,
Func<string, Exception> exception,
params Expression<Func<TTarget, object>>[] qualifierPath)
{
if (qualifierPath == null) throw new ArgumentNullException(nameof(qualifierPath));
var visitor = new SmartGetVisitor(target);
foreach (var expression in qualifierPath)
{
visitor.OnNull(
expression,
s =>
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
var toThrow = exception(s);
if (toThrow == null) throw new InvalidOperationException("Exception to throw returned null.");
throw toThrow;
});
visitor.ResetWith(target);
}
}
}
} | unlicense | C# |
a9b0eb0ac2447ab49319aabf798e943aa980f292 | fix external assets path in tests | reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap | unity/library/UtyMap.Unity.Tests/Helpers/TestHelper.cs | unity/library/UtyMap.Unity.Tests/Helpers/TestHelper.cs | using System;
using UtyMap.Unity;
using UtyMap.Unity.Core;
using UtyMap.Unity.Infrastructure.Config;
using UtyMap.Unity.Infrastructure.Diagnostic;
using UtyMap.Unity.Infrastructure.IO;
using UtyDepend;
using UtyDepend.Config;
namespace UtyMap.Unity.Tests.Helpers
{
internal static class TestHelper
{
#region Constants values
public const string IntegrationTestCategory = "Integration";
public static GeoCoordinate WorldZeroPoint = new GeoCoordinate(52.5317429, 13.3871987);
public const string TestAssetsFolder = @"../../../../demo/Assets/Resources";
public const string ConfigTestRootFile = TestAssetsFolder + @"/Config/test.json";
public const string BerlinXmlData = TestAssetsFolder + @"/Osm/berlin.osm.xml";
public const string BerlinPbfData = TestAssetsFolder + @"/Osm/berlin.osm.pbf";
public const string NmeaFilePath = TestAssetsFolder + @"/Nmea/invalidenstrasse_borsigstrasse.nme";
public const string DefaultMapCss = TestAssetsFolder + @"/MapCss/default/default.mapcss";
#endregion
public static CompositionRoot GetCompositionRoot(GeoCoordinate worldZeroPoint)
{
return GetCompositionRoot(worldZeroPoint, (container, section) => { });
}
public static CompositionRoot GetCompositionRoot(GeoCoordinate worldZeroPoint,
Action<IContainer, IConfigSection> action)
{
// create default container which should not be exposed outside
// to avoid Service Locator pattern.
IContainer container = new Container();
// create default application configuration
var config = ConfigBuilder.GetDefault()
.Build();
// initialize services
return new CompositionRoot(container, config)
.RegisterAction((c, _) => c.Register(Component.For<ITrace>().Use<ConsoleTrace>()))
.RegisterAction((c, _) => c.Register(Component.For<IPathResolver>().Use<TestPathResolver>()))
.RegisterAction((c, _) => c.Register(Component.For<Stylesheet>().Use<Stylesheet>(DefaultMapCss)))
.RegisterAction((c, _) => c.Register(Component.For<IProjection>().Use<CartesianProjection>(worldZeroPoint)))
.RegisterAction(action)
.Setup();
}
}
}
| using System;
using UtyMap.Unity;
using UtyMap.Unity.Core;
using UtyMap.Unity.Infrastructure.Config;
using UtyMap.Unity.Infrastructure.Diagnostic;
using UtyMap.Unity.Infrastructure.IO;
using UtyDepend;
using UtyDepend.Config;
namespace UtyMap.Unity.Tests.Helpers
{
internal static class TestHelper
{
#region Constants values
public const string IntegrationTestCategory = "Integration";
public static GeoCoordinate WorldZeroPoint = new GeoCoordinate(52.5317429, 13.3871987);
public const string TestAssetsFolder = @"../../../demo/Assets/Resources";
public const string ConfigTestRootFile = TestAssetsFolder + @"/Config/test.json";
public const string BerlinXmlData = TestAssetsFolder + @"/Osm/berlin.osm.xml";
public const string BerlinPbfData = TestAssetsFolder + @"/Osm/berlin.osm.pbf";
public const string NmeaFilePath = TestAssetsFolder + @"/Nmea/invalidenstrasse_borsigstrasse.nme";
public const string DefaultMapCss = TestAssetsFolder + @"/MapCss/default/default.mapcss";
#endregion
public static CompositionRoot GetCompositionRoot(GeoCoordinate worldZeroPoint)
{
return GetCompositionRoot(worldZeroPoint, (container, section) => { });
}
public static CompositionRoot GetCompositionRoot(GeoCoordinate worldZeroPoint,
Action<IContainer, IConfigSection> action)
{
// create default container which should not be exposed outside
// to avoid Service Locator pattern.
IContainer container = new Container();
// create default application configuration
var config = ConfigBuilder.GetDefault()
.Build();
// initialize services
return new CompositionRoot(container, config)
.RegisterAction((c, _) => c.Register(Component.For<ITrace>().Use<ConsoleTrace>()))
.RegisterAction((c, _) => c.Register(Component.For<IPathResolver>().Use<TestPathResolver>()))
.RegisterAction((c, _) => c.Register(Component.For<Stylesheet>().Use<Stylesheet>(DefaultMapCss)))
.RegisterAction((c, _) => c.Register(Component.For<IProjection>().Use<CartesianProjection>(worldZeroPoint)))
.RegisterAction(action)
.Setup();
}
}
}
| apache-2.0 | C# |
0cc472f38940f7ad11a923907941fa31d0139bbd | Remove unused constructor | appharbor/appharbor-cli | src/AppHarbor.Tests/Commands/CreateCommandTest.cs | src/AppHarbor.Tests/Commands/CreateCommandTest.cs | using System.Linq;
using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests.Commands
{
public class CreateCommandTest
{
[Theory, AutoCommandData]
public void ShouldCreateApplication([Frozen]Mock<IAppHarborClient> client, CreateCommand command, string[] arguments)
{
command.Execute(arguments);
client.Verify(x => x.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault()), Times.Once());
}
}
}
| using System.Linq;
using AppHarbor.Commands;
using Moq;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests.Commands
{
public class CreateCommandTest
{
private readonly IFixture _fixture;
public CreateCommandTest()
{
_fixture = new Fixture().Customize(new AutoMoqCustomization());
}
[Theory, AutoCommandData]
public void ShouldCreateApplication([Frozen]Mock<IAppHarborClient> client, CreateCommand command, string[] arguments)
{
command.Execute(arguments);
client.Verify(x => x.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault()), Times.Once());
}
}
}
| mit | C# |
f3b730e26a768f633adb9826b96e85867e83d51f | Update IAppLoader.cs | ivan-prodanov/DotNet.Startup | Contracts/IAppLoader.cs | Contracts/IAppLoader.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace DotNet.Startup.Contracts
{
public interface IAppLoader
{
void Run();
void Run(Assembly assembly);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DotNet.Startup.Contracts
{
public interface IAppLoader
{
void Run();
}
}
| unlicense | C# |
461c49939a5bfba7b716dec49788acbd169d518f | Update DefaultBufferPool.cs | justcoding121/StreamExtended | StreamExtended/BufferPool/DefaultBufferPool.cs | StreamExtended/BufferPool/DefaultBufferPool.cs | using System.Collections.Concurrent;
namespace StreamExtended
{
/// <summary>
/// A concrete IBufferPool implementation using a thread-safe stack.
/// Works well when all consumers ask for buffers with the same size.
/// If your application would use variable size buffers consider implementing IBufferPool using System.Buffers library from Microsoft.
/// </summary>
public class DefaultBufferPool : IBufferPool
{
private readonly ConcurrentStack<byte[]> buffers = new ConcurrentStack<byte[]>();
/// <summary>
/// Gets a buffer.
/// </summary>
/// <param name="bufferSize">Size of the buffer.</param>
/// <returns></returns>
public byte[] GetBuffer(int bufferSize)
{
if (!buffers.TryPop(out var buffer) || buffer.Length != bufferSize)
{
buffer = new byte[bufferSize];
}
return buffer;
}
/// <summary>
/// Returns the buffer.
/// </summary>
/// <param name="buffer">The buffer.</param>
public void ReturnBuffer(byte[] buffer)
{
if (buffer != null)
{
buffers.Push(buffer);
}
}
public void Dispose()
{
buffers.Clear();
}
}
}
| using System.Collections.Concurrent;
namespace StreamExtended
{
/// <summary>
/// A concrete IBufferPool implementation using a thread-safe stack.
/// Works well when all consumers ask for buffers with the same size.
/// If your application would use size buffers consider implementing IBufferPool using System.Buffers library from Microsoft.
/// </summary>
public class DefaultBufferPool : IBufferPool
{
private readonly ConcurrentStack<byte[]> buffers = new ConcurrentStack<byte[]>();
/// <summary>
/// Gets a buffer.
/// </summary>
/// <param name="bufferSize">Size of the buffer.</param>
/// <returns></returns>
public byte[] GetBuffer(int bufferSize)
{
if (!buffers.TryPop(out var buffer) || buffer.Length != bufferSize)
{
buffer = new byte[bufferSize];
}
return buffer;
}
/// <summary>
/// Returns the buffer.
/// </summary>
/// <param name="buffer">The buffer.</param>
public void ReturnBuffer(byte[] buffer)
{
if (buffer != null)
{
buffers.Push(buffer);
}
}
public void Dispose()
{
buffers.Clear();
}
}
}
| mit | C# |
9ba48ed61fe9e58d205f903f144f31f37bee9e69 | Test to see if running multiple works ok. | zarlo/Cosmos,tgiphil/Cosmos,trivalik/Cosmos,trivalik/Cosmos,CosmosOS/Cosmos,trivalik/Cosmos,CosmosOS/Cosmos,fanoI/Cosmos,jp2masa/Cosmos,CosmosOS/Cosmos,tgiphil/Cosmos,tgiphil/Cosmos,zarlo/Cosmos,fanoI/Cosmos,zarlo/Cosmos,jp2masa/Cosmos,zarlo/Cosmos,fanoI/Cosmos,jp2masa/Cosmos,CosmosOS/Cosmos | Tests/Cosmos.TestRunner.Core/TestKernelSets.cs | Tests/Cosmos.TestRunner.Core/TestKernelSets.cs | using System;
using System.Collections.Generic;
namespace Cosmos.TestRunner.Core
{
public static class TestKernelSets
{
public static IEnumerable<Type> GetStableKernelTypes()
{
for (int i = 0; i < 5; i++)
{
yield return typeof(VGACompilerCrash.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Encryption.Kernel);
yield return typeof(Cosmos.Compiler.Tests.Bcl.Kernel);
yield return typeof(Cosmos.Compiler.Tests.SingleEchoTest.Kernel);
yield return typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel);
yield return typeof(SimpleStructsAndArraysTest.Kernel);
yield return typeof(Cosmos.Compiler.Tests.Exceptions.Kernel);
yield return typeof(Cosmos.Compiler.Tests.LinqTests.Kernel);
yield return typeof(Cosmos.Compiler.Tests.MethodTests.Kernel);
//yield return typeof(Cosmos.Kernel.Tests.Fat.Kernel);
//yield return typeof(FrotzKernel.Kernel);
}
}
}
}
| using System;
using System.Collections.Generic;
namespace Cosmos.TestRunner.Core
{
public static class TestKernelSets
{
public static IEnumerable<Type> GetStableKernelTypes()
{
yield return typeof(VGACompilerCrash.Kernel);
//yield return typeof(Cosmos.Compiler.Tests.Encryption.Kernel);
yield return typeof(Cosmos.Compiler.Tests.Bcl.Kernel);
yield return typeof(Cosmos.Compiler.Tests.SingleEchoTest.Kernel);
yield return typeof(Cosmos.Compiler.Tests.SimpleWriteLine.Kernel.Kernel);
yield return typeof(SimpleStructsAndArraysTest.Kernel);
yield return typeof(Cosmos.Compiler.Tests.Exceptions.Kernel);
yield return typeof(Cosmos.Compiler.Tests.LinqTests.Kernel);
yield return typeof(Cosmos.Compiler.Tests.MethodTests.Kernel);
//yield return typeof(Cosmos.Kernel.Tests.Fat.Kernel);
//yield return typeof(FrotzKernel.Kernel);
}
}
}
| bsd-3-clause | C# |
0c924c027da49f5d348ba7a5918bfb1f8fd6d2b9 | Fix indentation | lucaslorentz/minicover,lucaslorentz/minicover,lucaslorentz/minicover | sample/src/Sample/TryFinally/ClassWithMultipleConstructors.cs | sample/src/Sample/TryFinally/ClassWithMultipleConstructors.cs | namespace Sample.TryFinally
{
public class ClassWithMultipleConstructors
{
private static readonly int staticValue;
private readonly int value;
private ClassWithMultipleConstructors() : this(15)
{
}
private ClassWithMultipleConstructors(int value)
{
this.value = value * staticValue;
}
static ClassWithMultipleConstructors()
{
staticValue = 15;
}
public static ClassWithMultipleConstructors BuildFor(int value) => new ClassWithMultipleConstructors(value);
public static ClassWithMultipleConstructors Default() => new ClassWithMultipleConstructors();
}
} | namespace Sample.TryFinally
{
public class ClassWithMultipleConstructors
{
private static readonly int staticValue;
private readonly int value;
private ClassWithMultipleConstructors() : this(15)
{
}
private ClassWithMultipleConstructors(int value)
{
this.value = value * staticValue;
}
static ClassWithMultipleConstructors()
{
staticValue = 15;
}
public static ClassWithMultipleConstructors BuildFor(int value) => new ClassWithMultipleConstructors(value);
public static ClassWithMultipleConstructors Default() => new ClassWithMultipleConstructors();
}
} | mit | C# |
ffbcc07388df6ab4938f4663105adc3528d03fd7 | Add MakeWritable binding | freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,GStreamer/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,GStreamer/gstreamer-sharp,GStreamer/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp | sources/custom/MiniObject.cs | sources/custom/MiniObject.cs | // Copyright (C) 2014 Stephan Sundermann <stephansundermann@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301 USA
namespace Gst {
using System;
using System.Runtime.InteropServices;
partial class MiniObject
{
protected MiniObject () {}
[DllImport("libgstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern bool gst_mini_object_replace(IntPtr olddata, IntPtr newdata);
public static bool Replace(ref Gst.MiniObject olddata, Gst.MiniObject newdata) {
return gst_mini_object_replace(olddata.Handle, newdata == null ? IntPtr.Zero : newdata.Handle);
}
public static bool Replace(ref Gst.MiniObject olddata) {
return Replace (ref olddata, null);
}
[DllImport("libgstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern bool gst_mini_object_take(IntPtr olddata, IntPtr newdata);
public static bool Take(ref Gst.MiniObject olddata, Gst.MiniObject newdata) {
return gst_mini_object_take(olddata.Handle, newdata == null ? IntPtr.Zero : newdata.Handle);
}
[DllImport("libgstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr gst_mini_object_make_writable(IntPtr mini_object);
public void MakeWritable() {
Console.WriteLine (Handle);
Raw = gst_mini_object_make_writable (Raw);
Console.WriteLine (Handle);
}
}
}
| // Copyright (C) 2014 Stephan Sundermann <stephansundermann@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301 USA
namespace Gst {
using System;
using System.Runtime.InteropServices;
partial class MiniObject
{
protected MiniObject () {}
[DllImport("libgstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern bool gst_mini_object_replace(IntPtr olddata, IntPtr newdata);
public static bool Replace(ref Gst.MiniObject olddata, Gst.MiniObject newdata) {
return gst_mini_object_replace(olddata.Handle, newdata == null ? IntPtr.Zero : newdata.Handle);
}
public static bool Replace(ref Gst.MiniObject olddata) {
return Replace (ref olddata, null);
}
[DllImport("libgstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern bool gst_mini_object_take(IntPtr olddata, IntPtr newdata);
public static bool Take(ref Gst.MiniObject olddata, Gst.MiniObject newdata) {
return gst_mini_object_take(olddata.Handle, newdata == null ? IntPtr.Zero : newdata.Handle);
}
}
}
| lgpl-2.1 | C# |
aa525038247c48f2f7709befb960cf5c73aed4f5 | Update CertificateRequestModel.cs | nomailme/TestAuthority | source/TestAuthorityCore/Contracts/CertificateRequestModel.cs | source/TestAuthorityCore/Contracts/CertificateRequestModel.cs | using System.ComponentModel;
using System.Linq;
namespace TestAuthorityCore.Contracts
{
/// <summary>
/// CertificateRequest
/// </summary>
public class CertificateRequestModel
{
private string commonName = string.Empty;
/// <summary>
/// Common Name
/// </summary>
public string CommonName
{
get
{
if (string.IsNullOrEmpty(commonName))
{
var allSanRecords = Hostname.ToList().Concat(IpAddress);
var firstRecord = allSanRecords.First();
return $"{firstRecord} certificate";
}
return commonName;
}
set
{
commonName = value;
}
}
/// <summary>
/// Password that will be used for PFX file.
/// </summary>
[DefaultValue("123123213")]
public string Password { get; set; }
/// <summary>
/// List of domain names to include in Subject Alternative Name extension.
/// </summary>
public string[] Hostname { get; set; } = new string[0];
/// <summary>
/// List of IP addresses to include in Subject Alternative Name extension.
/// </summary>
public string[] IpAddress { get; set; } = new string[0];
/// <summary>
/// Output filename (without extension).
/// </summary>
[DefaultValue("certificate")]
public string Filename { get; set; } = "certificate";
/// <summary>
/// Certificate validity in days.
/// </summary>
[DefaultValue(365)]
public int ValidityInDays { get; set; }
/// <summary>
/// Output format.
/// </summary>
/// <remarks>
/// Pfx will produce PFX file
/// Pem will produce ZIP file with certificate,key and root certificate.
/// </remarks>
[DefaultValue(CertificateFormat.Pfx)]
public CertificateFormat Format { get; set; } = CertificateFormat.Pfx;
}
}
| using System.ComponentModel;
using System.Linq;
namespace TestAuthorityCore.Contracts
{
/// <summary>
/// CertificateRequest
/// </summary>
public class CertificateRequestModel
{
private string commonName = string.Empty;
/// <summary>
/// Common Name
/// </summary>
public string CommonName
{
get
{
if (string.IsNullOrEmpty(commonName))
{
var allSanRecords = Hostname.ToList().Concat(IpAddress);
var firstRecord = allSanRecords.First();
return $"{firstRecord} certificate";
}
return commonName;
}
set
{
commonName = value;
}
}
/// <summary>
/// Password that will be used for PFX file.
/// </summary>
[DefaultValue("123123213")]
public string Password { get; set; }
/// <summary>
/// List of domain names to include in Subject Alternative Name extension.
/// </summary>
public string[] Hostname { get; set; } = new string[0];
/// <summary>
/// List of IP addresses to include in Subject Alternative Name extension.
/// </summary>
public string[] IpAddress { get; set; } = new string[0];
/// <summary>
/// Output filename (without extension).
/// </summary>
[DefaultValue("certificate")]
public string Filename { get; set; }
/// <summary>
/// Certificate validity in days.
/// </summary>
[DefaultValue(365)]
public int ValidityInDays { get; set; }
/// <summary>
/// Output format.
/// </summary>
/// <remarks>
/// Pfx will produce PFX file
/// Pem will produce ZIP file with certificate,key and root certificate.
/// </remarks>
[DefaultValue(CertificateFormat.Pfx)]
public CertificateFormat Format { get; set; } = CertificateFormat.Pfx;
}
}
| mit | C# |
3afcf7ca7f66554591c7d509ae858b0bd3967ef7 | Update ExitRenderDisable.cs | goodmorningcmdr/misc-unity-stuff,goodmorningcmdr/misc-unity-stuff | Assets/_Scripts/ExitRenderDisable.cs | Assets/_Scripts/ExitRenderDisable.cs | using UnityEngine;
using UnityEngine.Events;
public class ExitRenderDisable : MonoBehaviour {
public Transform target;
public bool distanceCheck;
public float maxDistance = 50;
[Range(0.001f, 60)]
public float interval = 1f;
public UnityEvent OnVisible;
public UnityEvent OnInvisible;
void Awake() {
if (target == null && Camera.main) target = Camera.main.transform;
if (distanceCheck && target) InvokeRepeating("DistanceCheck", 1, interval);
}
void DistanceCheck() {
if (!target)
{
distanceCheck = false;
CancelInvoke();
OnVisible.Invoke();
return;
}
float dist = (transform.position - target.position).sqrMagnitude;
if (dist > maxDistance * maxDistance)
{
OnInvisible.Invoke();
}
else
{
OnVisible.Invoke();
}
}
void OnBecameInvisible() {
OnInvisible.Invoke();
}
void OnBecameVisible() {
OnVisible.Invoke();
}
}
| using UnityEngine;
using UnityEngine.Events;
public class ExitRenderDisable : MonoBehaviour {
Transform player;
public bool distanceCheck;
public float maxDistance = 50;
[Range(0.001f, 60)]
public float interval = 1f;
public UnityEvent OnVisible;
public UnityEvent OnInvisible;
void Awake() {
player = Camera.main.transform;
if (distanceCheck) InvokeRepeating("DistanceCheck", 1, interval);
}
void DistanceCheck() {
float dist = (transform.position - player.position).sqrMagnitude;
if (dist > maxDistance * maxDistance)
{
OnInvisible.Invoke();
}
else
{
OnVisible.Invoke();
}
}
void OnBecameInvisible() {
OnInvisible.Invoke();
}
void OnBecameVisible() {
OnVisible.Invoke();
}
}
| unlicense | C# |
b46083773d97ef7bcac176c7426df1c98d5efa71 | Hide UserId | Michitaro-Naito/GameServer | GameServer/Character.cs | GameServer/Character.cs | using ApiScheme.Scheme;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GameServer
{
public class Character
{
/// <summary>
/// Player who owns this Character.
/// </summary>
public Player Player { get; private set; }
/// <summary>
/// Name of Character.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// UserId of Player. (Check)
/// </summary>
public string UserId { get; private set; }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="player"></param>
/// <param name="info"></param>
public Character(Player player, CharacterInfo info)
{
Player = player;
Name = info.name;
UserId = info.userId;
}
public override string ToString()
{
return Name;
//return string.Format("[{0}({1})]", Name, Player.userId);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj.GetType() != GetType())
return false;
var c = (Character)obj;
return c.Player == this.Player;
}
public static bool operator ==(Character a, Character b)
{
var oa = (object)a;
var ob = (object)b;
if (oa == null && ob == null)
return true;
if (oa == null || ob == null)
return false;
return a.Player == b.Player;
}
public static bool operator !=(Character a, Character b)
{
return !(a == b);
}
}
}
| using ApiScheme.Scheme;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GameServer
{
public class Character
{
/// <summary>
/// Player who owns this Character.
/// </summary>
public Player Player { get; private set; }
/// <summary>
/// Name of Character.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// UserId of Player. (Check)
/// </summary>
public string UserId { get; private set; }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="player"></param>
/// <param name="info"></param>
public Character(Player player, CharacterInfo info)
{
Player = player;
Name = info.name;
UserId = info.userId;
}
public override string ToString()
{
return string.Format("[{0}({1})]", Name, Player.userId);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj.GetType() != GetType())
return false;
var c = (Character)obj;
return c.Player == this.Player;
}
public static bool operator ==(Character a, Character b)
{
var oa = (object)a;
var ob = (object)b;
if (oa == null && ob == null)
return true;
if (oa == null || ob == null)
return false;
return a.Player == b.Player;
}
public static bool operator !=(Character a, Character b)
{
return !(a == b);
}
}
}
| mit | C# |
f2d0d89133e0bcf2c09ff560bee6413357ba9278 | Test checkin with new repo | EnigmaDragons/SecurityConsultantCore | src/SecurityConsultantCore/Factories/SecurityObjectFactory.cs | src/SecurityConsultantCore/Factories/SecurityObjectFactory.cs | using System.Collections.Generic;
using SecurityConsultantCore.Domain;
using SecurityConsultantCore.Domain.Basic;
namespace SecurityConsultantCore.Factories
{
public static class SecurityObjectFactory
{
private static SecurityObjectContainer _container;
public static SecurityObject Create(string type)
{
return GetContainer().Create(type);
}
public static List<string> GetConstructables()
{
return GetContainer().GetConstructables();
}
private static SecurityObjectContainer GetContainer()
{
return _container ?? (_container = new SecurityObjectContainer());
}
private class SecurityObjectContainer : Container<SecurityObject>
{
protected override string GetKey(string id)
{
return id;
}
protected override Dictionary<string, SecurityObject> GetObjects()
{
return new Dictionary<string, SecurityObject>
{
{
"FloorPressurePlate",
new SecurityObject
{
Type = "FloorPressurePlate",
ObjectLayer = ObjectLayer.GroundPlaceable,
Traits = new[] {"OpenSpace"}
}
},
{
"Guard",
new SecurityObject
{
Type = "Guard",
ObjectLayer = ObjectLayer.LowerPlaceable,
Traits = new[] {"OpenSpace"}
}
}
};
}
}
}
} | using System.Collections.Generic;
using SecurityConsultantCore.Domain;
using SecurityConsultantCore.Domain.Basic;
namespace SecurityConsultantCore.Factories
{
public static class SecurityObjectFactory
{
private static SecurityObjectContainer _container;
public static SecurityObject Create(string type)
{
return GetContainer().Create(type);
}
public static List<string> GetConstructables()
{
return GetContainer().GetConstructables();
}
private static SecurityObjectContainer GetContainer()
{
return _container ?? (_container = new SecurityObjectContainer());
}
private class SecurityObjectContainer : Container<SecurityObject>
{
protected override string GetKey(string id)
{
return id;
}
protected override Dictionary<string, SecurityObject> GetObjects()
{
return new Dictionary<string, SecurityObject>
{
{
"PressurePlate",
new SecurityObject
{
Type = "PressurePlate",
ObjectLayer = ObjectLayer.GroundPlaceable,
Traits = new[] {"OpenSpace"}
}
},
{
"Guard",
new SecurityObject
{
Type = "Guard",
ObjectLayer = ObjectLayer.LowerPlaceable,
Traits = new[] {"OpenSpace"}
}
}
};
}
}
}
} | mit | C# |
c70089cd09c5eb880933b1333d587e7631c69733 | remove unnecessary using | wilcommerce/Wilcommerce.Core.Data.EFCore | src/Wilcommerce.Core.Data.EFCore/ReadModels/CommonDatabase.cs | src/Wilcommerce.Core.Data.EFCore/ReadModels/CommonDatabase.cs | using System.Linq;
using Wilcommerce.Core.Common.Domain.Models;
using Wilcommerce.Core.Common.Domain.ReadModels;
namespace Wilcommerce.Core.Data.EFCore.ReadModels
{
/// <summary>
/// Implementation of <see cref="ICommonDatabase"/>
/// </summary>
public class CommonDatabase : ICommonDatabase
{
/// <summary>
/// The DbContext instance
/// </summary>
protected CommonContext _context;
public CommonDatabase(CommonContext context)
{
_context = context;
}
/// <summary>
/// Get the list of settings
/// </summary>
public IQueryable<GeneralSettings> Settings => _context.Settings;
/// <summary>
/// Get the list of users
/// </summary>
public IQueryable<User> Users => _context.Users;
}
}
| using System.Linq;
using Wilcommerce.Core.Common.Domain.Events;
using Wilcommerce.Core.Common.Domain.Models;
using Wilcommerce.Core.Common.Domain.ReadModels;
namespace Wilcommerce.Core.Data.EFCore.ReadModels
{
/// <summary>
/// Implementation of <see cref="ICommonDatabase"/>
/// </summary>
public class CommonDatabase : ICommonDatabase
{
/// <summary>
/// The DbContext instance
/// </summary>
protected CommonContext _context;
public CommonDatabase(CommonContext context)
{
_context = context;
}
/// <summary>
/// Get the list of settings
/// </summary>
public IQueryable<GeneralSettings> Settings => _context.Settings;
/// <summary>
/// Get the list of users
/// </summary>
public IQueryable<User> Users => _context.Users;
}
}
| mit | C# |
6c3781e38910931e4cc6f0062b6a77cbe25cc85b | remove "nameof" | Borayvor/ASP.NET-MVC-CourseProject,Borayvor/ASP.NET-MVC-CourseProject,Borayvor/ASP.NET-MVC-CourseProject | EntertainmentSystem/Data/EntertainmentSystem.Data.Common/Repositories/DbRepository{T}.cs | EntertainmentSystem/Data/EntertainmentSystem.Data.Common/Repositories/DbRepository{T}.cs | namespace EntertainmentSystem.Data.Common
{
using System;
using System.Data.Entity;
using System.Linq;
using Models;
using Repositories;
public class DbRepository<T> : IDbRepository<T>
where T : class, IAuditInfo, IDeletableEntity
{
public DbRepository(DbContext context)
{
if (context == null)
{
throw new ArgumentException("An instance of DbContext is required to use this repository.");
}
this.Context = context;
this.DbSet = this.Context.Set<T>();
}
private IDbSet<T> DbSet { get; set; }
private DbContext Context { get; set; }
public IQueryable<T> All()
{
return this.DbSet.Where(x => !x.IsDeleted);
}
public IQueryable<T> AllWithDeleted()
{
return this.DbSet;
}
public T GetById(object id)
{
return this.DbSet.Find(id);
}
public void Create(T entity)
{
this.DbSet.Add(entity);
}
public virtual void Update(T entity)
{
var entry = this.Context.Entry(entity);
if (entry.State == EntityState.Detached)
{
this.DbSet.Attach(entity);
}
entry.State = EntityState.Modified;
}
public void Delete(T entity)
{
entity.IsDeleted = true;
entity.DeletedOn = DateTime.Now;
}
public void DeletePermanent(T entity)
{
this.DbSet.Remove(entity);
}
public void Save()
{
this.Context.SaveChanges();
}
}
}
| namespace EntertainmentSystem.Data.Common
{
using System;
using System.Data.Entity;
using System.Linq;
using Models;
using Repositories;
public class DbRepository<T> : IDbRepository<T>
where T : class, IAuditInfo, IDeletableEntity
{
public DbRepository(DbContext context)
{
if (context == null)
{
throw new ArgumentException("An instance of DbContext is required to use this repository.", nameof(context));
}
this.Context = context;
this.DbSet = this.Context.Set<T>();
}
private IDbSet<T> DbSet { get; set; }
private DbContext Context { get; set; }
public IQueryable<T> All()
{
return this.DbSet.Where(x => !x.IsDeleted);
}
public IQueryable<T> AllWithDeleted()
{
return this.DbSet;
}
public T GetById(object id)
{
return this.DbSet.Find(id);
}
public void Create(T entity)
{
this.DbSet.Add(entity);
}
public virtual void Update(T entity)
{
var entry = this.Context.Entry(entity);
if (entry.State == EntityState.Detached)
{
this.DbSet.Attach(entity);
}
entry.State = EntityState.Modified;
}
public void Delete(T entity)
{
entity.IsDeleted = true;
entity.DeletedOn = DateTime.Now;
}
public void DeletePermanent(T entity)
{
this.DbSet.Remove(entity);
}
public void Save()
{
this.Context.SaveChanges();
}
}
}
| mit | C# |
e7783f6ab2c4edbf3ac734859bc7b40ef4c99157 | fix typo | Microsoft/ApplicationInsights-aspnet5,Microsoft/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnetcore,Microsoft/ApplicationInsights-aspnet5,Microsoft/ApplicationInsights-aspnet5,Microsoft/ApplicationInsights-aspnetcore | test/MVCFramework45.FunctionalTests/Views/_ViewImports.cshtml | test/MVCFramework45.FunctionalTests/Views/_ViewImports.cshtml | @using MVCFramework45.FunctionalTests
@using MVCFramework45.FunctionalTests.Models
@using MVCFramework45.FunctionalTests.Models.AccountViewModels
@using MVCFramework45.FunctionalTests.Models.ManageViewModels
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
| Moi@using MVCFramework45.FunctionalTests
@using MVCFramework45.FunctionalTests.Models
@using MVCFramework45.FunctionalTests.Models.AccountViewModels
@using MVCFramework45.FunctionalTests.Models.ManageViewModels
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
| mit | C# |
69e066ff4e1cdc304b74ac9860ac10d4c51f7385 | Fix DiscordChannel.IsGuildChannel returning false for news and store channels | BundledSticksInkorperated/Discore | src/Discore/DiscordChannel.cs | src/Discore/DiscordChannel.cs | using Discore.Http;
using System.Threading.Tasks;
namespace Discore
{
/// <summary>
/// A <see cref="DiscordDMChannel"/> or a <see cref="DiscordGuildChannel"/>.
/// </summary>
public abstract class DiscordChannel : DiscordIdEntity
{
/// <summary>
/// Gets the type of this channel.
/// </summary>
public DiscordChannelType ChannelType { get; }
/// <summary>
/// Gets whether this channel is a guild channel.
/// </summary>
public bool IsGuildChannel =>
ChannelType == DiscordChannelType.GuildText
|| ChannelType == DiscordChannelType.GuildVoice
|| ChannelType == DiscordChannelType.GuildCategory
|| ChannelType == DiscordChannelType.GuildNews
|| ChannelType == DiscordChannelType.GuildStore;
readonly DiscordHttpClient http;
internal DiscordChannel(DiscordHttpClient http, DiscordChannelType type)
{
this.http = http;
ChannelType = type;
}
internal DiscordChannel(DiscordHttpClient http, DiscordApiData data, DiscordChannelType type)
: base(data)
{
this.http = http;
ChannelType = type;
}
/// <summary>
/// Deletes/closes this channel.
/// <para>Requires <see cref="DiscordPermission.ManageChannels"/> if this is a guild channel.</para>
/// </summary>
/// <exception cref="DiscordHttpApiException"></exception>
public Task<DiscordChannel> Delete()
{
return http.DeleteChannel(Id);
}
public override string ToString()
{
return $"{ChannelType} Channel: {Id}";
}
}
}
| using Discore.Http;
using System.Threading.Tasks;
namespace Discore
{
/// <summary>
/// A <see cref="DiscordDMChannel"/> or a <see cref="DiscordGuildChannel"/>.
/// </summary>
public abstract class DiscordChannel : DiscordIdEntity
{
/// <summary>
/// Gets the type of this channel.
/// </summary>
public DiscordChannelType ChannelType { get; }
/// <summary>
/// Gets whether this channel is a guild channel.
/// </summary>
public bool IsGuildChannel =>
ChannelType == DiscordChannelType.GuildText
|| ChannelType == DiscordChannelType.GuildVoice
|| ChannelType == DiscordChannelType.GuildCategory;
DiscordHttpClient http;
internal DiscordChannel(DiscordHttpClient http, DiscordChannelType type)
{
this.http = http;
ChannelType = type;
}
internal DiscordChannel(DiscordHttpClient http, DiscordApiData data, DiscordChannelType type)
: base(data)
{
this.http = http;
ChannelType = type;
}
/// <summary>
/// Deletes/closes this channel.
/// <para>Requires <see cref="DiscordPermission.ManageChannels"/> if this is a guild channel.</para>
/// </summary>
/// <exception cref="DiscordHttpApiException"></exception>
public Task<DiscordChannel> Delete()
{
return http.DeleteChannel(Id);
}
public override string ToString()
{
return $"{ChannelType} Channel: {Id}";
}
}
}
| mit | C# |
4fd4b4f6f37c134a97ac8bbc878a9a7e04b89791 | Add method to AudioHelpers to get a random file from a sound collection | space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content | Content.Shared/Audio/AudioHelpers.cs | Content.Shared/Audio/AudioHelpers.cs | using System;
using Content.Shared.GameObjects.Components.Sound;
using Robust.Client.GameObjects.EntitySystems;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Random;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
namespace Content.Shared.Audio
{
public static class AudioHelpers{
/// <summary>
/// Returns a random pitch.
/// </summary>
public static AudioParams WithVariation(float amplitude)
{
var scale = (float)(IoCManager.Resolve<IRobustRandom>().NextGaussian(1, amplitude));
return AudioParams.Default.WithPitchScale(scale);
}
public static string GetRandomFileFromSoundCollection(string name)
{
var soundCollection = IoCManager.Resolve<IPrototypeManager>().Index<SoundCollectionPrototype>(name);
return IoCManager.Resolve<IRobustRandom>().Pick(soundCollection.PickFiles);
}
}
}
| using System;
using Content.Shared.GameObjects.Components.Sound;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.Random;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Random;
namespace Content.Shared.Audio
{
public static class AudioHelpers{
/// <summary>
/// Returns a random pitch.
/// </summary>
public static AudioParams WithVariation(float amplitude)
{
var scale = (float)(IoCManager.Resolve<IRobustRandom>().NextGaussian(1, amplitude));
return AudioParams.Default.WithPitchScale(scale);
}
}
}
| mit | C# |
e7ab2f3e5f4f4bd3ea1fa81607fbf92fb015041f | Add regression test for nullable array return value | DotNetAnalyzers/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp8/SpacingRules/SA1011CSharp8UnitTests.cs | StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp8/SpacingRules/SA1011CSharp8UnitTests.cs | // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp8.SpacingRules
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.Test.CSharp7.SpacingRules;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.SpacingRules.SA1011ClosingSquareBracketsMustBeSpacedCorrectly,
StyleCop.Analyzers.SpacingRules.TokenSpacingCodeFixProvider>;
public class SA1011CSharp8UnitTests : SA1011CSharp7UnitTests
{
/// <summary>
/// Verify that declaring a null reference type works for arrays.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(2927, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2927")]
public async Task VerifyNullableContextWithArraysAsync()
{
var testCode = @"namespace TestNamespace
{
public class TestClass
{
public void TestMethod()
{
byte[]? data = null;
}
}
}
";
await VerifyCSharpDiagnosticAsync(LanguageVersion.CSharp8, testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
[Fact]
[WorkItem(2900, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2900")]
public async Task VerifyNullableContextWithArrayReturnsAsync()
{
var testCode = @"namespace TestNamespace
{
public class TestClass
{
public byte[]? TestMethod()
{
return null;
}
}
}
";
await VerifyCSharpDiagnosticAsync(LanguageVersion.CSharp8, testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}
}
| // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp8.SpacingRules
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Testing;
using StyleCop.Analyzers.Test.CSharp7.SpacingRules;
using Xunit;
using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier<
StyleCop.Analyzers.SpacingRules.SA1011ClosingSquareBracketsMustBeSpacedCorrectly,
StyleCop.Analyzers.SpacingRules.TokenSpacingCodeFixProvider>;
public class SA1011CSharp8UnitTests : SA1011CSharp7UnitTests
{
/// <summary>
/// Verify that declaring a null reference type works for arrays.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
[WorkItem(2927, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2927")]
public async Task VerifyNullableContextWithArraysAsync()
{
var testCode = @"namespace TestNamespace
{
public class TestClass
{
public void TestMethod()
{
byte[]? data = null;
}
}
}
";
await VerifyCSharpDiagnosticAsync(LanguageVersion.CSharp8, testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
}
}
}
| mit | C# |
309045f58d6208fb98d3ef61383593679a9331a8 | リフレッシュ後にグループリストをリロードするようにした。 | finalstream/Movselex,finalstream/Movselex,finalstream/Movselex | Movselex.Core/Models/Actions/UpdateLibraryAction.cs | Movselex.Core/Models/Actions/UpdateLibraryAction.cs | namespace Movselex.Core.Models.Actions
{
internal class UpdateLibraryAction : MovselexProgressAction
{
public override void InvokeProgress(MovselexClient client)
{
client.LibraryUpdater.Update(client.ProgressInfo);
client.MovselexGroup.Load();
}
}
} | namespace Movselex.Core.Models.Actions
{
internal class UpdateLibraryAction : MovselexProgressAction
{
public override void InvokeProgress(MovselexClient client)
{
client.LibraryUpdater.Update(client.ProgressInfo);
}
}
} | mit | C# |
14878d23d94e12500c3d4d99c15cd21e2119f6e6 | Remove the .NET 3.5 specific Stream.CopyTo() extension method | akamsteeg/SwissArmyKnife | src/SwissArmyKnife/Extensions/StreamExtensions.cs | src/SwissArmyKnife/Extensions/StreamExtensions.cs | using System;
using System.IO;
namespace SwissArmyKnife.Extensions
{
/// <summary>
/// Extension methods for <see cref="Stream"/>
/// </summary>
public static class StreamExtensions
{
/// <summary>
/// Reset the position within the stream
/// back to the beginning
/// </summary>
/// <param name="source"></param>
public static void Reset(this Stream source)
{
if (!source.CanRead && !source.CanWrite)
throw new ObjectDisposedException(nameof(source));
if (!source.CanSeek)
throw new NotSupportedException("Cannot seek in the stream");
source.Seek(0, SeekOrigin.Begin);
}
}
}
| using System;
using System.IO;
namespace SwissArmyKnife.Extensions
{
/// <summary>
/// Extension methods for <see cref="Stream"/>
/// </summary>
public static class StreamExtensions
{
#if NET35 // || DEBUG
/// 81920 is the largest multiple of 4096 that's
/// smaller than 85900 bytes. This makes the
/// buffer as large as possible without the short
/// lived object ending up on the Large Object Heap
private const int _defaultBufferSize = 81920;
/// <summary>
/// Reads the bytes from the current stream
/// and writes them to another stream
/// </summary>
/// <param name="source"></param>
/// <param name="destination">
/// The stream to which the contents of the
/// current stream will be copied
/// </param>
public static void CopyTo(this Stream source, Stream destination)
{
source.CopyTo(destination, _defaultBufferSize);
}
/// <summary>
/// Reads the bytes from the current stream
/// and writes them to another stream, using
/// a specified buffer size
/// </summary>
/// <param name="source"></param>
/// <param name="destination">
/// The stream to which the contents of the
/// current stream will be copied
/// </param>
/// <param name="bufferSize">
/// The size of the buffer. This value must
/// be greater than zero
/// </param>
public static void CopyTo(this Stream source, Stream destination, int bufferSize)
{
if (!source.CanRead && !source.CanWrite)
throw new ObjectDisposedException(null, "Stream is disposed");
if (!source.CanRead)
throw new NotSupportedException("Cannot read from source stream");
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (!destination.CanRead && !destination.CanWrite)
throw new ObjectDisposedException(nameof(destination), "Destination stream is disposed");
if (!destination.CanWrite)
throw new NotSupportedException("Cannot write to destination stream");
if (bufferSize < 1)
throw new ArgumentOutOfRangeException("nameof(bufferSize), Buffer size must be 1 or higher");
var buffer = new byte[bufferSize];
int read = -1;
while (read != 0)
{
read = source.Read(buffer, 0, bufferSize);
destination.Write(buffer, 0, read);
}
}
#endif
/// <summary>
/// Reset the position within the stream
/// back to the beginning
/// </summary>
/// <param name="source"></param>
public static void Reset(this Stream source)
{
if (!source.CanRead && !source.CanWrite)
throw new ObjectDisposedException(nameof(source));
if (!source.CanSeek)
throw new NotSupportedException("Cannot seek in the stream");
source.Seek(0, SeekOrigin.Begin);
}
}
}
| mit | C# |
df68ff9644a1020170cfe4b301b314ba21f99ecb | Remove lie from event documentation | tgstation/tgstation-server,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server | src/Tgstation.Server.Host/Components/EventType.cs | src/Tgstation.Server.Host/Components/EventType.cs | namespace Tgstation.Server.Host.Components
{
/// <summary>
/// Types of events
/// </summary>
public enum EventType
{
/// <summary>
/// Parameters: Reference name, commit sha
/// </summary>
RepoResetOrigin = 0,
/// <summary>
/// Parameters: Checkout target
/// </summary>
RepoCheckout = 1,
/// <summary>
/// No parameters
/// </summary>
RepoFetch = 2,
/// <summary>
/// Parameters: Pull request number, pull request sha, merger name, merger message
/// </summary>
RepoMergePullRequest = 3,
/// <summary>
/// Parameters: Absolute path to repository root
/// </summary>
RepoPreSynchronize = 4,
/// <summary>
/// Parameters: Current version, new version
/// </summary>
ByondChangeStart = 5,
/// <summary>
/// Parameters: Error string
/// </summary>
ByondFail = 6,
/// <summary>
/// No parameters
/// </summary>
ByondChangeComplete = 7,
/// <summary>
/// Parameters: Game directory path, origin commit sha
/// </summary>
CompileStart = 8,
/// <summary>
/// No parameters
/// </summary>
CompileCancelled = 9,
/// <summary>
/// Parameters: Game directory path, "1" if compile succeeded and api validation failed, "0" otherwise
/// </summary>
CompileFailure = 10,
/// <summary>
/// Parameters: Game directory path
/// </summary>
CompileComplete = 11,
/// <summary>
/// Parameters: Exit code
/// </summary>
DDOtherCrash = 12,
/// <summary>
/// No parameters
/// </summary>
DDOtherExit = 13,
/// <summary>
/// No parameters
/// </summary>
InstanceAutoUpdateStart = 14,
/// <summary>
/// Parameters: Base sha, target sha, base reference, target reference
/// </summary>
RepoMergeConflict = 15,
}
}
| namespace Tgstation.Server.Host.Components
{
/// <summary>
/// Types of events
/// </summary>
public enum EventType
{
/// <summary>
/// Parameters: Reference name, commit sha
/// </summary>
RepoResetOrigin = 0,
/// <summary>
/// Parameters: Checkout target
/// </summary>
RepoCheckout = 1,
/// <summary>
/// No parameters
/// </summary>
RepoFetch = 2,
/// <summary>
/// Parameters: Pull request number, pull request sha, merger name, merger message
/// </summary>
RepoMergePullRequest = 3,
/// <summary>
/// Parameters: Absolute path to repository root, committer name, committer email
/// </summary>
RepoPreSynchronize = 4,
/// <summary>
/// Parameters: Current version, new version
/// </summary>
ByondChangeStart = 5,
/// <summary>
/// Parameters: Error string
/// </summary>
ByondFail = 6,
/// <summary>
/// No parameters
/// </summary>
ByondChangeComplete = 7,
/// <summary>
/// Parameters: Game directory path, origin commit sha
/// </summary>
CompileStart = 8,
/// <summary>
/// No parameters
/// </summary>
CompileCancelled = 9,
/// <summary>
/// Parameters: Game directory path, "1" if compile succeeded and api validation failed, "0" otherwise
/// </summary>
CompileFailure = 10,
/// <summary>
/// Parameters: Game directory path
/// </summary>
CompileComplete = 11,
/// <summary>
/// Parameters: Exit code
/// </summary>
DDOtherCrash = 12,
/// <summary>
/// No parameters
/// </summary>
DDOtherExit = 13,
/// <summary>
/// No parameters
/// </summary>
InstanceAutoUpdateStart = 14,
/// <summary>
/// Parameters: Base sha, target sha, base reference, target reference
/// </summary>
RepoMergeConflict = 15,
}
}
| agpl-3.0 | C# |
8a41298e01b276408b02e5f186d7c697c3422ce7 | Fix link to resource page; update year to 2018. | tf3604/SqlServerQueryTreeViewer | SqlServerQueryTreeViewer/Properties/AssemblyInfo.cs | SqlServerQueryTreeViewer/Properties/AssemblyInfo.cs | // Copyright(c) 2016-2017-2017 Brian Hansen.
// 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.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("SqlServerQueryTreeViewer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("tf3604.com/ssqtv")]
[assembly: AssemblyProduct("SqlServerQueryTreeViewer")]
[assembly: AssemblyCopyright("Copyright © Brian Hansen 2016-2018")]
[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("41c3fde9-a12a-4075-9abc-a53256530c8c")]
// 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.8.*")]
| // Copyright(c) 2016-2017-2017 Brian Hansen.
// 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.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("SqlServerQueryTreeViewer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("tf3604.com/ssptv")]
[assembly: AssemblyProduct("SqlServerQueryTreeViewer")]
[assembly: AssemblyCopyright("Copyright © Brian Hansen 2016-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("41c3fde9-a12a-4075-9abc-a53256530c8c")]
// 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.8.*")]
| mit | C# |
e1c9ab64088eef67fd7f1b539d9c3b6aeff26dcd | Fix update checker | DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer | LmpClient/Utilities/UpdateHandler.cs | LmpClient/Utilities/UpdateHandler.cs | using LmpClient.Windows.Update;
using LmpCommon;
using LmpGlobal;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
namespace LmpClient.Utilities
{
public static class UpdateHandler
{
public static IEnumerator CheckForUpdates()
{
using (var www = UnityWebRequest.Get(RepoConstants.ApiLatestGithubReleaseUrl))
{
yield return www.SendWebRequest();
if (!www.isNetworkError || !www.isHttpError)
{
if (!(Json.Deserialize(www.downloadHandler.text) is Dictionary<string, object> data))
yield break;
var latestVersion = new Version(data["tag_name"].ToString());
LunaLog.Log($"Latest version: {latestVersion}");
if (latestVersion > LmpVersioning.CurrentVersion)
{
using (var www2 = new UnityWebRequest(data["url"].ToString()))
{
yield return www2.SendWebRequest();
if (!www2.isNetworkError)
{
var changelog = data["body"].ToString();
UpdateWindow.LatestVersion = latestVersion;
UpdateWindow.Changelog = changelog;
UpdateWindow.Singleton.Display = true;
}
}
}
}
else
{
LunaLog.Log($"Could not check for latest version. Error: {www.error}");
}
}
}
}
}
| using LmpClient.Windows.Update;
using LmpCommon;
using LmpGlobal;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
namespace LmpClient.Utilities
{
public static class UpdateHandler
{
public static IEnumerator CheckForUpdates()
{
using (var www = new UnityWebRequest(RepoConstants.ApiLatestGithubReleaseUrl))
{
yield return www.SendWebRequest();
if (!www.isNetworkError)
{
if (!(Json.Deserialize(www.downloadHandler.text) is Dictionary<string, object> data))
yield break;
var latestVersion = new Version(data["tag_name"].ToString());
LunaLog.Log($"Latest version: {latestVersion}");
if (latestVersion > LmpVersioning.CurrentVersion)
{
using (var www2 = new UnityWebRequest(data["url"].ToString()))
{
yield return www2.SendWebRequest();
if (!www2.isNetworkError)
{
var changelog = data["body"].ToString();
UpdateWindow.LatestVersion = latestVersion;
UpdateWindow.Changelog = changelog;
UpdateWindow.Singleton.Display = true;
}
}
}
}
else
{
LunaLog.Log($"Could not check for latest version. Error: {www.error}");
}
}
}
}
}
| mit | C# |
86dfc9e440b8f9baaabd327b64b0ef71d76e9e36 | Refactor Elevator to use Dictionary | jmeas/simple-tower | Assets/Scripts/Elevator.cs | Assets/Scripts/Elevator.cs | public class Elevator : UnityEngine.MonoBehaviour {
CinematicMode cinematicMode;
UnityEngine.GameObject player;
// The time it takes the elevator to move up or down, in seconds
float transitionDuration = 1.5f;
// This is the difference in the elevator and player's y position
float playerHeightDiff = 0.0639f;
System.Collections.Generic.Dictionary<string, float> elevatorPositions = new System.Collections.Generic.Dictionary<string, float>() {
{"up", 9.94f},
{"down", 0.12f}
};
void Start() {
UnityEngine.GameObject cinematicModeObj = UnityEngine.GameObject.Find("CinematicMode");
cinematicMode = cinematicModeObj.GetComponent<CinematicMode>();
player = UnityEngine.GameObject.Find("ThirdPersonController");
}
System.Collections.IEnumerator MoveElevator(string direction) {
float endY = elevatorPositions[direction];
UnityEngine.Vector3 destination = new UnityEngine.Vector3(transform.position.x, endY, transform.position.z);
yield return new Transition(gameObject, destination, transitionDuration);
// Cinematic mode began while the elevator was going down. So we need to turn it off.
if (direction == "down") {
cinematicMode.ExitCinematicMode();
}
}
System.Collections.IEnumerator MovePlayer(string direction) {
float endY = elevatorPositions[direction];
endY += playerHeightDiff;
UnityEngine.Vector3 destination = new UnityEngine.Vector3(player.transform.position.x, endY, player.transform.position.z);
yield return new Transition(player, destination, transitionDuration);
}
void OnTriggerEnter(UnityEngine.Collider col) {
if (col.gameObject.name == "ThirdPersonController") {
cinematicMode.EnterCinematicMode();
StartCoroutine(MoveElevator("down"));
StartCoroutine(MovePlayer("down"));
}
}
// This is called by the child when the elevator has been exited
// by the player.
void ExitElevator() {
StopCoroutine("MoveElevator");
StartCoroutine(MoveElevator("up"));
}
}
| public class Elevator : UnityEngine.MonoBehaviour {
CinematicMode cinematicMode;
UnityEngine.GameObject player;
// The time it takes the elevator to move up or down, in seconds
float transitionDuration = 1.5f;
// This is the difference in the elevator and player's y position
float playerHeightDiff = 0.0639f;
void Start() {
UnityEngine.GameObject cinematicModeObj = UnityEngine.GameObject.Find("CinematicMode");
cinematicMode = cinematicModeObj.GetComponent<CinematicMode>();
player = UnityEngine.GameObject.Find("ThirdPersonController");
}
System.Collections.IEnumerator MoveElevator(string direction) {
float endY = direction == "down" ? 0.12f : 9.94f;
UnityEngine.Vector3 destination = new UnityEngine.Vector3(transform.position.x, endY, transform.position.z);
yield return new Transition(gameObject, destination, transitionDuration);
// Cinematic mode began while the elevator was going down. So we need to turn it off.
if (direction == "down") {
cinematicMode.ExitCinematicMode();
}
}
System.Collections.IEnumerator MovePlayer(string direction) {
float endY = direction == "down" ? 0.12f : 9.94f;
endY += playerHeightDiff;
UnityEngine.Vector3 destination = new UnityEngine.Vector3(player.transform.position.x, endY, player.transform.position.z);
yield return new Transition(player, destination, transitionDuration);
}
void OnTriggerEnter(UnityEngine.Collider col) {
if (col.gameObject.name == "ThirdPersonController") {
cinematicMode.EnterCinematicMode();
StartCoroutine(MoveElevator("down"));
StartCoroutine(MovePlayer("down"));
}
}
// This is called by the child when the elevator has been exited
// by the player.
void ExitElevator() {
StopCoroutine("MoveElevator");
StartCoroutine(MoveElevator("up"));
}
}
| mit | C# |
6e630737c12095335bd91408f1de91ea704029db | Fix algorithm not selected when adding a custom coin | nwoolls/MultiMiner,IWBWbiz/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner | MultiMiner.Win/Forms/CoinEditForm.cs | MultiMiner.Win/Forms/CoinEditForm.cs | using MultiMiner.Engine.Data;
using MultiMiner.Utility.Forms;
using MultiMiner.Xgminer.Data;
using MultiMiner.Win.Extensions;
using System;
using MultiMiner.Engine;
namespace MultiMiner.Win.Forms
{
public partial class CoinEditForm : MessageBoxFontForm
{
private readonly CryptoCoin cryptoCoin;
public CoinEditForm(CryptoCoin cryptoCoin)
{
InitializeComponent();
this.cryptoCoin = cryptoCoin;
}
private void CoinEditForm_Load(object sender, EventArgs e)
{
PopulateAlgorithmCombo();
LoadSettings();
}
private void PopulateAlgorithmCombo()
{
algorithmCombo.Items.Clear();
System.Collections.Generic.List<CoinAlgorithm> algorithms = MinerFactory.Instance.Algorithms;
foreach (CoinAlgorithm algorithm in algorithms)
algorithmCombo.Items.Add(algorithm.Name.ToSpaceDelimitedWords());
}
private void saveButton_Click(object sender, EventArgs e)
{
if (!ValidateInput())
return;
SaveSettings();
DialogResult = System.Windows.Forms.DialogResult.OK;
}
private bool ValidateInput()
{
//require a symbol be specified, symbol is used throughout the app
if (String.IsNullOrEmpty(cryptoCoin.Symbol))
{
symbolEdit.Focus();
return false;
}
return true;
}
private void LoadSettings()
{
algorithmCombo.Text = cryptoCoin.Algorithm.ToSpaceDelimitedWords();
cryptoCoinBindingSource.DataSource = cryptoCoin;
}
private void SaveSettings()
{
cryptoCoin.Algorithm = algorithmCombo.Text;
}
}
}
| using MultiMiner.Engine.Data;
using MultiMiner.Utility.Forms;
using MultiMiner.Xgminer.Data;
using MultiMiner.Win.Extensions;
using System;
using MultiMiner.Engine;
namespace MultiMiner.Win.Forms
{
public partial class CoinEditForm : MessageBoxFontForm
{
private readonly CryptoCoin cryptoCoin;
public CoinEditForm(CryptoCoin cryptoCoin)
{
InitializeComponent();
this.cryptoCoin = cryptoCoin;
}
private void CoinEditForm_Load(object sender, EventArgs e)
{
PopulateAlgorithmCombo();
LoadSettings();
}
private void PopulateAlgorithmCombo()
{
algorithmCombo.Items.Clear();
System.Collections.Generic.List<CoinAlgorithm> algorithms = MinerFactory.Instance.Algorithms;
foreach (CoinAlgorithm algorithm in algorithms)
algorithmCombo.Items.Add(algorithm.Name.ToSpaceDelimitedWords());
}
private void saveButton_Click(object sender, EventArgs e)
{
if (!ValidateInput())
return;
SaveSettings();
DialogResult = System.Windows.Forms.DialogResult.OK;
}
private bool ValidateInput()
{
//require a symbol be specified, symbol is used throughout the app
if (String.IsNullOrEmpty(cryptoCoin.Symbol))
{
symbolEdit.Focus();
return false;
}
return true;
}
private void LoadSettings()
{
algorithmCombo.Text = cryptoCoin.Algorithm;
cryptoCoinBindingSource.DataSource = cryptoCoin;
}
private void SaveSettings()
{
cryptoCoin.Algorithm = algorithmCombo.Text;
}
}
}
| mit | C# |
fa6f61bd326bc71e39a67177233057f4ea708a58 | Delete comment | bigfont/StackOverflow,bigfont/StackOverflow,bigfont/StackOverflow,bigfont/StackOverflow | AspNetCoreUriToAssoc/Startup.cs | AspNetCoreUriToAssoc/Startup.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace AspNetCoreUriToAssoc
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddMvcOptions(options =>
options.ValueProviderFactories.Add(new PathValueProviderFactory()));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc(routes => {
routes.MapRoute(
name: "properties-search",
template: "{controller=Properties}/{action=Search}/{*path}"
);
});
}
}
}
| using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace AspNetCoreUriToAssoc
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddMvcOptions(options =>
options.ValueProviderFactories.Add(new PathValueProviderFactory()));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc(routes => {
routes.MapRoute(
name: "properties-search",
template: "{controller=Properties}/{action=Search}/{*path}"
);
});
}
}
}
| mit | C# |
f4d6eadf7be551e8d037313fe3cd1ea4b4fa6c1f | Add dataTransferManager to Windows app. | wangjun/windows-app,wangjun/windows-app | wallabag/wallabag.Windows/Views/ItemPage.xaml.cs | wallabag/wallabag.Windows/Views/ItemPage.xaml.cs | using System;
using wallabag.Common;
using wallabag.ViewModel;
using Windows.ApplicationModel.DataTransfer;
using Windows.System;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace wallabag.Views
{
public sealed partial class ItemPage : basicPage
{
public ItemPage()
{
this.InitializeComponent();
backButton.Command = this.navigationHelper.GoBackCommand;
var dataTransferManager = DataTransferManager.GetForCurrentView();
dataTransferManager.DataRequested += dataTransferManager_DataRequested;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter != null)
this.DataContext = new ItemPageViewModel(e.Parameter as ItemViewModel);
base.OnNavigatedTo(e);
}
void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
DataRequest request = args.Request;
request.Data.Properties.Title = ((this.DataContext as ItemPageViewModel).Item as ItemViewModel).Title;
request.Data.SetWebLink(((this.DataContext as ItemPageViewModel).Item as ItemViewModel).Url);
}
private async void webView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
// Opens links in the Internet Explorer and not in the webView.
if (args.Uri != null && args.Uri.AbsoluteUri.StartsWith("http"))
{
args.Cancel = true;
await Launcher.LaunchUriAsync(new Uri(args.Uri.AbsoluteUri));
}
}
}
}
| using System;
using wallabag.Common;
using wallabag.ViewModel;
using Windows.ApplicationModel.DataTransfer;
using Windows.System;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace wallabag.Views
{
public sealed partial class ItemPage : basicPage
{
public ItemPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter != null)
this.DataContext = new ItemPageViewModel(e.Parameter as ItemViewModel);
base.OnNavigatedTo(e);
}
void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
DataRequest request = args.Request;
request.Data.Properties.Title = ((this.DataContext as ItemPageViewModel).Item as ItemViewModel).Title;
request.Data.SetWebLink(((this.DataContext as ItemPageViewModel).Item as ItemViewModel).Url);
}
private async void webView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
// Opens links in the Internet Explorer and not in the webView.
if (args.Uri != null && args.Uri.AbsoluteUri.StartsWith("http"))
{
args.Cancel = true;
await Launcher.LaunchUriAsync(new Uri(args.Uri.AbsoluteUri));
}
}
}
}
| mit | C# |
c3cc41b1123247dbaf59dbda615f308439344658 | Use DiplomContext in DI container | denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs | src/Diploms.WebUI/Startup.cs | src/Diploms.WebUI/Startup.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Diploms.DataLayer;
using Diploms.WebUI.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Diploms.WebUI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDepartments();
services.AddDbContext<DiplomContext>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Diploms.WebUI.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Diploms.WebUI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDepartments();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
}
}
| mit | C# |
f158aabe70b4b9d332bbd53964f9cdca352c8bce | Update ConvertXLSFileToPDF.cs | aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Articles/ConvertXLSFileToPDF.cs | Examples/CSharp/Articles/ConvertXLSFileToPDF.cs | using System;
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class ConvertXLSFileToPDF
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
try
{
//Get the template excel file path.
string designerFile = dataDir + "SampleInput.xlsx";
//Specify the pdf file path.
string pdfFile = dataDir + "Output.out.pdf";
//Create a new Workbook.
//Open the template excel file which you have to
Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook(designerFile);
//Save the pdf file.
wb.Save(pdfFile, SaveFormat.Pdf);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
//ExEnd:1
}
}
}
| using System;
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class ConvertXLSFileToPDF
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
try
{
//Get the template excel file path.
string designerFile = dataDir + "SampleInput.xlsx";
//Specify the pdf file path.
string pdfFile = dataDir + "Output.out.pdf";
//Create a new Workbook.
//Open the template excel file which you have to
Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook(designerFile);
//Save the pdf file.
wb.Save(pdfFile, SaveFormat.Pdf);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
}
| mit | C# |
dbf0727c986faea694057019948a40a6af3542a5 | change version | mika-f/Sagitta | Source/Sagitta/Clients/FileClient.cs | Source/Sagitta/Clients/FileClient.cs | using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Sagitta.Extensions;
namespace Sagitta.Clients
{
/// <summary>
/// 画像およびファイルへの間接的なアクセスを提供します。
/// </summary>
public class FileClient : ApiClient
{
private readonly HttpClient _httpClient;
/// <inheritdoc />
internal FileClient(PixivClient pixivClient) : base(pixivClient)
{
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("App-OS-Version", PixivClient.OsVersion);
_httpClient.DefaultRequestHeaders.Add("App-OS", "ios");
_httpClient.DefaultRequestHeaders.Add("App-Version", PixivClient.AppVersion);
_httpClient.DefaultRequestHeaders.Add("User-Agent", $"PixivIOSApp/{PixivClient.AppVersion} (iOS {PixivClient.OsVersion}; iPhone11,2)");
_httpClient.DefaultRequestHeaders.Referrer = new Uri("https://app-api.pixiv.net/");
}
/// <summary>
/// 指定した URL の画像を取得します。
/// **Pixiv の画像およびうごイラなどの ZIP ファイルは、指定された方法以外で取得することは出来ません。**
/// </summary>
/// <param name="url">Pximg URL</param>
/// <returns>バイナリ Stream</returns>
public async Task<Stream> GetAsync(string url)
{
var response = await _httpClient.GetAsync(url).Stay();
return await response.Content.ReadAsStreamAsync().Stay();
}
}
} | using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Sagitta.Extensions;
namespace Sagitta.Clients
{
/// <summary>
/// 画像およびファイルへの間接的なアクセスを提供します。
/// </summary>
public class FileClient : ApiClient
{
private readonly HttpClient _httpClient;
/// <inheritdoc />
internal FileClient(PixivClient pixivClient) : base(pixivClient)
{
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("App-OS-Version", PixivClient.OsVersion);
_httpClient.DefaultRequestHeaders.Add("App-OS", "ios");
_httpClient.DefaultRequestHeaders.Add("App-Version", PixivClient.AppVersion);
_httpClient.DefaultRequestHeaders.Add("User-Agent", $"PixivIOSApp/{PixivClient.AppVersion} (iOS {PixivClient.OsVersion}; iPhone7,2)");
_httpClient.DefaultRequestHeaders.Referrer = new Uri("https://app-api.pixiv.net/");
}
/// <summary>
/// 指定した URL の画像を取得します。
/// **Pixiv の画像およびうごイラなどの ZIP ファイルは、指定された方法以外で取得することは出来ません。**
/// </summary>
/// <param name="url">Pximg URL</param>
/// <returns>バイナリ Stream</returns>
public async Task<Stream> GetAsync(string url)
{
var response = await _httpClient.GetAsync(url).Stay();
return await response.Content.ReadAsStreamAsync().Stay();
}
}
} | mit | C# |
28acf0ae74128d2d13cc39197ba2ad416033aa61 | Add the default constructor, eventually needed for migrations. | jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr | src/HelloWorldDbContext.cs | src/HelloWorldDbContext.cs | using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace HelloWorldApp
{
public class HelloWorldDbContext : DbContext, IHelloWorldDbContext
{
public HelloWorldDbContext()
{ }
public HelloWorldDbContext(DbContextOptions<HelloWorldDbContext> options)
: base(options)
{ }
public DbSet<Greeting> Greetings { get; set; }
public async Task SaveChangesAsync()
{
await base.SaveChangesAsync();
}
public async Task EnsureCreatedAsync()
{
await Database.EnsureCreatedAsync();
}
}
} | using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace HelloWorldApp
{
public class HelloWorldDbContext : DbContext, IHelloWorldDbContext
{
public HelloWorldDbContext(DbContextOptions<HelloWorldDbContext> options)
: base(options)
{ }
public DbSet<Greeting> Greetings { get; set; }
public async Task SaveChangesAsync()
{
await base.SaveChangesAsync();
}
public async Task EnsureCreatedAsync()
{
await Database.EnsureCreatedAsync();
}
}
} | mit | C# |
3fb613d2af39bce9f082dde27452332606f4e99e | Fix not obfuscating correct FullName when flattening namespaces | HalidCisse/ConfuserEx,apexrichard/ConfuserEx,mirbegtlax/ConfuserEx,JPVenson/ConfuserEx,jbeshir/ConfuserEx,Desolath/ConfuserEx3,farmaair/ConfuserEx,timnboys/ConfuserEx,Desolath/Confuserex,MetSystem/ConfuserEx,KKKas/ConfuserEx,AgileJoshua/ConfuserEx,arpitpanwar/ConfuserEx,HalidCisse/ConfuserEx,mirbegtlax/ConfuserEx,yuligang1234/ConfuserEx,yeaicc/ConfuserEx,manojdjoshi/ConfuserEx,modulexcite/ConfuserEx,fretelweb/ConfuserEx,engdata/ConfuserEx,Immortal-/ConfuserEx,yuligang1234/ConfuserEx,JPVenson/ConfuserEx | Confuser.Renamer/RenamePhase.cs | Confuser.Renamer/RenamePhase.cs | using System.Collections.Generic;
using System.Linq;
using Confuser.Core;
using dnlib.DotNet;
namespace Confuser.Renamer {
internal class RenamePhase : ProtectionPhase {
public RenamePhase(NameProtection parent)
: base(parent) { }
public override ProtectionTargets Targets {
get { return ProtectionTargets.AllDefinitions; }
}
protected override void Execute(ConfuserContext context, ProtectionParameters parameters) {
var service = (NameService) context.Registry.GetService<INameService>();
context.Logger.Debug("Renaming...");
foreach (IRenamer renamer in service.Renamers) {
foreach (IDnlibDef def in parameters.Targets)
renamer.PreRename(context, service, def);
}
foreach (IDnlibDef def in parameters.Targets) {
if (def is MethodDef)
if (parameters.GetParameter(context, def, "renameArgs", true)) {
foreach (ParamDef param in ((MethodDef) def).ParamDefs)
param.Name = null;
}
if (!service.CanRename(def))
continue;
RenameMode mode = service.GetRenameMode(def);
IList<INameReference> references = service.GetReferences(def);
bool cancel = false;
foreach (INameReference refer in references) {
cancel |= refer.ShouldCancelRename();
if (cancel) break;
}
if (cancel)
continue;
if (def is TypeDef) {
var typeDef = (TypeDef) def;
if (parameters.GetParameter(context, def, "flatten", true)) {
typeDef.Name = service.ObfuscateName(typeDef.FullName, mode);
typeDef.Namespace = "";
}
else {
typeDef.Namespace = service.ObfuscateName(typeDef.Namespace, mode);
typeDef.Name = service.ObfuscateName(typeDef.Name, mode);
}
}
else
def.Name = service.ObfuscateName(def.Name, mode);
foreach (INameReference refer in references.ToList()) {
if (!refer.UpdateNameReference(context, service)) {
context.Logger.ErrorFormat("Failed to update name reference on '{0}'.", def);
throw new ConfuserException(null);
}
}
}
}
}
} | using System.Collections.Generic;
using System.Linq;
using Confuser.Core;
using dnlib.DotNet;
namespace Confuser.Renamer {
internal class RenamePhase : ProtectionPhase {
public RenamePhase(NameProtection parent)
: base(parent) { }
public override ProtectionTargets Targets {
get { return ProtectionTargets.AllDefinitions; }
}
protected override void Execute(ConfuserContext context, ProtectionParameters parameters) {
var service = (NameService) context.Registry.GetService<INameService>();
context.Logger.Debug("Renaming...");
foreach (IRenamer renamer in service.Renamers) {
foreach (IDnlibDef def in parameters.Targets)
renamer.PreRename(context, service, def);
}
foreach (IDnlibDef def in parameters.Targets) {
if (def is MethodDef)
if (parameters.GetParameter(context, def, "renameArgs", true)) {
foreach (ParamDef param in ((MethodDef) def).ParamDefs)
param.Name = null;
}
if (!service.CanRename(def))
continue;
RenameMode mode = service.GetRenameMode(def);
IList<INameReference> references = service.GetReferences(def);
bool cancel = false;
foreach (INameReference refer in references) {
cancel |= refer.ShouldCancelRename();
if (cancel) break;
}
if (cancel)
continue;
if (def is TypeDef) {
var typeDef = (TypeDef) def;
if (parameters.GetParameter(context, def, "flatten", true)) {
typeDef.Namespace = "";
typeDef.Name = service.ObfuscateName(typeDef.FullName, mode);
}
else {
typeDef.Namespace = service.ObfuscateName(typeDef.Namespace, mode);
typeDef.Name = service.ObfuscateName(typeDef.Name, mode);
}
}
else
def.Name = service.ObfuscateName(def.Name, mode);
foreach (INameReference refer in references.ToList()) {
if (!refer.UpdateNameReference(context, service)) {
context.Logger.ErrorFormat("Failed to update name reference on '{0}'.", def);
throw new ConfuserException(null);
}
}
}
}
}
} | mit | C# |
7d0227426566cb502ef03a8035486d6ec8f14c69 | migrate and seed on startup | tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web | src/Tugberk.Web/Startup.cs | src/Tugberk.Web/Startup.cs | using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Tugberk.Persistance.Abstractions;
using Tugberk.Persistance.InMemory;
using Tugberk.Persistance.SqlServer;
using Tugberk.Web.Controllers;
namespace Tugberk.Web
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IImageStorage, LocalImageStorage>();
services.AddMvc();
services.Configure<RouteOptions>(options => options.LowercaseUrls = true);
services.AddScoped<IPostsStore, InMemoryPostsStore>();
services.AddDbContext<BlogDbContext>(options =>
options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
MigrateAndEnsureDataIsSeeded(app);
}
private void MigrateAndEnsureDataIsSeeded(IApplicationBuilder app)
{
// https://blogs.msdn.microsoft.com/dotnet/2016/09/29/implementing-seeding-custom-conventions-and-interceptors-in-ef-core-1-0/
using(var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<BlogDbContext>();
var userManager = serviceScope.ServiceProvider.GetService<UserManager<IdentityUser>>();
context.Database.Migrate();
context.EnsureSeedData(userManager);
}
}
}
public static class BlogDbContextExtensions
{
public static void EnsureSeedData(this BlogDbContext context, UserManager<IdentityUser> userManager)
{
if(!context.Users.AnyAsync().Result)
{
var defaultUser = new IdentityUser
{
UserName = "default",
Email = "foo@example.com"
};
userManager.CreateAsync(defaultUser, "P@asW0rd").Wait();
}
}
}
}
| using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Tugberk.Persistance.Abstractions;
using Tugberk.Persistance.InMemory;
using Tugberk.Persistance.SqlServer;
using Tugberk.Web.Controllers;
namespace Tugberk.Web
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IImageStorage, LocalImageStorage>();
services.AddMvc();
services.Configure<RouteOptions>(options => options.LowercaseUrls = true);
services.AddScoped<IPostsStore, InMemoryPostsStore>();
services.AddDbContext<BlogDbContext>(options =>
options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
}
| agpl-3.0 | C# |
eed0ba16abf8e7dd9d2d5e32a678a8e4fb3ebc57 | Bump version 1.1.0 | tugberkugurlu/Owin.Limits,damianh/LimitsMiddleware,damianh/LimitsMiddleware | src/SharedAssemblyInfo.cs | src/SharedAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Damian Hickey")]
[assembly: AssemblyProduct("Owin.Limits")]
[assembly: AssemblyCopyright("Copyright © Damian Hickey 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| using System.Reflection;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Damian Hickey")]
[assembly: AssemblyProduct("Owin.Limits")]
[assembly: AssemblyCopyright("Copyright © Damian Hickey 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
| mit | C# |
c822b83eb05efa62b497f961a2d26cc234957b8e | Add nullcheck | effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer | Dev/Editor/Effekseer/GUI/ThumbnailManager.cs | Dev/Editor/Effekseer/GUI/ThumbnailManager.cs | using Effekseer.swig;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Effekseer.GUI
{
class Thumbnail
{
public swig.ImageResource Image = null;
}
class ThumbnailManager
{
class IOCallback : swig.IOCallback
{
public override void OnFileChanged(StaticFileType fileType, string path)
{
if(thumbnails.ContainsKey(path))
{
thumbnails[path].Image.Invalidate();
thumbnails[path].Image.Validate();
}
}
}
static IOCallback callback = new IOCallback();
static Dictionary<string, Thumbnail> thumbnails = new Dictionary<string, Thumbnail>();
public static Thumbnail Load(string path)
{
if (!System.IO.Path.IsPathRooted(path))
throw new Exception("Not root");
if(thumbnails.ContainsKey(path))
{
return thumbnails[path];
}
var image = Manager.Native.LoadImageResource(path);
if (image == null) return null;
Thumbnail thumbnail = new Thumbnail();
thumbnail.Image = image;
thumbnails.Add(path, thumbnail);
return thumbnail;
}
internal static void Initialize()
{
Manager.IO.AddCallback(callback);
}
internal static void Terminate()
{
foreach(var th in thumbnails)
{
th.Value.Image.Dispose();
}
thumbnails.Clear();
}
}
}
| using Effekseer.swig;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Effekseer.GUI
{
class Thumbnail
{
public swig.ImageResource Image = null;
}
class ThumbnailManager
{
class IOCallback : swig.IOCallback
{
public override void OnFileChanged(StaticFileType fileType, string path)
{
if(thumbnails.ContainsKey(path))
{
thumbnails[path].Image.Invalidate();
thumbnails[path].Image.Validate();
}
}
}
static IOCallback callback = new IOCallback();
static Dictionary<string, Thumbnail> thumbnails = new Dictionary<string, Thumbnail>();
public static Thumbnail Load(string path)
{
if (!System.IO.Path.IsPathRooted(path))
throw new Exception("Not root");
if(thumbnails.ContainsKey(path))
{
return thumbnails[path];
}
var image = Manager.Native.LoadImageResource(path);
Thumbnail thumbnail = new Thumbnail();
thumbnail.Image = image;
thumbnails.Add(path, thumbnail);
return thumbnail;
}
internal static void Initialize()
{
Manager.IO.AddCallback(callback);
}
internal static void Terminate()
{
foreach(var th in thumbnails)
{
th.Value.Image.Dispose();
}
thumbnails.Clear();
}
}
}
| mit | C# |
1f40845a917c20459d9a0594478393fa092cb0bf | Fix doc comment | skizzerz/DiceRoller | DiceRoller/MacroContext.cs | DiceRoller/MacroContext.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dice
{
/// <summary>
/// Contains the context of a macro execution, to be filled out
/// by the function which is responsible for executing the macro.
/// </summary>
public class MacroContext
{
/// <summary>
/// The overall value of the macro.
/// </summary>
public decimal Value { get; set; }
/// <summary>
/// What sort of value the macro returns.
/// </summary>
public ResultType ValueType { get; set; }
/// <summary>
/// If the macro rolls any dice, it should add their results to this list.
/// If the macro does not roll dice, this need not be touched. If null or empty,
/// a Literal DieResult will be inserted with its value set to Value.
/// </summary>
public IEnumerable<DieResult> Values { get; set; }
/// <summary>
/// The parameter passed to the macro. The function is responsible for
/// parsing this into something usable.
/// </summary>
public string Param { get; private set; }
/// <summary>
/// The name of the macro, if using the recommended method of separating arguments with colons.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// The arguments of the macro (including the name), if using the recommended method of separating
/// arguments with colons.
/// </summary>
public IReadOnlyList<string> Arguments { get; private set; }
/// <summary>
/// RollData attached to this macro execution
/// </summary>
public RollData Data { get; private set; }
internal MacroContext(string param, RollData data)
{
Value = Decimal.MinValue;
Values = null;
ValueType = ResultType.Total;
Param = param;
Data = data;
// parse Param
Param = Param.Trim();
string[] args = Param.Split(':');
for (int i = 0; i < args.Length; i++)
{
args[i] = args[i].Trim();
}
Name = args[0];
Arguments = args;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dice
{
/// <summary>
/// Contains the context of a macro execution, to be filled out
/// by the function which is responsible for executing the macro.
/// </summary>
public class MacroContext
{
/// <summary>
/// The overall value of the macro.
/// </summary>
public decimal Value { get; set; }
/// <summary>
/// What sort of value the macro returns.
/// </summary>
public ResultType ValueType { get; set; }
/// <summary>
/// If the macro rolls any dice, it should add their results to this list.
/// If the macro does not roll dice, this need not be touched. If null or empty,
/// a Literal DieResult will be inserted with its value set to Value.
/// </summary>
public IEnumerable<DieResult> Values { get; set; }
/// <summary>
/// The parameter passed to the macro. The function is responsible for
/// parsing this into something usable.
/// </summary>
public string Param { get; private set; }
/// <summary>
/// The name of the macro, if using the recommended method of separating arguments with colons.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// The arguments of the macro (including the name), if using the recommended method of separating
/// arguments with colons.
/// </summary>
public IReadOnlyList<string> Arguments { get; private set; }
/// <summary>
/// RollData attached to this function execution
/// </summary>
public RollData Data { get; private set; }
internal MacroContext(string param, RollData data)
{
Value = Decimal.MinValue;
Values = null;
ValueType = ResultType.Total;
Param = param;
Data = data;
// parse Param
Param = Param.Trim();
string[] args = Param.Split(':');
for (int i = 0; i < args.Length; i++)
{
args[i] = args[i].Trim();
}
Name = args[0];
Arguments = args;
}
}
}
| mit | C# |
a73949f714b261f3347d4700bab8d6efe46d0db4 | Check for ERROR anywhere in the response | mycroes/SupportManager,mycroes/SupportManager,mycroes/SupportManager | MYCroes.ATCommands/ATCommand.cs | MYCroes.ATCommands/ATCommand.cs | using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MYCroes.ATCommands
{
public class ATCommand
{
private const string AT_OK = "OK";
private const string AT_ERROR = "ERROR";
public string Command { get; }
public IEnumerable<ATCommandArgument> Arguments { get; }
public ATCommand(string command, IEnumerable<ATCommandArgument> arguments)
{
Command = command;
Arguments = arguments;
}
public ATCommand(string command, params ATCommandArgument[] arguments)
: this(command, arguments.AsEnumerable())
{
}
public static implicit operator string (ATCommand atCommand)
{
return atCommand.Command + "=" + string.Join(",", atCommand.Arguments);
}
public string[] Execute(Stream stream)
{
var chat = new ATChat(stream);
return ExecuteCore(chat).ToArray();
}
protected virtual IEnumerable<string> ExecuteCore(ATChat chat)
{
WriteCommand(chat);
return ReadResponse(chat);
}
protected IEnumerable<string> ReadResponse(ATChat chat)
{
string responsePrefix = Command + ": ";
var lines = new List<string>();
foreach (var line in chat.ReadLines())
{
lines.Add(line);
if (line.StartsWith(responsePrefix))
{
yield return line.Substring(responsePrefix.Length);
continue;
}
if (line == AT_OK) yield break;
if (line.Contains(AT_ERROR))
{
throw new ATCommandException(lines);
}
}
throw new ATCommandException(lines);
}
protected void WriteCommand(ATChat chat)
{
chat.WriteLine("AT" + Command + "=" + string.Join(",", Arguments));
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MYCroes.ATCommands
{
public class ATCommand
{
private const string AT_OK = "OK";
private const string AT_ERROR = "ERROR";
public string Command { get; }
public IEnumerable<ATCommandArgument> Arguments { get; }
public ATCommand(string command, IEnumerable<ATCommandArgument> arguments)
{
Command = command;
Arguments = arguments;
}
public ATCommand(string command, params ATCommandArgument[] arguments)
: this(command, arguments.AsEnumerable())
{
}
public static implicit operator string (ATCommand atCommand)
{
return atCommand.Command + "=" + string.Join(",", atCommand.Arguments);
}
public string[] Execute(Stream stream)
{
var chat = new ATChat(stream);
return ExecuteCore(chat).ToArray();
}
protected virtual IEnumerable<string> ExecuteCore(ATChat chat)
{
WriteCommand(chat);
return ReadResponse(chat);
}
protected IEnumerable<string> ReadResponse(ATChat chat)
{
string responsePrefix = Command + ": ";
var lines = new List<string>();
foreach (var line in chat.ReadLines())
{
lines.Add(line);
if (line.StartsWith(responsePrefix))
{
yield return line.Substring(responsePrefix.Length);
continue;
}
if (line == AT_OK) yield break;
if (line.EndsWith(AT_ERROR))
{
throw new ATCommandException(lines);
}
}
throw new ATCommandException(lines);
}
protected void WriteCommand(ATChat chat)
{
chat.WriteLine("AT" + Command + "=" + string.Join(",", Arguments));
}
}
}
| mit | C# |
2b011871409fbfd7b44438817934cf4c461d967d | Update VotingRequest.cs | bdjukic/glasajDijasporo,bdjukic/glasajDijasporo,bdjukic/glasajDijasporo | GlasajDijasporo/GlasajDijasporoService/Models/VotingRequest.cs | GlasajDijasporo/GlasajDijasporoService/Models/VotingRequest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GlasajDijasporoService.Model
{
public class VotingRequest
{
public string FirstLastName { get; set; }
public string BirthPlace { get; set; }
public string BirthDate { get; set; }
public string Gender { get; set; }
public string ParentName { get; set; }
public string PersonalId { get; set; }
public string PassportId { get; set; }
public string HomeCountryAddress { get; set; }
public string TemporaryAddress { get; set; }
public string ForeignCountryName { get; set; }
public string ForeignCountryAddress { get; set; }
public string VotingLocation { get; set; }
public string CurrentLocation { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
public string Signature { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GlasajDijasporoService.Model
{
public class VotingRequest
{
public string FirstLastName { get; set; }
public string BirthPlaceDate { get; set; }
public string Gender { get; set; }
public string ParentName { get; set; }
public string PersonalId { get; set; }
public string PassportId { get; set; }
public string HomeCountryAddress { get; set; }
public string TemporaryAddress { get; set; }
public string ForeignCountryName { get; set; }
public string ForeignCountryAddress { get; set; }
public string VotingLocation { get; set; }
public string CurrentLocation { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
public string Signature { get; set; }
}
} | apache-2.0 | C# |
46d9eb13069e83a23f844648cfb2f98d684aa1d8 | Package update | Azure/azure-iot-hub-vs-cs,Azure/azure-iot-hub-vs-cs,Azure/azure-iot-hub-vs-cs | AzureIoTHubConnectedServiceLibrary/Handler.CSharp.WAC.cs | AzureIoTHubConnectedServiceLibrary/Handler.CSharp.WAC.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See license.txt file in the project root for full license information.
using System;
using Microsoft.VisualStudio.ConnectedServices;
namespace AzureIoTHubConnectedService
{
[ConnectedServiceHandlerExport("Microsoft.AzureIoTHubService",
AppliesTo = "CSharp+WindowsAppContainer")]
internal class CSharpHandlerWAC : GenericAzureIoTHubServiceHandler
{
protected override HandlerManifest BuildHandlerManifest(ConnectedServiceHandlerContext context)
{
HandlerManifest manifest = new HandlerManifest();
manifest.PackageReferences.Add(new NuGetReference("Newtonsoft.Json", "6.0.8"));
manifest.PackageReferences.Add(new NuGetReference("Microsoft.Azure.Devices.Client", "1.0.2"));
manifest.Files.Add(new FileToAdd("CSharp/AzureIoTHub.cs"));
return manifest;
}
protected override AddServiceInstanceResult CreateAddServiceInstanceResult(ConnectedServiceHandlerContext context)
{
return new AddServiceInstanceResult(
context.ServiceInstance.Name,
new Uri("http://aka.ms/azure-iot-connected-service-cs")
);
}
protected override ConnectedServiceHandlerHelper GetConnectedServiceHandlerHelper(ConnectedServiceHandlerContext context)
{
return context.HandlerHelper;
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See license.txt file in the project root for full license information.
using System;
using Microsoft.VisualStudio.ConnectedServices;
namespace AzureIoTHubConnectedService
{
[ConnectedServiceHandlerExport("Microsoft.AzureIoTHubService",
AppliesTo = "CSharp+WindowsAppContainer")]
internal class CSharpHandlerWAC : GenericAzureIoTHubServiceHandler
{
protected override HandlerManifest BuildHandlerManifest(ConnectedServiceHandlerContext context)
{
HandlerManifest manifest = new HandlerManifest();
manifest.PackageReferences.Add(new NuGetReference("Newtonsoft.Json", "6.0.8"));
manifest.PackageReferences.Add(new NuGetReference("Microsoft.Azure.Devices.Client", "1.0.1"));
manifest.Files.Add(new FileToAdd("CSharp/AzureIoTHub.cs"));
return manifest;
}
protected override AddServiceInstanceResult CreateAddServiceInstanceResult(ConnectedServiceHandlerContext context)
{
return new AddServiceInstanceResult(
context.ServiceInstance.Name,
new Uri("http://aka.ms/azure-iot-connected-service-cs")
);
}
protected override ConnectedServiceHandlerHelper GetConnectedServiceHandlerHelper(ConnectedServiceHandlerContext context)
{
return context.HandlerHelper;
}
}
}
| mit | C# |
d1c480c197eee7e1d2e367b19759efedc1e0cbef | fix test for Sitecore 7 (Old JObject version) | dharnitski/Sitecore.Algolia | Score.ContentSearch.Algolia.Tests/AlgoliaUpdateContextTests.cs | Score.ContentSearch.Algolia.Tests/AlgoliaUpdateContextTests.cs | using System.Collections.Generic;
using System.Linq;
using Moq;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using Score.ContentSearch.Algolia.Abstract;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq.Common;
namespace Score.ContentSearch.Algolia.Tests
{
[TestFixture]
public class AlgoliaUpdateContextTests
{
[TestCase(1, 1)]
[TestCase(100, 1)]
[TestCase(101, 2)]
public void ShouldChunkUpdate(int docCount, int chunksCount)
{
//Arrange
var repository = new Mock<IAlgoliaRepository>();
var index = new Mock<ISearchIndex>();
var sut = new AlgoliaUpdateContext(index.Object, repository.Object);
for (int i = 0; i < docCount; i++)
{
sut.AddDocument(JObject.Parse("{\"objectID\": \"" + i + "\"}"), (IExecutionContext) null);
}
//Act
sut.Commit();
//Assert
repository.Verify(t => t.SaveObjectsAsync(It.Is<IEnumerable<JObject>>(o => o.Any())),
Times.Exactly(chunksCount));
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Moq;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using Score.ContentSearch.Algolia.Abstract;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq.Common;
namespace Score.ContentSearch.Algolia.Tests
{
[TestFixture]
public class AlgoliaUpdateContextTests
{
[TestCase(1, 1)]
[TestCase(100, 1)]
[TestCase(101, 2)]
public void ShouldChunkUpdate(int docCount, int chunksCount)
{
//Arrange
var repository = new Mock<IAlgoliaRepository>();
var index = new Mock<ISearchIndex>();
var sut = new AlgoliaUpdateContext(index.Object, repository.Object);
for (int i = 0; i < docCount; i++)
{
sut.AddDocument(JObject.Parse("{\"objectID\": " + i + "}"), (IExecutionContext) null);
}
//Act
sut.Commit();
//Assert
repository.Verify(t => t.SaveObjectsAsync(It.Is<IEnumerable<JObject>>(o => o.Any())),
Times.Exactly(chunksCount));
}
}
}
| mit | C# |
ab347a38b9a33151fe1f887319c756c1a0aecd75 | Put Linfu's proxyfactory as a (static) field making it more visible it caches the proxytypes. | RogerKratz/mbcache | MbCache.ProxyImpl.LinFu/LinfuProxyFactory.cs | MbCache.ProxyImpl.LinFu/LinfuProxyFactory.cs | using System;
using LinFu.DynamicProxy;
using MbCache.Configuration;
using MbCache.Core;
using MbCache.Logic;
namespace MbCache.ProxyImpl.LinFu
{
[Serializable]
public class LinFuProxyFactory : IProxyFactory
{
private CacheAdapter _cache;
private ICacheKey _cacheKey;
private ILockObjectGenerator _lockObjectGenerator;
private static readonly ProxyFactory _proxyFactory = new ProxyFactory();
public void Initialize(CacheAdapter cache, ICacheKey cacheKey, ILockObjectGenerator lockObjectGenerator)
{
_cache = cache;
_cacheKey = cacheKey;
_lockObjectGenerator = lockObjectGenerator;
}
public T CreateProxy<T>(ConfigurationForType methodData, params object[] parameters) where T : class
{
var target = createTarget<T>(methodData.ConcreteType, parameters);
var interceptor = new CacheInterceptor(_cache, _cacheKey, _lockObjectGenerator, typeof(T), methodData, target);
return _proxyFactory.CreateProxy<T>(interceptor, typeof(ICachingComponent));
}
private static object createTarget<T>(Type type, object[] ctorParameters)
{
try
{
return Activator.CreateInstance(type, ctorParameters);
}
catch (MissingMethodException ex)
{
var ctorParamMessage = "Incorrect number of parameters to ctor for type " + type;
throw new ArgumentException(ctorParamMessage, ex);
}
}
public bool AllowNonVirtualMember
{
get { return false; }
}
}
} | using System;
using LinFu.DynamicProxy;
using MbCache.Configuration;
using MbCache.Core;
using MbCache.Logic;
namespace MbCache.ProxyImpl.LinFu
{
[Serializable]
public class LinFuProxyFactory : IProxyFactory
{
private CacheAdapter _cache;
private ICacheKey _cacheKey;
private ILockObjectGenerator _lockObjectGenerator;
public void Initialize(CacheAdapter cache, ICacheKey cacheKey, ILockObjectGenerator lockObjectGenerator)
{
_cache = cache;
_cacheKey = cacheKey;
_lockObjectGenerator = lockObjectGenerator;
}
public T CreateProxy<T>(ConfigurationForType methodData, params object[] parameters) where T : class
{
var proxyFactory = new ProxyFactory();
var target = createTarget<T>(methodData.ConcreteType, parameters);
var interceptor = new CacheInterceptor(_cache, _cacheKey, _lockObjectGenerator, typeof(T), methodData, target);
return proxyFactory.CreateProxy<T>(interceptor, typeof(ICachingComponent));
}
private static object createTarget<T>(Type type, object[] ctorParameters)
{
try
{
return Activator.CreateInstance(type, ctorParameters);
}
catch (MissingMethodException ex)
{
var ctorParamMessage = "Incorrect number of parameters to ctor for type " + type;
throw new ArgumentException(ctorParamMessage, ex);
}
}
public bool AllowNonVirtualMember
{
get { return false; }
}
}
} | mit | C# |
6319d4f3690fbd19fcbfa0a46fed2ea6470edb65 | Fix unit test for changed implementation | charlenni/Mapsui,charlenni/Mapsui | Tests/Mapsui.Nts.Tests/Extensions/CoordinateExtensionsTests.cs | Tests/Mapsui.Nts.Tests/Extensions/CoordinateExtensionsTests.cs | using System.Collections.Generic;
using NetTopologySuite.Geometries;
using NUnit.Framework;
using Mapsui.Nts.Extensions;
using System;
namespace Mapsui.Nts.Tests;
[TestFixture]
public class CoordinateExtensionsTests
{
[Test]
public void ToLineStringShouldNotThrowWhenCoordinatesIsEmpty()
{
// Arrange
IEnumerable<Coordinate> coordinates = new List<Coordinate>();
// Act & Assert
Assert.DoesNotThrow(() => coordinates.ToLineString());
}
}
| using System.Collections.Generic;
using NetTopologySuite.Geometries;
using NUnit.Framework;
using Mapsui.Nts.Extensions;
using System;
namespace Mapsui.Nts.Tests;
[TestFixture]
public class CoordinateExtensionsTests
{
[Test]
public void CoordinateExtensionsShouldThrow()
{
// Arrange
IEnumerable<Coordinate> coordinates = new List<Coordinate>();
// Act & Assert
var lineString = Assert.Throws<Exception>(() => coordinates.ToLineString());
}
}
| mit | C# |
6d86ff307eea5240866545ab4cb363dd2b402fcc | Fix version bump | 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 Audiotica.Data.Collection;
using Audiotica.Data.Collection.SqlHelper;
using Microsoft.Xbox.Music.Platform.Contract.DataModel;
#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 XboxAlbum;
if (album != null) Frame.Navigate(typeof (AlbumPage), album.Id);
}
private void Grid_Tapped(object sender, TappedRoutedEventArgs e)
{
var artist = ((Grid) sender).DataContext as XboxArtist;
if (artist != null) Frame.Navigate(typeof (ArtistPage), artist.Id);
}
}
} | #region
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
using Audiotica.Data.Collection;
using Audiotica.Data.Collection.SqlHelper;
using Microsoft.Xbox.Music.Platform.Contract.DataModel;
#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-patch0";
else
{
ApplicationData.Current.LocalSettings.Values.Add("CurrentBuild", "1409-beta3-patch0");
new MessageDialog(
"Test out saving, deleting and playing songs",
"v1409 (BETA3)").ShowAsync();
}
if (!justUpdated || firstRun) return;
new MessageDialog("-delete songs \n-view albums in collection\n-view artist in collection\n-new notifications", "Beta3")
.ShowAsync();
ApplicationData.Current.LocalSettings.Values["CurrentBuild"] = "1409-beta2-patch0";
}
//TODO [Harry,20140908] move this to view model with RelayCommand
private void ListView_ItemClick(object sender, ItemClickEventArgs e)
{
var album = e.ClickedItem as XboxAlbum;
if (album != null) Frame.Navigate(typeof (AlbumPage), album.Id);
}
private void Grid_Tapped(object sender, TappedRoutedEventArgs e)
{
var artist = ((Grid) sender).DataContext as XboxArtist;
if (artist != null) Frame.Navigate(typeof (ArtistPage), artist.Id);
}
}
} | apache-2.0 | C# |
93124f14bce33787adbe09eb75eae2bc9057ef6e | Fix cast error. | FamilySearch/gedcomx-csharp,shanewalters/gedcomx-csharp,weitzhandler/gedcomx-csharp | FamilySearch.Api/Memories/FamilySearchMemories.cs | FamilySearch.Api/Memories/FamilySearchMemories.cs | using Gx.Rs.Api;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Gx.Rs.Api.Util;
using FamilySearch.Api.Ft;
using Gedcomx.Support;
namespace FamilySearch.Api.Memories
{
public class FamilySearchMemories : FamilySearchCollectionState
{
public static readonly String URI = "https://familysearch.org/platform/collections/memories";
public static readonly String SANDBOX_URI = "https://sandbox.familysearch.org/platform/collections/memories";
public FamilySearchMemories()
: this(false)
{
}
public FamilySearchMemories(bool sandbox)
: this(new Uri(sandbox ? SANDBOX_URI : URI))
{
}
public FamilySearchMemories(Uri uri)
: this(uri, new FamilySearchStateFactory())
{
}
private FamilySearchMemories(Uri uri, FamilySearchStateFactory stateFactory)
: this(uri, stateFactory.LoadDefaultClientInt(uri), stateFactory)
{
}
private FamilySearchMemories(Uri uri, IFilterableRestClient client, FamilySearchStateFactory stateFactory)
: this(new RestRequest().Accept(MediaTypes.GEDCOMX_JSON_MEDIA_TYPE).Build(uri, Method.GET), client, stateFactory)
{
}
private FamilySearchMemories(IRestRequest request, IFilterableRestClient client, FamilySearchStateFactory stateFactory)
: this(request, client.Handle(request), client, null, stateFactory)
{
}
protected FamilySearchMemories(IRestRequest request, IRestResponse response, IFilterableRestClient client, String accessToken, FamilySearchStateFactory stateFactory)
: base(request, response, client, accessToken, stateFactory)
{
}
protected override GedcomxApplicationState<Gx.Gedcomx> Clone(IRestRequest request, IRestResponse response, IFilterableRestClient client)
{
return new FamilySearchMemories(request, response, this.Client, this.CurrentAccessToken, (FamilySearchStateFactory)this.stateFactory);
}
public FamilySearchMemories AuthenticateViaUnauthenticatedAccess(String clientId, String ipAddress)
{
IDictionary<String, String> formData = new Dictionary<String, String>();
formData.Add("grant_type", "unauthenticated_session");
formData.Add("client_id", clientId);
formData.Add("ip_address", ipAddress);
return (FamilySearchMemories)this.AuthenticateViaOAuth2(formData);
}
}
}
| using Gx.Rs.Api;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Gx.Rs.Api.Util;
using FamilySearch.Api.Ft;
using Gedcomx.Support;
namespace FamilySearch.Api.Memories
{
public class FamilySearchMemories : FamilySearchCollectionState
{
public static readonly String URI = "https://familysearch.org/platform/collections/memories";
public static readonly String SANDBOX_URI = "https://sandbox.familysearch.org/platform/collections/memories";
public FamilySearchMemories()
: this(false)
{
}
public FamilySearchMemories(bool sandbox)
: this(new Uri(sandbox ? SANDBOX_URI : URI))
{
}
public FamilySearchMemories(Uri uri)
: this(uri, new FamilySearchStateFactory())
{
}
private FamilySearchMemories(Uri uri, FamilySearchStateFactory stateFactory)
: this(uri, stateFactory.LoadDefaultClientInt(uri), stateFactory)
{
}
private FamilySearchMemories(Uri uri, IFilterableRestClient client, FamilySearchStateFactory stateFactory)
: this(new RestRequest().Accept(MediaTypes.GEDCOMX_JSON_MEDIA_TYPE).Build(uri, Method.GET), client, stateFactory)
{
}
private FamilySearchMemories(IRestRequest request, IFilterableRestClient client, FamilySearchStateFactory stateFactory)
: this(request, client.Handle(request), client, null, stateFactory)
{
}
protected FamilySearchMemories(IRestRequest request, IRestResponse response, IFilterableRestClient client, String accessToken, FamilySearchStateFactory stateFactory)
: base(request, response, client, accessToken, stateFactory)
{
}
protected override GedcomxApplicationState<Gx.Gedcomx> Clone(IRestRequest request, IRestResponse response, IFilterableRestClient client)
{
return new FamilySearchMemories(request, response, this.Client, this.CurrentAccessToken, (FamilyTreeStateFactory)this.stateFactory);
}
public FamilySearchMemories AuthenticateViaUnauthenticatedAccess(String clientId, String ipAddress)
{
IDictionary<String, String> formData = new Dictionary<String, String>();
formData.Add("grant_type", "unauthenticated_session");
formData.Add("client_id", clientId);
formData.Add("ip_address", ipAddress);
return (FamilySearchMemories)this.AuthenticateViaOAuth2(formData);
}
}
}
| apache-2.0 | C# |
a415661a9f8d07725a273deaae4e4a52e87268b4 | Write the AR Codes using String Interpolation | CryZe/GekkoAssembler | GekkoAssembler/ActionReplay/ActionReplayWriter.cs | GekkoAssembler/ActionReplay/ActionReplayWriter.cs | using System;
using System.IO;
using GekkoAssembler.IntermediateRepresentation;
namespace GekkoAssembler.ActionReplay
{
public class ActionReplayWriter : IIRUnitVisitor
{
public Stream Stream { get; }
private readonly StreamWriter writer;
public ActionReplayWriter(Stream stream)
{
Stream = stream;
writer = new StreamWriter(stream) { AutoFlush = true };
}
public void Visit(IRWriteData instruction)
{
var i = 0;
while ((i + 4) <= instruction.Data.Length)
{
writer.WriteLine($"{0x04 << 24 | (instruction.Address + i) & 0x1FFFFFF:X8} {instruction.Data[i] << 24 | instruction.Data[i + 1] << 16 | instruction.Data[i + 2] << 8 | instruction.Data[i + 3]:X8}");
i += 4;
}
if ((i + 2) <= instruction.Data.Length)
{
writer.WriteLine($"{0x02 << 24 | (instruction.Address + i) & 0x1FFFFFF:X8} {instruction.Data[i] << 8 | instruction.Data[i + 1]:X8}");
i += 2;
}
if (i < instruction.Data.Length)
{
writer.WriteLine($"{0x00 << 24 | (instruction.Address + i) & 0x1FFFFFF:X8} {instruction.Data[i]:X8}");
}
}
public void Visit(IRCodeBlock block)
{
block.Accept(this);
}
public void Visit(IRUnsigned8Equal instruction)
{
//TODO: Differentiate between Multi Line and Single Line Activators
writer.WriteLine($"{0x08 << 24 | instruction.Address & 0x1FFFFFF:X8} {instruction.Value:X8}");
}
}
}
| using System;
using System.IO;
using GekkoAssembler.IntermediateRepresentation;
namespace GekkoAssembler.ActionReplay
{
public class ActionReplayWriter : IIRUnitVisitor
{
public Stream Stream { get; }
private readonly StreamWriter writer;
public ActionReplayWriter(Stream stream)
{
Stream = stream;
writer = new StreamWriter(stream) { AutoFlush = true };
}
public void Visit(IRWriteData instruction)
{
var i = 0;
while ((i + 4) <= instruction.Data.Length)
{
writer.WriteLine(string.Format("04{0:X6} {1:X2}{2:X2}{3:X2}{4:X2}", ((instruction.Address + i) & 0xFFFFFF), instruction.Data[i], instruction.Data[i + 1], instruction.Data[i + 2], instruction.Data[i + 3]));
i += 4;
}
if ((i + 2) <= instruction.Data.Length)
{
writer.WriteLine(string.Format("02{0:X6} 0000{1:X2}{2:X2}", ((instruction.Address + i) & 0xFFFFFF), instruction.Data[i], instruction.Data[i + 1]));
i += 2;
}
if (i < instruction.Data.Length)
{
writer.WriteLine(string.Format("00{0:X6} 000000{1:X2}", ((instruction.Address + i) & 0xFFFFFF), instruction.Data[i]));
}
}
public void Visit(IRCodeBlock block)
{
block.Accept(this);
}
public void Visit(IRUnsigned8Equal instruction)
{
//TODO: Differentiate between Multi Line and Single Line Activators
writer.WriteLine(string.Format("08{0:X6} 000000{1:X2}", (instruction.Address & 0xFFFFFF), instruction.Value));
}
}
}
| mit | C# |
bd37216fce6c13204c7d4edc4b70dc40109797cf | Set test version to auto increment | alexmaris/simplezipcode | SimpleZipeCode.Tests/Properties/AssemblyInfo.cs | SimpleZipeCode.Tests/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("SimpleZipeCode.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SimpleZipeCode.Tests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff6363b4-eb03-4a68-9217-ba65deff4f59")]
// 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.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SimpleZipeCode.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SimpleZipeCode.Tests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff6363b4-eb03-4a68-9217-ba65deff4f59")]
// 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.2")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
3cd203699b485067d79eed122e27fd822895e695 | Apply beatmap converter mods in PerformanceCalculator | smoogipoo/osu,johnneijzen/osu,UselessToucan/osu,peppy/osu,ZLima12/osu,smoogipoo/osu,2yangk23/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,naoey/osu,peppy/osu,NeoAdonis/osu,DrabWeb/osu,ZLima12/osu,peppy/osu,Nabile-Rahmani/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu-new,2yangk23/osu,EVAST9919/osu,ppy/osu,NeoAdonis/osu,johnneijzen/osu,ppy/osu,naoey/osu,EVAST9919/osu,Frontear/osuKyzer,smoogipoo/osu,UselessToucan/osu,DrabWeb/osu,naoey/osu | osu.Game/Rulesets/Scoring/PerformanceCalculator.cs | osu.Game/Rulesets/Scoring/PerformanceCalculator.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
namespace osu.Game.Rulesets.Scoring
{
public abstract class PerformanceCalculator
{
public abstract double Calculate(Dictionary<string, double> categoryDifficulty = null);
}
public abstract class PerformanceCalculator<TObject> : PerformanceCalculator
where TObject : HitObject
{
private readonly Dictionary<string, double> attributes = new Dictionary<string, double>();
protected IDictionary<string, double> Attributes => attributes;
protected readonly Beatmap<TObject> Beatmap;
protected readonly Score Score;
protected PerformanceCalculator(Ruleset ruleset, Beatmap beatmap, Score score)
{
Score = score;
var converter = CreateBeatmapConverter();
foreach (var mod in score.Mods.OfType<IApplicableToBeatmapConverter<TObject>>())
mod.ApplyToBeatmapConverter(converter);
Beatmap = converter.Convert(beatmap);
var diffCalc = ruleset.CreateDifficultyCalculator(beatmap, score.Mods);
diffCalc.Calculate(attributes);
}
protected abstract BeatmapConverter<TObject> CreateBeatmapConverter();
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Objects;
namespace osu.Game.Rulesets.Scoring
{
public abstract class PerformanceCalculator
{
public abstract double Calculate(Dictionary<string, double> categoryDifficulty = null);
}
public abstract class PerformanceCalculator<TObject> : PerformanceCalculator
where TObject : HitObject
{
private readonly Dictionary<string, double> attributes = new Dictionary<string, double>();
protected IDictionary<string, double> Attributes => attributes;
protected readonly Beatmap<TObject> Beatmap;
protected readonly Score Score;
protected PerformanceCalculator(Ruleset ruleset, Beatmap beatmap, Score score)
{
Beatmap = CreateBeatmapConverter().Convert(beatmap);
Score = score;
var diffCalc = ruleset.CreateDifficultyCalculator(beatmap, score.Mods);
diffCalc.Calculate(attributes);
}
protected abstract BeatmapConverter<TObject> CreateBeatmapConverter();
}
}
| mit | C# |
1ca93891109d0eb95532295c78e260545ff6565b | Update class to inherite from Settings.ProgramSource | qianlifeng/Wox,qianlifeng/Wox,Wox-launcher/Wox,qianlifeng/Wox,Wox-launcher/Wox | Plugins/Wox.Plugin.Program/Views/Models/ProgramSource.cs | Plugins/Wox.Plugin.Program/Views/Models/ProgramSource.cs |
namespace Wox.Plugin.Program.Views.Models
{
public class ProgramSource : Settings.ProgramSource { }
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wox.Plugin.Program.Views.Models
{
public class ProgramSource
{
private string name;
public string Location { get; set; }
public string Name { get => name ?? new DirectoryInfo(Location).Name; set => name = value; }
public string UniqueIdentifier { get; set; }
public bool Enabled { get; set; } = true;
}
}
| mit | C# |
58fe4d78ff274a513669979a7e37aa2facdeb8dd | Mark undocumented endpoints with Obsolete | nozzlegear/ShopifySharp,addsb/ShopifySharp,clement911/ShopifySharp | ShopifySharp/Services/Checkout/CheckoutService.cs | ShopifySharp/Services/Checkout/CheckoutService.cs | using Newtonsoft.Json.Linq;
using System.Net.Http;
using ShopifySharp.Filters;
using System.Collections.Generic;
using System.Threading.Tasks;
using ShopifySharp.Infrastructure;
using System;
namespace ShopifySharp
{
/// <summary>
/// A service for manipulating Shopify orders.
/// </summary>
public class CheckoutService : ShopifyService
{
/// <summary>
/// Creates a new instance of <see cref="OrderService" />.
/// </summary>
/// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param>
/// <param name="shopAccessToken">An API access token for the shop.</param>
public CheckoutService(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken) { }
/// <summary>
/// Gets a count of all of the shop's abandoned checkouts.
/// </summary>
/// <param name="filter">Options for filtering the count.</param>
/// <returns>The count of all orders for the shop.</returns>
[Obsolete("This endpoint is an undocumented feature. Shopify may remove support for this endpoint at any time, without warning.")]
public virtual async Task<int> CountAsync(CheckoutFilter filter = null)
{
var req = PrepareRequest("checkouts/count.json");
if (filter != null)
{
req.QueryParams.AddRange(filter.ToParameters());
}
return await ExecuteRequestAsync<int>(req, HttpMethod.Get, rootElement: "count");
}
/// <summary>
/// Gets a list of up to 250 of the shop's abandoned carts.
/// </summary>
/// <returns></returns>
[Obsolete("This endpoint is an undocumented feature. Shopify may remove support for this endpoint at any time, without warning.")]
public virtual async Task<IEnumerable<Checkout>> ListAsync(CheckoutFilter options = null)
{
var req = PrepareRequest("checkouts.json");
if (options != null)
{
req.QueryParams.AddRange(options.ToParameters());
}
return await ExecuteRequestAsync<List<Checkout>>(req, HttpMethod.Get, rootElement: "checkouts");
}
}
}
| using Newtonsoft.Json.Linq;
using System.Net.Http;
using ShopifySharp.Filters;
using System.Collections.Generic;
using System.Threading.Tasks;
using ShopifySharp.Infrastructure;
namespace ShopifySharp
{
/// <summary>
/// A service for manipulating Shopify orders.
/// </summary>
public class CheckoutService : ShopifyService
{
/// <summary>
/// Creates a new instance of <see cref="OrderService" />.
/// </summary>
/// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param>
/// <param name="shopAccessToken">An API access token for the shop.</param>
public CheckoutService(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken) { }
/// <summary>
/// Gets a count of all of the shop's abandoned checkouts.
/// </summary>
/// <param name="filter">Options for filtering the count.</param>
/// <returns>The count of all orders for the shop.</returns>
public virtual async Task<int> CountAsync(CheckoutFilter filter = null)
{
var req = PrepareRequest("checkouts/count.json");
if (filter != null)
{
req.QueryParams.AddRange(filter.ToParameters());
}
return await ExecuteRequestAsync<int>(req, HttpMethod.Get, rootElement: "count");
}
/// <summary>
/// Gets a list of up to 250 of the shop's abandoned carts.
/// </summary>
/// <returns></returns>
public virtual async Task<IEnumerable<Checkout>> ListAsync(CheckoutFilter options = null)
{
var req = PrepareRequest("checkouts.json");
if (options != null)
{
req.QueryParams.AddRange(options.ToParameters());
}
return await ExecuteRequestAsync<List<Checkout>>(req, HttpMethod.Get, rootElement: "checkouts");
}
}
}
| mit | C# |
835d684c579c3e3d623aec5ce577b3c639a8ccd1 | create action method in player api controller for retrieve the players stats | yoliva/game-of-drones,yoliva/game-of-drones,yoliva/game-of-drones | Source/GameOfDrones.API/Controllers/PlayersController.cs | Source/GameOfDrones.API/Controllers/PlayersController.cs | using System.Linq;
using System.Web.Http;
using GameOfDrones.Domain.Entities;
using GameOfDrones.Domain.Enums;
using GameOfDrones.Domain.Repositories;
namespace GameOfDrones.API.Controllers
{
[RoutePrefix("api/v1/players")]
public class PlayersController : ApiController
{
private readonly IGameOfDronesRepository _gameOfDronesRepository;
public PlayersController(IGameOfDronesRepository gameOfDronesRepository)
{
_gameOfDronesRepository = gameOfDronesRepository;
}
[Route("allPlayers")]
public IHttpActionResult GetPlayers()
{
return Ok(_gameOfDronesRepository.GetAllPlayers());
}
[Route("{playerId}")]
public IHttpActionResult GetPlayer(int playerId)
{
var player = _gameOfDronesRepository.GetPlayerById(playerId);
if (player == null)
return NotFound();
return Ok(player);
}
[Route("stats/{playerName}")]
public IHttpActionResult GetPlayerStats(string playerName)
{
var player = _gameOfDronesRepository.GetPlayerByName(playerName);
if (player == null)
return NotFound();
var validStats = player.PlayerStatses.Where(x => x.MatchResult != MatchResult.Invalid);
int wins = 0, loses = 0, wonRounds = 0, tiedRounds = 0, loseRounds = 0;
foreach (var playerStat in validStats)
{
if (playerStat.Match.Winner.Id == player.Id)
wins++;
else
loses++;
wonRounds += playerStat.WinnerRounds;
tiedRounds += playerStat.DrawRounds;
loseRounds += playerStat.LoserRounds;
}
return Ok(new
{
id = player.Id,
name=player.Name,
wins,
loses,
wonRounds,
tiedRounds,
loseRounds
});
}
}
}
| using System.Web.Http;
using GameOfDrones.Domain.Entities;
using GameOfDrones.Domain.Repositories;
namespace GameOfDrones.API.Controllers
{
[RoutePrefix("api/v1/players")]
public class PlayersController : ApiController
{
private readonly IGameOfDronesRepository _gameOfDronesRepository;
public PlayersController(IGameOfDronesRepository gameOfDronesRepository)
{
_gameOfDronesRepository = gameOfDronesRepository;
}
[Route("allPlayers")]
public IHttpActionResult GetPlayers()
{
return Ok(_gameOfDronesRepository.GetAllPlayers());
}
[Route("{playerId}")]
public IHttpActionResult GetPlayer(int playerId)
{
var player = _gameOfDronesRepository.GetPlayerById(playerId);
if (player == null)
{
return NotFound();
}
return Ok(player);
}
}
}
| mit | C# |
f26105e9c5574e2a63f5c30a16fe6b34b452c703 | Fix archiving tests on Linux | sillsdev/libpalaso,gtryus/libpalaso,glasseyes/libpalaso,gmartin7/libpalaso,gmartin7/libpalaso,glasseyes/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso,tombogle/libpalaso,ermshiperete/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,ermshiperete/libpalaso,gtryus/libpalaso,andrew-polk/libpalaso,gmartin7/libpalaso,andrew-polk/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,gtryus/libpalaso,sillsdev/libpalaso | SIL.Archiving/Generic/ArchivingFileSystem.cs | SIL.Archiving/Generic/ArchivingFileSystem.cs |
using System;
using System.IO;
namespace SIL.Archiving.Generic
{
/// <summary />
public static class ArchivingFileSystem
{
internal const string kAccessProtocolFolderName = "Archiving";
/// <summary />
public static string SilCommonDataFolder
{
get
{
// On Linux we have to use /var/lib (instead of CommonApplicationData which
// translates to /usr/share and isn't writable by default)
string folder = Palaso.PlatformUtilities.Platform.IsLinux ? "/var/lib" :
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
return CheckFolder(Path.Combine(folder, "SIL"));
}
}
/// <summary />
public static string SilCommonArchivingDataFolder
{
get { return CheckFolder(Path.Combine(SilCommonDataFolder, kAccessProtocolFolderName)); }
}
/// <summary />
public static string SilCommonIMDIDataFolder
{
get { return CheckFolder(Path.Combine(SilCommonArchivingDataFolder, "IMDI")); }
}
/// <summary />
public static string CheckFolder(string folderName)
{
if (!Directory.Exists(folderName))
{
try
{
Directory.CreateDirectory(folderName);
}
catch (UnauthorizedAccessException)
{
if (Palaso.PlatformUtilities.Platform.IsLinux)
{
if (folderName.StartsWith("/var/lib/SIL"))
{
// by default /var/lib isn't writable on Linux, so we can't create a new
// directory. Create a folder in the user's home directory instead.
var endFolder = folderName.Substring("/var/lib/SIL".Length).TrimStart('/');
folderName = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"SIL", endFolder);
return CheckFolder(folderName);
}
}
throw;
}
}
return folderName;
}
}
}
|
using System;
using System.IO;
namespace SIL.Archiving.Generic
{
/// <summary />
public static class ArchivingFileSystem
{
internal const string kAccessProtocolFolderName = "Archiving";
/// <summary />
public static string SilCommonDataFolder
{
get
{
// On Linux we have to use /var/lib (instead of CommonApplicationData which
// translates to /usr/share and isn't writable by default)
string folder = Palaso.PlatformUtilities.Platform.IsLinux ? "/var/lib" :
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
return CheckFolder(Path.Combine(folder, "SIL"));
}
}
/// <summary />
public static string SilCommonArchivingDataFolder
{
get { return CheckFolder(Path.Combine(SilCommonDataFolder, kAccessProtocolFolderName)); }
}
/// <summary />
public static string SilCommonIMDIDataFolder
{
get { return CheckFolder(Path.Combine(SilCommonArchivingDataFolder, "IMDI")); }
}
/// <summary />
public static string CheckFolder(string folderName)
{
if (!Directory.Exists(folderName))
{
try
{
Directory.CreateDirectory(folderName);
}
catch (UnauthorizedAccessException)
{
if (Palaso.PlatformUtilities.Platform.IsLinux)
{
if (folderName.StartsWith("/var/lib/SIL/"))
{
// by default /var/lib isn't writable on Linux, so we can't create a new
// directory. Create a folder in the user's home directory instead.
var endFolder = folderName.Substring("/var/lib/SIL/".Length);
folderName = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"SIL", endFolder);
return CheckFolder(folderName);
}
}
throw;
}
}
return folderName;
}
}
}
| mit | C# |
a001b6b44217dc7ecf23ee859edd51844f03c03e | test fix | ACEmulator/ACE,ACEmulator/ACE,ACEmulator/ACE,LtRipley36706/ACE,LtRipley36706/ACE,Lidefeath/ACE,LtRipley36706/ACE | Source/ACE.Server.Tests/SkillFormulaTests.cs | Source/ACE.Server.Tests/SkillFormulaTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using ACE.Server.WorldObjects.Entity;
namespace ACE.Server.Tests
{
[TestClass]
public class SkillFormulaTests
{
[TestMethod]
public void FiftyFiftyIsAccurate()
{
var result = CreatureSkill.GetPercentSuccess(100, 100);
Assert.AreEqual(0.5d, result);
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using ACE.Entity;
namespace ACE.Server.Tests
{
[TestClass]
public class SkillFormulaTests
{
[TestMethod]
public void FiftyFiftyIsAccurate()
{
var result = CreatureSkillOld.GetPercentSuccess(100, 100);
Assert.AreEqual(0.5d, result);
}
}
}
| agpl-3.0 | C# |
43626573df0308b599d32499feb65458dc883277 | Fix combo break sounds playing when seeking | NeoAdonis/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu | osu.Game/Screens/Play/ComboEffects.cs | osu.Game/Screens/Play/ComboEffects.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Game.Audio;
using osu.Game.Configuration;
using osu.Game.Rulesets.Scoring;
using osu.Game.Skinning;
namespace osu.Game.Screens.Play
{
public class ComboEffects : CompositeDrawable
{
private readonly ScoreProcessor processor;
private SkinnableSound comboBreakSample;
private Bindable<bool> alwaysPlay;
private bool firstTime = true;
public ComboEffects(ScoreProcessor processor)
{
this.processor = processor;
}
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
InternalChild = comboBreakSample = new SkinnableSound(new SampleInfo("Gameplay/combobreak"));
alwaysPlay = config.GetBindable<bool>(OsuSetting.AlwaysPlayFirstComboBreak);
}
protected override void LoadComplete()
{
base.LoadComplete();
processor.Combo.BindValueChanged(onComboChange);
}
[Resolved(canBeNull: true)]
private ISamplePlaybackDisabler samplePlaybackDisabler { get; set; }
private void onComboChange(ValueChangedEvent<int> combo)
{
if (combo.NewValue == 0 && (combo.OldValue > 20 || (alwaysPlay.Value && firstTime)))
{
firstTime = false;
// combo break isn't a pausable sound itself as we want to let it play out.
// we still need to disable during seeks, though.
if (samplePlaybackDisabler?.SamplePlaybackDisabled.Value == true)
return;
comboBreakSample?.Play();
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Game.Audio;
using osu.Game.Configuration;
using osu.Game.Rulesets.Scoring;
using osu.Game.Skinning;
namespace osu.Game.Screens.Play
{
public class ComboEffects : CompositeDrawable
{
private readonly ScoreProcessor processor;
private SkinnableSound comboBreakSample;
private Bindable<bool> alwaysPlay;
private bool firstTime = true;
public ComboEffects(ScoreProcessor processor)
{
this.processor = processor;
}
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
InternalChild = comboBreakSample = new SkinnableSound(new SampleInfo("Gameplay/combobreak"));
alwaysPlay = config.GetBindable<bool>(OsuSetting.AlwaysPlayFirstComboBreak);
}
protected override void LoadComplete()
{
base.LoadComplete();
processor.Combo.BindValueChanged(onComboChange);
}
private void onComboChange(ValueChangedEvent<int> combo)
{
if (combo.NewValue == 0 && (combo.OldValue > 20 || (alwaysPlay.Value && firstTime)))
{
comboBreakSample?.Play();
firstTime = false;
}
}
}
}
| mit | C# |
54e1a74452761daeeded46b0d7dd88494711f62c | Add xmldoc to ITransformable methods | peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework | osu.Framework/Graphics/Transforms/ITransformable.cs | osu.Framework/Graphics/Transforms/ITransformable.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Timing;
namespace osu.Framework.Graphics.Transforms
{
public interface ITransformable
{
/// <summary>
/// Start a sequence of <see cref="Transform"/>s with a (cumulative) relative delay applied.
/// </summary>
/// <param name="delay">The offset in milliseconds from current time. Note that this stacks with other nested sequences.</param>
/// <param name="recursive">Whether this should be applied to all children.</param>
/// <returns>A <see cref="InvokeOnDisposal"/> to be used in a using() statement.</returns>
IDisposable BeginDelayedSequence(double delay, bool recursive = false);
/// <summary>
/// Start a sequence of <see cref="Transform"/>s from an absolute time value (adjusts <see cref="TransformStartTime"/>).
/// </summary>
/// <param name="newTransformStartTime">The new value for <see cref="TransformStartTime"/>.</param>
/// <param name="recursive">Whether this should be applied to all children.</param>
/// <returns>A <see cref="InvokeOnDisposal"/> to be used in a using() statement.</returns>
/// <exception cref="InvalidOperationException">Absolute sequences should never be nested inside another existing sequence.</exception>
IDisposable BeginAbsoluteSequence(double newTransformStartTime, bool recursive = false);
/// <summary>
/// The current frame's time as observed by this class's <see cref="Transform"/>s.
/// </summary>
FrameTimeInfo Time { get; }
double TransformStartTime { get; }
void AddTransform(Transform transform, ulong? customTransformID = null);
void RemoveTransform(Transform toRemove);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Timing;
namespace osu.Framework.Graphics.Transforms
{
public interface ITransformable
{
IDisposable BeginDelayedSequence(double delay, bool recursive = false);
IDisposable BeginAbsoluteSequence(double newTransformStartTime, bool recursive = false);
/// <summary>
/// The current frame's time as observed by this class's <see cref="Transform"/>s.
/// </summary>
FrameTimeInfo Time { get; }
double TransformStartTime { get; }
void AddTransform(Transform transform, ulong? customTransformID = null);
void RemoveTransform(Transform toRemove);
}
}
| mit | C# |
e1052d8b1414eef3f4a20d9a0e46f760f60f320e | Fix closing bracket. | clicketyclack/gtksharp_clock | gtksharp_clock/Properties/AssemblyInfo.cs | gtksharp_clock/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("gtksharp_clock")]
[assembly: AssemblyDescription("Simple analog clock in GTK-C#")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCompany("Erik Mossberg <clickety@klantig.se>")]
[assembly: AssemblyProduct("GTK-C# analog clock")]
[assembly: AssemblyCopyright("${AuthorCopyright}")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.1.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("gtksharp_clock")]
[assembly: AssemblyDescription("Simple analog clock in GTK-C#")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCompany("Erik Mossberg <clickety@klantig.se>")
[assembly: AssemblyProduct("GTK-C# analog clock")]
[assembly: AssemblyCopyright("${AuthorCopyright}")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.1.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit | C# |
0ccb08c9c8e2be0632e091c5795285297791517b | Make fullname optional for receiver | aduggleby/dragon,aduggleby/dragon,jbinder/dragon,jbinder/dragon,jbinder/dragon,aduggleby/dragon | proj/Mail/Dragon.Mail/Impl/DefaultReceiverMapper.cs | proj/Mail/Dragon.Mail/Impl/DefaultReceiverMapper.cs | using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dragon.Mail.Interfaces;
namespace Dragon.Mail.Impl
{
public class DefaultReceiverMapper : IReceiverMapper
{
public void Map(dynamic receiver, Models.Mail mail)
{
var displayName = (string)null;
if (receiver.GetType().GetProperty("fullname") != null)
{
displayName = receiver.fullname;
}
var email = receiver.email;
mail.Receiver = new System.Net.Mail.MailAddress(email, displayName);
}
}
}
| using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dragon.Mail.Interfaces;
namespace Dragon.Mail.Impl
{
public class DefaultReceiverMapper : IReceiverMapper
{
public void Map(dynamic receiver, Models.Mail mail)
{
var displayName = receiver.fullname;
var email = receiver.email;
mail.Receiver = new System.Net.Mail.MailAddress(email, displayName);
}
}
}
| mit | C# |
b167dbde9f27dddc6d4f6797f6129d05b1908cbf | fix error name. | ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP | src/DotNetCore.CAP.Kafka/CAP.Options.Extensions.cs | src/DotNetCore.CAP.Kafka/CAP.Options.Extensions.cs | using System;
using DotNetCore.CAP;
// ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.DependencyInjection
{
public static class CapOptionsExtensions
{
public static CapOptions UseKafka(this CapOptions options, string bootstrapServers)
{
return options.UseKafka(opt =>
{
opt.Servers = bootstrapServers;
});
}
public static CapOptions UseKafka(this CapOptions options, Action<KafkaOptions> configure)
{
if (configure == null) throw new ArgumentNullException(nameof(configure));
options.RegisterExtension(new KafkaCapOptionsExtension(configure));
return options;
}
}
} | using System;
using DotNetCore.CAP;
// ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.DependencyInjection
{
public static class CapOptionsExtensions
{
public static CapOptions UseKafka(this CapOptions options, string bootstrapServers)
{
return options.UseRabbitMQ(opt =>
{
opt.Servers = bootstrapServers;
});
}
public static CapOptions UseRabbitMQ(this CapOptions options, Action<KafkaOptions> configure)
{
if (configure == null) throw new ArgumentNullException(nameof(configure));
options.RegisterExtension(new KafkaCapOptionsExtension(configure));
return options;
}
}
} | mit | C# |
096ca6c6d7e6e4d6fdf7e0712a6ce3256bb44901 | Update Test Class Name | JoeBurns27/FactoryByReflection | src/Security/Factory/Test/SecurityFactoryTests2.cs | src/Security/Factory/Test/SecurityFactoryTests2.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Jebur27.Security;
using Jebur27.FactoryBase.Exceptions;
using Jebur27.Security.Factory;
using Jebur27.Security.Interfaces;
using Jebur27.Security.Factory;
namespace Test
{
[TestClass]
public class SecurityFactoryTests2
{
[TestMethod]
public void TestGetSecurityManagerOne()
{
Factory target = new Factory();
ISecurityManager securityManager = target.GetSecurityManager("Jebur27.Security.SecurityManagerOne");
SecurityManagerOne securityManagerOne = new SecurityManagerOne();
Assert.AreEqual(securityManager.GetType(), securityManagerOne.GetType());
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Jebur27.Security;
using Jebur27.FactoryBase.Exceptions;
using Jebur27.Security.Factory;
using Jebur27.Security.Interfaces;
using Jebur27.Security.Factory;
namespace Test
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestGetSecurityManagerOne()
{
Factory target = new Factory();
ISecurityManager securityManager = target.GetSecurityManager("Jebur27.Security.SecurityManagerOne");
SecurityManagerOne securityManagerOne = new SecurityManagerOne();
Assert.AreEqual(securityManager.GetType(), securityManagerOne.GetType());
}
}
}
| mit | C# |
d4d930ca34739e851ea9c986cc4354f20c468e97 | Fix IdleTaskQueueTest | AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS | src/Windows/Editor/Test/Properties/AssemblyInfo.cs | src/Windows/Editor/Test/Properties/AssemblyInfo.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.UnitTests.Core.Threading;
using Microsoft.UnitTests.Core.XUnit;
[assembly: TestFrameworkOverride]
[assembly: VsAssemblyLoader]
[assembly: AssemblyFixtureImport(typeof(TestMainThreadFixture))] | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.Common.Core.Test.Fixtures;
using Microsoft.UnitTests.Core.XUnit;
[assembly: TestFrameworkOverride]
[assembly: VsAssemblyLoader] | mit | C# |
96dd5f98ed02513037009c6804ff860dffef22ba | change backing field to resolve net core serializer problem | trenoncourt/AutoQueryable | src/AutoQueryable/Extensions/TypeBuilderExtension.cs | src/AutoQueryable/Extensions/TypeBuilderExtension.cs | using System;
using System.Reflection;
using System.Reflection.Emit;
namespace AutoQueryable.Extensions
{
public static class TypeBuilderExtension
{
private static void AddProperty(this TypeBuilder typeBuilder, string propName, PropertyAttributes attributes, Type propertyType) {
const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName;
var field = typeBuilder.DefineField("_" + propName, propertyType, FieldAttributes.Private);
var property = typeBuilder.DefineProperty(propName, attributes, propertyType, new Type[] { });
var getMethodBuilder = typeBuilder.DefineMethod($"get_{propName}", getSetAttr, propertyType, Type.EmptyTypes);
var getIl = getMethodBuilder.GetILGenerator();
getIl.Emit(OpCodes.Ldarg_0);
getIl.Emit(OpCodes.Ldfld, field);
getIl.Emit(OpCodes.Ret);
var setMethodBuilder = typeBuilder.DefineMethod($"set_{propName}", getSetAttr, null, new[] { propertyType });
var setIl = setMethodBuilder.GetILGenerator();
setIl.Emit(OpCodes.Ldarg_0);
setIl.Emit(OpCodes.Ldarg_1);
setIl.Emit(OpCodes.Stfld, field);
setIl.Emit(OpCodes.Ret);
property.SetGetMethod(getMethodBuilder);
property.SetSetMethod(setMethodBuilder);
}
public static void AddProperty(this TypeBuilder typeBuilder, string propName, PropertyInfo propertyInfo)
{
typeBuilder.AddProperty(propName, propertyInfo.Attributes, propertyInfo.PropertyType);
}
public static void AddProperty(this TypeBuilder typeBuilder, string propName, Type propertyType)
{
typeBuilder.AddProperty(propName, PropertyAttributes.None, propertyType);
}
}
} | using System;
using System.Reflection;
using System.Reflection.Emit;
namespace AutoQueryable.Extensions
{
public static class TypeBuilderExtension
{
private static void AddProperty(this TypeBuilder typeBuilder, string propName, PropertyAttributes attributes, Type propertyType) {
const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName;
var field = typeBuilder.DefineField(propName, propertyType, FieldAttributes.Private);
var property = typeBuilder.DefineProperty(propName, attributes, propertyType, new Type[] { });
var getMethodBuilder = typeBuilder.DefineMethod($"get_{propName}", getSetAttr, propertyType, Type.EmptyTypes);
var getIl = getMethodBuilder.GetILGenerator();
getIl.Emit(OpCodes.Ldarg_0);
getIl.Emit(OpCodes.Ldfld, field);
getIl.Emit(OpCodes.Ret);
var setMethodBuilder = typeBuilder.DefineMethod($"set_{propName}", getSetAttr, null, new[] { propertyType });
var setIl = setMethodBuilder.GetILGenerator();
setIl.Emit(OpCodes.Ldarg_0);
setIl.Emit(OpCodes.Ldarg_1);
setIl.Emit(OpCodes.Stfld, field);
setIl.Emit(OpCodes.Ret);
property.SetGetMethod(getMethodBuilder);
property.SetSetMethod(setMethodBuilder);
}
public static void AddProperty(this TypeBuilder typeBuilder, string propName, PropertyInfo propertyInfo)
{
typeBuilder.AddProperty(propName, propertyInfo.Attributes, propertyInfo.PropertyType);
}
public static void AddProperty(this TypeBuilder typeBuilder, string propName, Type propertyType)
{
typeBuilder.AddProperty(propName, PropertyAttributes.None, propertyType);
}
}
} | mit | C# |
156f5f6723e6e7ffb00909e8115b976fa7a9da3b | Fix for https://github.com/fluentmigrator/fluentmigrator/issues/957. | spaccabit/fluentmigrator,schambers/fluentmigrator,igitur/fluentmigrator,schambers/fluentmigrator,fluentmigrator/fluentmigrator,eloekset/fluentmigrator,fluentmigrator/fluentmigrator,stsrki/fluentmigrator,stsrki/fluentmigrator,amroel/fluentmigrator,eloekset/fluentmigrator,amroel/fluentmigrator,spaccabit/fluentmigrator,igitur/fluentmigrator | src/FluentMigrator.Runner/MigrationScopeHandler.cs | src/FluentMigrator.Runner/MigrationScopeHandler.cs | #region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
namespace FluentMigrator.Runner
{
public class MigrationScopeHandler
{
private readonly IMigrationProcessor _processor;
public MigrationScopeHandler(IMigrationProcessor processor)
{
_processor = processor;
}
public IMigrationScope CurrentScope { get; set; }
public IMigrationScope BeginScope()
{
GuardAgainstActiveMigrationScope();
CurrentScope = new TransactionalMigrationScope(_processor, () => CurrentScope = null);
return CurrentScope;
}
public IMigrationScope CreateOrWrapMigrationScope(bool transactional = true)
{
//prevent connection from being opened when --no-connection is specified in preview mode
if (_processor.Options.PreviewOnly)
{
return new NoOpMigrationScope();
}
if (HasActiveMigrationScope) return new NoOpMigrationScope();
if (transactional) return BeginScope();
return new NoOpMigrationScope();
}
private void GuardAgainstActiveMigrationScope()
{
if (HasActiveMigrationScope) throw new InvalidOperationException("The runner is already in an active migration scope.");
}
private bool HasActiveMigrationScope
{
get { return CurrentScope != null && CurrentScope.IsActive; }
}
}
}
| #region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
namespace FluentMigrator.Runner
{
public class MigrationScopeHandler
{
private readonly IMigrationProcessor _processor;
public MigrationScopeHandler(IMigrationProcessor processor)
{
_processor = processor;
}
public IMigrationScope CurrentScope { get; set; }
public IMigrationScope BeginScope()
{
GuardAgainstActiveMigrationScope();
CurrentScope = new TransactionalMigrationScope(_processor, ()=> CurrentScope = null);
return CurrentScope;
}
public IMigrationScope CreateOrWrapMigrationScope(bool transactional = true)
{
if (HasActiveMigrationScope) return new NoOpMigrationScope();
if (transactional) return BeginScope();
return new NoOpMigrationScope();
}
private void GuardAgainstActiveMigrationScope()
{
if (HasActiveMigrationScope) throw new InvalidOperationException("The runner is already in an active migration scope.");
}
private bool HasActiveMigrationScope
{
get { return CurrentScope != null && CurrentScope.IsActive; }
}
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.