commit
stringlengths 40
40
| old_file
stringlengths 4
237
| new_file
stringlengths 4
237
| old_contents
stringlengths 1
4.24k
| new_contents
stringlengths 1
4.87k
| subject
stringlengths 15
778
| message
stringlengths 15
8.75k
| lang
stringclasses 266
values | license
stringclasses 13
values | repos
stringlengths 5
127k
|
|---|---|---|---|---|---|---|---|---|---|
b0ea5de8343fa100da14b43142ce5034421daae4
|
webscripthook-android/WebActivity.cs
|
webscripthook-android/WebActivity.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
namespace webscripthook_android
{
[Activity(Label = "GTAV WebScriptHook", ScreenOrientation = ScreenOrientation.Sensor)]
public class WebActivity : Activity
{
WebView webView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
Window.RequestFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Web);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
webView.LoadUrl(Intent.GetStringExtra("Address"));
}
public override void OnBackPressed()
{
if (webView.CanGoBack())
{
webView.GoBack();
}
else
{
base.OnBackPressed();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
namespace webscripthook_android
{
[Activity(Label = "GTAV WebScriptHook", ScreenOrientation = ScreenOrientation.Sensor)]
public class WebActivity : Activity
{
WebView webView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
Window.RequestFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Web);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new WebViewClient()); // stops request going to Web Browser
if (savedInstanceState == null)
{
webView.LoadUrl(Intent.GetStringExtra("Address"));
}
}
public override void OnBackPressed()
{
if (webView.CanGoBack())
{
webView.GoBack();
}
else
{
base.OnBackPressed();
}
}
protected override void OnSaveInstanceState (Bundle outState)
{
base.OnSaveInstanceState(outState);
webView.SaveState(outState);
}
protected override void OnRestoreInstanceState(Bundle savedInstanceState)
{
base.OnRestoreInstanceState(savedInstanceState);
webView.RestoreState(savedInstanceState);
}
}
}
|
Fix webview reload on rotation
|
Fix webview reload on rotation
|
C#
|
mit
|
LibertyLocked/webscripthook-android
|
ec6ee635637bb42b7ae681233308d4ff0193c575
|
Espera.Core/Analytics/XamarinAnalyticsEndpoint.cs
|
Espera.Core/Analytics/XamarinAnalyticsEndpoint.cs
|
using System;
using System.Collections.Generic;
using Xamarin;
namespace Espera.Core.Analytics
{
internal class XamarinAnalyticsEndpoint : IAnalyticsEndpoint
{
private Guid id;
public void Dispose()
{
// Xamarin Insights can only be terminated if it has been started before, otherwise it
// throws an exception
if (Insights.IsInitialized)
{
Insights.Terminate();
}
}
public void Identify(string id, IDictionary<string, string> traits = null)
{
traits.Add(Insights.Traits.Name, id);
Insights.Identify(id, traits);
}
public void Initialize(Guid id)
{
this.id = id;
Insights.Initialize("ed4fea5ffb4fa2a1d36acfeb3df4203153d92acf", AppInfo.Version.ToString(), "Espera", AppInfo.BlobCachePath);
}
public void ReportBug(string message)
{
var exception = new Exception(message);
Insights.Report(exception);
}
public void ReportFatalException(Exception exception) => Insights.Report(exception, ReportSeverity.Error);
public void ReportNonFatalException(Exception exception) => Insights.Report(exception);
public void Track(string key, IDictionary<string, string> traits = null) => Insights.Track(key, traits);
public IDisposable TrackTime(string key, IDictionary<string, string> traits = null) => Insights.TrackTime(key, traits);
public void UpdateEmail(string email) => Insights.Identify(id.ToString(), Insights.Traits.Email, email);
}
}
|
using System;
using System.Collections.Generic;
using Xamarin;
namespace Espera.Core.Analytics
{
internal class XamarinAnalyticsEndpoint : IAnalyticsEndpoint
{
private Guid id;
public void Dispose()
{
// Xamarin Insights can only be terminated if it has been started before, otherwise it
// throws an exception
if (Insights.IsInitialized)
{
Insights.Terminate();
}
}
public void Identify(string id, IDictionary<string, string> traits = null)
{
traits.Add(Insights.Traits.Name, id);
Insights.Identify(id, traits);
}
public void Initialize(Guid id)
{
this.id = id;
Insights.Initialize("ed4fea5ffb4fa2a1d36acfeb3df4203153d92acf", AppInfo.Version.ToString(), "Espera", AppInfo.BlobCachePath);
}
public void ReportBug(string message)
{
var exception = new Exception(message);
Insights.Report(exception);
}
public void ReportFatalException(Exception exception)
{
Insights.Report(exception, ReportSeverity.Error);
Insights.Save().Wait();
}
public void ReportNonFatalException(Exception exception) => Insights.Report(exception);
public void Track(string key, IDictionary<string, string> traits = null) => Insights.Track(key, traits);
public IDisposable TrackTime(string key, IDictionary<string, string> traits = null) => Insights.TrackTime(key, traits);
public void UpdateEmail(string email) => Insights.Identify(id.ToString(), Insights.Traits.Email, email);
}
}
|
Call Insights.Save when reporting a crash
|
Call Insights.Save when reporting a crash
|
C#
|
mit
|
punker76/Espera,flagbug/Espera
|
5631b3aa009ad3d1f20b40b12106ac8342a2c12f
|
templates/AvaloniaMvvmApplicationTemplate/Program.cs
|
templates/AvaloniaMvvmApplicationTemplate/Program.cs
|
using System;
using Avalonia;
using Avalonia.Logging.Serilog;
using $safeprojectname$.ViewModels;
using $safeprojectname$.Views;
namespace $safeprojectname$
{
class Program
{
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
public static void Main(string[] args) => BuildAvaloniaApp().Start(AppMain, args);
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToDebug();
// Your application's entry point. Here you can initialize your MVVM framework, DI
// container, etc.
private static void AppMain(Application app, string[] args)
{
app.Run(new MainWindow());
}
}
}
|
using System;
using Avalonia;
using Avalonia.Logging.Serilog;
using $safeprojectname$.ViewModels;
using $safeprojectname$.Views;
namespace $safeprojectname$
{
class Program
{
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
public static void Main(string[] args) => BuildAvaloniaApp().Start(AppMain, args);
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToDebug();
// Your application's entry point. Here you can initialize your MVVM framework, DI
// container, etc.
private static void AppMain(Application app, string[] args)
{
var window = new MainWindow
{
DataContext = new MainWindowViewModel(),
};
app.Run(window);
}
}
}
|
Create VM in MVVM app template.
|
Create VM in MVVM app template.
|
C#
|
mit
|
AvaloniaUI/PerspexVS
|
86d8aa2915e73aa33e06315bf72015380faeec0b
|
TestStack.ConventionTests/ConventionData/Types.cs
|
TestStack.ConventionTests/ConventionData/Types.cs
|
namespace TestStack.ConventionTests.ConventionData
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// This is where we set what our convention is all about.
/// </summary>
public class Types : IConventionData
{
public Types(string descriptionOfTypes)
{
Description = descriptionOfTypes;
}
public Type[] TypesToVerify { get; set; }
public string Description { get; private set; }
public bool HasData {get { return TypesToVerify.Any(); }}
public static Types InAssemblyOf<T>()
{
var assembly = typeof(T).Assembly;
return new Types(assembly.GetName().Name)
{
TypesToVerify = assembly.GetTypes()
};
}
public static Types InAssemblyOf<T>(string descriptionOfTypes, Func<IEnumerable<Type>, IEnumerable<Type>> types)
{
var assembly = typeof (T).Assembly;
return new Types(descriptionOfTypes)
{
TypesToVerify = types(assembly.GetTypes()).ToArray()
};
}
}
}
|
namespace TestStack.ConventionTests.ConventionData
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
/// <summary>
/// This is where we set what our convention is all about.
/// </summary>
public class Types : IConventionData
{
public Types(string descriptionOfTypes)
{
Description = descriptionOfTypes;
}
public Type[] TypesToVerify { get; set; }
public string Description { get; private set; }
public bool HasData {get { return TypesToVerify.Any(); }}
public static Types InAssemblyOf<T>(bool excludeCompilerGeneratedTypes = true)
{
var assembly = typeof(T).Assembly;
var typesToVerify = assembly.GetTypes();
if (excludeCompilerGeneratedTypes)
{
typesToVerify = typesToVerify
.Where(t => !t.GetCustomAttributes(typeof (CompilerGeneratedAttribute), true).Any())
.ToArray();
}
return new Types(assembly.GetName().Name)
{
TypesToVerify = typesToVerify
};
}
public static Types InAssemblyOf<T>(string descriptionOfTypes, Func<IEnumerable<Type>, IEnumerable<Type>> types)
{
var assembly = typeof (T).Assembly;
return new Types(descriptionOfTypes)
{
TypesToVerify = types(assembly.GetTypes()).ToArray()
};
}
}
}
|
Exclude compiler generated types by default
|
Exclude compiler generated types by default
|
C#
|
mit
|
JakeGinnivan/TestStack.ConventionTests,TestStack/TestStack.ConventionTests
|
972d78f0b42ef731b087619b9c5c30a0965b338b
|
src/Redists/Core/TimeSeriesWriter.cs
|
src/Redists/Core/TimeSeriesWriter.cs
|
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace Redists.Core
{
internal class TimeSeriesWriter : ITimeSeriesWriter
{
private readonly IDatabaseAsync dbAsync;
private TimeSpan? ttl;
private IDataPointParser parser;
private ConcurrentDictionary<string, DateTime> expirations = new ConcurrentDictionary<string, DateTime>();
public TimeSeriesWriter(IDatabaseAsync dbAsync, IDataPointParser parser, TimeSpan? ttl)
{
this.dbAsync = dbAsync;
this.parser = parser;
this.ttl = ttl;
}
public Task<long> AppendAsync(string redisKey, params DataPoint[] dataPoints)
{
ManageKeyExpiration(redisKey);
var toAppend = parser.Serialize(dataPoints) + Constants.InterDelimiter;
return this.dbAsync.StringAppendAsync(redisKey, toAppend);
}
private void ManageKeyExpiration(string key)
{
DateTime lastSent=expirations.GetOrAdd(key, DateTime.MinValue);
if ((DateTime.UtcNow- lastSent)> this.ttl.Value)
{
this.dbAsync.KeyExpireAsync(key, ttl);
expirations.TryUpdate(key, DateTime.UtcNow, lastSent);
}
}
}
}
|
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace Redists.Core
{
internal class TimeSeriesWriter : ITimeSeriesWriter
{
private readonly IDatabaseAsync dbAsync;
private TimeSpan? ttl;
private IDataPointParser parser;
private ConcurrentDictionary<string, DateTime> expirations = new ConcurrentDictionary<string, DateTime>();
public TimeSeriesWriter(IDatabaseAsync dbAsync, IDataPointParser parser, TimeSpan? ttl)
{
this.dbAsync = dbAsync;
this.parser = parser;
this.ttl = ttl;
}
public Task<long> AppendAsync(string redisKey, params DataPoint[] dataPoints)
{
ManageKeyExpiration(redisKey);
var toAppend = parser.Serialize(dataPoints) + Constants.InterDelimiter;
return this.dbAsync.StringAppendAsync(redisKey, toAppend);
}
private void ManageKeyExpiration(string key)
{
if (!this.ttl.HasValue)
return;
DateTime lastSent=expirations.GetOrAdd(key, DateTime.MinValue);
if ((DateTime.UtcNow- lastSent)> this.ttl.Value)
{
this.dbAsync.KeyExpireAsync(key, ttl);
expirations.TryUpdate(key, DateTime.UtcNow, lastSent);
}
}
}
}
|
Fix : Null ttl value
|
Fix : Null ttl value
|
C#
|
mit
|
Cybermaxs/Redists
|
8e041146e54e6dfdfff5de6056536b4ff69a6acb
|
src/Utils/Properties/AssemblyInfo.cs
|
src/Utils/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("Utils.Net")]
[assembly: AssemblyDescription("Collection of utilities for .NET projects")]
[assembly: AssemblyProduct("Utils.Net")]
[assembly: AssemblyCopyright("Copyright © Utils.NET 2015")]
// 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("91da47c7-b676-42c6-935f-b42282c46c27")]
// 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: InternalsVisibleTo("UtilsTest")]
|
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("Utils.Net")]
[assembly: AssemblyDescription("Collection of utilities for .NET projects")]
[assembly: AssemblyProduct("Utils.Net")]
[assembly: AssemblyCopyright("Copyright © Utils.NET 2015")]
// 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("91da47c7-b676-42c6-935f-b42282c46c27")]
// 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: InternalsVisibleTo("UtilsTest")]
|
Revert "Removing the assembly version attribute since appveyor doesn't seem to respect custom version format"
|
Revert "Removing the assembly version attribute since appveyor doesn't seem to respect custom version format"
This reverts commit e7c328ca35f92db8eeeea7a5a53223a2370d697a.
|
C#
|
mit
|
nayanshah/UtilsDotNet
|
3c5be4d85609b8be8c2f33c45efe6aed92c8d584
|
source/Core/Models/SignInMessage.cs
|
source/Core/Models/SignInMessage.cs
|
/*
* Copyright 2014 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
namespace Thinktecture.IdentityServer.Core.Models
{
public class SignInMessage : Message
{
public string ReturnUrl { get; set; }
public string ClientId { get; set; }
public string IdP { get; set; }
public string Tenant { get; set; }
public string DisplayMode { get; set; }
public string UiLocales { get; set; }
public IEnumerable<string> AcrValues { get; set; }
}
}
|
/*
* Copyright 2014 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using System.Linq;
namespace Thinktecture.IdentityServer.Core.Models
{
public class SignInMessage : Message
{
public string ReturnUrl { get; set; }
public string ClientId { get; set; }
public string IdP { get; set; }
public string Tenant { get; set; }
public string DisplayMode { get; set; }
public string UiLocales { get; set; }
public IEnumerable<string> AcrValues { get; set; }
public SignInMessage()
{
AcrValues = Enumerable.Empty<string>();
}
}
}
|
Make sure AcrValues is not null
|
Make sure AcrValues is not null
|
C#
|
apache-2.0
|
charoco/IdentityServer3,mvalipour/IdentityServer3,IdentityServer/IdentityServer3,yanjustino/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,remunda/IdentityServer3,openbizgit/IdentityServer3,tbitowner/IdentityServer3,jackswei/IdentityServer3,delloncba/IdentityServer3,SonOfSam/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,uoko-J-Go/IdentityServer,yanjustino/IdentityServer3,jonathankarsh/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,faithword/IdentityServer3,jackswei/IdentityServer3,tbitowner/IdentityServer3,tonyeung/IdentityServer3,kouweizhong/IdentityServer3,bestwpw/IdentityServer3,codeice/IdentityServer3,IdentityServer/IdentityServer3,kouweizhong/IdentityServer3,wondertrap/IdentityServer3,jackswei/IdentityServer3,roflkins/IdentityServer3,jonathankarsh/IdentityServer3,Agrando/IdentityServer3,wondertrap/IdentityServer3,uoko-J-Go/IdentityServer,charoco/IdentityServer3,iamkoch/IdentityServer3,bodell/IdentityServer3,roflkins/IdentityServer3,buddhike/IdentityServer3,bodell/IdentityServer3,delRyan/IdentityServer3,chicoribas/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,EternalXw/IdentityServer3,delRyan/IdentityServer3,tuyndv/IdentityServer3,faithword/IdentityServer3,tonyeung/IdentityServer3,kouweizhong/IdentityServer3,Agrando/IdentityServer3,jonathankarsh/IdentityServer3,ryanvgates/IdentityServer3,codeice/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,mvalipour/IdentityServer3,faithword/IdentityServer3,ryanvgates/IdentityServer3,openbizgit/IdentityServer3,openbizgit/IdentityServer3,18098924759/IdentityServer3,SonOfSam/IdentityServer3,angelapper/IdentityServer3,buddhike/IdentityServer3,iamkoch/IdentityServer3,paulofoliveira/IdentityServer3,18098924759/IdentityServer3,mvalipour/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,olohmann/IdentityServer3,EternalXw/IdentityServer3,remunda/IdentityServer3,paulofoliveira/IdentityServer3,angelapper/IdentityServer3,tonyeung/IdentityServer3,bestwpw/IdentityServer3,18098924759/IdentityServer3,uoko-J-Go/IdentityServer,bodell/IdentityServer3,codeice/IdentityServer3,tbitowner/IdentityServer3,angelapper/IdentityServer3,buddhike/IdentityServer3,SonOfSam/IdentityServer3,delRyan/IdentityServer3,bestwpw/IdentityServer3,olohmann/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,delloncba/IdentityServer3,iamkoch/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,olohmann/IdentityServer3,wondertrap/IdentityServer3,paulofoliveira/IdentityServer3,tuyndv/IdentityServer3,remunda/IdentityServer3,chicoribas/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,chicoribas/IdentityServer3,EternalXw/IdentityServer3,tuyndv/IdentityServer3,roflkins/IdentityServer3,charoco/IdentityServer3,IdentityServer/IdentityServer3,Agrando/IdentityServer3,yanjustino/IdentityServer3,ryanvgates/IdentityServer3,delloncba/IdentityServer3
|
fe9dff9fd832b2b854e3e4df75e23709bdb1ffde
|
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/Internals/ProductInformation.cs
|
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/Internals/ProductInformation.cs
|
using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2018";
public const string Trademark = "";
public const string Version = "3.0.2.0";
}
}
|
using System;
namespace Xamarin.Forms.GoogleMaps.Internals
{
internal class ProductInformation
{
public const string Author = "amay077";
public const string Name = "Xamarin.Forms.GoogleMaps";
public const string Copyright = "Copyright © amay077. 2016 - 2018";
public const string Trademark = "";
public const string Version = "3.0.3.0";
}
}
|
Update file ver to 3.0.3.0
|
Update file ver to 3.0.3.0
|
C#
|
mit
|
amay077/Xamarin.Forms.GoogleMaps,JKennedy24/Xamarin.Forms.GoogleMaps,JKennedy24/Xamarin.Forms.GoogleMaps
|
f4afbe2ac5979bb396de642969833c0931dd1808
|
src/HttpMock.Integration.Tests/PortHelper.cs
|
src/HttpMock.Integration.Tests/PortHelper.cs
|
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Security;
namespace HttpMock.Integration.Tests
{
internal static class PortHelper
{
internal static int FindLocalAvailablePortForTesting ()
{
for (var i = 1025; i <= 65000; i++)
{
if (!ConnectToPort(i))
return i;
}
throw new HostProtectionException("localhost seems to have ALL ports open, are you mad?");
}
private static bool ConnectToPort(int i)
{
var allIpAddresses = (from adapter in NetworkInterface.GetAllNetworkInterfaces()
from unicastAddress in adapter.GetIPProperties().UnicastAddresses
select unicastAddress.Address)
.ToList();
bool connected = false;
foreach (var ipAddress in allIpAddresses)
{
using (var tcpClient = new TcpClient())
{
try
{
tcpClient.Connect(ipAddress, i);
connected = tcpClient.Connected;
}
catch (SocketException)
{
}
finally
{
try
{
tcpClient.Close();
}
catch
{
}
}
}
if (connected)
return true;
}
return false;
}
}
}
|
using System;
using System.Linq;
using System.Net.NetworkInformation;
using System.Security;
namespace HttpMock.Integration.Tests
{
internal static class PortHelper
{
internal static int FindLocalAvailablePortForTesting ()
{
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
var activeTcpConnections = properties.GetActiveTcpConnections();
var minPort = activeTcpConnections.Select(a => a.LocalEndPoint.Port).Max();
var random = new Random();
var randomPort = random.Next(minPort, 65000);
while (activeTcpConnections.Any(a => a.LocalEndPoint.Port == randomPort))
{
randomPort = random.Next(minPort, 65000);
}
return randomPort;
}
}
}
|
Change how we find a local port. Connecting to a local port and releasing it is flaky and slow. use network info to find what port is available
|
Change how we find a local port. Connecting to a local port and releasing it is flaky and slow.
use network info to find what port is available
|
C#
|
mit
|
zhdusurfin/HttpMock,oschwald/HttpMock,mattolenik/HttpMock,hibri/HttpMock
|
430d5cf23eedcae09d0eb7d602da7dec69114f30
|
game/server/weapons/sniperrifle.sfx.cs
|
game/server/weapons/sniperrifle.sfx.cs
|
//------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Revenge Of The Cats - sniperrifle.sfx.cs
// Sounds for the sniper rifle
//------------------------------------------------------------------------------
datablock AudioProfile(SniperRifleFireSound)
{
filename = "share/sounds/rotc/fire6.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperExplosionSound)
{
filename = "share/sounds/rotc/fire2.wav";
description = AudioFar3D;
preload = true;
};
datablock AudioProfile(SniperDebrisSound)
{
filename = "share/sounds/rotc/debris1.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperPowerUpSound)
{
filename = "share/sounds/rotc/charge2.wav";
description = AudioClose3D;
preload = true;
};
datablock AudioProfile(SniperProjectileImpactSound)
{
filename = "share/sounds/rotc/explosion5.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperProjectileMissedEnemySound)
{
filename = "share/sounds/rotc/flyby1.wav";
description = AudioClose3D;
preload = true;
};
|
//------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Revenge Of The Cats - sniperrifle.sfx.cs
// Sounds for the sniper rifle
//------------------------------------------------------------------------------
datablock AudioProfile(SniperRifleFireSound)
{
filename = "share/sounds/rotc/fire6.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperExplosionSound)
{
filename = "share/sounds/rotc/explosion5.wav";
description = AudioFar3D;
preload = true;
};
datablock AudioProfile(SniperDebrisSound)
{
filename = "share/sounds/rotc/debris1.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperPowerUpSound)
{
filename = "share/sounds/rotc/charge2.wav";
description = AudioClose3D;
preload = true;
};
datablock AudioProfile(SniperProjectileImpactSound)
{
filename = "share/sounds/rotc/explosion5.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(SniperProjectileMissedEnemySound)
{
filename = "share/sounds/rotc/flyby1.wav";
description = AudioClose3D;
preload = true;
};
|
Change sniper rifle projectile explosion sound.
|
Change sniper rifle projectile explosion sound.
|
C#
|
lgpl-2.1
|
fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game
|
ea67c191bf23c36a6a208e7c6c8c85162ce94fd8
|
src/shared/Collections/PoolFactory.cs
|
src/shared/Collections/PoolFactory.cs
|
// Copyright 2015 Renaud Paquay All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace mtsuite.shared.Collections {
/// <summary>
/// Default pool factory, create most generally useful <see cref="IPool{T}"/>
/// instances.
/// </summary>
public static class PoolFactory<T> where T : class {
public static IPool<T> Create(Func<T> creator, Action<T> recycler) {
return new ConcurrentFixedSizeArrayPool<T>(creator, recycler);
}
public static IPool<T> Create(Func<T> creator, Action<T> recycler, int size) {
return new ConcurrentFixedSizeArrayPool<T>(creator, recycler, size);
}
}
}
|
// Copyright 2015 Renaud Paquay All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace mtsuite.shared.Collections {
/// <summary>
/// Default pool factory, create most generally useful <see cref="IPool{T}"/>
/// instances.
/// </summary>
public static class PoolFactory<T> where T : class {
#if USE_NOOP_POOL
public static IPool<T> Create(Func<T> creator) {
return Create(creator, _ => { });
}
public static IPool<T> Create(Func<T> creator, Action<T> recycler) {
return new ConcurrentNoOpPool<T>(creator);
}
#else
public static IPool<T> Create(Func<T> creator) {
return Create(creator, _ => { });
}
public static IPool<T> Create(Func<T> creator, Action<T> recycler) {
return new ConcurrentFixedSizeArrayPool<T>(creator, recycler);
}
#endif
}
}
|
Add compile-time constant to switch to no-op pool
|
Add compile-time constant to switch to no-op pool
|
C#
|
apache-2.0
|
rpaquay/mtsuite
|
98392957a526a488a8f0f3eef704cdc7acb78d02
|
src/Diploms.DataLayer/DiplomContext.cs
|
src/Diploms.DataLayer/DiplomContext.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Diploms.Core;
namespace Diploms.DataLayer
{
public class DiplomContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DiplomContext() : base()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//TODO: Use appsettings.json or environment variable, not the string here.
optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=diploms;UserId=postgres;Password=12345678;Pooling=true");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Diploms.Core;
namespace Diploms.DataLayer
{
public class DiplomContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DiplomContext() : base()
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserRole>()
.HasKey(t => new { t.UserId, t.RoleId });
modelBuilder.Entity<UserRole>()
.HasOne(pt => pt.User)
.WithMany(p => p.Roles)
.HasForeignKey(pt => pt.RoleId);
modelBuilder.Entity<UserRole>()
.HasOne(pt => pt.Role)
.WithMany(t => t.Users)
.HasForeignKey(pt => pt.UserId);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//TODO: Use appsettings.json or environment variable, not the string here.
optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=diploms;UserId=postgres;Password=12345678;Pooling=true");
}
}
}
|
Set M:M relationsheep beetween Users and Roles
|
Set M:M relationsheep beetween Users and Roles
|
C#
|
mit
|
denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs
|
6cb55cb4ead912d37358dad467c57f487fd6d1bb
|
Assets/Scripts/Faking/LookAtSpeaker.cs
|
Assets/Scripts/Faking/LookAtSpeaker.cs
|
using UnityEngine;
public class LookAtSpeaker : MonoBehaviour {
public bool active = false;
public float speed;
public float jitterFreq;
public float jitterLerp;
public float jitterScale;
public float blankGazeDistance;
public Transform trackedTransform;
public float lerp;
private Vector3 randomValue;
private Vector3 randomTarget;
void Start()
{
InvokeRepeating("Repeatedly", 0, 1 / jitterFreq);
}
void Repeatedly()
{
randomTarget = Random.insideUnitSphere;
}
void Update()
{
if (active)
{
randomValue = Vector3.Lerp(randomValue, randomTarget, Time.deltaTime * jitterLerp);
GameObject speaker = PlayerTalking.speaker;
Vector3 target;
if (speaker != null && speaker != transform.parent.parent.gameObject)
{
target = speaker.transform.Find("HeadController").position;
}
else
{
target = transform.position + transform.forward * blankGazeDistance;
}
SlowlyRotateTowards(target);
} else {
transform.position = Vector3.Lerp(transform.position, trackedTransform.position, lerp * Time.deltaTime);
transform.rotation = Quaternion.Lerp(transform.rotation, trackedTransform.rotation, lerp * Time.deltaTime);
}
}
void SlowlyRotateTowards(Vector3 target)
{
Vector3 direction = (target - transform.position + randomValue * jitterScale).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * speed);
}
}
|
using UnityEngine;
public class LookAtSpeaker : MonoBehaviour {
public bool active = false;
public float speed;
public float jitterFreq;
public float jitterLerp;
public float jitterScale;
public float blankGazeDistance;
public Transform trackedTransform;
public float lerp;
private Vector3 randomValue;
private Vector3 randomTarget;
void Start()
{
InvokeRepeating("Repeatedly", 0, 1 / jitterFreq);
}
void Repeatedly()
{
randomTarget = Random.insideUnitSphere;
}
void Update()
{
if (active)
{
randomValue = Vector3.Lerp(randomValue, randomTarget, Time.deltaTime * jitterLerp);
GameObject speaker = PlayerTalking.speaker;
Vector3 target;
if (speaker != null && speaker != transform.parent.parent.gameObject)
{
target = speaker.transform.Find("Performative/Head").position;
}
else
{
target = transform.position + transform.forward * blankGazeDistance;
}
SlowlyRotateTowards(target);
} else {
transform.position = Vector3.Lerp(transform.position, trackedTransform.position, lerp * Time.deltaTime);
transform.rotation = Quaternion.Lerp(transform.rotation, trackedTransform.rotation, lerp * Time.deltaTime);
}
}
void SlowlyRotateTowards(Vector3 target)
{
Vector3 direction = (target - transform.position + randomValue * jitterScale).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * speed);
}
}
|
Fix look at speaker to follow Performative/Head
|
Fix look at speaker to follow Performative/Head
|
C#
|
mit
|
Nagasaki45/UnsocialVR,Nagasaki45/UnsocialVR
|
3615b826853ff78e929d6e975fe1596c42500569
|
Palaso/UsbDrive/Linux/UDisks.cs
|
Palaso/UsbDrive/Linux/UDisks.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NDesk.DBus;
namespace Palaso.UsbDrive.Linux
{
public class UDisks
{
private readonly IUDisks _udisks;
public UDisks()
{
_udisks = Bus.System.GetObject<IUDisks>("org.freedesktop.UDisks", new ObjectPath("/org/freedesktop/UDisks"));
}
public IUDisks Interface
{
get { return _udisks; }
}
public IEnumerable<string> EnumerateDeviceOnInterface(string onInterface)
{
var devices = Interface.EnumerateDevices();
foreach (var device in devices)
{
var uDiskDevice = new UDiskDevice(device);
string iface = uDiskDevice.GetProperty("DriveConnectionInterface");
string partition = uDiskDevice.GetProperty("DeviceIsPartition");
if (iface == onInterface && uDiskDevice.IsMounted)
{
yield return device;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NDesk.DBus;
namespace Palaso.UsbDrive.Linux
{
public class UDisks
{
private readonly IUDisks _udisks;
public UDisks()
{
_udisks = Bus.System.GetObject<IUDisks>("org.freedesktop.UDisks", new ObjectPath("/org/freedesktop/UDisks"));
}
public IUDisks Interface
{
get { return _udisks; }
}
public IEnumerable<string> EnumerateDeviceOnInterface(string onInterface)
{
var devices = Interface.EnumerateDevices();
foreach (var device in devices)
{
var uDiskDevice = new UDiskDevice(device);
string iface = uDiskDevice.GetProperty("DriveConnectionInterface");
string partition = uDiskDevice.GetProperty("DeviceIsPartition");
if (iface == onInterface && uDiskDevice.IsMounted)
{
yield return device;
}
}
// If Bus.System is not closed, the program hangs when it ends, waiting for
// the associated thread to quit. It appears to properly reopen Bus.System
// if we try to use it again after closing it.
// And calling Close() here appears to work okay in conjunction with the
// yield return above.
Bus.System.Close();
}
}
}
|
Fix Linux hanging bug due to USB drive enumeration
|
Fix Linux hanging bug due to USB drive enumeration
|
C#
|
mit
|
hatton/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,gmartin7/libpalaso,chrisvire/libpalaso,mccarthyrb/libpalaso,tombogle/libpalaso,JohnThomson/libpalaso,darcywong00/libpalaso,gtryus/libpalaso,JohnThomson/libpalaso,ermshiperete/libpalaso,ermshiperete/libpalaso,ddaspit/libpalaso,mccarthyrb/libpalaso,ddaspit/libpalaso,hatton/libpalaso,marksvc/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,chrisvire/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,mccarthyrb/libpalaso,darcywong00/libpalaso,marksvc/libpalaso,marksvc/libpalaso,darcywong00/libpalaso,gmartin7/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,chrisvire/libpalaso,tombogle/libpalaso,sillsdev/libpalaso,JohnThomson/libpalaso,tombogle/libpalaso,hatton/libpalaso,andrew-polk/libpalaso,glasseyes/libpalaso,sillsdev/libpalaso,glasseyes/libpalaso,sillsdev/libpalaso,gtryus/libpalaso,andrew-polk/libpalaso,ddaspit/libpalaso,gtryus/libpalaso,hatton/libpalaso,JohnThomson/libpalaso,andrew-polk/libpalaso,ddaspit/libpalaso,glasseyes/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,chrisvire/libpalaso
|
31e454a597d46ebb2a629cdd4edcead201052f1f
|
src/ToDoList.Automation/Api/Remove.cs
|
src/ToDoList.Automation/Api/Remove.cs
|
using System.Threading.Tasks;
using ToDoList.Automation.Api.ApiActions;
using Tranquire;
namespace ToDoList.Automation.Api
{
public static class Remove
{
public static IAction<Task> ToDoItem(string title) => Get.TheToDoItem(title)
.SelectMany<Task<Model.ToDoItem>, Task>(itemTask =>
{
return Actions.Create(
$"Remove to-do item",
async actor =>
{
var item = await itemTask;
return actor.Execute(new RemoveToDoItem(item.Id));
});
});
}
}
|
using System.Threading.Tasks;
using ToDoList.Automation.Api.ApiActions;
using Tranquire;
namespace ToDoList.Automation.Api
{
public static class Remove
{
public static IAction<Task> ToDoItem(string title) => Get.TheToDoItem(title)
.SelectMany(item => new RemoveToDoItem(item.Id));
}
}
|
Use SelectMany in demo application
|
Use SelectMany in demo application
|
C#
|
mit
|
Galad/tranquire,Galad/tranquire,Galad/tranquire
|
545d383dd82ffbffe36fc1c48b74f39f6157c237
|
src/Tgstation.Server.Api/Models/TestMergeParameters.cs
|
src/Tgstation.Server.Api/Models/TestMergeParameters.cs
|
using System.ComponentModel.DataAnnotations;
namespace Tgstation.Server.Api.Models
{
/// <summary>
/// Parameters for creating a <see cref="TestMerge"/>
/// </summary>
public class TestMergeParameters
{
/// <summary>
/// The number of the pull request
/// </summary>
public int? Number { get; set; }
/// <summary>
/// The sha of the pull request revision to merge. If not specified, the latest commit shall be used (semi-unsafe)
/// </summary>
[Required]
public string PullRequestRevision { get; set; }
/// <summary>
/// Optional comment about the test
/// </summary>
public string Comment { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Tgstation.Server.Api.Models
{
/// <summary>
/// Parameters for creating a <see cref="TestMerge"/>
/// </summary>
public class TestMergeParameters
{
/// <summary>
/// The number of the pull request
/// </summary>
[Required]
public int? Number { get; set; }
/// <summary>
/// The sha of the pull request revision to merge. If not specified, the latest commit shall be used (semi-unsafe)
/// </summary>
[Required]
public string PullRequestRevision { get; set; }
/// <summary>
/// Optional comment about the test
/// </summary>
public string Comment { get; set; }
}
}
|
Mark this as required since it's nullable now
|
Mark this as required since it's nullable now
|
C#
|
agpl-3.0
|
tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,Cyberboss/tgstation-server
|
41813402be374a527c7c355ca3cc73d3811b25c5
|
Tests/IntegrationTests/BittrexTests.cs
|
Tests/IntegrationTests/BittrexTests.cs
|
using BittrexSharp;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Tests.IntegrationTests
{
[TestClass]
public class BittrexTests
{
[TestMethod]
public void GetMarketSummaries_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarketSummaries(); };
action.ShouldNotThrow();
}
}
}
|
using BittrexSharp;
using BittrexSharp.Domain;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Tests.IntegrationTests
{
[TestClass]
public class BittrexTests
{
#region Public Api
private const string DefaultMarketName = "BTC-ETH";
[TestMethod]
public void GetMarkets_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarkets(); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetSupportedCurrencies_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetSupportedCurrencies(); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetTicker_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetTicker(DefaultMarketName); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetMarketSummaries_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarketSummaries(); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetMarketSummary_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarketSummary(DefaultMarketName); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetOrderBook_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetOrderBook(DefaultMarketName, OrderType.Both, 1); };
action.ShouldNotThrow();
}
[TestMethod]
public void GetMarketHistory_ShouldNotThrowException()
{
var bittrex = new Bittrex();
Func<Task> action = async () => { var _ = await bittrex.GetMarketHistory(DefaultMarketName); };
action.ShouldNotThrow();
}
#endregion
}
}
|
Add Tests for all public Api Methods
|
Add Tests for all public Api Methods
|
C#
|
mit
|
Domysee/BittrexSharp
|
0f0875e6c5b16d4d349d2b104a7d7e4db9b2fc6d
|
Toolkit/Test/Utils/AlertHandlerTest.cs
|
Toolkit/Test/Utils/AlertHandlerTest.cs
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using Toolkit.Utils;
namespace Toolkit
{
[TestClass]
public class AlertHandlerTest
{
FirefoxDriver _driver;
[TestMethod]
public void isAlertPresent()
{
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/alertHandler.html");
Assert.IsTrue(AlertHandler.isAlertPresent(_driver, 3));
}
[TestMethod]
public void handleAlertTest()
{
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/alertHandler.html");
Assert.IsTrue(AlertHandler.handleAlert(_driver,3));
}
[TestMethod]
public void handleAllAlertTest()
{
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/alertHandler.html");
Assert.IsTrue(AlertHandler.handleAllAlerts(_driver, 2));
}
[TestCleanup]
public void TearDown()
{
_driver.Quit();
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using Toolkit.Utils;
namespace Toolkit
{
[TestClass]
public class AlertHandlerTest
{
FirefoxDriver _driver;
[TestInitialize]
public void startup()
{
_driver = new FirefoxDriver();
_driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/alertHandler.html");
}
[TestMethod]
public void isAlertPresent()
{
Assert.IsTrue(AlertHandler.isAlertPresent(_driver, 3));
}
[TestMethod]
public void handleAlertTest()
{
Assert.IsTrue(AlertHandler.handleAlert(_driver,3));
}
[TestMethod]
public void handleAllAlertTest()
{
Assert.IsTrue(AlertHandler.handleAllAlerts(_driver, 2));
Assert.IsTrue(_driver.FindElement(By.Id("button")).Enabled);
}
[TestCleanup]
public void TearDown()
{
_driver.Quit();
}
}
}
|
Update test to ensure page is accessible after alert
|
Update test to ensure page is accessible after alert
|
C#
|
mit
|
JustinPhlegar/Orasi
|
de8fed9e8b0cf7377735e0c31376750942190220
|
src/mscorlib/shared/System/InvalidTimeZoneException.cs
|
src/mscorlib/shared/System/InvalidTimeZoneException.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class InvalidTimeZoneException : Exception
{
public InvalidTimeZoneException()
{
}
public InvalidTimeZoneException(String message)
: base(message)
{
}
public InvalidTimeZoneException(String message, Exception innerException)
: base(message, innerException)
{
}
protected InvalidTimeZoneException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class InvalidTimeZoneException : Exception
{
public InvalidTimeZoneException()
{
}
public InvalidTimeZoneException(String message)
: base(message)
{
}
public InvalidTimeZoneException(String message, Exception innerException)
: base(message, innerException)
{
}
protected InvalidTimeZoneException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
|
Update typeforward assemblyqualifiedname for TimeZoneInfoException
|
Update typeforward assemblyqualifiedname for TimeZoneInfoException
|
C#
|
mit
|
wtgodbe/coreclr,wtgodbe/coreclr,poizan42/coreclr,yizhang82/coreclr,wateret/coreclr,yizhang82/coreclr,poizan42/coreclr,JosephTremoulet/coreclr,yizhang82/coreclr,krk/coreclr,wateret/coreclr,yizhang82/coreclr,mmitche/coreclr,cshung/coreclr,yizhang82/coreclr,krk/coreclr,wtgodbe/coreclr,JosephTremoulet/coreclr,ruben-ayrapetyan/coreclr,wtgodbe/coreclr,JosephTremoulet/coreclr,cshung/coreclr,ruben-ayrapetyan/coreclr,cshung/coreclr,ruben-ayrapetyan/coreclr,krk/coreclr,mmitche/coreclr,cshung/coreclr,krk/coreclr,mmitche/coreclr,wateret/coreclr,mmitche/coreclr,wtgodbe/coreclr,ruben-ayrapetyan/coreclr,mmitche/coreclr,wateret/coreclr,ruben-ayrapetyan/coreclr,poizan42/coreclr,mmitche/coreclr,JosephTremoulet/coreclr,cshung/coreclr,krk/coreclr,JosephTremoulet/coreclr,poizan42/coreclr,wtgodbe/coreclr,wateret/coreclr,wateret/coreclr,poizan42/coreclr,krk/coreclr,cshung/coreclr,JosephTremoulet/coreclr,ruben-ayrapetyan/coreclr,poizan42/coreclr,yizhang82/coreclr
|
db80b6f3167ebcbf737680b5d5774f5e5f2e2929
|
NBi.Core/Etl/IntegrationService/SsisEtlRunnerFactory.cs
|
NBi.Core/Etl/IntegrationService/SsisEtlRunnerFactory.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NBi.Core.Etl.IntegrationService
{
class SsisEtlRunnerFactory
{
public IEtlRunner Get(IEtl etl)
{
if (string.IsNullOrEmpty(etl.Server))
return new EtlFileRunner(etl);
else if (!string.IsNullOrEmpty(etl.Catalog) || !string.IsNullOrEmpty(etl.Folder) || !string.IsNullOrEmpty(etl.Project))
return new EtlCatalogRunner(etl);
else if (string.IsNullOrEmpty(etl.UserName))
return new EtlDtsWindowsRunner(etl);
else
return new EtlDtsSqlServerRunner(etl);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NBi.Core.Etl.IntegrationService
{
class SsisEtlRunnerFactory
{
public IEtlRunner Get(IEtl etl)
{
if (string.IsNullOrEmpty(etl.Server))
return new EtlFileRunner(etl);
else if (!string.IsNullOrEmpty(etl.Catalog) && !string.IsNullOrEmpty(etl.Folder) && !string.IsNullOrEmpty(etl.Project))
return new EtlCatalogRunner(etl);
else if (string.IsNullOrEmpty(etl.UserName))
return new EtlDtsWindowsRunner(etl);
else
return new EtlDtsSqlServerRunner(etl);
}
}
}
|
Fix issue that Builder for CatalogRunner is chosen when a builder for DtsRunner should be
|
Fix issue that Builder for CatalogRunner is chosen when a builder for DtsRunner should be
|
C#
|
apache-2.0
|
Seddryck/NBi,Seddryck/NBi
|
6a2a8458aab5d3b9576cac5d893a04020b80eaa7
|
Assets/MixedRealityToolkit.Providers/WindowsMixedReality/XRSDK/XRSDKWindowsMixedRealityUtilitiesProvider.cs
|
Assets/MixedRealityToolkit.Providers/WindowsMixedReality/XRSDK/XRSDKWindowsMixedRealityUtilitiesProvider.cs
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.WindowsMixedReality;
using System;
#if WMR_ENABLED
using UnityEngine.XR.WindowsMR;
#endif // WMR_ENABLED
namespace Microsoft.MixedReality.Toolkit.XRSDK.WindowsMixedReality
{
/// <summary>
/// An implementation of <see cref="Toolkit.WindowsMixedReality.IWindowsMixedRealityUtilitiesProvider"/> for Unity's XR SDK pipeline.
/// </summary>
public class XRSDKWindowsMixedRealityUtilitiesProvider : IWindowsMixedRealityUtilitiesProvider
{
/// <inheritdoc />
IntPtr IWindowsMixedRealityUtilitiesProvider.ISpatialCoordinateSystemPtr =>
#if WMR_ENABLED
WindowsMREnvironment.OriginSpatialCoordinateSystem;
#else
IntPtr.Zero;
#endif
/// <inheritdoc />
IntPtr IWindowsMixedRealityUtilitiesProvider.IHolographicFramePtr
{
get
{
// NOTE: Currently unable to access HolographicFrame in XR SDK.
return IntPtr.Zero;
}
}
}
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.WindowsMixedReality;
using System;
#if WMR_ENABLED
using UnityEngine.XR.WindowsMR;
#endif // WMR_ENABLED
namespace Microsoft.MixedReality.Toolkit.XRSDK.WindowsMixedReality
{
/// <summary>
/// An implementation of <see cref="Toolkit.WindowsMixedReality.IWindowsMixedRealityUtilitiesProvider"/> for Unity's XR SDK pipeline.
/// </summary>
public class XRSDKWindowsMixedRealityUtilitiesProvider : IWindowsMixedRealityUtilitiesProvider
{
/// <inheritdoc />
IntPtr IWindowsMixedRealityUtilitiesProvider.ISpatialCoordinateSystemPtr =>
#if WMR_ENABLED
WindowsMREnvironment.OriginSpatialCoordinateSystem;
#else
IntPtr.Zero;
#endif
/// <summary>
/// Currently unable to access HolographicFrame in XR SDK. Always returns IntPtr.Zero.
/// </summary>
IntPtr IWindowsMixedRealityUtilitiesProvider.IHolographicFramePtr => IntPtr.Zero;
}
}
|
Update docs on XR SDK IHolographicFramePtr
|
Update docs on XR SDK IHolographicFramePtr
|
C#
|
mit
|
DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
|
66c831d15918f6308a3d3b78a52ab97455c7617c
|
GeoChallenger.Web.Api/Controllers/PoisController.cs
|
GeoChallenger.Web.Api/Controllers/PoisController.cs
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using AutoMapper;
using GeoChallenger.Services.Interfaces;
using GeoChallenger.Web.Api.Models;
namespace GeoChallenger.Web.Api.Controllers
{
/// <summary>
/// Geo tags controller
/// </summary>
[RoutePrefix("api/tags")]
public class PoisController : ApiController
{
private readonly IPoisService _poisService;
private readonly IMapper _mapper;
public PoisController(IPoisService poisService, IMapper mapper)
{
if (poisService == null) {
throw new ArgumentNullException(nameof(poisService));
}
_poisService = poisService;
if (mapper == null) {
throw new ArgumentNullException(nameof(mapper));
}
_mapper = mapper;
}
/// <summary>
/// Get all stub pois
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("")]
public async Task<IList<PoiReadViewModel>> Get()
{
return _mapper.Map<IList<PoiReadViewModel>>(await _poisService.GetPoisAsync());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using AutoMapper;
using GeoChallenger.Services.Interfaces;
using GeoChallenger.Web.Api.Models;
namespace GeoChallenger.Web.Api.Controllers
{
/// <summary>
/// Point of Interests controller
/// </summary>
[RoutePrefix("api/pois")]
public class PoisController : ApiController
{
private readonly IPoisService _poisService;
private readonly IMapper _mapper;
public PoisController(IPoisService poisService, IMapper mapper)
{
if (poisService == null) {
throw new ArgumentNullException(nameof(poisService));
}
_poisService = poisService;
if (mapper == null) {
throw new ArgumentNullException(nameof(mapper));
}
_mapper = mapper;
}
/// <summary>
/// Get all stub pois
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("")]
public async Task<IList<PoiReadViewModel>> Get()
{
return _mapper.Map<IList<PoiReadViewModel>>(await _poisService.GetPoisAsync());
}
}
}
|
Refactor route url for poiController
|
Refactor route url for poiController
|
C#
|
mit
|
GAnatoliy/geochallenger,GAnatoliy/geochallenger
|
fcd70a70546563ffc6d1eed390c002b6aa1414de
|
MCloud/MCloud.Linode/LinodeResponse.cs
|
MCloud/MCloud.Linode/LinodeResponse.cs
|
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MCloud.Linode {
internal class LinodeResponse {
public LinodeResponse ()
{
}
public string Action {
get;
set;
}
public JObject [] Data {
get;
set;
}
public LinodeError [] Errors {
get;
set;
}
public static LinodeResponse FromJson (string json)
{
JObject obj = JObject.Parse (json);
LinodeResponse response = new LinodeResponse ();
response.Action = (string) obj ["ACTION"];
List<LinodeError> errors = new List<LinodeError> ();
foreach (JObject error in obj ["ERRORARRAY"]) {
errors.Add (new LinodeError ((string) error ["ERRORMESSAGE"], (int) error ["ERRORCODE"]));
}
response.Errors = errors.ToArray ();
List<JObject> datas = new List<JObject> ();
JArray data = obj ["DATA"] as JArray;
if (data != null) {
foreach (JObject dobj in data) {
datas.Add (dobj);
}
} else
datas.Add ((JObject) obj ["DATA"]);
response.Data = datas.ToArray ();
return response;
}
}
}
|
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MCloud.Linode {
internal class LinodeResponse {
public LinodeResponse ()
{
}
public string Action {
get;
set;
}
public JObject [] Data {
get;
set;
}
public LinodeError [] Errors {
get;
set;
}
public static LinodeResponse FromJson (string json)
{
JObject obj = JObject.Parse (json);
LinodeResponse response = new LinodeResponse ();
response.Action = (string) obj ["ACTION"];
List<LinodeError> errors = new List<LinodeError> ();
foreach (JObject error in obj ["ERRORARRAY"]) {
errors.Add (new LinodeError ((string) error ["ERRORMESSAGE"], (int) error ["ERRORCODE"]));
}
response.Errors = errors.ToArray ();
if (errors.Count > 0)
throw new Exception (errors [0].Message);
List<JObject> datas = new List<JObject> ();
JArray data = obj ["DATA"] as JArray;
if (data != null) {
foreach (JObject dobj in data) {
datas.Add (dobj);
}
} else
datas.Add ((JObject) obj ["DATA"]);
response.Data = datas.ToArray ();
return response;
}
}
}
|
Raise an exception if there is an error from linode
|
Raise an exception if there is an error from linode
|
C#
|
mit
|
jacksonh/MCloud,jacksonh/MCloud
|
3354db9a5144e4a281a849948c8904c85fe53404
|
src/VideoConverter.cs
|
src/VideoConverter.cs
|
using System.Diagnostics;
namespace Cams
{
public static class VideoConverter
{
public static bool CodecCopy(string inputFile, string outputFile)
{
return Run($"-y -i {inputFile} -codec copy {outputFile}");
}
public static bool Concat(string listFilePath, string outputFile)
{
return Run($"-y -safe 0 -f concat -i {listFilePath} -c copy {outputFile}");
}
public static bool FastForward(string inputFile, string outputFile)
{
return Run($"-y -i {inputFile} -filter:v \"setpts = 0.01 * PTS\" -an {outputFile}");
}
public static bool CheckValidVideoFile(string inputFile)
{
return Run($"-v error -i {inputFile} -f null -");
}
static bool Run(string args)
{
using (var process = new Process
{
StartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "ffmpeg",
Arguments = args
}
})
{
process.Start();
process.WaitForExit();
return process.ExitCode == 0;
}
}
}
}
|
using System.Diagnostics;
namespace Cams
{
public static class VideoConverter
{
public static bool CodecCopy(string inputFile, string outputFile)
{
return Run($"-y -i {inputFile} -codec copy {outputFile}");
}
public static bool Concat(string listFilePath, string outputFile)
{
return Run($"-y -safe 0 -f concat -i {listFilePath} -c copy {outputFile}");
}
public static bool FastForward(string inputFile, string outputFile)
{
return Run($"-y -i {inputFile} -filter:v \"setpts=0.01*PTS, scale=-1:720\" -an {outputFile}");
}
public static bool CheckValidVideoFile(string inputFile)
{
return Run($"-v error -i {inputFile} -f null -");
}
static bool Run(string args)
{
using (var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "ffmpeg",
Arguments = args
}
})
{
process.Start();
process.WaitForExit();
return process.ExitCode == 0;
}
}
}
}
|
Scale summary video to 720p
|
Scale summary video to 720p
|
C#
|
mit
|
chadly/vlc-rtsp,chadly/cams,chadly/vlc-rtsp,chadly/vlc-rtsp
|
6b734c8e6a6d8e59e9bfb236d2d70832bd672bc8
|
Source/SharedAssemblyInfo.cs
|
Source/SharedAssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
using System;
[assembly: AssemblyCompany("Connective DX")]
[assembly: AssemblyProduct("Synthesis")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("8.1.1.0")]
[assembly: AssemblyFileVersion("8.1.1.0")]
[assembly: AssemblyInformationalVersion("8.1.1")]
[assembly: CLSCompliant(false)]
|
using System.Reflection;
using System.Runtime.InteropServices;
using System;
[assembly: AssemblyCompany("Connective DX")]
[assembly: AssemblyProduct("Synthesis")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("8.2.0.0")]
[assembly: AssemblyFileVersion("8.2.0.0")]
[assembly: AssemblyInformationalVersion("8.2.0")]
[assembly: CLSCompliant(false)]
|
Bump version to 8.2. For Sitecore 8.1.
|
Bump version to 8.2. For Sitecore 8.1.
SemVer is confusing sometimes :)
|
C#
|
mit
|
kamsar/Synthesis
|
1f1cd8dae245fa595255940f6a7bdf9808454fbf
|
src/cli/Strategy/ActivateStrategy.cs
|
src/cli/Strategy/ActivateStrategy.cs
|
namespace Linterhub.Cli.Strategy
{
using System.IO;
using System.Linq;
using Runtime;
using Engine;
using Engine.Exceptions;
using Linterhub.Engine.Extensions;
public class ActivateStrategy : IStrategy
{
public object Run(RunContext context, LinterEngine engine, LogManager log)
{
if (string.IsNullOrEmpty(context.Linter))
{
throw new LinterEngineException("Linter is not specified: " + context.Linter);
}
var projectConfigFile = Path.Combine(context.Project, ".linterhub.json");
ExtConfig extConfig;
if (!File.Exists(projectConfigFile))
{
extConfig = new ExtConfig();
}
else
{
using (var fs = File.Open(projectConfigFile, FileMode.Open))
{
extConfig = fs.DeserializeAsJson<ExtConfig>();
}
}
var linter = extConfig.Linters.FirstOrDefault(x => x.Name == context.Linter);
if (linter != null)
{
linter.Active = context.Activate;
}
else
{
extConfig.Linters.Add(new ExtConfig.ExtLint
{
Name = context.Linter,
Active = context.Activate,
Command = engine.Factory.GetArguments(context.Linter)
});
}
var content = extConfig.SerializeAsJson();
File.WriteAllText(projectConfigFile, content);
return content;
}
}
}
|
namespace Linterhub.Cli.Strategy
{
using System.IO;
using System.Linq;
using Runtime;
using Engine;
using Engine.Exceptions;
using Linterhub.Engine.Extensions;
public class ActivateStrategy : IStrategy
{
public object Run(RunContext context, LinterEngine engine, LogManager log)
{
if (string.IsNullOrEmpty(context.Linter))
{
throw new LinterEngineException("Linter is not specified: " + context.Linter);
}
var projectConfigFile = Path.Combine(context.Project, ".linterhub.json");
ExtConfig extConfig;
if (!File.Exists(projectConfigFile))
{
extConfig = new ExtConfig();
}
else
{
using (var fs = File.Open(projectConfigFile, FileMode.Open))
{
extConfig = fs.DeserializeAsJson<ExtConfig>();
}
}
var linter = extConfig.Linters.FirstOrDefault(x => x.Name == context.Linter);
if (linter != null)
{
linter.Active = context.Activate ? null : false;
}
else
{
extConfig.Linters.Add(new ExtConfig.ExtLint
{
Name = context.Linter,
Active = context.Activate,
Command = engine.Factory.GetArguments(context.Linter)
});
}
var content = extConfig.SerializeAsJson();
File.WriteAllText(projectConfigFile, content);
return content;
}
}
}
|
Set active to null (true) by default
|
Set active to null (true) by default
|
C#
|
mit
|
repometric/linterhub-cli,binore/linterhub-cli,repometric/linterhub-cli,binore/linterhub-cli,repometric/linterhub-cli,binore/linterhub-cli
|
ff4362ef2b831377f632a1d346abb50f79fdb54c
|
osu.Framework/Graphics/Textures/RawTextureLoaderStore.cs
|
osu.Framework/Graphics/Textures/RawTextureLoaderStore.cs
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Threading.Tasks;
using osu.Framework.IO.Stores;
namespace osu.Framework.Graphics.Textures
{
public class RawTextureLoaderStore : ResourceStore<RawTexture>
{
private IResourceStore<byte[]> store { get; }
public RawTextureLoaderStore(IResourceStore<byte[]> store)
{
this.store = store;
(store as ResourceStore<byte[]>)?.AddExtension(@"png");
(store as ResourceStore<byte[]>)?.AddExtension(@"jpg");
}
public override async Task<RawTexture> GetAsync(string name)
{
return await Task.Run(() =>
{
try
{
using (var stream = store.GetStream(name))
{
if (stream == null) return null;
return new RawTexture(stream);
}
}
catch
{
return null;
}
});
}
}
}
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Threading.Tasks;
using osu.Framework.IO.Stores;
namespace osu.Framework.Graphics.Textures
{
public class RawTextureLoaderStore : ResourceStore<RawTexture>
{
private IResourceStore<byte[]> store { get; }
public RawTextureLoaderStore(IResourceStore<byte[]> store)
{
this.store = store;
(store as ResourceStore<byte[]>)?.AddExtension(@"png");
(store as ResourceStore<byte[]>)?.AddExtension(@"jpg");
}
public override Task<RawTexture> GetAsync(string name)
{
try
{
using (var stream = store.GetStream(name))
{
if (stream != null)
return Task.FromResult(new RawTexture(stream));
}
}
catch
{
}
return Task.FromResult<RawTexture>(null);
}
}
}
|
Remove one more async-await pair
|
Remove one more async-await pair
|
C#
|
mit
|
ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework
|
859035ce5d210a4dd0dd01ccfb71a7141d537573
|
src/Stripe.net/Services/Plans/StripePlanUpdateOptions.cs
|
src/Stripe.net/Services/Plans/StripePlanUpdateOptions.cs
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Stripe
{
public class StripePlanUpdateOptions : StripeBaseOptions, ISupportMetadata
{
[JsonProperty("active")]
public bool? Active { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("nickname")]
public string Nickname { get; set; }
}
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Stripe
{
public class StripePlanUpdateOptions : StripeBaseOptions, ISupportMetadata
{
[JsonProperty("active")]
public bool? Active { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("nickname")]
public string Nickname { get; set; }
[JsonProperty("product")]
public string ProductId { get; set; }
}
}
|
Add support for `product` on the Plan Update API
|
Add support for `product` on the Plan Update API
|
C#
|
apache-2.0
|
richardlawley/stripe.net,stripe/stripe-dotnet
|
710a7524a14f6ffc5791311c5eac79bfced68246
|
subprocess/Program.cs
|
subprocess/Program.cs
|
using System;
using CefSharp.BrowserSubprocess;
namespace TweetDuck.Browser{
static class Program{
internal const string Version = "1.4.1.0";
private static int Main(string[] args){
SubProcess.EnableHighDPISupport();
const string typePrefix = "--type=";
string type = Array.Find(args, arg => arg.StartsWith(typePrefix, StringComparison.OrdinalIgnoreCase)).Substring(typePrefix.Length);
if (type == "renderer"){
using(SubProcess subProcess = new SubProcess(args)){
return subProcess.Run();
}
}
else{
return SubProcess.ExecuteProcess();
}
}
}
}
|
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using CefSharp.BrowserSubprocess;
namespace TweetDuck.Browser{
static class Program{
internal const string Version = "1.4.1.0";
private static int Main(string[] args){
SubProcess.EnableHighDPISupport();
string FindArg(string key){
return Array.Find(args, arg => arg.StartsWith(key, StringComparison.OrdinalIgnoreCase)).Substring(key.Length);
}
const string typePrefix = "--type=";
const string parentIdPrefix = "--host-process-id=";
if (!int.TryParse(FindArg(parentIdPrefix), out int parentId)){
return 0;
}
Task.Factory.StartNew(() => KillWhenHung(parentId), TaskCreationOptions.LongRunning);
if (FindArg(typePrefix) == "renderer"){
using(SubProcess subProcess = new SubProcess(args)){
return subProcess.Run();
}
}
else{
return SubProcess.ExecuteProcess();
}
}
private static async void KillWhenHung(int parentId){
try{
using(Process process = Process.GetProcessById(parentId)){
process.WaitForExit();
}
}catch{
// ded
}
await Task.Delay(10000);
Environment.Exit(0);
}
}
}
|
Kill subprocess if it doesn't exit after the app is closed
|
Kill subprocess if it doesn't exit after the app is closed
|
C#
|
mit
|
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
|
6dd905fc641faafa49d6a1c36f57aaf62e4dfe45
|
src/Defs/MainButtonWorkerToggleWorld.cs
|
src/Defs/MainButtonWorkerToggleWorld.cs
|
using RimWorld;
using Verse;
namespace PrepareLanding.Defs
{
/// <summary>
/// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing
/// (see "PrepareLanding/Defs/Misc/MainButtonDefs/MainButtons.xml").
/// </summary>
public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld
{
public override void Activate()
{
// default behavior (go to the world map)
base.Activate();
// do not show the main window if in tutorial mode
if (TutorSystem.TutorialMode)
{
Log.Message(
"[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window.");
return;
}
// don't add a new window if the window is already there; if it's not create a new one.
if (PrepareLanding.Instance.MainWindow == null)
PrepareLanding.Instance.MainWindow = new MainWindow(PrepareLanding.Instance.GameData);
// show the main window, minimized.
PrepareLanding.Instance.MainWindow.Show(true);
}
}
}
|
using RimWorld;
using Verse;
namespace PrepareLanding.Defs
{
/// <summary>
/// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing
/// (see "\PrepareLanding\Patches\MainButtonDef_Patch.xml").
/// </summary>
public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld
{
public override void Activate()
{
// default behavior (go to the world map)
base.Activate();
// do not show the main window if in tutorial mode
if (TutorSystem.TutorialMode)
{
Log.Message(
"[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window.");
return;
}
// don't add a new window if the window is already there; if it's not create a new one.
if (PrepareLanding.Instance.MainWindow == null)
PrepareLanding.Instance.MainWindow = new MainWindow(PrepareLanding.Instance.GameData);
// show the main window, minimized.
PrepareLanding.Instance.MainWindow.Show(true);
}
}
}
|
Fix comment about the patch path.
|
Fix comment about the patch path.
|
C#
|
mit
|
neitsa/PrepareLanding,neitsa/PrepareLanding
|
3bf1058969c881588e0e801b4917cd56ea6b250a
|
src/ZobShop.Services/CategoryService.cs
|
src/ZobShop.Services/CategoryService.cs
|
using System.Linq;
using ZobShop.Data.Contracts;
using ZobShop.Factories;
using ZobShop.Models;
using ZobShop.Services.Contracts;
namespace ZobShop.Services
{
public class CategoryService : ICategoryService
{
private readonly IRepository<Category> repository;
private readonly IUnitOfWork unitOfWork;
private readonly ICategoryFactory factory;
public CategoryService(IRepository<Category> repository, IUnitOfWork unitOfWork, ICategoryFactory factory)
{
this.repository = repository;
this.unitOfWork = unitOfWork;
this.factory = factory;
}
public Category GetCategoryByName(string name)
{
var category = this.repository
.GetAll((Category c) => c.Name == name)
.FirstOrDefault();
return category;
}
public Category CreateCategory(string name)
{
var category = this.factory.CreateCategory(name);
this.repository.Add(category);
this.unitOfWork.Commit();
return category;
}
}
}
|
using System;
using System.Linq;
using ZobShop.Data.Contracts;
using ZobShop.Factories;
using ZobShop.Models;
using ZobShop.Services.Contracts;
namespace ZobShop.Services
{
public class CategoryService : ICategoryService
{
private readonly IRepository<Category> repository;
private readonly IUnitOfWork unitOfWork;
private readonly ICategoryFactory factory;
public CategoryService(IRepository<Category> repository, IUnitOfWork unitOfWork, ICategoryFactory factory)
{
if (repository == null)
{
throw new ArgumentNullException("repository cannot be null");
}
if (factory == null)
{
throw new ArgumentNullException("factory cannot be null");
}
if (unitOfWork == null)
{
throw new ArgumentNullException("unit of work cannot be null");
}
this.repository = repository;
this.unitOfWork = unitOfWork;
this.factory = factory;
}
public Category GetCategoryByName(string name)
{
var category = this.repository
.GetAll((Category c) => c.Name == name)
.FirstOrDefault();
return category;
}
public Category CreateCategory(string name)
{
var category = this.factory.CreateCategory(name);
this.repository.Add(category);
this.unitOfWork.Commit();
return category;
}
}
}
|
Add category service constructor validation
|
Add category service constructor validation
|
C#
|
mit
|
Branimir123/ZobShop,Branimir123/ZobShop,Branimir123/ZobShop
|
fc4c48ea8c3a03c1303f24627b1990e07ab46b50
|
src/InEngine.Commands/AlwaysSucceed.cs
|
src/InEngine.Commands/AlwaysSucceed.cs
|
using InEngine.Core;
namespace InEngine.Commands
{
/// <summary>
/// Dummy command for testing and sample code.
/// </summary>
public class AlwaysSucceed : AbstractCommand
{
public override void Run()
{
Info("Ths command always succeeds.");
}
}
}
|
using InEngine.Core;
namespace InEngine.Commands
{
/// <summary>
/// Dummy command for testing and sample code.
/// </summary>
public class AlwaysSucceed : AbstractCommand
{
public override void Run()
{
Info("This command always succeeds.");
}
}
}
|
Fix typo in succeed command output
|
Fix typo in succeed command output
|
C#
|
mit
|
InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET
|
d17b4f6978697885af87586d64fd04f11d23112e
|
WalletWasabi.Gui/Controls/LockScreen/PinLockScreen.xaml.cs
|
WalletWasabi.Gui/Controls/LockScreen/PinLockScreen.xaml.cs
|
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia;
using Avalonia.Input;
using ReactiveUI;
using System.Reactive.Linq;
using System;
namespace WalletWasabi.Gui.Controls.LockScreen
{
public class PinLockScreen : UserControl
{
public static readonly DirectProperty<PinLockScreen, bool> IsLockedProperty =
AvaloniaProperty.RegisterDirect<PinLockScreen, bool>(nameof(IsLocked),
o => o.IsLocked,
(o, v) => o.IsLocked = v);
private bool _isLocked;
public bool IsLocked
{
get => _isLocked;
set => SetAndRaise(IsLockedProperty, ref _isLocked, value);
}
public PinLockScreen() : base()
{
InitializeComponent();
var inputField = this.FindControl<NoparaPasswordBox>("InputField");
this.WhenAnyValue(x => x.IsLocked)
.Where(x => x)
.Subscribe(x => inputField.Focus());
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
|
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia;
using Avalonia.Input;
using ReactiveUI;
using System.Reactive.Linq;
using System;
using Avalonia.LogicalTree;
namespace WalletWasabi.Gui.Controls.LockScreen
{
public class PinLockScreen : UserControl
{
public static readonly DirectProperty<PinLockScreen, bool> IsLockedProperty =
AvaloniaProperty.RegisterDirect<PinLockScreen, bool>(nameof(IsLocked),
o => o.IsLocked,
(o, v) => o.IsLocked = v);
private bool _isLocked;
public bool IsLocked
{
get => _isLocked;
set => SetAndRaise(IsLockedProperty, ref _isLocked, value);
}
public PinLockScreen() : base()
{
InitializeComponent();
var inputField = this.FindControl<NoparaPasswordBox>("InputField");
this.WhenAnyValue(x => x.IsLocked)
.Where(x => x)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(x => inputField.Focus());
}
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
// When the control first created on AppStart set the Focus of the password box.
// If you just simply set the Focus without delay it won't work.
Observable
.Interval(TimeSpan.FromSeconds(1))
.Take(1)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(x =>
{
var inputField = this.FindControl<NoparaPasswordBox>("InputField");
inputField.Focus();
});
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
|
Set the focus of passwordbox after app start.
|
Set the focus of passwordbox after app start.
|
C#
|
mit
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
bf94d22b2f054275eaa65f1f91384a3101bdef37
|
src/ScriptCs.Octokit.Sample/sample.csx
|
src/ScriptCs.Octokit.Sample/sample.csx
|
var octokit = Require<OctokitPack>();
var client = octokit.Create("ScriptCs.Octokit");
var userTask = client.User.Get("alfhenrik");
var user = userTask.Result;
Console.WriteLine(user.Name);
var repoTask = client.Repository.GetAllBranches("alfhenrik", "octokit.net");
var branches = repoTask.Result;
Console.WriteLine(branches.Count);
foreach(var branch in branches)
{
Console.WriteLine(branch.Name);
}
|
var octokit = Require<OctokitPack>();
var client = octokit.Create("ScriptCs.Octokit");
var userTask = client.User.Get("alfhenrik");
var user = userTask.Result;
Console.WriteLine(user.Name);
var repoTask = client.Repository.Branch.GetAll("alfhenrik", "octokit.net");
var branches = repoTask.Result;
Console.WriteLine(branches.Count);
foreach(var branch in branches)
{
Console.WriteLine(branch.Name);
}
|
Fix integration test due to breaking change in latest Octokit.net release
|
Fix integration test due to breaking change in latest Octokit.net release
|
C#
|
mit
|
alfhenrik/ScriptCs.OctoKit
|
13499d0f7b0c57e95226ded8facc85319cb7e60c
|
Mocca/MoccaCompiler.cs
|
Mocca/MoccaCompiler.cs
|
using System;
namespace Mocca {
public class MoccaCompiler {
public MoccaCompiler() {
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Mocca.DataType;
namespace Mocca {
public enum TargetLanguage {
Python, // Now available
Java, // NOT available
Javascript, // NOT available
C_sharp, // NOT available
Swift // NOT Available
}
public interface Compiler {
string compile(List<MoccaBlockGroup> source);
}
public class MoccaCompiler {
List<MoccaBlockGroup> source;
TargetLanguage lang;
public MoccaCompiler(List<MoccaBlockGroup> source, TargetLanguage lang) {
this.source = source;
this.lang = lang;
}
}
}
|
Add Target Language, Compiler Interface
|
Add Target Language, Compiler Interface
|
C#
|
mit
|
ngEPL/Mocca
|
9b34cb365541ec2f1e4e057368f2dfdd96f85384
|
JoinRpg.Domain/FieldExtensions.cs
|
JoinRpg.Domain/FieldExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using JoinRpg.DataModel;
namespace JoinRpg.Domain
{
public static class FieldExtensions
{
public static bool HasValueList(this ProjectField field)
{
return field.FieldType == ProjectFieldType.Dropdown || field.FieldType == ProjectFieldType.MultiSelect;
}
public static bool HasSpecialGroup(this ProjectField field)
{
return field.HasValueList() && field.FieldBoundTo == FieldBoundTo.Character;
}
public static IReadOnlyList<ProjectFieldDropdownValue> GetDropdownValues(this FieldWithValue field)
{
var value = field.GetSelectedIds();
return field.GetPossibleValues().Where(
v => value.Contains(v.ProjectFieldDropdownValueId)).ToList().AsReadOnly();
}
private static IEnumerable<int> GetSelectedIds(this FieldWithValue field)
{
return string.IsNullOrWhiteSpace(field.Value) ? Enumerable.Empty<int>() : field.Value.Split(',').Select(Int32.Parse);
}
public static IEnumerable<ProjectFieldDropdownValue> GetPossibleValues(this FieldWithValue field)
=> field.Field.GetOrderedValues();
public static string GetSpecialGroupName(this ProjectFieldDropdownValue fieldValue)
{
return $"{fieldValue.Label}";
}
public static string GetSpecialGroupName(this ProjectField field)
{
return $"{field.FieldName}";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using JoinRpg.DataModel;
namespace JoinRpg.Domain
{
public static class FieldExtensions
{
public static bool HasValueList(this ProjectField field)
{
return field.FieldType == ProjectFieldType.Dropdown || field.FieldType == ProjectFieldType.MultiSelect;
}
public static bool HasSpecialGroup(this ProjectField field)
{
return field.HasValueList() && field.FieldBoundTo == FieldBoundTo.Character;
}
public static IReadOnlyList<ProjectFieldDropdownValue> GetDropdownValues(this FieldWithValue field)
{
var value = field.GetSelectedIds();
return field.GetPossibleValues().Where(
v => value.Contains(v.ProjectFieldDropdownValueId)).ToList().AsReadOnly();
}
private static IEnumerable<int> GetSelectedIds(this FieldWithValue field)
{
return string.IsNullOrWhiteSpace(field.Value) ? Enumerable.Empty<int>() : field.Value.Split(',').Select(int.Parse);
}
public static IEnumerable<ProjectFieldDropdownValue> GetPossibleValues(this FieldWithValue field)
{
var value = field.GetSelectedIds();
return field.Field.GetOrderedValues().Where(v => v.IsActive || value.Contains(v.ProjectFieldDropdownValueId));
}
public static string GetSpecialGroupName(this ProjectFieldDropdownValue fieldValue)
{
return $"{fieldValue.Label}";
}
public static string GetSpecialGroupName(this ProjectField field)
{
return $"{field.FieldName}";
}
}
}
|
Hide already deleted variants if not set
|
Hide already deleted variants if not set
|
C#
|
mit
|
leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net
|
0ba2b20c0d588e7580dcec903a3c132a2e78cb8d
|
SettlersOfCatan/Mutable/Player.cs
|
SettlersOfCatan/Mutable/Player.cs
|
namespace SettlersOfCatan.Mutable
{
public class Player
{
public Resources Hand { get; private set; }
public Player()
{
Hand = new Resources();
}
public void Trade(Player other, Resources give, Resources take)
{
Hand.RequireAtLeast(give);
other.Hand.RequireAtLeast(take);
Hand.Subtract(give);
other.Hand.Add(give);
Hand.Add(take);
other.Hand.Subtract(take);
}
}
}
|
namespace SettlersOfCatan.Mutable
{
public class Player
{
public Resources Hand { get; }
public Player()
{
Hand = new Resources();
}
public void Trade(Player other, Resources give, Resources take)
{
Hand.RequireAtLeast(give);
other.Hand.RequireAtLeast(take);
Hand.Subtract(give);
other.Hand.Add(give);
Hand.Add(take);
other.Hand.Subtract(take);
}
}
}
|
Use getter only auto property for player resources.
|
Use getter only auto property for player resources.
|
C#
|
mit
|
michaellperry/dof
|
c55c16ccef5ddfa6e6194e1331d012568d833597
|
tools/src/MyGet/DataServices/Routes.cs
|
tools/src/MyGet/DataServices/Routes.cs
|
using System.Data.Services;
using System.ServiceModel.Activation;
using System.Web.Routing;
using NuGet.Server;
using NuGet.Server.DataServices;
using NuGet.Server.Publishing;
using RouteMagic;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyGet.NuGetRoutes), "Start")]
namespace MyGet
{
public static class NuGetRoutes
{
public static void Start()
{
ServiceResolver.SetServiceResolver(new DefaultServiceResolver());
MapRoutes(RouteTable.Routes);
}
private static void MapRoutes(RouteCollection routes)
{
// Route to create a new package(http://{root}/nuget)
routes.MapDelegate("CreatePackageNuGet",
"nuget",
new { httpMethod = new HttpMethodConstraint("PUT") },
context => CreatePackageService().CreatePackage(context.HttpContext));
// The default route is http://{root}/nuget/Packages
var factory = new DataServiceHostFactory();
var serviceRoute = new ServiceRoute("nuget", factory, typeof(Packages));
serviceRoute.Defaults = new RouteValueDictionary { { "serviceType", "odata" } };
serviceRoute.Constraints = new RouteValueDictionary { { "serviceType", "odata" } };
routes.Add("nuget", serviceRoute);
}
private static IPackageService CreatePackageService()
{
return ServiceResolver.Resolve<IPackageService>();
}
}
}
|
using System.Data.Services;
using System.ServiceModel.Activation;
using System.Web.Routing;
using NuGet.Server;
using NuGet.Server.DataServices;
using NuGet.Server.Publishing;
using RouteMagic;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyGet.NuGetRoutes), "Start")]
namespace MyGet {
public static class NuGetRoutes {
public static void Start() {
ServiceResolver.SetServiceResolver(new DefaultServiceResolver());
MapRoutes(RouteTable.Routes);
}
private static void MapRoutes(RouteCollection routes) {
// Route to create a new package(http://{root}/nuget)
routes.MapDelegate("CreatePackageNuGet",
"nuget",
new { httpMethod = new HttpMethodConstraint("PUT") },
context => CreatePackageService().CreatePackage(context.HttpContext));
// The default route is http://{root}/nuget/Packages
var factory = new DataServiceHostFactory();
var serviceRoute = new ServiceRoute("nuget", factory, typeof(Packages));
serviceRoute.Defaults = new RouteValueDictionary { { "serviceType", "odata" } };
serviceRoute.Constraints = new RouteValueDictionary { { "serviceType", "odata" } };
routes.Add("nuget", serviceRoute);
}
private static IPackageService CreatePackageService()
{
return ServiceResolver.Resolve<IPackageService>();
}
}
}
|
Use default routes from package.
|
Use default routes from package.
|
C#
|
bsd-2-clause
|
chtoucas/Narvalo.NET,chtoucas/Narvalo.NET
|
a0718326f57f64b598f8a9ac0bb9373d10b5b73b
|
VGPrompter/Logger.cs
|
VGPrompter/Logger.cs
|
using System;
namespace VGPrompter {
public class Logger {
public bool Enabled { get; set; }
public string Name { get; private set; }
Action<object> _logger;
public Logger(bool enabled = true) : this("Default", enabled: enabled) { }
public Logger(string name, Action<object> f = null, bool enabled = true) {
Enabled = enabled;
Name = name;
_logger = f ?? Console.WriteLine;
}
public void Log(object s) {
if (Enabled) _logger(s);
}
}
}
|
using System;
namespace VGPrompter {
[Serializable]
public class Logger {
public bool Enabled { get; set; }
public string Name { get; private set; }
Action<object> _logger;
public Logger(bool enabled = true) : this("Default", enabled: enabled) { }
public Logger(string name, Action<object> f = null, bool enabled = true) {
Enabled = enabled;
Name = name;
_logger = f ?? Console.WriteLine;
}
public void Log(object s) {
if (Enabled) _logger(s);
}
}
}
|
Fix regression in Script serialization
|
Fix regression in Script serialization
Since the logger in Script is no longer static, the Logger class needs to be serializable.
|
C#
|
mit
|
eugeniusfox/vgprompter
|
9621958556aa5583f79d0d351fa410e92bde5c67
|
kafka-net/DefaultPartitionSelector.cs
|
kafka-net/DefaultPartitionSelector.cs
|
using System;
using System.Collections.Concurrent;
using System.Linq;
using KafkaNet.Model;
using KafkaNet.Protocol;
namespace KafkaNet
{
public class DefaultPartitionSelector : IPartitionSelector
{
private readonly ConcurrentDictionary<string, Partition> _roundRobinTracker = new ConcurrentDictionary<string, Partition>();
public Partition Select(Topic topic, string key)
{
if (topic == null) throw new ArgumentNullException("topic");
if (topic.Partitions.Count <= 0) throw new ApplicationException(string.Format("Topic ({0}) has no partitions.", topic));
//use round robing
var partitions = topic.Partitions;
if (key == null)
{
return _roundRobinTracker.AddOrUpdate(topic.Name, x => partitions.First(), (s, i) =>
{
var index = partitions.FindIndex(0, p => p.Equals(i));
if (index == -1) return partitions.First();
if (++index >= partitions.Count) return partitions.First();
return partitions[index];
});
}
//use key hash
var partitionId = key.GetHashCode() % partitions.Count;
var partition = partitions.FirstOrDefault(x => x.PartitionId == partitionId);
if (partition == null)
throw new InvalidPartitionException(string.Format("Hash function return partition id: {0}, but the available partitions are:{1}",
partitionId, string.Join(",", partitions.Select(x => x.PartitionId))));
return partition;
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Linq;
using KafkaNet.Model;
using KafkaNet.Protocol;
namespace KafkaNet
{
public class DefaultPartitionSelector : IPartitionSelector
{
private readonly ConcurrentDictionary<string, Partition> _roundRobinTracker = new ConcurrentDictionary<string, Partition>();
public Partition Select(Topic topic, string key)
{
if (topic == null) throw new ArgumentNullException("topic");
if (topic.Partitions.Count <= 0) throw new ApplicationException(string.Format("Topic ({0}) has no partitions.", topic));
//use round robing
var partitions = topic.Partitions;
if (key == null)
{
return _roundRobinTracker.AddOrUpdate(topic.Name, x => partitions.First(), (s, i) =>
{
var index = partitions.FindIndex(0, p => p.Equals(i));
if (index == -1) return partitions.First();
if (++index >= partitions.Count) return partitions.First();
return partitions[index];
});
}
//use key hash
var partitionId = Math.Abs(key.GetHashCode()) % partitions.Count;
var partition = partitions.FirstOrDefault(x => x.PartitionId == partitionId);
if (partition == null)
throw new InvalidPartitionException(string.Format("Hash function return partition id: {0}, but the available partitions are:{1}",
partitionId, string.Join(",", partitions.Select(x => x.PartitionId))));
return partition;
}
}
}
|
Fix error in hash key selector would return -1
|
Fix error in hash key selector would return -1
|
C#
|
apache-2.0
|
PKRoma/kafka-net,CenturyLinkCloud/kafka-net,Jroland/kafka-net,aNutForAJarOfTuna/kafka-net,gigya/KafkaNetClient,bridgewell/kafka-net,nightkid1027/kafka-net,BDeus/KafkaNetClient,martijnhoekstra/kafka-net,EranOfer/KafkaNetClient,geffzhang/kafka-net
|
80ef1b69f07a943961c5000d1fd2a4be21efe4e2
|
src/keypay-dotnet/ApiFunctions/V2/ManagerFunction.cs
|
src/keypay-dotnet/ApiFunctions/V2/ManagerFunction.cs
|
using KeyPay.DomainModels.V2.Business;
using KeyPay.DomainModels.V2.Manager;
using System.Collections.Generic;
namespace KeyPay.ApiFunctions.V2
{
public class ManagerFunction : BaseFunction
{
public ManagerFunction(ApiRequestExecutor api) : base(api)
{
LeaveRequests = new ManagerLeaveRequestsFunction(api);
Kiosk = new ManagerKioskFunction(api);
TimeAndAttendance = new ManagerTimeAndAttendanceFunction(api);
}
public ManagerLeaveRequestsFunction LeaveRequests { get; set; }
public List<ManagerLeaveEmployeeModel> Employees(int businessId)
{
return ApiRequest<List<ManagerLeaveEmployeeModel>>($"/business/{businessId}/manager/employees");
}
public List<LocationModel> Locations(int businessId)
{
return ApiRequest<List<LocationModel>>($"/business/{businessId}/manager/locations");
}
public ManagerKioskFunction Kiosk { get; set; }
public ManagerTimeAndAttendanceFunction TimeAndAttendance { get; set; }
}
}
|
using KeyPay.DomainModels.V2.Business;
using KeyPay.DomainModels.V2.Manager;
using System.Collections.Generic;
namespace KeyPay.ApiFunctions.V2
{
public class ManagerFunction : BaseFunction
{
public ManagerFunction(ApiRequestExecutor api) : base(api)
{
LeaveRequests = new ManagerLeaveRequestsFunction(api);
Kiosk = new ManagerKioskFunction(api);
TimeAndAttendance = new ManagerTimeAndAttendanceFunction(api);
}
public ManagerLeaveRequestsFunction LeaveRequests { get; set; }
public ManagerKioskFunction Kiosk { get; set; }
public ManagerTimeAndAttendanceFunction TimeAndAttendance { get; set; }
public List<ManagerLeaveEmployeeModel> Employees(int businessId)
{
return ApiRequest<List<ManagerLeaveEmployeeModel>>($"/business/{businessId}/manager/employees");
}
public List<LocationModel> Locations(int businessId)
{
return ApiRequest<List<LocationModel>>($"/business/{businessId}/manager/locations");
}
}
}
|
Include manager leave request functions and update to version 1.1.0.15-rc2
|
Include manager leave request functions and update to version 1.1.0.15-rc2
|
C#
|
mit
|
KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet
|
9c3ccfca13b80ab6b80479d27e1c344af78bc962
|
MIMWebClient/Core/Update/UpdateWorld.cs
|
MIMWebClient/Core/Update/UpdateWorld.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace MIMWebClient.Core.Update
{
public class UpdateWorld
{
public static void Init()
{
Task.Run(UpdateTime);
}
public static void CleanRoom()
{
Task.Run(UpdateRoom);
}
public static void UpdateMob()
{
Task.Run(MoveMob);
}
/// <summary>
/// Wahoo! This works
/// Now needs to update player/mob stats, spells, reset rooms and mobs. Move mobs around?
/// Global Timer every 60 seconds? quicker timer for mob movement?
/// </summary>
/// <returns></returns>
public static async Task UpdateTime()
{
Time.UpdateTIme();
Init();
}
public static async Task UpdateRoom()
{
await Task.Delay(300000);
HubContext.getHubContext.Clients.All.addNewMessageToPage("This is will update Rooms every 5 minutes and not block the game");
CleanRoom();
}
public static async Task MoveMob()
{
//await Task.Delay(5000);
//HubContext.getHubContext.Clients.All.addNewMessageToPage("This task will update Mobs every 5 seconds and not block the game");
//UpdateMob();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace MIMWebClient.Core.Update
{
public class UpdateWorld
{
public static void Init()
{
Task.Run(UpdateTime);
}
public static void CleanRoom()
{
Task.Run(UpdateRoom);
}
public static void UpdateMob()
{
Task.Run(MoveMob);
}
/// <summary>
/// Wahoo! This works
/// Now needs to update player/mob stats, spells, reset rooms and mobs. Move mobs around?
/// Global Timer every 60 seconds? quicker timer for mob movement?
/// </summary>
/// <returns></returns>
public static async Task UpdateTime()
{
await Task.Delay(30000);
Time.UpdateTIme();
Init();
}
public static async Task UpdateRoom()
{
await Task.Delay(300000);
HubContext.getHubContext.Clients.All.addNewMessageToPage("This is will update Rooms every 5 minutes and not block the game");
CleanRoom();
}
public static async Task MoveMob()
{
//await Task.Delay(5000);
//HubContext.getHubContext.Clients.All.addNewMessageToPage("This task will update Mobs every 5 seconds and not block the game");
//UpdateMob();
}
}
}
|
Update Delay to 30 seconds
|
Update Delay to 30 seconds
|
C#
|
mit
|
LiamKenneth/ArchaicQuest,LiamKenneth/ArchaicQuest,LiamKenneth/ArchaicQuest,LiamKenneth/MIM,LiamKenneth/MIM,LiamKenneth/ArchaicQuest,LiamKenneth/MIM
|
7facad1ba03c33a1ba8f6968f79cce31e702c66b
|
Engine/GameObject/PrefabsPool.cs
|
Engine/GameObject/PrefabsPool.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PrefabsPool : GameObjectBehavior {
public Dictionary<string, GameObject> prefabs;
// Only one ObjectPoolManager can exist. We use a singleton pattern to enforce this.
private static PrefabsPool _instance = null;
public static PrefabsPool instance {
get {
if (!_instance) {
_instance = FindObjectOfType(typeof(PrefabsPool)) as PrefabsPool;
if (!_instance) {
var obj = new GameObject("_PrefabsPool");
_instance = obj.AddComponent<PrefabsPool>();
}
}
return _instance;
}
}
private void OnApplicationQuit() {
_instance = null;
}
public static void CheckPrefabs() {
if(instance == null) {
return;
}
if(instance.prefabs == null) {
instance.prefabs = new Dictionary<string, GameObject>();
}
}
public static GameObject PoolPrefab(string path) {
if(instance == null) {
return null;
}
CheckPrefabs();
string key = CryptoUtil.CalculateSHA1ASCII(path);
if(!instance.prefabs.ContainsKey(key)) {
GameObject prefab = Resources.Load(path) as GameObject;
if(prefab != null) {
instance.prefabs.Add(key, Resources.Load(path) as GameObject);
}
}
if(instance.prefabs.ContainsKey(key)) {
return instance.prefabs[key];
}
return null;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PrefabsPool : GameObjectBehavior {
public Dictionary<string, GameObject> prefabs;
// Only one ObjectPoolManager can exist. We use a singleton pattern to enforce this.
private static PrefabsPool _instance = null;
public static PrefabsPool instance {
get {
if (!_instance) {
_instance = FindObjectOfType(typeof(PrefabsPool)) as PrefabsPool;
if (!_instance) {
var obj = new GameObject("_PrefabsPool");
_instance = obj.AddComponent<PrefabsPool>();
}
}
return _instance;
}
}
private void OnApplicationQuit() {
_instance = null;
}
public static void CheckPrefabs() {
if(instance == null) {
return;
}
if(instance.prefabs == null) {
instance.prefabs = new Dictionary<string, GameObject>();
}
}
public static GameObject PoolPrefab(string path) {
if(instance == null) {
return null;
}
CheckPrefabs();
string key = CryptoUtil.CalculateSHA1ASCII(path);
if(!instance.prefabs.ContainsKey(key)) {
GameObject prefab = Resources.Load(path) as GameObject;
if(prefab != null) {
instance.prefabs.Add(key, prefab);
}
}
if(instance.prefabs.ContainsKey(key)) {
return instance.prefabs[key];
}
return null;
}
}
|
Update prefabs resources.load flow, fix dual load.
|
Update prefabs resources.load flow, fix dual load.
|
C#
|
mit
|
drawcode/game-lib-engine
|
924e8521ae9765af922b73be17cd22893d69e7f6
|
BMPClient/Program.cs
|
BMPClient/Program.cs
|
using System;
using System.Net;
using BmpListener.Bmp;
using BmpListener.JSON;
using Newtonsoft.Json;
namespace BmpListener
{
internal class Program
{
private static void Main()
{
JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new IPAddressConverter());
settings.Converters.Add(new TestConverter());
return settings;
};
var ip = IPAddress.Parse("192.168.1.126");
var bmpListener = new BmpListener(ip);
bmpListener.Start(WriteJson).Wait();
}
private static void WriteJson(BmpMessage msg)
{
var json = JsonConvert.SerializeObject(msg);
Console.WriteLine(json);
}
}
}
|
using System;
using System.Net;
using BmpListener.Bmp;
using BmpListener.JSON;
using Newtonsoft.Json;
namespace BmpListener
{
internal class Program
{
private static void Main()
{
JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new IPAddressConverter());
settings.Converters.Add(new TestConverter());
return settings;
};
var bmpListener = new BmpListener();
bmpListener.Start(WriteJson).Wait();
}
private static void WriteJson(BmpMessage msg)
{
var json = JsonConvert.SerializeObject(msg);
Console.WriteLine(json);
}
}
}
|
Change default behaviour to listen on all IP addresses
|
Change default behaviour to listen on all IP addresses
|
C#
|
mit
|
mstrother/BmpListener
|
04cfae9bdeb525855a34527a217e8b2cba34b115
|
osu.Game/Database/RealmLiveUnmanaged.cs
|
osu.Game/Database/RealmLiveUnmanaged.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 Realms;
#nullable enable
namespace osu.Game.Database
{
/// <summary>
/// Provides a method of working with unmanaged realm objects.
/// Usually used for testing purposes where the instance is never required to be managed.
/// </summary>
/// <typeparam name="T">The underlying object type.</typeparam>
public class RealmLiveUnmanaged<T> : ILive<T> where T : RealmObjectBase, IHasGuidPrimaryKey
{
/// <summary>
/// Construct a new instance of live realm data.
/// </summary>
/// <param name="data">The realm data.</param>
public RealmLiveUnmanaged(T data)
{
Value = data;
}
public bool Equals(ILive<T>? other) => ID == other?.ID;
public Guid ID => Value.ID;
public void PerformRead(Action<T> perform) => perform(Value);
public TReturn PerformRead<TReturn>(Func<T, TReturn> perform) => perform(Value);
public void PerformWrite(Action<T> perform) => throw new InvalidOperationException(@"Can't perform writes on a non-managed underlying value");
public bool IsManaged => false;
/// <summary>
/// The original live data used to create this instance.
/// </summary>
public T Value { get; }
}
}
|
// 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 Realms;
#nullable enable
namespace osu.Game.Database
{
/// <summary>
/// Provides a method of working with unmanaged realm objects.
/// Usually used for testing purposes where the instance is never required to be managed.
/// </summary>
/// <typeparam name="T">The underlying object type.</typeparam>
public class RealmLiveUnmanaged<T> : ILive<T> where T : RealmObjectBase, IHasGuidPrimaryKey
{
/// <summary>
/// Construct a new instance of live realm data.
/// </summary>
/// <param name="data">The realm data.</param>
public RealmLiveUnmanaged(T data)
{
Value = data;
}
public bool Equals(ILive<T>? other) => ID == other?.ID;
public override string ToString() => Value.ToString();
public Guid ID => Value.ID;
public void PerformRead(Action<T> perform) => perform(Value);
public TReturn PerformRead<TReturn>(Func<T, TReturn> perform) => perform(Value);
public void PerformWrite(Action<T> perform) => throw new InvalidOperationException(@"Can't perform writes on a non-managed underlying value");
public bool IsManaged => false;
/// <summary>
/// The original live data used to create this instance.
/// </summary>
public T Value { get; }
}
}
|
Fix "Random Skin" text not showing up correctly
|
Fix "Random Skin" text not showing up correctly
|
C#
|
mit
|
NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu
|
53d8a0e4e955f5e8c57babc3c9e69b025df2fd45
|
src/git-istage/ConsoleCommand.cs
|
src/git-istage/ConsoleCommand.cs
|
using System;
namespace GitIStage
{
internal sealed class ConsoleCommand
{
private readonly Action _handler;
private readonly ConsoleKey _key;
public readonly string Description;
private readonly ConsoleModifiers _modifiers;
public ConsoleCommand(Action handler, ConsoleKey key, string description)
{
_handler = handler;
_key = key;
Description = description;
_modifiers = 0;
}
public ConsoleCommand(Action handler, ConsoleKey key, ConsoleModifiers modifiers, string description)
{
_handler = handler;
_key = key;
_modifiers = modifiers;
Description = description;
}
public void Execute()
{
_handler();
}
public bool MatchesKey(ConsoleKeyInfo keyInfo)
{
return _key == keyInfo.Key && _modifiers == keyInfo.Modifiers;
}
public string GetCommandShortcut()
{
string key = _key.ToString().Replace("Arrow", "");
if (_modifiers != 0)
{
return $"{_modifiers.ToString().Replace("Control", "CTRL")} + {key.ToString()}";
}
else
return key.ToString();
}
}
}
|
using System;
namespace GitIStage
{
internal sealed class ConsoleCommand
{
private readonly Action _handler;
private readonly ConsoleKey _key;
public readonly string Description;
private readonly ConsoleModifiers _modifiers;
public ConsoleCommand(Action handler, ConsoleKey key, string description)
{
_handler = handler;
_key = key;
Description = description;
_modifiers = 0;
}
public ConsoleCommand(Action handler, ConsoleKey key, ConsoleModifiers modifiers, string description)
{
_handler = handler;
_key = key;
_modifiers = modifiers;
Description = description;
}
public void Execute()
{
_handler();
}
public bool MatchesKey(ConsoleKeyInfo keyInfo)
{
return _key == keyInfo.Key && _modifiers == keyInfo.Modifiers;
}
public string GetCommandShortcut()
{
string key = _key.ToString().Replace("Arrow", "");
if (_modifiers != 0)
{
return $"{_modifiers.ToString().Replace("Control", "Ctrl")} + {key.ToString()}";
}
else
return key.ToString();
}
}
}
|
Change CTRL to Ctrl in commands description.
|
Change CTRL to Ctrl in commands description.
Co-Authored-By: tomaszprasolek <1a877c38cb151259581ee0940a398d86d3acddc2@o2.pl>
|
C#
|
mit
|
terrajobst/git-istage,terrajobst/git-istage
|
e8bd737f10b003aea52e54e8e182c90eb589b68c
|
ComputeClient/Compute.Contracts/Backup/ServicePlan.cs
|
ComputeClient/Compute.Contracts/Backup/ServicePlan.cs
|
namespace DD.CBU.Compute.Api.Contracts.Backup
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://oec.api.opsource.net/schemas/backup")]
public enum ServicePlan {
/// <remarks/>
Essentials,
/// <remarks/>
Advanced,
/// <remarks/>
Enterprise,
}
}
|
namespace DD.CBU.Compute.Api.Contracts.Backup
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://oec.api.opsource.net/schemas/backup")]
public enum ServicePlan {
/// <remarks/>
Essentials = 1,
/// <remarks/>
Advanced,
/// <remarks/>
Enterprise,
}
}
|
Change default backup service plan enum value.
|
Change default backup service plan enum value.
|
C#
|
mit
|
DimensionDataCBUSydney/DimensionData.ComputeClient,riveryc/DimensionData.ComputeClient,DimensionDataCBUSydney/Compute.Api.Client,riveryc/DimensionData.ComputeClient,DimensionDataCBUSydney/DimensionData.ComputeClient,riveryc/DimensionData.ComputeClient,samuelchong/Compute.Api.Client,DimensionDataCBUSydney/DimensionData.ComputeClient
|
1665d6c5254b0df97c75a65e8399e7185851765d
|
test/csharp/test_SessionState.cs
|
test/csharp/test_SessionState.cs
|
using Xunit;
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Internal.Host;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;
using Microsoft.PowerShell.Linux.Host;
namespace PSTests
{
public class SessionStateTests
{
[Fact]
public void TestDrives()
{
PowerShellAssemblyLoadContextInitializer.SetPowerShellAssemblyLoadContext(AppContext.BaseDirectory);
CultureInfo currentCulture = CultureInfo.CurrentCulture;
PSHost hostInterface = new DefaultHost(currentCulture,currentCulture);
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
InitialSessionState iss = InitialSessionState.CreateDefault2();
AutomationEngine engine = new AutomationEngine(hostInterface, runspaceConfiguration, iss);
ExecutionContext executionContext = new ExecutionContext(engine, hostInterface, iss);
SessionStateInternal sessionState = new SessionStateInternal(executionContext);
Collection<PSDriveInfo> drives = sessionState.Drives(null);
Assert.True(drives.Count>0);
}
}
}
|
using Xunit;
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Internal.Host;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;
using Microsoft.PowerShell.Linux.Host;
namespace PSTests
{
[Collection("AssemblyLoadContext")]
public class SessionStateTests
{
[Fact]
public void TestDrives()
{
CultureInfo currentCulture = CultureInfo.CurrentCulture;
PSHost hostInterface = new DefaultHost(currentCulture,currentCulture);
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
InitialSessionState iss = InitialSessionState.CreateDefault2();
AutomationEngine engine = new AutomationEngine(hostInterface, runspaceConfiguration, iss);
ExecutionContext executionContext = new ExecutionContext(engine, hostInterface, iss);
SessionStateInternal sessionState = new SessionStateInternal(executionContext);
Collection<PSDriveInfo> drives = sessionState.Drives(null);
Assert.True(drives.Count>0);
}
}
}
|
Add SessionStateTests to AssemblyLoadContext collection
|
Add SessionStateTests to AssemblyLoadContext collection
|
C#
|
mit
|
daxian-dbw/PowerShell,jsoref/PowerShell,TravisEz13/PowerShell,PaulHigin/PowerShell,PaulHigin/PowerShell,JamesWTruher/PowerShell-1,jsoref/PowerShell,bmanikm/PowerShell,JamesWTruher/PowerShell-1,bmanikm/PowerShell,kmosher/PowerShell,KarolKaczmarek/PowerShell,JamesWTruher/PowerShell-1,bmanikm/PowerShell,kmosher/PowerShell,bingbing8/PowerShell,TravisEz13/PowerShell,jsoref/PowerShell,KarolKaczmarek/PowerShell,KarolKaczmarek/PowerShell,KarolKaczmarek/PowerShell,bingbing8/PowerShell,bmanikm/PowerShell,kmosher/PowerShell,jsoref/PowerShell,JamesWTruher/PowerShell-1,bingbing8/PowerShell,jsoref/PowerShell,TravisEz13/PowerShell,kmosher/PowerShell,PaulHigin/PowerShell,bingbing8/PowerShell,daxian-dbw/PowerShell,daxian-dbw/PowerShell,bmanikm/PowerShell,kmosher/PowerShell,TravisEz13/PowerShell,bingbing8/PowerShell,daxian-dbw/PowerShell,PaulHigin/PowerShell,KarolKaczmarek/PowerShell
|
56612b09fb0535fc8132231c0752442ea8592db3
|
Mail2Bug/Email/AckEmailHandler.cs
|
Mail2Bug/Email/AckEmailHandler.cs
|
using System.Text;
using log4net;
using Mail2Bug.Email.EWS;
namespace Mail2Bug.Email
{
class AckEmailHandler
{
private readonly Config.InstanceConfig _config;
public AckEmailHandler(Config.InstanceConfig config)
{
_config = config;
}
/// <summary>
/// Send mail announcing receipt of new ticket
/// </summary>
public void SendAckEmail(IIncomingEmailMessage originalMessage, string workItemId)
{
// Don't send ack emails if it's disabled in configuration or if we're in simulation mode
if (!_config.EmailSettings.SendAckEmails || _config.TfsServerConfig.SimulationMode)
{
Logger.DebugFormat("Ack emails disabled in configuration - skipping");
return;
}
var ewsMessage = originalMessage as EWSIncomingMessage;
if (ewsMessage != null)
{
HandleEWSMessage(ewsMessage, workItemId);
}
}
private void HandleEWSMessage(EWSIncomingMessage originalMessage, string workItemId)
{
originalMessage.Reply(GetReplyContents(workItemId), _config.EmailSettings.AckEmailsRecipientsAll);
}
private string GetReplyContents(string workItemId)
{
var bodyBuilder = new StringBuilder();
bodyBuilder.Append(_config.EmailSettings.GetReplyTemplate());
bodyBuilder.Replace("[BUGID]", workItemId);
bodyBuilder.Replace("[TFSCollectionUri]", _config.TfsServerConfig.CollectionUri);
return bodyBuilder.ToString();
}
private static readonly ILog Logger = LogManager.GetLogger(typeof(AckEmailHandler));
}
}
|
using System.Text;
using log4net;
using Mail2Bug.Email.EWS;
namespace Mail2Bug.Email
{
class AckEmailHandler
{
private readonly Config.InstanceConfig _config;
public AckEmailHandler(Config.InstanceConfig config)
{
_config = config;
}
/// <summary>
/// Send mail announcing receipt of new ticket
/// </summary>
public void SendAckEmail(IIncomingEmailMessage originalMessage, string workItemId)
{
// Don't send ack emails if it's disabled in configuration
if (!_config.EmailSettings.SendAckEmails)
{
Logger.DebugFormat("Ack emails disabled in configuration - skipping");
return;
}
var ewsMessage = originalMessage as EWSIncomingMessage;
if (ewsMessage != null)
{
HandleEWSMessage(ewsMessage, workItemId);
}
}
private void HandleEWSMessage(EWSIncomingMessage originalMessage, string workItemId)
{
originalMessage.Reply(GetReplyContents(workItemId), _config.EmailSettings.AckEmailsRecipientsAll);
}
private string GetReplyContents(string workItemId)
{
var bodyBuilder = new StringBuilder();
bodyBuilder.Append(_config.EmailSettings.GetReplyTemplate());
bodyBuilder.Replace("[BUGID]", workItemId);
bodyBuilder.Replace("[TFSCollectionUri]", _config.TfsServerConfig.CollectionUri);
return bodyBuilder.ToString();
}
private static readonly ILog Logger = LogManager.GetLogger(typeof(AckEmailHandler));
}
}
|
Send Ack emails even if the system is in Simulation Mode.
|
Send Ack emails even if the system is in Simulation Mode.
|
C#
|
mit
|
vitru/mail2bug,Spurrya/mail2bug,mrpeterson27/mail2bug,mbmccormick/mail2bug
|
1d57d0cba6bd60d0f5a28630b349e75b36ccd89e
|
src/Discord.Net.Rest/Entities/Invites/RestInviteMetadata.cs
|
src/Discord.Net.Rest/Entities/Invites/RestInviteMetadata.cs
|
using System;
using Model = Discord.API.InviteMetadata;
namespace Discord.Rest
{
public class RestInviteMetadata : RestInvite, IInviteMetadata
{
private long _createdAtTicks;
public bool IsRevoked { get; private set; }
public bool IsTemporary { get; private set; }
public int? MaxAge { get; private set; }
public int? MaxUses { get; private set; }
public int Uses { get; private set; }
public RestUser Inviter { get; private set; }
public DateTimeOffset CreatedAt => DateTimeUtils.FromTicks(_createdAtTicks);
internal RestInviteMetadata(BaseDiscordClient discord, IGuild guild, IChannel channel, string id)
: base(discord, guild, channel, id)
{
}
internal static RestInviteMetadata Create(BaseDiscordClient discord, IGuild guild, IChannel channel, Model model)
{
var entity = new RestInviteMetadata(discord, guild, channel, model.Code);
entity.Update(model);
return entity;
}
internal void Update(Model model)
{
base.Update(model);
Inviter = RestUser.Create(Discord, model.Inviter);
IsRevoked = model.Revoked;
IsTemporary = model.Temporary;
MaxAge = model.MaxAge != 0 ? model.MaxAge : (int?)null;
MaxUses = model.MaxUses;
Uses = model.Uses;
_createdAtTicks = model.CreatedAt.UtcTicks;
}
IUser IInviteMetadata.Inviter => Inviter;
}
}
|
using System;
using Model = Discord.API.InviteMetadata;
namespace Discord.Rest
{
public class RestInviteMetadata : RestInvite, IInviteMetadata
{
private long _createdAtTicks;
public bool IsRevoked { get; private set; }
public bool IsTemporary { get; private set; }
public int? MaxAge { get; private set; }
public int? MaxUses { get; private set; }
public int Uses { get; private set; }
public RestUser Inviter { get; private set; }
public DateTimeOffset CreatedAt => DateTimeUtils.FromTicks(_createdAtTicks);
internal RestInviteMetadata(BaseDiscordClient discord, IGuild guild, IChannel channel, string id)
: base(discord, guild, channel, id)
{
}
internal static RestInviteMetadata Create(BaseDiscordClient discord, IGuild guild, IChannel channel, Model model)
{
var entity = new RestInviteMetadata(discord, guild, channel, model.Code);
entity.Update(model);
return entity;
}
internal void Update(Model model)
{
base.Update(model);
Inviter = model.Inviter != null ? RestUser.Create(Discord, model.Inviter) : null;
IsRevoked = model.Revoked;
IsTemporary = model.Temporary;
MaxAge = model.MaxAge != 0 ? model.MaxAge : (int?)null;
MaxUses = model.MaxUses;
Uses = model.Uses;
_createdAtTicks = model.CreatedAt.UtcTicks;
}
IUser IInviteMetadata.Inviter => Inviter;
}
}
|
Add support for invites without attached users
|
Add support for invites without attached users
|
C#
|
mit
|
AntiTcb/Discord.Net,Confruggy/Discord.Net,LassieME/Discord.Net,RogueException/Discord.Net
|
dd2a0eb00226f0564ef26581edf784177be52313
|
src/Webpack.AspNetCore/Static/PhysicalFileManifestReader.cs
|
src/Webpack.AspNetCore/Static/PhysicalFileManifestReader.cs
|
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Webpack.AspNetCore.Internal;
namespace Webpack.AspNetCore.Static
{
internal class PhysicalFileManifestReader : IManifestReader
{
private readonly WebpackContext context;
public PhysicalFileManifestReader(WebpackContext context)
{
this.context = context ?? throw new System.ArgumentNullException(nameof(context));
}
public async ValueTask<IDictionary<string, string>> ReadAsync()
{
var manifestFileInfo = context.GetManifestFileInfo();
if (!manifestFileInfo.Exists)
{
return null;
}
try
{
using (var manifestStream = manifestFileInfo.CreateReadStream())
{
using (var manifestReader = new StreamReader(manifestStream))
{
var manifestJson = await manifestReader.ReadToEndAsync();
try
{
return JsonConvert.DeserializeObject<Dictionary<string, string>>(
manifestJson
);
}
catch (JsonException)
{
return null;
}
}
}
}
catch (FileNotFoundException)
{
return null;
}
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Webpack.AspNetCore.Internal;
namespace Webpack.AspNetCore.Static
{
internal class PhysicalFileManifestReader : IManifestReader
{
private readonly WebpackContext context;
public PhysicalFileManifestReader(WebpackContext context)
{
this.context = context ?? throw new System.ArgumentNullException(nameof(context));
}
/// <summary>
/// Reads manifest from the physical file, specified in
/// <see cref="WebpackContext" /> as a deserialized dictionary
/// </summary>
/// <returns>
/// Manifest dictionary if succeeded to read and parse json manifest file,
/// otherwise false
/// </returns>
public async ValueTask<IDictionary<string, string>> ReadAsync()
{
var manifestFileInfo = context.GetManifestFileInfo();
if (!manifestFileInfo.Exists)
{
return null;
}
try
{
// even though we've checked if the manifest
// file exists by the time we get here the file
// could become deleted or partially updated
using (var manifestStream = manifestFileInfo.CreateReadStream())
using (var manifestReader = new StreamReader(manifestStream))
{
var manifestJson = await manifestReader.ReadToEndAsync();
return JsonConvert.DeserializeObject<Dictionary<string, string>>(
manifestJson
);
}
}
catch (Exception ex) when (shouldHandle(ex))
{
return null;
}
bool shouldHandle(Exception ex) => ex is IOException || ex is JsonException;
}
}
}
|
Update exception handling for physical file manifest reader
|
Update exception handling for physical file manifest reader
|
C#
|
mit
|
sergeysolovev/webpack-aspnetcore,sergeysolovev/webpack-aspnetcore,sergeysolovev/webpack-aspnetcore
|
9b750783527ab7f6daedf410c25832171ffecb9d
|
Assets/scripts/utils/TableNetworking.cs
|
Assets/scripts/utils/TableNetworking.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class TableNetworking : NetworkBehaviour
{
[SyncVar]
public string variant;
[SyncVar]
public string table;
[SyncVar]
public bool selected;
[ServerCallback]
void Start ()
{
selected = false;
table = "";
variant = "";
}
public string GetTable()
{
return table;
}
public string GetVariant()
{
return variant;
}
public bool ServerHasSelected()
{
return selected;
}
public void SetTableInfo(string serverVariant, string serverTable)
{
selected = true;
variant = serverVariant;
table = serverTable;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class TableNetworking : NetworkBehaviour
{
[SyncVar]
public string variant;
[SyncVar]
public string table;
[SyncVar]
public bool selected;
public float logPingFrequency = 5.0f;
[ServerCallback]
void Start ()
{
selected = false;
table = "";
variant = "";
InvokeRepeating("LogPing", 0.0f, logPingFrequency);
}
void OnClientConnect(NetworkConnection conn)
{
InvokeRepeating("LogPing", 0.0f, logPingFrequency);
}
void LogPing()
{
foreach (NetworkClient conn in NetworkClient.allClients)
{
Debug.Log("Ping for connection " + conn.connection.address.ToString() + ": " + conn.GetRTT().ToString() + " (ms)");
}
}
public string GetTable()
{
return table;
}
public string GetVariant()
{
return variant;
}
public bool ServerHasSelected()
{
return selected;
}
public void SetTableInfo(string serverVariant, string serverTable)
{
selected = true;
variant = serverVariant;
table = serverTable;
}
}
|
Add debug log for latency on server
|
Add debug log for latency on server
|
C#
|
mit
|
Double-Fine-Game-Club/pongball
|
9055f5426deecf1069e5e3054cfbee2a09832a66
|
Rainy/WebService/Admin/StatusService.cs
|
Rainy/WebService/Admin/StatusService.cs
|
using ServiceStack.ServiceHost;
using Rainy.Db;
using ServiceStack.OrmLite;
using System;
using ServiceStack.ServiceInterface.Cors;
using ServiceStack.Common.Web;
namespace Rainy.WebService.Admin
{
[Route("/api/admin/status/","GET, OPTIONS")]
[AdminPasswordRequired]
public class StatusRequest : IReturn<Status>
{
}
public class StatusService : ServiceBase {
public StatusService (IDbConnectionFactory fac) : base (fac)
{
}
public Status Get (StatusRequest req)
{
var s = new Status ();
s.Uptime = MainClass.Uptime;
s.NumberOfRequests = MainClass.ServedRequests;
// determine number of users
using (var conn = connFactory.OpenDbConnection ()) {
s.NumberOfUser = conn.Scalar<int>("SELECT COUNT(*) FROM DBUser");
s.TotalNumberOfNotes = conn.Scalar<int>("SELECT COUNT(*) FROM DBNote");
s.AverageNotesPerUser = (float)s.TotalNumberOfNotes / (float)s.NumberOfUser;
};
return s;
}
}
public class Status
{
public DateTime Uptime { get; set; }
public int NumberOfUser { get; set; }
public long NumberOfRequests { get; set; }
public int TotalNumberOfNotes { get; set; }
public float AverageNotesPerUser { get; set; }
}
}
|
using ServiceStack.ServiceHost;
using Rainy.Db;
using ServiceStack.OrmLite;
using System;
using ServiceStack.ServiceInterface.Cors;
using ServiceStack.Common.Web;
namespace Rainy.WebService.Admin
{
[Route("/api/admin/status/","GET, OPTIONS")]
[AdminPasswordRequired]
public class StatusRequest : IReturn<Status>
{
}
public class StatusService : ServiceBase {
public StatusService (IDbConnectionFactory fac) : base (fac)
{
}
public Status Get (StatusRequest req)
{
var s = new Status ();
s.Uptime = MainClass.Uptime;
s.NumberOfRequests = MainClass.ServedRequests;
// determine number of users
using (var conn = connFactory.OpenDbConnection ()) {
s.NumberOfUser = conn.Scalar<int>("SELECT COUNT(*) FROM DBUser");
s.TotalNumberOfNotes = conn.Scalar<int>("SELECT COUNT(*) FROM DBNote");
if (s.NumberOfUser > 0)
s.AverageNotesPerUser = (float)s.TotalNumberOfNotes / (float)s.NumberOfUser;
};
return s;
}
}
public class Status
{
public DateTime Uptime { get; set; }
public int NumberOfUser { get; set; }
public long NumberOfRequests { get; set; }
public int TotalNumberOfNotes { get; set; }
public float AverageNotesPerUser { get; set; }
}
}
|
Fix division by zero bug for status service
|
Fix division by zero bug for status service
|
C#
|
agpl-3.0
|
Dynalon/Rainy,Dynalon/Rainy,Dynalon/Rainy,Dynalon/Rainy
|
a49289141c5760ebd31818af1882d7a569a9c1fb
|
src/TestHelper/OracleConnectionBuilder.cs
|
src/TestHelper/OracleConnectionBuilder.cs
|
#if NETFRAMEWORK
using System;
using Oracle.ManagedDataAccess.Client;
public static class OracleConnectionBuilder
{
public static OracleConnection Build()
{
return Build(false);
}
public static OracleConnection Build(bool disableMetadataPooling)
{
var connection = Environment.GetEnvironmentVariable("OracleConnectionString");
if (string.IsNullOrWhiteSpace(connection))
{
throw new Exception("OracleConnectionString environment variable is empty");
}
if (disableMetadataPooling)
{
var builder = new OracleConnectionStringBuilder(connection)
{
MetadataPooling = false
};
connection = builder.ConnectionString;
}
return new OracleConnection(connection);
}
}
#endif
|
using System;
using Oracle.ManagedDataAccess.Client;
public static class OracleConnectionBuilder
{
public static OracleConnection Build()
{
return Build(false);
}
public static OracleConnection Build(bool disableMetadataPooling)
{
var connection = Environment.GetEnvironmentVariable("OracleConnectionString");
if (string.IsNullOrWhiteSpace(connection))
{
throw new Exception("OracleConnectionString environment variable is empty");
}
if (disableMetadataPooling)
{
var builder = new OracleConnectionStringBuilder(connection)
{
MetadataPooling = false
};
connection = builder.ConnectionString;
}
return new OracleConnection(connection);
}
}
|
Remove conditional Oracle connection builder compilation
|
Remove conditional Oracle connection builder compilation
|
C#
|
mit
|
NServiceBusSqlPersistence/NServiceBus.SqlPersistence
|
ed36084c25845bfbf69307b1f26499175c3fd933
|
samples/MvcSample.Web/Startup.cs
|
samples/MvcSample.Web/Startup.cs
|
#if NET45
using Microsoft.AspNet.Abstractions;
using Microsoft.AspNet.DependencyInjection;
using Microsoft.AspNet.DependencyInjection.Fallback;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Routing;
namespace MvcSample.Web
{
public class Startup
{
public void Configuration(IBuilder builder)
{
var services = new ServiceCollection();
services.Add(MvcServices.GetDefaultServices());
services.AddSingleton<PassThroughAttribute, PassThroughAttribute>();
var serviceProvider = services.BuildServiceProvider(builder.ServiceProvider);
var routes = new RouteCollection()
{
DefaultHandler = new MvcApplication(serviceProvider),
};
// TODO: Add support for route constraints, so we can potentially constrain by existing routes
routes.MapRoute("{area}/{controller}/{action}");
routes.MapRoute(
"{controller}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute(
"{controller}",
new { controller = "Home" });
builder.UseRouter(routes);
}
}
}
#endif
|
using Microsoft.AspNet.Abstractions;
using Microsoft.AspNet.DependencyInjection;
using Microsoft.AspNet.DependencyInjection.Fallback;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Routing;
namespace MvcSample.Web
{
public class Startup
{
public void Configuration(IBuilder builder)
{
var services = new ServiceCollection();
services.Add(MvcServices.GetDefaultServices());
services.AddSingleton<PassThroughAttribute, PassThroughAttribute>();
var serviceProvider = services.BuildServiceProvider(builder.ServiceProvider);
var routes = new RouteCollection()
{
DefaultHandler = new MvcApplication(serviceProvider),
};
// TODO: Add support for route constraints, so we can potentially constrain by existing routes
routes.MapRoute("{area}/{controller}/{action}");
routes.MapRoute(
"{controller}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute(
"{controller}",
new { controller = "Home" });
builder.UseRouter(routes);
}
}
}
|
Remove ifdef for net45 in sample
|
Remove ifdef for net45 in sample
|
C#
|
apache-2.0
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
5b5e95b69af18a8f22b975fb409e0937f7b70247
|
Battery-Commander.Tests/ACFTTests.cs
|
Battery-Commander.Tests/ACFTTests.cs
|
using BatteryCommander.Web.Models.Data;
using System;
using Xunit;
namespace BatteryCommander.Tests
{
public class ACFTTests
{
[Theory]
[InlineData(15, 54, 84)]
public void Calculate_Run_Score(int minutes, int seconds, int expected)
{
Assert.Equal(expected, ACFTScoreTables.TwoMileRun(new TimeSpan(0, minutes, seconds)));
}
}
}
|
using BatteryCommander.Web.Models.Data;
using System;
using Xunit;
namespace BatteryCommander.Tests
{
public class ACFTTests
{
[Theory]
[InlineData(15, 54, 84)]
[InlineData(13, 29, 100)]
[InlineData(23, 01, 0)]
[InlineData(19, 05, 64)]
[InlineData(17, 42, 72)]
public void Calculate_Run_Score(int minutes, int seconds, int expected)
{
Assert.Equal(expected, ACFTScoreTables.TwoMileRun(new TimeSpan(0, minutes, seconds)));
}
[Theory]
[InlineData(61, 100)]
[InlineData(30, 70)]
public void Calculate_Pushups(int reps, int expected)
{
Assert.Equal(expected, ACFTScoreTables.HandReleasePushUps(reps));
}
}
}
|
Add basic test for pushups and run
|
Add basic test for pushups and run
|
C#
|
mit
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
8e961dba625185f4742ddc2e27b67bfc37af90af
|
Commencement.Core/Domain/Template.cs
|
Commencement.Core/Domain/Template.cs
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using FluentNHibernate.Mapping;
using UCDArch.Core.DomainModel;
namespace Commencement.Core.Domain
{
public class Template : DomainObject
{
public Template(string bodyText, TemplateType templateType, Ceremony ceremony)
{
BodyText = bodyText;
TemplateType = templateType;
Ceremony = ceremony;
SetDefaults();
}
public Template()
{
SetDefaults();
}
private void SetDefaults()
{
IsActive = true;
}
[Required]
public virtual string BodyText { get; set; }
[Required]
public virtual TemplateType TemplateType { get; set; }
[Required]
public virtual Ceremony Ceremony { get; set; }
public virtual bool IsActive { get; set; }
[StringLength(100)]
public virtual string Subject { get; set; }
}
public class TemplateMap : ClassMap<Template>
{
public TemplateMap()
{
Id(x => x.Id);
Map(x => x.BodyText);
Map(x => x.IsActive);
Map(x => x.Subject);
References(x => x.TemplateType);
References(x => x.Ceremony);
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using FluentNHibernate.Mapping;
using UCDArch.Core.DomainModel;
namespace Commencement.Core.Domain
{
public class Template : DomainObject
{
public Template(string bodyText, TemplateType templateType, Ceremony ceremony)
{
BodyText = bodyText;
TemplateType = templateType;
Ceremony = ceremony;
SetDefaults();
}
public Template()
{
SetDefaults();
}
private void SetDefaults()
{
IsActive = true;
}
[Required]
public virtual string BodyText { get; set; }
[Required]
public virtual TemplateType TemplateType { get; set; }
[Required]
public virtual Ceremony Ceremony { get; set; }
public virtual bool IsActive { get; set; }
[StringLength(100)]
public virtual string Subject { get; set; }
}
public class TemplateMap : ClassMap<Template>
{
public TemplateMap()
{
Id(x => x.Id);
Map(x => x.BodyText).Length(int.MaxValue);
Map(x => x.IsActive);
Map(x => x.Subject);
References(x => x.TemplateType);
References(x => x.Ceremony);
}
}
}
|
Make sure BodyText can take a large string.
|
Make sure BodyText can take a large string.
|
C#
|
mit
|
ucdavis/Commencement,ucdavis/Commencement,ucdavis/Commencement
|
93fe57d39970ee9c9dcc7dc0a757c2537aa10e55
|
osu.Game.Tests/NonVisual/BeatmapSetInfoEqualityTest.cs
|
osu.Game.Tests/NonVisual/BeatmapSetInfoEqualityTest.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
namespace osu.Game.Tests.NonVisual
{
[TestFixture]
public class BeatmapSetInfoEqualityTest
{
[Test]
public void TestOnlineWithOnline()
{
var ourInfo = new BeatmapSetInfo { OnlineID = 123 };
var otherInfo = new BeatmapSetInfo { OnlineID = 123 };
Assert.AreEqual(ourInfo, otherInfo);
}
[Test]
public void TestDatabasedWithDatabased()
{
var ourInfo = new BeatmapSetInfo { ID = 123 };
var otherInfo = new BeatmapSetInfo { ID = 123 };
Assert.AreEqual(ourInfo, otherInfo);
}
[Test]
public void TestDatabasedWithOnline()
{
var ourInfo = new BeatmapSetInfo { ID = 123, OnlineID = 12 };
var otherInfo = new BeatmapSetInfo { OnlineID = 12 };
Assert.AreEqual(ourInfo, otherInfo);
}
[Test]
public void TestCheckNullID()
{
var ourInfo = new BeatmapSetInfo { Hash = "1" };
var otherInfo = new BeatmapSetInfo { Hash = "2" };
Assert.AreNotEqual(ourInfo, otherInfo);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Extensions;
namespace osu.Game.Tests.NonVisual
{
[TestFixture]
public class BeatmapSetInfoEqualityTest
{
[Test]
public void TestOnlineWithOnline()
{
var ourInfo = new BeatmapSetInfo { OnlineID = 123 };
var otherInfo = new BeatmapSetInfo { OnlineID = 123 };
Assert.AreNotEqual(ourInfo, otherInfo);
Assert.IsTrue(ourInfo.MatchesOnlineID(otherInfo));
}
[Test]
public void TestDatabasedWithDatabased()
{
var ourInfo = new BeatmapSetInfo { ID = 123 };
var otherInfo = new BeatmapSetInfo { ID = 123 };
Assert.AreEqual(ourInfo, otherInfo);
}
[Test]
public void TestDatabasedWithOnline()
{
var ourInfo = new BeatmapSetInfo { ID = 123, OnlineID = 12 };
var otherInfo = new BeatmapSetInfo { OnlineID = 12 };
Assert.AreNotEqual(ourInfo, otherInfo);
Assert.IsTrue(ourInfo.MatchesOnlineID(otherInfo));
}
[Test]
public void TestCheckNullID()
{
var ourInfo = new BeatmapSetInfo { Hash = "1" };
var otherInfo = new BeatmapSetInfo { Hash = "2" };
Assert.AreNotEqual(ourInfo, otherInfo);
}
}
}
|
Update tests to match new equality not including online ID checks
|
Update tests to match new equality not including online ID checks
|
C#
|
mit
|
ppy/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu
|
456a83f396932bdf65f31f151cbc5ef5141c0542
|
ExpressionToCodeTest/ApprovalTest.cs
|
ExpressionToCodeTest/ApprovalTest.cs
|
using System.IO;
using System.Runtime.CompilerServices;
using Assent;
namespace ExpressionToCodeTest
{
static class ApprovalTest
{
public static void Verify(string text, [CallerFilePath] string filepath = null, [CallerMemberName] string membername = null)
{
var filename = Path.GetFileNameWithoutExtension(filepath);
var filedir = Path.GetDirectoryName(filepath);
var config = new Configuration().UsingNamer(new Assent.Namers.FixedNamer(Path.Combine(filedir, filename + "." + membername)));
"bla".Assent(text, config, membername, filepath);
//var writer = WriterFactory.CreateTextWriter(text);
//var namer = new SaneNamer { Name = filename + "." + membername, SourcePath = filedir };
//var reporter = new DiffReporter();
//Approver.Verify(new FileApprover(writer, namer, true), reporter);
}
//public class SaneNamer : IApprovalNamer
//{
// public string SourcePath { get; set; }
// public string Name { get; set; }
//}
}
}
|
using System.IO;
using System.Runtime.CompilerServices;
using Assent;
namespace ExpressionToCodeTest
{
static class ApprovalTest
{
public static void Verify(string text, [CallerFilePath] string filepath = null, [CallerMemberName] string membername = null)
{
var filename = Path.GetFileNameWithoutExtension(filepath);
var filedir = Path.GetDirectoryName(filepath) ?? throw new InvalidOperationException("path " + filepath + " has no directory");
var config = new Configuration().UsingNamer(new Assent.Namers.FixedNamer(Path.Combine(filedir, filename + "." + membername)));
"bla".Assent(text, config, membername, filepath);
//var writer = WriterFactory.CreateTextWriter(text);
//var namer = new SaneNamer { Name = filename + "." + membername, SourcePath = filedir };
//var reporter = new DiffReporter();
//Approver.Verify(new FileApprover(writer, namer, true), reporter);
}
//public class SaneNamer : IApprovalNamer
//{
// public string SourcePath { get; set; }
// public string Name { get; set; }
//}
}
}
|
Throw exception for crazy input
|
Throw exception for crazy input
|
C#
|
apache-2.0
|
EamonNerbonne/ExpressionToCode
|
bb8ce18207a48a01e4e9ffa878392c27103e3cd5
|
tests/Faker.Tests/RandomNumberFixture.cs
|
tests/Faker.Tests/RandomNumberFixture.cs
|
using System;
using System.Linq;
using NUnit.Framework;
namespace Faker.Tests
{
[TestFixture]
public class RandomNumberFixture
{
[TestCase(1, "Coin flip")] // 0 ... 1 Coin flip
[TestCase(6, "6 sided die")] // 0 .. 6
[TestCase(9, "Random single digit")] // 0 ... 9
[TestCase(20, "D20")] // 0 ... 20 The signature dice of the dungeons and dragons
public void Should_Yield_All_ValuesWithinRange(int maxValue, string testName)
{
var maxExclusiveLimit = maxValue + 1;
Console.WriteLine($@"RandomNumber.Next [{testName}]");
var results = Enumerable.Range(0, maxExclusiveLimit).ToDictionary(k => k, k => false);
do
{
var randValue = RandomNumber.Next(0, maxExclusiveLimit);
results[randValue] = true;
Console.WriteLine($@"RandomNumber.Next(0,maxValueExclusive)=[{randValue}]");
} while (!results.All(j => j.Value));
Assert.IsTrue(results.Select(z => z.Value).All(y => y));
}
[Test]
public void Should_Create_Zero()
{
var zero = RandomNumber.Next(0, 0);
Console.WriteLine($@"RandomNumber.Next(0,0)=[{zero}]");
Assert.IsTrue(zero == 0);
}
}
}
|
using System;
using System.Linq;
using NUnit.Framework;
namespace Faker.Tests
{
[TestFixture]
public class RandomNumberFixture
{
[TestCase(1, "Coin flip")] // 0 ... 1 Coin flip
[TestCase(6, "6 sided die")] // 0 .. 6
[TestCase(9, "Random single digit")] // 0 ... 9
[TestCase(20, "D20")] // 0 ... 20 The signature dice of the dungeons and dragons
public void Should_Yield_All_ValuesWithinRange(int maxValue, string testName)
{
var maxExclusiveLimit = maxValue + 1;
Console.WriteLine($@"RandomNumber.Next [{testName}]");
var results = Enumerable.Range(0, maxExclusiveLimit).ToDictionary(k => k, k => false);
do
{
var randValue = RandomNumber.Next(0, maxExclusiveLimit);
results[randValue] = true;
Console.WriteLine($@"RandomNumber.Next(0,{maxExclusiveLimit})=[{randValue}]");
} while (!results.All(j => j.Value));
Assert.IsTrue(results.Select(z => z.Value).All(y => y));
}
[Test]
public void Should_Create_Zero()
{
var zero = RandomNumber.Next(0, 0);
Console.WriteLine($@"RandomNumber.Next(0,0)=[{zero}]");
Assert.IsTrue(zero == 0);
}
}
}
|
Fix name on test console write out
|
Fix name on test console write out
|
C#
|
mit
|
oriches/faker-cs,oriches/faker-cs
|
b2e29c2473db10f46394ded80f88f548df54c8e2
|
src/Data/Settings.cs
|
src/Data/Settings.cs
|
using System;
namespace Rooijakkers.MeditationTimer.Data
{
/// <summary>
/// Stores settings data in local settings storage
/// </summary>
public class Settings
{
private const string TIME_TO_GET_READY_IN_SECONDS_STORAGE = "TimeToGetReadyStorage";
public TimeSpan TimeToGetReady
{
get
{
var secondsToGetReady =
Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE];
if (secondsToGetReady == null)
{
secondsToGetReady = Constants.DEFAULT_TIME_TO_GET_READY_IN_SECONDS;
SetTimeToGetReady(Convert.ToInt32(secondsToGetReady));
}
// Return stored time in seconds as a TimeSpan.
return new TimeSpan(0, 0, Convert.ToInt32(secondsToGetReady));
}
set
{
// Store time in seconds obtained from TimeSpan.
SetTimeToGetReady(value.Seconds);
}
}
private void SetTimeToGetReady(int value)
{
Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] = value;
}
}
}
|
using System;
namespace Rooijakkers.MeditationTimer.Data
{
/// <summary>
/// Stores settings data in local settings storage
/// </summary>
public class Settings
{
private const string TIME_TO_GET_READY_IN_SECONDS_STORAGE = "TimeToGetReadyStorage";
public TimeSpan TimeToGetReady
{
get
{
int? secondsToGetReady =
Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] as int?;
// If settings were not yet stored set to default value.
if (secondsToGetReady == null)
{
secondsToGetReady = Constants.DEFAULT_TIME_TO_GET_READY_IN_SECONDS;
SetTimeToGetReady(secondsToGetReady.Value);
}
// Return stored time in seconds as a TimeSpan.
return new TimeSpan(0, 0, secondsToGetReady.Value);
}
set
{
// Store time in seconds obtained from TimeSpan.
SetTimeToGetReady(value.Seconds);
}
}
private void SetTimeToGetReady(int value)
{
Windows.Storage.ApplicationData.Current.LocalSettings.Values[TIME_TO_GET_READY_IN_SECONDS_STORAGE] = value;
}
}
}
|
Make settings object bit cleaner
|
Make settings object bit cleaner
|
C#
|
mit
|
erooijak/MeditationTimer
|
3fb41a20b55aa7e2d5270195e1a182dec18ed80b
|
osu.Game/Online/RealtimeMultiplayer/MultiplayerRoomSettings.cs
|
osu.Game/Online/RealtimeMultiplayer/MultiplayerRoomSettings.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Game.Online.API;
namespace osu.Game.Online.RealtimeMultiplayer
{
[Serializable]
public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
{
public int? BeatmapID { get; set; }
public int? RulesetID { get; set; }
[NotNull]
public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();
public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID;
public override string ToString() => $"Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}";
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Game.Online.API;
namespace osu.Game.Online.RealtimeMultiplayer
{
[Serializable]
public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
{
public int? BeatmapID { get; set; }
public int? RulesetID { get; set; }
public string Name { get; set; } = "Unnamed room";
[NotNull]
public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();
public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID && Name.Equals(other.Name, StringComparison.Ordinal);
public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}";
}
}
|
Add room name to settings
|
Add room name to settings
|
C#
|
mit
|
smoogipoo/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,ppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu
|
840a96480fdf7ba510152b16e59d6f80f7aa295d
|
CalendarProxy/Views/Shared/_Layout.cshtml
|
CalendarProxy/Views/Shared/_Layout.cshtml
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - Calendar Proxy</title>
<link href="~/Content/iCalStyles.min.css" rel="stylesheet" />
<link href="~/Content/timer.min.css" rel="stylesheet" />
<link href="~/Content/calendar-proxy-form.css" rel="stylesheet" />
<link href="~/Content/texteffects.min.css" rel="stylesheet" />
</head>
<body>
<div class="navbar fixed-top navbar-dark bg-primary">
<div class="container">
<div class="navbar-header">
@Html.ActionLink("Calendar Proxy", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
</div>
</div>
<div class="body-content">
<div class="container">
@RenderBody()
</div>
</div>
<script src="~/Scripts/ical.min.js"></script>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/icalrender.min.js"></script>
<script src="~/Scripts/calendar-proxy-form.min.js"></script>
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - Calendar Proxy</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/iCalStyles.min.css" rel="stylesheet" />
<link href="~/Content/timer.min.css" rel="stylesheet" />
<link href="~/Content/calendar-proxy-form.css" rel="stylesheet" />
<link href="~/Content/texteffects.min.css" rel="stylesheet" />
</head>
<body>
<div class="navbar fixed-top navbar-dark bg-primary">
<div class="container">
<div class="navbar-header">
@Html.ActionLink("Calendar Proxy", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
</div>
</div>
<div class="body-content">
<div class="container">
@RenderBody()
</div>
</div>
<script src="~/Scripts/ical.min.js"></script>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/icalrender.min.js"></script>
<script src="~/Scripts/calendar-proxy-form.min.js"></script>
</body>
</html>
|
Add missing bootstrap reference (after removing bootswatch)
|
Add missing bootstrap reference (after removing bootswatch)
|
C#
|
mit
|
taurit/TodoistCalendar,taurit/TodoistCalendar,taurit/CalendarProxy,taurit/CalendarProxy,taurit/TodoistCalendar
|
1032ba42c3813af861604bd9fc2e116c5cc5e458
|
OmniSharp/Rename/ModifiedFileResponse.cs
|
OmniSharp/Rename/ModifiedFileResponse.cs
|
namespace OmniSharp.Rename
{
public class ModifiedFileResponse
{
public ModifiedFileResponse() {}
public ModifiedFileResponse(string fileName, string buffer) {
this.FileName = fileName;
this.Buffer = buffer;
}
public string FileName { get; set; }
public string Buffer { get; set; }
}
}
|
using OmniSharp.Solution;
namespace OmniSharp.Rename
{
public class ModifiedFileResponse
{
private string _fileName;
public ModifiedFileResponse() {}
public ModifiedFileResponse(string fileName, string buffer) {
this.FileName = fileName;
this.Buffer = buffer;
}
public string FileName
{
get { return _fileName; }
set
{
_fileName = value.ApplyPathReplacementsForClient();
}
}
public string Buffer { get; set; }
}
}
|
Add Cygwin path replacement for Rename/Override
|
Add Cygwin path replacement for Rename/Override
|
C#
|
mit
|
x335/omnisharp-server,corngood/omnisharp-server,syl20bnr/omnisharp-server,corngood/omnisharp-server,x335/omnisharp-server,syl20bnr/omnisharp-server,svermeulen/omnisharp-server,OmniSharp/omnisharp-server
|
53e1d700d4896e893cc1d743c8c58e1c7af16129
|
Gu.Units.Tests/UnitParserTests.cs
|
Gu.Units.Tests/UnitParserTests.cs
|
namespace Gu.Units.Tests
{
using NUnit.Framework;
public class UnitParserTests
{
[TestCase("1m", 1)]
[TestCase("-1m", -1)]
[TestCase("1e3m", 1e3)]
[TestCase("1e+3m", 1e+3)]
[TestCase("-1e+3m", -1e+3)]
[TestCase("1e-3m", 1e-3)]
[TestCase("-1e-3m", -1e-3)]
[TestCase(" 1m", 1)]
[TestCase("1m ", 1)]
[TestCase("1 m", 1)]
[TestCase("1 m ", 1)]
[TestCase("1 m", 1)]
[TestCase("1m ", 1)]
public void ParseLength(string s, double expected)
{
var length = UnitParser.Parse<ILengthUnit, Length>(s, Length.From);
Assert.AreEqual(expected, length.Meters);
}
[TestCase("1s", 1)]
public void ParseTime(string s, double expected)
{
var time = UnitParser.Parse<ITimeUnit, Time>(s, Time.From);
Assert.AreEqual(expected, time.Seconds);
}
}
}
|
namespace Gu.Units.Tests
{
using NUnit.Framework;
public class UnitParserTests
{
[TestCase("1m", 1)]
[TestCase("-1m", 1)]
[TestCase("1e3m", 1e3)]
[TestCase("1e+3m", 1e+3)]
[TestCase("1e-3m", 1e-3)]
[TestCase(" 1m", 1)]
[TestCase("1 m", 1)]
[TestCase("1m ", 1)]
public void ParseLength(string s, double expected)
{
var length = UnitParser.Parse<ILengthUnit, Length>(s, Length.From);
Assert.AreEqual(expected, length.Meters);
}
}
}
|
Revert "Added 5 tests for Length and a test for Time"
|
Revert "Added 5 tests for Length and a test for Time"
This reverts commit fc9d9dd8deef45fa4946f25d9293d1c6fc8bf970.
|
C#
|
mit
|
JohanLarsson/Gu.Units
|
56e27f01d72f7c4a786fbdd570143dba1b590396
|
Source/Eto.Mac/Properties/AssemblyInfo.cs
|
Source/Eto.Mac/Properties/AssemblyInfo.cs
|
using System.Reflection;
#if XAMMAC
[assembly: AssemblyTitle("Eto.Forms - OS X Platform using Xamarin.Mac")]
[assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac")]
#else
[assembly: AssemblyTitle("Eto.Forms - OS X Platform using MonoMac")]
[assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac")]
#endif
|
using System.Reflection;
#if XAMMAC
[assembly: AssemblyTitle("Eto.Forms - Xamarin.Mac Platform")]
[assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using Xamarin.Mac")]
#elif Mac64
[assembly: AssemblyTitle("Eto.Forms - MonoMac Platform")]
[assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac")]
#else
[assembly: AssemblyTitle("Eto.Forms - MonoMac 64-bit Platform")]
[assembly: AssemblyDescription("OS X Platform for the Eto.Forms UI Framework using the open-source MonoMac with 64-bit mono")]
#endif
|
Use better title for Mac/Mac64/XamMac assemblies/nuget packages
|
Use better title for Mac/Mac64/XamMac assemblies/nuget packages
|
C#
|
bsd-3-clause
|
l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto
|
0084527eab1f2b8586258050cf300a296398295b
|
mvc-individual-authentication/Views/Shared/_LoginPartial.cshtml
|
mvc-individual-authentication/Views/Shared/_LoginPartial.cshtml
|
@using Microsoft.AspNetCore.Identity
@using mvc_individual_authentication.Models
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</li>
</ul>
</form>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
|
@using Microsoft.AspNetCore.Identity
@using mvc_individual_authentication.Models
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" class="form-inline">
<ul class="navbar-nav">
<li>
<a class="btn btn-link nav-link" asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link nav-link">Log out</button>
</li>
</ul>
</form>
}
else
{
<ul class="navbar-nav">
<li><a class="nav-link" asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a class="nav-link" asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
|
Rework login partial to BS4
|
Rework login partial to BS4
|
C#
|
mit
|
peterblazejewicz/aspnet-5-bootstrap-4,peterblazejewicz/aspnet-5-bootstrap-4
|
3020a3a4bc32a2c61d2dbf654705bbf1ad5ccb78
|
Microsoft.DirectX/AssemblyInfo.cs
|
Microsoft.DirectX/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.
using System;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft.DirectX")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("alesliehughes")]
[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("1.0.*")]
// 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("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
|
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.
using System;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft.DirectX")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("alesliehughes")]
[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("1.0.2902.0")]
// 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("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
|
Set specific version for Microsoft.DirectX.dll.
|
Set specific version for Microsoft.DirectX.dll.
This is needed for strong-name references to work.
|
C#
|
mit
|
alesliehughes/monoDX,alesliehughes/monoDX
|
f9a6468ba47d1bf98233946f9e0b49499189ecba
|
Yeena/PathOfExile/PoEItemSocket.cs
|
Yeena/PathOfExile/PoEItemSocket.cs
|
// Copyright 2013 J.C. Moyer
//
// 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.
#pragma warning disable 649
using System;
using Newtonsoft.Json;
namespace Yeena.PathOfExile {
[JsonObject]
class PoEItemSocket {
[JsonProperty("group")] private readonly int _group;
[JsonProperty("attr")] private readonly string _attr;
public int Group {
get { return _group; }
}
public PoESocketColor Color {
get { return PoESocketColorUtilities.Parse(_attr); }
}
public override string ToString() {
return Enum.GetName(typeof(PoESocketColor), Color);
}
}
}
|
// Copyright 2013 J.C. Moyer
//
// 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.
#pragma warning disable 649
using Newtonsoft.Json;
namespace Yeena.PathOfExile {
[JsonObject]
class PoEItemSocket {
[JsonProperty("group")] private readonly int _group;
[JsonProperty("attr")] private readonly string _attr;
public int Group {
get { return _group; }
}
public PoESocketColor Color {
get { return PoESocketColorUtilities.Parse(_attr); }
}
public override string ToString() {
return Color.ToString();
}
}
}
|
Use ToString instead of Enum.GetName
|
Use ToString instead of Enum.GetName
|
C#
|
apache-2.0
|
jcmoyer/Yeena
|
d9e0e39a898acbc2a64fbf18bb90a924fe17be5f
|
TopLevelProgramExample/Program.cs
|
TopLevelProgramExample/Program.cs
|
using System;
Console.WriteLine("Hello World!");
|
using System;
using System.Linq.Expressions;
using ExpressionToCodeLib;
const int SomeConst = 27;
var myVariable = "implicitly closed over";
var withImplicitType = new {
A = "ImplicitTypeMember",
};
Console.WriteLine(ExpressionToCode.ToCode(() => myVariable));
new InnerClass().DoIt();
LocalFunction(123);
void LocalFunction(int arg)
{
var inLocalFunction = 42;
Expression<Func<int>> expression1 = () => inLocalFunction + myVariable.Length - arg - withImplicitType.A.Length * SomeConst;
Console.WriteLine(ExpressionToCode.ToCode(expression1));
}
sealed class InnerClass
{
public static int StaticInt = 37;
public int InstanceInt = 12;
public void DoIt()
=> Console.WriteLine(ExpressionToCode.ToCode(() => StaticInt + InstanceInt));
}
|
Add a bunch of junk you might find in a top-level program
|
Add a bunch of junk you might find in a top-level program
|
C#
|
apache-2.0
|
EamonNerbonne/ExpressionToCode
|
73e9a902a1372cfd2a3bb96ee4d2f24afc3df111
|
src/SlackConnector.Tests.Unit/SlackConnectionTests/PingTests.cs
|
src/SlackConnector.Tests.Unit/SlackConnectionTests/PingTests.cs
|
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Ploeh.AutoFixture.NUnit3;
using SlackConnector.Connections;
using SlackConnector.Connections.Clients.Channel;
using SlackConnector.Connections.Models;
using SlackConnector.Connections.Sockets;
using SlackConnector.Connections.Sockets.Messages.Outbound;
using SlackConnector.Models;
namespace SlackConnector.Tests.Unit.SlackConnectionTests
{
internal class PingTests
{
[Test, AutoMoqData]
public async Task should_return_expected_slack_hub([Frozen]Mock<IConnectionFactory> connectionFactory,
Mock<IChannelClient> channelClient, Mock<IWebSocketClient> webSocket, SlackConnection slackConnection)
{
// given
const string slackKey = "key-yay";
const string userId = "some-id";
var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey };
await slackConnection.Initialise(connectionInfo);
connectionFactory
.Setup(x => x.CreateChannelClient())
.Returns(channelClient.Object);
var returnChannel = new Channel { Id = "super-id", Name = "dm-channel" };
channelClient
.Setup(x => x.JoinDirectMessageChannel(slackKey, userId))
.ReturnsAsync(returnChannel);
// when
await slackConnection.Ping();
// then
webSocket.Verify(x => x.SendMessage(It.IsAny<PingMessage>()));
}
}
}
|
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Ploeh.AutoFixture.NUnit3;
using SlackConnector.Connections;
using SlackConnector.Connections.Sockets;
using SlackConnector.Connections.Sockets.Messages.Outbound;
using SlackConnector.Models;
namespace SlackConnector.Tests.Unit.SlackConnectionTests
{
internal class PingTests
{
[Test, AutoMoqData]
public async Task should_send_ping([Frozen]Mock<IConnectionFactory> connectionFactory,
Mock<IWebSocketClient> webSocket, SlackConnection slackConnection)
{
// given
const string slackKey = "key-yay";
var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey };
await slackConnection.Initialise(connectionInfo);
// when
await slackConnection.Ping();
// then
webSocket.Verify(x => x.SendMessage(It.IsAny<PingMessage>()));
}
}
}
|
Remove unused depedency from test
|
Remove unused depedency from test
|
C#
|
mit
|
noobot/SlackConnector
|
3ad687023bc4abf4133d26476e9d930c6d952247
|
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Repo/IRepository.cs
|
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Repo/IRepository.cs
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
public interface IRepository<TEntity, TPk>
where TEntity : class
{
TEntity GetKey(TPk key, ISession session);
Task<TEntity> GetKeyAsync(TPk key, ISession session );
TEntity Get(TEntity entity, ISession session);
Task<TEntity> GetAsync(TEntity entity, ISession session);
IEnumerable<TEntity> GetAll(ISession session);
Task<IEnumerable<TEntity>> GetAllAsync(ISession session);
TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow);
Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow);
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
public interface IRepository<TEntity, TPk>
where TEntity : class
{
TEntity GetKey(TPk key, ISession session);
TEntity GetKey<TSesssion>(TPk key) where TSesssion : class, ISession;
Task<TEntity> GetKeyAsync(TPk key, ISession session);
Task<TEntity> GetKeyAsync<TSesssion>(TPk key) where TSesssion : class, ISession;
TEntity Get(TEntity entity, ISession session);
TEntity Get<TSesssion>(TEntity entity) where TSesssion : class, ISession;
Task<TEntity> GetAsync(TEntity entity, ISession session);
Task<TEntity> GetAsync<TSesssion>(TEntity entity) where TSesssion : class, ISession;
IEnumerable<TEntity> GetAll(ISession session);
IEnumerable<TEntity> GetAll<TSesssion>() where TSesssion : class, ISession;
Task<IEnumerable<TEntity>> GetAllAsync(ISession session);
Task<IEnumerable<TEntity>> GetAllAsync<TSesssion>() where TSesssion : class, ISession;
TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow);
TPk SaveOrUpdate<TSesssion>(TEntity entity) where TSesssion : class, ISession;
Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow);
Task<TPk> SaveOrUpdateAsync<TSesssion>(TEntity entity) where TSesssion : class, ISession;
}
}
|
Expand interface to be more testable. So methods must have a session (i.e. not null) and add a generic for session when no session is needed.
|
Expand interface to be more testable. So methods must have a session (i.e. not null) and add a generic for session when no session is needed.
|
C#
|
mit
|
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork
|
93b639c93a204423513a9b8133021d42a7ab6b17
|
source/Glimpse.Core/Plugin/Assist/FormattingKeywords.cs
|
source/Glimpse.Core/Plugin/Assist/FormattingKeywords.cs
|
namespace Glimpse.Core.Plugin.Assist
{
public static class FormattingKeywords
{
public const string Error = "error";
public const string Fail = "fail";
public const string Info = "info";
public const string Loading = "loading";
public const string Ms = "ms";
public const string Quiet = "quiet";
public const string Selected = "selected";
public const string Warn = "warn";
}
}
|
namespace Glimpse.Core.Plugin.Assist
{
public static class FormattingKeywords
{
public const string Error = "error";
public const string Fail = "fail";
public const string Info = "info";
public const string Loading = "loading";
public const string Ms = "ms";
public const string Quiet = "quiet";
public const string Selected = "selected";
public const string Warn = "warn";
public static string Convert(FormattingKeywordEnum keyword)
{
switch (keyword)
{
case FormattingKeywordEnum.Error:
return Error;
case FormattingKeywordEnum.Fail:
return Fail;
case FormattingKeywordEnum.Info:
return Info;
case FormattingKeywordEnum.Loading:
return Loading;
case FormattingKeywordEnum.Quite:
return Quiet;
case FormattingKeywordEnum.Selected:
return Selected;
case FormattingKeywordEnum.System:
return Ms;
case FormattingKeywordEnum.Warn:
return Warn;
default:
return null;
}
}
}
}
|
Convert FormattingKeyword enum to it class name counterparts
|
Convert FormattingKeyword enum to it class name counterparts
|
C#
|
apache-2.0
|
SusanaL/Glimpse,rho24/Glimpse,paynecrl97/Glimpse,gabrielweyer/Glimpse,codevlabs/Glimpse,elkingtonmcb/Glimpse,codevlabs/Glimpse,elkingtonmcb/Glimpse,SusanaL/Glimpse,flcdrg/Glimpse,paynecrl97/Glimpse,sorenhl/Glimpse,dudzon/Glimpse,flcdrg/Glimpse,sorenhl/Glimpse,SusanaL/Glimpse,rho24/Glimpse,gabrielweyer/Glimpse,Glimpse/Glimpse,elkingtonmcb/Glimpse,paynecrl97/Glimpse,Glimpse/Glimpse,dudzon/Glimpse,rho24/Glimpse,sorenhl/Glimpse,paynecrl97/Glimpse,rho24/Glimpse,gabrielweyer/Glimpse,flcdrg/Glimpse,dudzon/Glimpse,Glimpse/Glimpse,codevlabs/Glimpse
|
e6329f4123fe6ed60de4871e96e46e3207b46a2c
|
src/Auth0.AuthenticationApi/OpenIdConfigurationCache.cs
|
src/Auth0.AuthenticationApi/OpenIdConfigurationCache.cs
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Auth0.AuthenticationApi
{
internal class OpenIdConfigurationCache
{
private static volatile OpenIdConfigurationCache _instance;
private static readonly object SyncRoot = new object();
private readonly ConcurrentDictionary<string, OpenIdConnectConfiguration> _innerCache = new ConcurrentDictionary<string, OpenIdConnectConfiguration>();
private OpenIdConfigurationCache() {}
public static OpenIdConfigurationCache Instance
{
get
{
if (_instance == null)
{
lock (SyncRoot)
{
if (_instance == null)
_instance = new OpenIdConfigurationCache();
}
}
return _instance;
}
}
public async Task<OpenIdConnectConfiguration> GetAsync(string domain)
{
_innerCache.TryGetValue(domain, out var configuration);
if (configuration == null)
{
var uri = new Uri(domain);
IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{uri.AbsoluteUri}.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
configuration = await configurationManager.GetConfigurationAsync(CancellationToken.None);
_innerCache[domain] = configuration;
}
return configuration;
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Auth0.AuthenticationApi
{
internal class OpenIdConfigurationCache
{
private static volatile OpenIdConfigurationCache _instance;
private static readonly object SyncRoot = new object();
private readonly ConcurrentDictionary<string, OpenIdConnectConfiguration> _innerCache = new ConcurrentDictionary<string, OpenIdConnectConfiguration>();
private OpenIdConfigurationCache() {}
public static OpenIdConfigurationCache Instance
{
get
{
if (_instance == null)
{
lock (SyncRoot)
{
if (_instance == null)
_instance = new OpenIdConfigurationCache();
}
}
return _instance;
}
}
public async Task<OpenIdConnectConfiguration> GetAsync(string domain)
{
_innerCache.TryGetValue(domain, out var configuration);
if (configuration == null)
{
var uri = new Uri(domain);
IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(
$"{uri.Scheme}://{uri.Authority}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
configuration = await configurationManager.GetConfigurationAsync(CancellationToken.None);
_innerCache[domain] = configuration;
}
return configuration;
}
}
}
|
Load OIDC configuration from root of Authority
|
Load OIDC configuration from root of Authority
|
C#
|
mit
|
auth0/auth0.net,jerriep/auth0.net,auth0/auth0.net,jerriep/auth0.net,jerriep/auth0.net
|
bf6815b2a7496042bf63538349eaf048594c1a25
|
osu.Game.Tests/Visual/TestCaseOsuGame.cs
|
osu.Game.Tests/Visual/TestCaseOsuGame.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Screens;
using osu.Game.Screens;
using osu.Game.Screens.Menu;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual
{
[TestFixture]
public class TestCaseOsuGame : OsuTestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(OsuLogo),
};
public TestCaseOsuGame()
{
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black,
},
new ScreenStack(new Loader())
{
RelativeSizeAxes = Axes.Both,
}
};
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Platform;
using osu.Game.Screens.Menu;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual
{
[TestFixture]
public class TestCaseOsuGame : OsuTestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(OsuLogo),
};
[BackgroundDependencyLoader]
private void load(GameHost host)
{
OsuGame game = new OsuGame();
game.SetHost(host);
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black,
},
game
};
}
}
}
|
Fix OsuGame test case not working
|
Fix OsuGame test case not working
|
C#
|
mit
|
naoey/osu,DrabWeb/osu,ZLima12/osu,ZLima12/osu,DrabWeb/osu,UselessToucan/osu,ppy/osu,EVAST9919/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,2yangk23/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,NeoAdonis/osu,naoey/osu,johnneijzen/osu,UselessToucan/osu,2yangk23/osu,johnneijzen/osu,EVAST9919/osu,ppy/osu,ppy/osu,naoey/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,DrabWeb/osu
|
bcd61e8ad2204611d1c3969ce62bca470e4ded76
|
Assets/Scripts/HarryPotterUnity/Utils/StaticCoroutine.cs
|
Assets/Scripts/HarryPotterUnity/Utils/StaticCoroutine.cs
|
using System.Collections;
using JetBrains.Annotations;
using UnityEngine;
namespace HarryPotterUnity.Utils
{
public class StaticCoroutine : MonoBehaviour
{
private static StaticCoroutine _mInstance;
private static StaticCoroutine Instance
{
get
{
if (_mInstance != null) return _mInstance;
_mInstance = FindObjectOfType(typeof(StaticCoroutine)) as StaticCoroutine ??
new GameObject("StaticCoroutineManager").AddComponent<StaticCoroutine>();
return _mInstance;
}
}
[UsedImplicitly]
void Awake()
{
if (_mInstance == null)
{
_mInstance = this;
}
}
IEnumerator Perform(IEnumerator coroutine)
{
yield return StartCoroutine(coroutine);
Die();
}
/// <summary>
/// Place your lovely static IEnumerator in here and witness magic!
/// </summary>
/// <param name="coroutine">Static IEnumerator</param>
public static void DoCoroutine(IEnumerator coroutine)
{
Instance.StartCoroutine(Instance.Perform(coroutine)); //this will launch the coroutine on our instance
}
public static void Die()
{
Destroy(_mInstance.gameObject);
_mInstance = null;
}
[UsedImplicitly]
void OnApplicationQuit()
{
_mInstance = null;
}
}
}
|
using System.Collections;
using JetBrains.Annotations;
using UnityEngine;
namespace HarryPotterUnity.Utils
{
public class StaticCoroutine : MonoBehaviour
{
private static StaticCoroutine _mInstance;
private static StaticCoroutine Instance
{
get
{
if (_mInstance != null) return _mInstance;
_mInstance = FindObjectOfType(typeof(StaticCoroutine)) as StaticCoroutine ??
new GameObject("StaticCoroutineManager").AddComponent<StaticCoroutine>();
return _mInstance;
}
}
[UsedImplicitly]
void Awake()
{
if (_mInstance == null)
{
_mInstance = this;
}
}
IEnumerator Perform(IEnumerator coroutine)
{
yield return StartCoroutine(coroutine);
Die();
}
/// <summary>
/// Place your lovely static IEnumerator in here and witness magic!
/// </summary>
/// <param name="coroutine">Static IEnumerator</param>
public static void DoCoroutine(IEnumerator coroutine)
{
Instance.StartCoroutine(Instance.Perform(coroutine)); //this will launch the coroutine on our instance
}
public static void Die()
{
_mInstance.StopAllCoroutines();
Destroy(_mInstance.gameObject);
_mInstance = null;
}
[UsedImplicitly]
void OnApplicationQuit()
{
_mInstance = null;
}
}
}
|
Stop all coroutines on Die()
|
Stop all coroutines on Die()
|
C#
|
mit
|
StefanoFiumara/Harry-Potter-Unity
|
ca3e85d395dfadadf309e6111f254eea35cdcbde
|
src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs
|
src/mscorlib/src/System/Reflection/Metadata/AssemblyExtensions.cs
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Reflection.Metadata
{
public static class AssemblyExtensions
{
[DllImport(JitHelpers.QCall)]
[SecurityCritical] // unsafe method
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length);
// Retrieves the metadata section of the assembly, for use with System.Reflection.Metadata.MetadataReader.
// - Returns false upon failure. Metadata might not be available for some assemblies, such as AssemblyBuilder, .NET
// native images, etc.
// - Callers should not write to the metadata blob
// - The metadata blob pointer will remain valid as long as the AssemblyLoadContext with which the assembly is
// associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the
// metadata blob.
[CLSCompliant(false)] // out byte* blob
[SecurityCritical] // unsafe method
public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
blob = null;
length = 0;
return InternalTryGetRawMetadata((RuntimeAssembly)assembly, ref blob, ref length);
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Reflection.Metadata
{
public static class AssemblyExtensions
{
[DllImport(JitHelpers.QCall)]
[SecurityCritical] // unsafe method
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private unsafe static extern bool InternalTryGetRawMetadata(RuntimeAssembly assembly, ref byte* blob, ref int length);
// Retrieves the metadata section of the assembly, for use with System.Reflection.Metadata.MetadataReader.
// - Returns false upon failure. Metadata might not be available for some assemblies, such as AssemblyBuilder, .NET
// native images, etc.
// - Callers should not write to the metadata blob
// - The metadata blob pointer will remain valid as long as the AssemblyLoadContext with which the assembly is
// associated, is alive. The caller is responsible for keeping the assembly object alive while accessing the
// metadata blob.
[CLSCompliant(false)] // out byte* blob
[SecurityCritical] // unsafe method
public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
blob = null;
length = 0;
var runtimeAssembly = assembly as RuntimeAssembly;
if (runtimeAssembly == null)
{
return false;
}
return InternalTryGetRawMetadata(runtimeAssembly, ref blob, ref length);
}
}
}
|
Fix TryGetRawMetadata to return false when the assembly is not a RuntimeAssembly
|
Fix TryGetRawMetadata to return false when the assembly is not a RuntimeAssembly
Related to dotnet/corefx#2768
|
C#
|
mit
|
cmckinsey/coreclr,jamesqo/coreclr,ramarag/coreclr,blackdwarf/coreclr,yeaicc/coreclr,ramarag/coreclr,dasMulli/coreclr,manu-silicon/coreclr,OryJuVog/coreclr,wkchoy74/coreclr,taylorjonl/coreclr,parjong/coreclr,ruben-ayrapetyan/coreclr,wkchoy74/coreclr,mskvortsov/coreclr,James-Ko/coreclr,AlfredoMS/coreclr,schellap/coreclr,KrzysztofCwalina/coreclr,Sridhar-MS/coreclr,shahid-pk/coreclr,manu-silicon/coreclr,zmaruo/coreclr,manu-silicon/coreclr,sjsinju/coreclr,serenabenny/coreclr,serenabenny/coreclr,bitcrazed/coreclr,bartdesmet/coreclr,ktos/coreclr,mskvortsov/coreclr,ericeil/coreclr,James-Ko/coreclr,JosephTremoulet/coreclr,sejongoh/coreclr,wtgodbe/coreclr,sagood/coreclr,Lucrecious/coreclr,yeaicc/coreclr,ericeil/coreclr,shahid-pk/coreclr,Samana/coreclr,ktos/coreclr,Djuffin/coreclr,wateret/coreclr,kyulee1/coreclr,ZhichengZhu/coreclr,Dmitry-Me/coreclr,ragmani/coreclr,AlexGhiondea/coreclr,hseok-oh/coreclr,shahid-pk/coreclr,sperling/coreclr,hseok-oh/coreclr,shahid-pk/coreclr,shahid-pk/coreclr,dpodder/coreclr,kyulee1/coreclr,Godin/coreclr,roncain/coreclr,martinwoodward/coreclr,Dmitry-Me/coreclr,xoofx/coreclr,zmaruo/coreclr,chaos7theory/coreclr,OryJuVog/coreclr,mocsy/coreclr,OryJuVog/coreclr,alexperovich/coreclr,ragmani/coreclr,schellap/coreclr,parjong/coreclr,JonHanna/coreclr,rartemev/coreclr,wkchoy74/coreclr,mmitche/coreclr,xoofx/coreclr,krixalis/coreclr,Lucrecious/coreclr,KrzysztofCwalina/coreclr,JonHanna/coreclr,serenabenny/coreclr,bitcrazed/coreclr,wtgodbe/coreclr,vinnyrom/coreclr,ruben-ayrapetyan/coreclr,naamunds/coreclr,cydhaselton/coreclr,taylorjonl/coreclr,vinnyrom/coreclr,naamunds/coreclr,yeaicc/coreclr,ruben-ayrapetyan/coreclr,mocsy/coreclr,Alcaro/coreclr,iamjasonp/coreclr,ericeil/coreclr,dasMulli/coreclr,ktos/coreclr,botaberg/coreclr,Samana/coreclr,mmitche/coreclr,russellhadley/coreclr,krytarowski/coreclr,cmckinsey/coreclr,JonHanna/coreclr,parjong/coreclr,KrzysztofCwalina/coreclr,Godin/coreclr,bartdesmet/coreclr,LLITCHEV/coreclr,parjong/coreclr,ruben-ayrapetyan/coreclr,serenabenny/coreclr,sperling/coreclr,Samana/coreclr,chaos7theory/coreclr,Lucrecious/coreclr,jhendrixMSFT/coreclr,LLITCHEV/coreclr,stormleoxia/coreclr,roncain/coreclr,AlexGhiondea/coreclr,iamjasonp/coreclr,geertdoornbos/coreclr,Alcaro/coreclr,Sridhar-MS/coreclr,josteink/coreclr,Djuffin/coreclr,jhendrixMSFT/coreclr,sagood/coreclr,martinwoodward/coreclr,LLITCHEV/coreclr,rartemev/coreclr,LLITCHEV/coreclr,benpye/coreclr,pgavlin/coreclr,neurospeech/coreclr,JosephTremoulet/coreclr,russellhadley/coreclr,Djuffin/coreclr,yeaicc/coreclr,jhendrixMSFT/coreclr,YongseopKim/coreclr,manu-silicon/coreclr,Samana/coreclr,taylorjonl/coreclr,OryJuVog/coreclr,sagood/coreclr,ZhichengZhu/coreclr,ericeil/coreclr,SlavaRa/coreclr,alexperovich/coreclr,vinnyrom/coreclr,SlavaRa/coreclr,xoofx/coreclr,josteink/coreclr,dpodder/coreclr,swgillespie/coreclr,russellhadley/coreclr,pgavlin/coreclr,chuck-mitchell/coreclr,sagood/coreclr,stormleoxia/coreclr,krixalis/coreclr,andschwa/coreclr,mocsy/coreclr,xoofx/coreclr,LLITCHEV/coreclr,benpye/coreclr,zmaruo/coreclr,jamesqo/coreclr,bartonjs/coreclr,wtgodbe/coreclr,iamjasonp/coreclr,kyulee1/coreclr,andschwa/coreclr,JosephTremoulet/coreclr,mocsy/coreclr,LLITCHEV/coreclr,botaberg/coreclr,bartdesmet/coreclr,geertdoornbos/coreclr,stormleoxia/coreclr,bartdesmet/coreclr,sejongoh/coreclr,yizhang82/coreclr,cmckinsey/coreclr,cshung/coreclr,krytarowski/coreclr,tijoytom/coreclr,sperling/coreclr,ramarag/coreclr,cydhaselton/coreclr,AlexGhiondea/coreclr,bartdesmet/coreclr,orthoxerox/coreclr,manu-silicon/coreclr,James-Ko/coreclr,Sridhar-MS/coreclr,iamjasonp/coreclr,sjsinju/coreclr,Godin/coreclr,mokchhya/coreclr,Alcaro/coreclr,hseok-oh/coreclr,pgavlin/coreclr,jamesqo/coreclr,parjong/coreclr,wkchoy74/coreclr,rartemev/coreclr,benpye/coreclr,andschwa/coreclr,wtgodbe/coreclr,martinwoodward/coreclr,ruben-ayrapetyan/coreclr,martinwoodward/coreclr,russellhadley/coreclr,roncain/coreclr,sagood/coreclr,cshung/coreclr,orthoxerox/coreclr,schellap/coreclr,cydhaselton/coreclr,geertdoornbos/coreclr,AlfredoMS/coreclr,Godin/coreclr,mocsy/coreclr,josteink/coreclr,blackdwarf/coreclr,vinnyrom/coreclr,iamjasonp/coreclr,botaberg/coreclr,mocsy/coreclr,blackdwarf/coreclr,vinnyrom/coreclr,bartonjs/coreclr,ragmani/coreclr,chrishaly/coreclr,KrzysztofCwalina/coreclr,ktos/coreclr,bartonjs/coreclr,Lucrecious/coreclr,ruben-ayrapetyan/coreclr,jamesqo/coreclr,blackdwarf/coreclr,xoofx/coreclr,AlexGhiondea/coreclr,gkhanna79/coreclr,stormleoxia/coreclr,sagood/coreclr,geertdoornbos/coreclr,bitcrazed/coreclr,Dmitry-Me/coreclr,tijoytom/coreclr,AlfredoMS/coreclr,neurospeech/coreclr,krk/coreclr,qiudesong/coreclr,OryJuVog/coreclr,andschwa/coreclr,swgillespie/coreclr,hseok-oh/coreclr,chuck-mitchell/coreclr,swgillespie/coreclr,krk/coreclr,benpye/coreclr,SlavaRa/coreclr,yeaicc/coreclr,shahid-pk/coreclr,blackdwarf/coreclr,stormleoxia/coreclr,Sridhar-MS/coreclr,YongseopKim/coreclr,dasMulli/coreclr,sjsinju/coreclr,sjsinju/coreclr,geertdoornbos/coreclr,Alcaro/coreclr,russellhadley/coreclr,pgavlin/coreclr,martinwoodward/coreclr,schellap/coreclr,mskvortsov/coreclr,neurospeech/coreclr,pgavlin/coreclr,AlfredoMS/coreclr,sejongoh/coreclr,tijoytom/coreclr,alexperovich/coreclr,poizan42/coreclr,ktos/coreclr,Lucrecious/coreclr,KrzysztofCwalina/coreclr,orthoxerox/coreclr,russellhadley/coreclr,ktos/coreclr,James-Ko/coreclr,Lucrecious/coreclr,perfectphase/coreclr,dpodder/coreclr,mmitche/coreclr,roncain/coreclr,chaos7theory/coreclr,manu-silicon/coreclr,geertdoornbos/coreclr,AlfredoMS/coreclr,bartonjs/coreclr,hseok-oh/coreclr,gkhanna79/coreclr,pgavlin/coreclr,rartemev/coreclr,ragmani/coreclr,cmckinsey/coreclr,botaberg/coreclr,sejongoh/coreclr,yizhang82/coreclr,tijoytom/coreclr,ramarag/coreclr,dpodder/coreclr,cmckinsey/coreclr,AlfredoMS/coreclr,taylorjonl/coreclr,cydhaselton/coreclr,poizan42/coreclr,benpye/coreclr,dpodder/coreclr,cydhaselton/coreclr,wateret/coreclr,yizhang82/coreclr,bartdesmet/coreclr,chrishaly/coreclr,dasMulli/coreclr,mokchhya/coreclr,Samana/coreclr,chrishaly/coreclr,AlexGhiondea/coreclr,swgillespie/coreclr,gkhanna79/coreclr,JosephTremoulet/coreclr,taylorjonl/coreclr,vinnyrom/coreclr,cmckinsey/coreclr,sjsinju/coreclr,naamunds/coreclr,yeaicc/coreclr,AlexGhiondea/coreclr,ZhichengZhu/coreclr,mokchhya/coreclr,krk/coreclr,Lucrecious/coreclr,krk/coreclr,josteink/coreclr,ZhichengZhu/coreclr,Alcaro/coreclr,mskvortsov/coreclr,yizhang82/coreclr,wtgodbe/coreclr,swgillespie/coreclr,Djuffin/coreclr,cydhaselton/coreclr,Djuffin/coreclr,taylorjonl/coreclr,qiudesong/coreclr,martinwoodward/coreclr,andschwa/coreclr,YongseopKim/coreclr,roncain/coreclr,sejongoh/coreclr,shahid-pk/coreclr,qiudesong/coreclr,gkhanna79/coreclr,sjsinju/coreclr,jhendrixMSFT/coreclr,dasMulli/coreclr,Dmitry-Me/coreclr,mokchhya/coreclr,wateret/coreclr,bitcrazed/coreclr,chrishaly/coreclr,roncain/coreclr,SlavaRa/coreclr,blackdwarf/coreclr,krixalis/coreclr,mokchhya/coreclr,Sridhar-MS/coreclr,dpodder/coreclr,YongseopKim/coreclr,krytarowski/coreclr,cshung/coreclr,OryJuVog/coreclr,yizhang82/coreclr,Djuffin/coreclr,chuck-mitchell/coreclr,Dmitry-Me/coreclr,chrishaly/coreclr,poizan42/coreclr,mskvortsov/coreclr,jhendrixMSFT/coreclr,mskvortsov/coreclr,qiudesong/coreclr,dasMulli/coreclr,yeaicc/coreclr,mmitche/coreclr,geertdoornbos/coreclr,kyulee1/coreclr,naamunds/coreclr,gkhanna79/coreclr,KrzysztofCwalina/coreclr,mokchhya/coreclr,krk/coreclr,manu-silicon/coreclr,poizan42/coreclr,gkhanna79/coreclr,qiudesong/coreclr,SlavaRa/coreclr,mmitche/coreclr,mocsy/coreclr,ramarag/coreclr,krixalis/coreclr,josteink/coreclr,jamesqo/coreclr,kyulee1/coreclr,rartemev/coreclr,LLITCHEV/coreclr,roncain/coreclr,bartdesmet/coreclr,ragmani/coreclr,wateret/coreclr,sejongoh/coreclr,krk/coreclr,vinnyrom/coreclr,dasMulli/coreclr,chrishaly/coreclr,zmaruo/coreclr,bitcrazed/coreclr,swgillespie/coreclr,mokchhya/coreclr,jhendrixMSFT/coreclr,chaos7theory/coreclr,alexperovich/coreclr,zmaruo/coreclr,sperling/coreclr,kyulee1/coreclr,bartonjs/coreclr,chaos7theory/coreclr,stormleoxia/coreclr,cmckinsey/coreclr,bitcrazed/coreclr,wkchoy74/coreclr,taylorjonl/coreclr,JonHanna/coreclr,hseok-oh/coreclr,neurospeech/coreclr,qiudesong/coreclr,Sridhar-MS/coreclr,krytarowski/coreclr,benpye/coreclr,ragmani/coreclr,James-Ko/coreclr,YongseopKim/coreclr,blackdwarf/coreclr,alexperovich/coreclr,schellap/coreclr,sejongoh/coreclr,orthoxerox/coreclr,krytarowski/coreclr,James-Ko/coreclr,wateret/coreclr,KrzysztofCwalina/coreclr,cshung/coreclr,alexperovich/coreclr,andschwa/coreclr,chuck-mitchell/coreclr,neurospeech/coreclr,ericeil/coreclr,sperling/coreclr,SlavaRa/coreclr,ramarag/coreclr,parjong/coreclr,neurospeech/coreclr,orthoxerox/coreclr,mmitche/coreclr,bartonjs/coreclr,krixalis/coreclr,ramarag/coreclr,jamesqo/coreclr,serenabenny/coreclr,benpye/coreclr,botaberg/coreclr,perfectphase/coreclr,iamjasonp/coreclr,ktos/coreclr,sperling/coreclr,ZhichengZhu/coreclr,ericeil/coreclr,JosephTremoulet/coreclr,josteink/coreclr,Samana/coreclr,Dmitry-Me/coreclr,chuck-mitchell/coreclr,perfectphase/coreclr,YongseopKim/coreclr,Godin/coreclr,perfectphase/coreclr,serenabenny/coreclr,wkchoy74/coreclr,schellap/coreclr,sperling/coreclr,jhendrixMSFT/coreclr,chuck-mitchell/coreclr,orthoxerox/coreclr,ZhichengZhu/coreclr,poizan42/coreclr,cshung/coreclr,ZhichengZhu/coreclr,wateret/coreclr,Alcaro/coreclr,rartemev/coreclr,tijoytom/coreclr,botaberg/coreclr,chaos7theory/coreclr,perfectphase/coreclr,perfectphase/coreclr,naamunds/coreclr,JosephTremoulet/coreclr,yizhang82/coreclr,Godin/coreclr,Dmitry-Me/coreclr,poizan42/coreclr,naamunds/coreclr,cshung/coreclr,bartonjs/coreclr,schellap/coreclr,naamunds/coreclr,swgillespie/coreclr,tijoytom/coreclr,Godin/coreclr,bitcrazed/coreclr,JonHanna/coreclr,martinwoodward/coreclr,wkchoy74/coreclr,josteink/coreclr,wtgodbe/coreclr,chuck-mitchell/coreclr,andschwa/coreclr,xoofx/coreclr,JonHanna/coreclr,krytarowski/coreclr,zmaruo/coreclr,stormleoxia/coreclr,krixalis/coreclr
|
6d091534699a1fcfeca8cf235e17c6d69507cd34
|
src/FromString.Tests/ParsedTTests.cs
|
src/FromString.Tests/ParsedTTests.cs
|
using System;
using Xunit;
namespace FromString.Tests
{
public class ParsedTTests
{
[Fact]
public void CanParseAnInt()
{
var parsedInt = new Parsed<int>("123");
Assert.True(parsedInt.HasValue);
Assert.Equal(123, parsedInt.Value);
}
[Fact]
public void AnInvalidStringSetsHasValueFalse()
{
var parsedInt = new Parsed<int>("this is not a string");
Assert.False(parsedInt.HasValue);
}
[Fact]
public void AnInvalidStringThrowsExceptionWhenAccessingValue()
{
var parsedInt = new Parsed<int>("this is not a string");
Assert.Throws<InvalidOperationException>(() => parsedInt.Value);
}
[Fact]
public void CanGetBackRawValue()
{
var parsedInt = new Parsed<int>("this is not a string");
Assert.Equal("this is not a string", parsedInt.RawValue);
}
[Fact]
public void CanAssignValueDirectly()
{
Parsed<decimal> directDecimal = 123.45m;
Assert.True(directDecimal.HasValue);
Assert.Equal(123.45m, directDecimal.Value);
}
[Fact]
public void ParsingInvalidUriFails()
{
var parsedUri = new Parsed<Uri>("this is not an URI");
Assert.False(parsedUri.HasValue);
}
}
}
|
using System;
using Xunit;
namespace FromString.Tests
{
public class ParsedTTests
{
[Fact]
public void CanParseAnInt()
{
var parsedInt = new Parsed<int>("123");
Assert.True(parsedInt.HasValue);
Assert.Equal(123, parsedInt.Value);
}
[Fact]
public void AnInvalidStringSetsHasValueFalse()
{
var parsedInt = new Parsed<int>("this is not a string");
Assert.False(parsedInt.HasValue);
}
[Fact]
public void AnInvalidStringThrowsExceptionWhenAccessingValue()
{
var parsedInt = new Parsed<int>("this is not a string");
Assert.Throws<InvalidOperationException>(() => parsedInt.Value);
}
[Fact]
public void CanGetBackRawValue()
{
var parsedInt = new Parsed<int>("this is not a string");
Assert.Equal("this is not a string", parsedInt.RawValue);
}
[Fact]
public void CanAssignValueDirectly()
{
Parsed<decimal> directDecimal = 123.45m;
Assert.True(directDecimal.HasValue);
Assert.Equal(123.45m, directDecimal.Value);
}
[Fact]
public void ParsingInvalidUriFails()
{
var parsedUri = new Parsed<Uri>("this is not an URI");
Assert.False(parsedUri.HasValue);
}
[Fact]
public void ParsingValidAbsoluteUriSucceeds()
{
var parsedUri = new Parsed<Uri>("https://github.com/");
Assert.True(parsedUri.HasValue);
Assert.Equal(new Uri("https://github.com/"), parsedUri.Value);
}
}
}
|
Test parsing valid absolute URI
|
Test parsing valid absolute URI
|
C#
|
mit
|
vgrigoriu/FromString
|
55cc509f2f6e51388b752a79577c6ff7de443c5c
|
src/SwissArmyKnife.Benchmarks/Program.cs
|
src/SwissArmyKnife.Benchmarks/Program.cs
|
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using SwissArmyKnife.Benchmarks.Benches.Extensions;
using System;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Toolchains.CsProj;
namespace SwissArmyKnife.Benchmarks
{
class Program
{
private static void Main(string[] args)
{
var config = GetConfig();
var benchmarks = GetBenchmarks();
for (var i = 0; i < benchmarks.Length; i++)
{
var typeToRun = benchmarks[i];
BenchmarkRunner.Run(typeToRun, config);
}
//BenchmarkRunner.Run<StringExtensionsBenchmarks>(config);
}
private static Type[] GetBenchmarks()
{
var result = new Type[]
{
// Extensions
typeof(ObjectExtensionsBenchmarks),
typeof(IComparableExtensionsBenchmarks),
typeof(StringBuilderExtensionsBenchmarks),
typeof(StringExtensionsBenchmarks),
typeof(IntExtensionsBenchmarks),
};
return result;
}
private static IConfig GetConfig()
{
var config = ManualConfig.Create(DefaultConfig.Instance);
config
.AddDiagnoser(MemoryDiagnoser.Default);
config.AddJob(
Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp31).AsBaseline(),
Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp21),
Job.Default.WithToolchain(CsProjClassicNetToolchain.Net48)
);
return config;
}
}
}
|
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using SwissArmyKnife.Benchmarks.Benches.Extensions;
using System;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Toolchains.CsProj;
namespace SwissArmyKnife.Benchmarks
{
class Program
{
private static void Main(string[] args)
{
var config = GetConfig();
var benchmarks = GetBenchmarks();
for (var i = 0; i < benchmarks.Length; i++)
{
var typeToRun = benchmarks[i];
BenchmarkRunner.Run(typeToRun, config);
}
//BenchmarkRunner.Run<StringExtensionsBenchmarks>(config);
}
private static Type[] GetBenchmarks()
{
var result = new Type[]
{
// Extensions
typeof(ObjectExtensionsBenchmarks),
typeof(IComparableExtensionsBenchmarks),
typeof(StringBuilderExtensionsBenchmarks),
typeof(StringExtensionsBenchmarks),
typeof(IntExtensionsBenchmarks),
};
return result;
}
private static IConfig GetConfig()
{
var config = ManualConfig.Create(DefaultConfig.Instance);
config
.AddDiagnoser(MemoryDiagnoser.Default);
config.AddJob(
Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp31).AsBaseline(),
Job.Default.WithToolchain(CsProjClassicNetToolchain.Net48)
);
return config;
}
}
}
|
Remove running benchmarks on .NET Core 2.1
|
Remove running benchmarks on .NET Core 2.1
We're only running benchmarks on the latest LTS releases of frameworks, so currently we're only running benchmarks on .NET 4.8 and .NET Core 3.1.
|
C#
|
mit
|
akamsteeg/SwissArmyKnife
|
f54fb1c4ac98bc724f7cc9945b11d2e32a308bd0
|
BudgetAnalyser.Engine/Widgets/BudgetBucketMonitorWidget.cs
|
BudgetAnalyser.Engine/Widgets/BudgetBucketMonitorWidget.cs
|
using System;
using BudgetAnalyser.Engine.Annotations;
namespace BudgetAnalyser.Engine.Widgets
{
public sealed class BudgetBucketMonitorWidget : RemainingBudgetBucketWidget, IUserDefinedWidget
{
private readonly string disabledToolTip;
private string doNotUseId;
public BudgetBucketMonitorWidget()
{
this.disabledToolTip = "Either a Statement, Budget, or a Filter are not present, or the Bucket Code is not valid, remaining budget cannot be calculated.";
}
public string Id
{
get { return this.doNotUseId; }
set
{
this.doNotUseId = value;
OnPropertyChanged();
BucketCode = Id;
}
}
public Type WidgetType => GetType();
public void Initialise(MultiInstanceWidgetState state, ILogger logger)
{
}
public override void Update([NotNull] params object[] input)
{
base.Update(input);
if (!Enabled)
{
ToolTip = this.disabledToolTip;
}
}
}
}
|
using System;
using BudgetAnalyser.Engine.Annotations;
namespace BudgetAnalyser.Engine.Widgets
{
public sealed class BudgetBucketMonitorWidget : RemainingBudgetBucketWidget, IUserDefinedWidget
{
private readonly string disabledToolTip;
private string doNotUseId;
public BudgetBucketMonitorWidget()
{
this.disabledToolTip = "Either a Statement, Budget, or a Filter are not present, or the Bucket Code is not valid, remaining budget cannot be calculated.";
}
public string Id
{
get { return this.doNotUseId; }
set
{
this.doNotUseId = value;
OnPropertyChanged();
BucketCode = Id;
}
}
public Type WidgetType => GetType();
public void Initialise(MultiInstanceWidgetState state, ILogger logger)
{
}
public override void Update([NotNull] params object[] input)
{
base.Update(input);
DetailedText = BucketCode;
if (!Enabled)
{
ToolTip = this.disabledToolTip;
}
}
}
}
|
Fix labels not appearing on BucketMonitorWidget
|
Fix labels not appearing on BucketMonitorWidget
|
C#
|
mit
|
Benrnz/BudgetAnalyser
|
da5d3837f0c16f83859381953001c1f93401d0a8
|
TicTacToe/Controllers/GameController.cs
|
TicTacToe/Controllers/GameController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TicTacToe.Core;
using TicTacToe.Web.Data;
using TicTacToe.Web.ViewModels;
namespace TicTacToe.Controllers
{
public class GameController : Controller
{
private ApplicationDbContext context;
public ApplicationDbContext Context => context ?? (context = new ApplicationDbContext());
public ActionResult Index()
{
//var context = new ApplicationDbContext();
//var game = new Game {Player = "123"};
//var field = new Field() {Game = game};
//game.Field = field;
//context.Games.Add(game);
//context.Commit();
//context.Dispose();
return View();
}
public ActionResult Play(string playerName)
{
if (string.IsNullOrEmpty(playerName))
return View("Index");
var game = new Game();
game.CreateField();
game.Player = playerName;
Context.Games.Add(game);
return View(game);
}
public JsonResult Turn(TurnClientViewModel turn)
{
return Json(turn);
}
public ActionResult About()
{
var context = new ApplicationDbContext();
var games = context.Games.ToArray();
context.Dispose();
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
protected override void Dispose(bool disposing)
{
context?.Dispose();
base.Dispose(disposing);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TicTacToe.Core;
using TicTacToe.Web.Data;
using TicTacToe.Web.ViewModels;
namespace TicTacToe.Controllers
{
public class GameController : Controller
{
private ApplicationDbContext context;
public ApplicationDbContext Context => context ?? (context = new ApplicationDbContext());
public ActionResult Index()
{
//var context = new ApplicationDbContext();
//var game = new Game {Player = "123"};
//var field = new Field() {Game = game};
//game.Field = field;
//context.Games.Add(game);
//context.Commit();
//context.Dispose();
return View();
}
public ActionResult Play(string playerName)
{
if (string.IsNullOrEmpty(playerName))
return View("Index");
var game = new Game();
game.CreateField();
game.Player = playerName;
Context.Games.Add(game);
Context.Commit();
return View(game);
}
public JsonResult Turn(TurnClientViewModel turn)
{
return Json(turn);
}
public ActionResult About()
{
var context = new ApplicationDbContext();
var games = context.Games.ToArray();
context.Dispose();
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
protected override void Dispose(bool disposing)
{
context?.Dispose();
base.Dispose(disposing);
}
}
}
|
Add missing Commit, when game starts.
|
Add missing Commit, when game starts.
|
C#
|
mit
|
beta-tank/TicTacToe,beta-tank/TicTacToe,beta-tank/TicTacToe
|
031c581be09285582e81b7ff4798d73f549c0781
|
test/Autofac.Test/Features/OpenGenerics/OpenGenericDelegateTests.cs
|
test/Autofac.Test/Features/OpenGenerics/OpenGenericDelegateTests.cs
|
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Autofac.Test.Features.OpenGenerics
{
public class OpenGenericDelegateTests
{
private interface IInterfaceA<T>
{
}
private class ImplementationA<T> : IInterfaceA<T>
{
}
[Fact]
public void CanResolveByGenericInterface()
{
var builder = new ContainerBuilder();
builder.RegisterGeneric((ctxt, types) => Activator.CreateInstance(typeof(ImplementationA<>).MakeGenericType(types)))
.As(typeof(IInterfaceA<>));
var container = builder.Build();
var instance = container.Resolve<IInterfaceA<string>>();
var implementedType = instance.GetType().GetGenericTypeDefinition();
Assert.Equal(typeof(ImplementationA<>), implementedType);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Autofac.Core;
using Autofac.Core.Registration;
using Xunit;
namespace Autofac.Test.Features.OpenGenerics
{
public class OpenGenericDelegateTests
{
private interface IInterfaceA<T>
{
}
private interface IInterfaceB<T>
{
}
private class ImplementationA<T> : IInterfaceA<T>
{
}
[Fact]
public void CanResolveByGenericInterface()
{
var builder = new ContainerBuilder();
builder.RegisterGeneric((ctxt, types) => Activator.CreateInstance(typeof(ImplementationA<>).MakeGenericType(types)))
.As(typeof(IInterfaceA<>));
var container = builder.Build();
var instance = container.Resolve<IInterfaceA<string>>();
var implementedType = instance.GetType().GetGenericTypeDefinition();
Assert.Equal(typeof(ImplementationA<>), implementedType);
}
[Fact]
public void DoesNotResolveForDifferentGenericService()
{
var builder = new ContainerBuilder();
builder.RegisterGeneric((ctxt, types) => Activator.CreateInstance(typeof(ImplementationA<>).MakeGenericType(types)))
.As(typeof(IInterfaceA<>));
var container = builder.Build();
Assert.Throws<ComponentNotRegisteredException>(() => container.Resolve<IInterfaceB<string>>());
}
}
}
|
Add negative test for the registration source.
|
Add negative test for the registration source.
|
C#
|
mit
|
autofac/Autofac
|
f637977985c6aed9e997b390e72196248abbdbb0
|
AgileMapper.UnitTests/SimpleTypeConversion/WhenMappingToDateTimes.cs
|
AgileMapper.UnitTests/SimpleTypeConversion/WhenMappingToDateTimes.cs
|
namespace AgileObjects.AgileMapper.UnitTests.SimpleTypeConversion
{
using System;
using TestClasses;
using Xunit;
public class WhenMappingToDateTimes
{
[Fact]
public void ShouldMapANullableDateTimeToADateTime()
{
var source = new PublicProperty<DateTime?> { Value = DateTime.Today };
var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>();
result.Value.ShouldBe(DateTime.Today);
}
[Fact]
public void ShouldMapAYearMonthDayStringToADateTime()
{
var source = new PublicProperty<string> { Value = "2016/06/08" };
var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>();
result.Value.ShouldBe(new DateTime(2016, 06, 08));
}
}
}
|
namespace AgileObjects.AgileMapper.UnitTests.SimpleTypeConversion
{
using System;
using Shouldly;
using TestClasses;
using Xunit;
public class WhenMappingToDateTimes
{
[Fact]
public void ShouldMapANullableDateTimeToADateTime()
{
var source = new PublicProperty<DateTime?> { Value = DateTime.Today };
var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>();
result.Value.ShouldBe(DateTime.Today);
}
[Fact]
public void ShouldMapAYearMonthDayStringToADateTime()
{
var source = new PublicProperty<string> { Value = "2016/06/08" };
var result = Mapper.Map(source).ToNew<PublicProperty<DateTime>>();
result.Value.ShouldBe(new DateTime(2016, 06, 08));
}
[Fact]
public void ShouldMapAnUnparseableStringToANullableDateTime()
{
var source = new PublicProperty<string> { Value = "OOH OOH OOH" };
var result = Mapper.Map(source).ToNew<PublicProperty<DateTime?>>();
result.Value.ShouldBeNull();
}
}
}
|
Test coverage for unparseable string -> DateTime conversion
|
Test coverage for unparseable string -> DateTime conversion
|
C#
|
mit
|
agileobjects/AgileMapper
|
bfba639b94d88dc22b1cd2ac43fd04d8813ffcb7
|
WalletWasabi/BlockchainAnalysis/Cluster.cs
|
WalletWasabi/BlockchainAnalysis/Cluster.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using WalletWasabi.Bases;
using WalletWasabi.Coins;
namespace WalletWasabi.BlockchainAnalysis
{
public class Cluster : NotifyPropertyChangedBase
{
private List<SmartCoin> Coins { get; set; }
private string _labels;
public Cluster(params SmartCoin[] coins)
: this(coins as IEnumerable<SmartCoin>)
{
}
public Cluster(IEnumerable<SmartCoin> coins)
{
Coins = coins.ToList();
Labels = string.Join(", ", KnownBy);
}
public string Labels
{
get => _labels;
private set => RaiseAndSetIfChanged(ref _labels, value);
}
public int Size => Coins.Count();
public IEnumerable<string> KnownBy => Coins.SelectMany(x => x.Label.Labels).Distinct(StringComparer.OrdinalIgnoreCase);
public void Merge(Cluster clusters) => Merge(clusters.Coins);
public void Merge(IEnumerable<SmartCoin> coins)
{
var insertPosition = 0;
foreach (var coin in coins.ToList())
{
if (!Coins.Contains(coin))
{
Coins.Insert(insertPosition++, coin);
}
coin.Clusters = this;
}
if (insertPosition > 0) // at least one element was inserted
{
Labels = string.Join(", ", KnownBy);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using WalletWasabi.Bases;
using WalletWasabi.Coins;
namespace WalletWasabi.BlockchainAnalysis
{
public class Cluster : NotifyPropertyChangedBase
{
private List<SmartCoin> Coins { get; set; }
private string _labels;
public Cluster(params SmartCoin[] coins)
: this(coins as IEnumerable<SmartCoin>)
{
}
public Cluster(IEnumerable<SmartCoin> coins)
{
Coins = coins.ToList();
Labels = string.Join(", ", KnownBy);
}
public string Labels
{
get => _labels;
private set => RaiseAndSetIfChanged(ref _labels, value);
}
public int Size => Coins.Count;
public IEnumerable<string> KnownBy => Coins.SelectMany(x => x.Label.Labels).Distinct(StringComparer.OrdinalIgnoreCase);
public void Merge(Cluster clusters) => Merge(clusters.Coins);
public void Merge(IEnumerable<SmartCoin> coins)
{
var insertPosition = 0;
foreach (var coin in coins.ToList())
{
if (!Coins.Contains(coin))
{
Coins.Insert(insertPosition++, coin);
}
coin.Clusters = this;
}
if (insertPosition > 0) // at least one element was inserted
{
Labels = string.Join(", ", KnownBy);
}
}
}
}
|
Use Count instead of Count()
|
Use Count instead of Count()
Co-Authored-By: Dávid Molnár <6d607974c44f675e0e525d39b2684f7b117c5263@gmail.com>
|
C#
|
mit
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
321da87399e00ab525ac67b3cdd7d3f578744ca4
|
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
|
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
|
using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;
namespace Promact.Trappist.Core.Controllers
{
[Route("api/question")]
public class QuestionsController : Controller
{
private readonly IQuestionRepository _questionsRepository;
public QuestionsController(IQuestionRepository questionsRepository)
{
_questionsRepository = questionsRepository;
}
[HttpGet]
/// <summary>
/// Gets all questions
/// </summary>
/// <returns>Questions list</returns>
public IActionResult GetQuestions()
{
var questions = _questionsRepository.GetAllQuestions();
return Json(questions);
}
[HttpPost]
/// <summary>
///
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
return Ok();
}
/// <summary>
///
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
return Ok();
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;
namespace Promact.Trappist.Core.Controllers
{
[Route("api/question")]
public class QuestionsController : Controller
{
private readonly IQuestionRepository _questionsRepository;
public QuestionsController(IQuestionRepository questionsRepository)
{
_questionsRepository = questionsRepository;
}
[HttpGet]
/// <summary>
/// Gets all questions
/// </summary>
/// <returns>Questions list</returns>
public IActionResult GetQuestions()
{
var questions = _questionsRepository.GetAllQuestions();
return Json(questions);
}
[HttpPost]
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
return Ok();
}
/// <summary>
/// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestionOption"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
return Ok();
}
}
}
|
Update server side API for single multiple answer question
|
Update server side API for single multiple answer question
|
C#
|
mit
|
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
|
eda5204cecaca8a0e3dedc75cb22b5b3fdfcad16
|
NOpenCL.Test/TestCategories.cs
|
NOpenCL.Test/TestCategories.cs
|
// Copyright (c) Tunnel Vision Laboratories, LLC. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace NOpenCL.Test
{
internal static class TestCategories
{
public const string RequireGpu = nameof(RequireGpu);
}
}
|
// Copyright (c) Tunnel Vision Laboratories, LLC. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace NOpenCL.Test
{
internal static class TestCategories
{
public const string RequireGpu = nameof(RequireGpu);
}
}
|
Fix a build warning for missing blank line at end of file
|
Fix a build warning for missing blank line at end of file
|
C#
|
mit
|
sharwell/NOpenCL,tunnelvisionlabs/NOpenCL
|
2cce60da347d6d99709a83bc7a8b3dbae711e8ec
|
Samples/Validation/App.xaml.cs
|
Samples/Validation/App.xaml.cs
|
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
namespace Sample
{
sealed partial class App : Template10.Common.BootStrapper
{
public App()
{
InitializeComponent();
}
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
NavigationService.Navigate(typeof(Views.MainPage));
await Task.Yield();
}
}
}
|
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
namespace Sample
{
sealed partial class App : Template10.Common.BootStrapper
{
public App()
{
InitializeComponent();
}
public override Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
NavigationService.Navigate(typeof(Views.MainPage));
return Task.CompletedTask;
}
}
}
|
Replace another Task.Yield with Task.CompletedTask.
|
Replace another Task.Yield with Task.CompletedTask.
|
C#
|
apache-2.0
|
abubberman/Template10,kenshinthebattosai/Template10,pekspro/Template10,liptonbeer/Template10,gsantopaolo/Template10,teamneusta/Template10,ivesely/Template10,dkackman/Template10,AparnaChinya/Template10,Windows-XAML/Template10,devinfluencer/Template10,lombo75/Template10,artfuldev/Template10,Viachaslau-Zinkevich/Template10,gsantopaolo/Template10,abubberman/Template10,ivesely/Template10,bc3tech/Template10,liptonbeer/Template10,callummoffat/Template10,callummoffat/Template10,lombo75/Template10,mvermef/Template10,AparnaChinya/Template10,devinfluencer/Template10,teamneusta/Template10,SimoneBWS/Template10,MichaelPetrinolis/Template10,bc3tech/Template10,dkackman/Template10,Viachaslau-Zinkevich/Template10,MichaelPetrinolis/Template10,GFlisch/Template10,dg2k/Template10,artfuldev/Template10,kenshinthebattosai/Template10,GFlisch/Template10,pekspro/Template10,SimoneBWS/Template10
|
571ca8d3fd5d8499f287ff4197cc37d4e0717ba7
|
src/FrontEnd/Pages/Session.cshtml
|
src/FrontEnd/Pages/Session.cshtml
|
@page "{id}"
@model SessionModel
<ol class="breadcrumb">
<li><a asp-page="/Index">Agenda</a></li>
<li><a asp-page="/Index" asp-route-day="@Model.DayOffset">Day @(Model.DayOffset + 1)</a></li>
<li class="active">@Model.Session.Title</li>
</ol>
<h1>@Model.Session.Title</h1>
<span class="label label-default">@Model.Session.Track?.Name</span>
@foreach (var speaker in Model.Session.Speakers)
{
<em><a asp-page="Speaker" asp-route-id="@speaker.ID">@speaker.Name</a></em>
}
<p>@Html.Raw(Model.Session.Abstract)</p>
<form method="post">
<input type="hidden" name="sessionId" value="@Model.Session.ID" />
<p>
<a authz-policy="Admin" asp-page="/Admin/EditSession" asp-route-id="@Model.Session.ID" class="btn btn-default btn-sm">Edit</a>
@if (Model.IsFavorite)
{
<button authz="true" type="submit" asp-page-handler="Remove" class="btn btn-primary">Remove from Favorites</button>
}
else
{
<button authz="true" type="submit" class="btn btn-primary">Add to Favorites</button>
}
</p>
</form>
|
@page "{id}"
@model SessionModel
<ol class="breadcrumb">
<li><a asp-page="/Index">Agenda</a></li>
<li><a asp-page="/Index" asp-route-day="@Model.DayOffset">Day @(Model.DayOffset + 1)</a></li>
<li class="active">@Model.Session.Title</li>
</ol>
<h1>@Model.Session.Title</h1>
<span class="label label-default">@Model.Session.Track?.Name</span>
@foreach (var speaker in Model.Session.Speakers)
{
<em><a asp-page="Speaker" asp-route-id="@speaker.ID">@speaker.Name</a></em>
}
<p>@Html.Raw(Model.Session.Abstract)</p>
<form method="post">
<input type="hidden" name="sessionId" value="@Model.Session.ID" />
<p>
<a authz-policy="Admin" asp-page="/Admin/EditSession" asp-route-id="@Model.Session.ID" class="btn btn-default btn-sm">Edit</a>
@if (Model.IsFavorite)
{
<button authz="true" type="submit" asp-page-handler="Remove" class="btn btn-primary">Remove from My Agenda</button>
}
else
{
<button authz="true" type="submit" class="btn btn-primary">Add to My Agenda</button>
}
</p>
</form>
|
Change text from favorites to "My Agenda"
|
Change text from favorites to "My Agenda"
|
C#
|
mit
|
csharpfritz/aspnetcore-app-workshop,csharpfritz/aspnetcore-app-workshop,csharpfritz/aspnetcore-app-workshop,anurse/ConferencePlanner,anurse/ConferencePlanner,dotnet-presentations/aspnetcore-app-workshop,jongalloway/aspnetcore-app-workshop,dotnet-presentations/aspnetcore-app-workshop,anurse/ConferencePlanner,dotnet-presentations/aspnetcore-app-workshop,csharpfritz/aspnetcore-app-workshop,jongalloway/aspnetcore-app-workshop,dotnet-presentations/aspnetcore-app-workshop
|
565786a9f79a21bc4d20aaa55da66a888a385769
|
IdentityManagement.ApplicationServices/Mapping/RoleMapper.cs
|
IdentityManagement.ApplicationServices/Mapping/RoleMapper.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using Affecto.IdentityManagement.ApplicationServices.Model;
using Affecto.IdentityManagement.Interfaces.Model;
using Affecto.Mapping.AutoMapper;
using AutoMapper;
namespace Affecto.IdentityManagement.ApplicationServices.Mapping
{
internal class RoleMapper : OneWayMapper<Querying.Data.Role, Role>
{
protected override void ConfigureMaps()
{
Func<Querying.Data.Permission, IPermission> permissionCreator = o => new Permission();
Mapper.CreateMap<Querying.Data.Permission, IPermission>().ConvertUsing(permissionCreator);
Mapper.CreateMap<Querying.Data.Permission, Permission>();
Mapper.CreateMap<Querying.Data.Role, Role>()
.ForMember(s => s.Permissions, m => m.MapFrom(c => Mapper.Map<ICollection<Querying.Data.Permission>, List<IPermission>>(c.Permissions.ToList())));
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Affecto.IdentityManagement.ApplicationServices.Model;
using Affecto.Mapping.AutoMapper;
using AutoMapper;
namespace Affecto.IdentityManagement.ApplicationServices.Mapping
{
internal class RoleMapper : OneWayMapper<Querying.Data.Role, Role>
{
protected override void ConfigureMaps()
{
Mapper.CreateMap<Querying.Data.Permission, Permission>();
Mapper.CreateMap<Querying.Data.Role, Role>()
.ForMember(s => s.Permissions, m => m.MapFrom(c => Mapper.Map<ICollection<Querying.Data.Permission>, List<Permission>>(c.Permissions.ToList())));
}
}
}
|
Remove interface mapping from role mapper
|
Remove interface mapping from role mapper
|
C#
|
mit
|
affecto/dotnet-IdentityManagement
|
c13eacefa03cf226af35f51c5ef22303764aef29
|
Source/Engine/AGS.Engine.IOS/AGSEngineIOS.cs
|
Source/Engine/AGS.Engine.IOS/AGSEngineIOS.cs
|
using System;
using Autofac;
namespace AGS.Engine.IOS
{
public class AGSEngineIOS
{
private static IOSAssemblies _assembly;
public static void Init()
{
OpenTK.Toolkit.Init();
var device = new IOSDevice(_assembly);
AGSGame.Device = device;
//Resolver.Override(resolver => resolver.Builder.RegisterType<AndroidGameWindowSize>().SingleInstance().As<IGameWindowSize>());
Resolver.Override(resolver => resolver.Builder.RegisterType<ALAudioBackend>().SingleInstance().As<IAudioBackend>());
}
public static void SetAssembly()
{
_assembly = new IOSAssemblies();
}
}
}
|
using System;
using Autofac;
namespace AGS.Engine.IOS
{
public class AGSEngineIOS
{
private static IOSAssemblies _assembly;
public static void Init()
{
// On IOS, when the mono linker is enabled (and it's enabled by default) it strips out all parts of
// the framework which are not in use. The linker does not support reflection, however, therefore it
// does not recognize the call to 'GetRuntimeMethod(nameof(Convert.ChangeType)' (which is called from
// a method in this Autofac in ConstructorParameterBinding class, ConvertPrimitiveType method)
// as using the 'Convert.ChangeType' method and strips it away unless it's
// explicitly used somewhere else, crashing Autofac if that method is called.
// Therefore, by explicitly calling it here, we're playing nicely with the linker and making sure
// Autofac works on IOS.
Convert.ChangeType((object)1234f, typeof(float));
OpenTK.Toolkit.Init();
var device = new IOSDevice(_assembly);
AGSGame.Device = device;
//Resolver.Override(resolver => resolver.Builder.RegisterType<AndroidGameWindowSize>().SingleInstance().As<IGameWindowSize>());
Resolver.Override(resolver => resolver.Builder.RegisterType<ALAudioBackend>().SingleInstance().As<IAudioBackend>());
}
public static void SetAssembly()
{
_assembly = new IOSAssemblies();
}
}
}
|
Fix Autofac crash due to linker stripping out a function used by reflection only
|
Fix Autofac crash due to linker stripping out a function used by reflection only
|
C#
|
artistic-2.0
|
tzachshabtay/MonoAGS
|
aca2a2884f8628db65a63c62a8afe3a25636a2b2
|
Scanner/Scanner/BackingStore.cs
|
Scanner/Scanner/BackingStore.cs
|
using System;
using System.IO;
using Newtonsoft.Json;
namespace Scanner
{
using System.Collections.Generic;
public class BackingStore
{
private string backingStoreName;
public BackingStore(string backingStoreName)
{
this.backingStoreName = backingStoreName;
}
public IEnumerable<Child> GetAll()
{
string json = File.ReadAllText(GetBackingStoreFilename());
return JsonConvert.DeserializeObject<IEnumerable<Child>>(json);
}
public void SaveAll(IEnumerable<Child> children)
{
string json = JsonConvert.SerializeObject(children);
var applicationFile = GetBackingStoreFilename();
File.WriteAllText(applicationFile, json);
}
private static string GetBackingStoreFilename()
{
var applicationFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Scanner");
Directory.CreateDirectory(applicationFolder);
var applicationFile = Path.Combine(applicationFolder, "children.json");
return applicationFile;
}
}
}
|
using System;
using System.IO;
using Newtonsoft.Json;
namespace Scanner
{
using System.Collections.Generic;
public class BackingStore
{
private string backingStoreName;
public BackingStore(string backingStoreName)
{
this.backingStoreName = backingStoreName;
}
public IEnumerable<Child> GetAll()
{
string json = File.ReadAllText(GetBackingStoreFilename());
return JsonConvert.DeserializeObject<IEnumerable<Child>>(json);
}
public void SaveAll(IEnumerable<Child> children)
{
string json = JsonConvert.SerializeObject(children);
var applicationFile = GetBackingStoreFilename();
File.WriteAllText(applicationFile, json);
}
private string GetBackingStoreFilename()
{
var applicationFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Scanner");
Directory.CreateDirectory(applicationFolder);
var applicationFile = Path.Combine(applicationFolder, string.Format("{0}.json", backingStoreName));
return applicationFile;
}
}
}
|
Make sure we read the backing store name properly.
|
Make sure we read the backing store name properly.
|
C#
|
mit
|
JeremyMcGee/WhosPlayingWhen,JeremyMcGee/WhosPlayingWhen,JeremyMcGee/WhosPlayingWhen
|
0c737d3622395f9397efa480112cef41c4fb9be9
|
Assets/Scripts/HarryPotterUnity/Cards/Generic/GenericSpell.cs
|
Assets/Scripts/HarryPotterUnity/Cards/Generic/GenericSpell.cs
|
using System.Collections;
using System.Collections.Generic;
using HarryPotterUnity.Tween;
using HarryPotterUnity.Utils;
using JetBrains.Annotations;
using UnityEngine;
namespace HarryPotterUnity.Cards.Generic
{
public abstract class GenericSpell : GenericCard {
private static readonly Vector3 SpellOffset = new Vector3(0f, 0f, -400f);
protected sealed override void OnClickAction(List<GenericCard> targets)
{
Enable();
PreviewSpell();
Player.Hand.Remove(this);
Player.Discard.Add(this);
SpellAction(targets);
}
protected abstract void SpellAction(List<GenericCard> targets);
private void PreviewSpell()
{
State = CardStates.Discarded;
var rotate180 = Player.OppositePlayer.IsLocalPlayer ? TweenQueue.RotationType.Rotate180 : TweenQueue.RotationType.NoRotate;
UtilManager.TweenQueue.AddTweenToQueue(new MoveTween(gameObject, SpellOffset, 0.5f, 0f, FlipStates.FaceUp, rotate180, State));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using HarryPotterUnity.Tween;
using HarryPotterUnity.Utils;
using JetBrains.Annotations;
using UnityEngine;
namespace HarryPotterUnity.Cards.Generic
{
public abstract class GenericSpell : GenericCard {
private static readonly Vector3 SpellOffset = new Vector3(0f, 0f, -400f);
protected sealed override void OnClickAction(List<GenericCard> targets)
{
Enable();
PreviewSpell();
Player.Hand.Remove(this);
Player.Discard.Add(this);
SpellAction(targets);
}
protected abstract void SpellAction(List<GenericCard> targets);
private void PreviewSpell()
{
State = CardStates.Discarded;
var rotate180 = Player.OppositePlayer.IsLocalPlayer ? TweenQueue.RotationType.Rotate180 : TweenQueue.RotationType.NoRotate;
UtilManager.TweenQueue.AddTweenToQueue(new MoveTween(gameObject, SpellOffset, 0.5f, 0f, FlipStates.FaceUp, rotate180, State, 0.6f));
}
}
}
|
Add 0.6 seconds preview time for spells
|
Add 0.6 seconds preview time for spells
|
C#
|
mit
|
StefanoFiumara/Harry-Potter-Unity
|
fbdec250e5d824a812ed84d97b096a01d4ea07df
|
src/Azure/Storage.Net.Microsoft.Azure.ServiceBus/Converter.cs
|
src/Azure/Storage.Net.Microsoft.Azure.ServiceBus/Converter.cs
|
using Microsoft.Azure.ServiceBus;
using System;
using System.Collections.Generic;
using QueueMessage = Storage.Net.Messaging.QueueMessage;
namespace Storage.Net.Microsoft.Azure.ServiceBus
{
static class Converter
{
public static Message ToMessage(QueueMessage message)
{
if(message == null)
throw new ArgumentNullException(nameof(message));
var result = new Message(message.Content);
if(message.Properties != null && message.Properties.Count > 0)
{
foreach(KeyValuePair<string, string> prop in message.Properties)
{
result.UserProperties.Add(prop.Key, prop.Value);
}
}
return result;
}
public static QueueMessage ToQueueMessage(Message message)
{
string id = message.MessageId ?? message.SystemProperties.SequenceNumber.ToString();
var result = new QueueMessage(id, message.Body);
result.DequeueCount = message.SystemProperties.DeliveryCount;
if(message.UserProperties != null && message.UserProperties.Count > 0)
{
foreach(KeyValuePair<string, object> pair in message.UserProperties)
{
result.Properties[pair.Key] = pair.Value == null ? null : pair.Value.ToString();
}
}
return result;
}
}
}
|
using Microsoft.Azure.ServiceBus;
using System;
using System.Collections.Generic;
using QueueMessage = Storage.Net.Messaging.QueueMessage;
namespace Storage.Net.Microsoft.Azure.ServiceBus
{
static class Converter
{
public static Message ToMessage(QueueMessage message)
{
if(message == null)
throw new ArgumentNullException(nameof(message));
var result = new Message(message.Content)
{
MessageId = message.Id
};
if(message.Properties != null && message.Properties.Count > 0)
{
foreach(KeyValuePair<string, string> prop in message.Properties)
{
result.UserProperties.Add(prop.Key, prop.Value);
}
}
return result;
}
public static QueueMessage ToQueueMessage(Message message)
{
string id = message.MessageId ?? message.SystemProperties.SequenceNumber.ToString();
var result = new QueueMessage(id, message.Body);
result.DequeueCount = message.SystemProperties.DeliveryCount;
if(message.UserProperties != null && message.UserProperties.Count > 0)
{
foreach(KeyValuePair<string, object> pair in message.UserProperties)
{
result.Properties[pair.Key] = pair.Value == null ? null : pair.Value.ToString();
}
}
return result;
}
}
}
|
Add message id to storage convert process
|
Add message id to storage convert process
|
C#
|
mit
|
aloneguid/storage
|
b2ce6f56a6de0eb987433057ea45b869b37b8cd1
|
NoAdsHere/Commands/Blocks/BlockModule.cs
|
NoAdsHere/Commands/Blocks/BlockModule.cs
|
using System;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;
using NoAdsHere.Database;
using NoAdsHere.Database.Models.GuildSettings;
using NoAdsHere.Common;
using NoAdsHere.Common.Preconditions;
using NoAdsHere.Services.AntiAds;
namespace NoAdsHere.Commands.Blocks
{
[Name("Blocks"), Group("Blocks")]
public class BlockModule : ModuleBase
{
private readonly MongoClient _mongo;
public BlockModule(IServiceProvider provider)
{
_mongo = provider.GetService<MongoClient>();
}
[Command("Invites"), Alias("Invite")]
[RequirePermission(AccessLevel.HighModerator)]
public async Task Invites(bool setting)
{
bool success;
if (setting)
success = await AntiAds.TryEnableGuild(BlockType.InstantInvite, Context.Guild.Id);
else
success = await AntiAds.TryDisableGuild(BlockType.InstantInvite, Context.Guild.Id);
if (success)
await ReplyAsync($":white_check_mark: Discord Invite Blockings have been set to {setting}. {(setting ? "Please ensure that the bot can ManageMessages in the required channels" : "")} :white_check_mark:");
else
await ReplyAsync($":exclamation: Discord Invite Blocks already set to {setting} :exclamation:");
}
}
}
|
using System.Threading.Tasks;
using Discord.Commands;
using NoAdsHere.Common;
using NoAdsHere.Common.Preconditions;
using NoAdsHere.Services.AntiAds;
namespace NoAdsHere.Commands.Blocks
{
[Name("Blocks"), Group("Blocks")]
public class BlockModule : ModuleBase
{
[Command("Invite")]
[RequirePermission(AccessLevel.HighModerator)]
public async Task Invites(bool setting)
{
bool success;
if (setting)
success = await AntiAds.TryEnableGuild(BlockType.InstantInvite, Context.Guild.Id);
else
success = await AntiAds.TryDisableGuild(BlockType.InstantInvite, Context.Guild.Id);
if (success)
await ReplyAsync($":white_check_mark: Discord Invite Blockings have been set to {setting}. {(setting ? "Please ensure that the bot can ManageMessages in the required channels" : "")} :white_check_mark:");
else
await ReplyAsync($":exclamation: Discord Invite Blocks already set to {setting} :exclamation:");
}
}
}
|
Clean the Blocks Module of unused code
|
Clean the Blocks Module of unused code
|
C#
|
mit
|
Nanabell/NoAdsHere
|
58891a55ff285790e904f0253978cd8d3236b6df
|
src/PrivateCache/CacheEntry.cs
|
src/PrivateCache/CacheEntry.cs
|
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using ClientSamples.CachingTools;
namespace Tavis.PrivateCache
{
public class CacheEntry
{
public PrimaryCacheKey Key { get; private set; }
public HttpHeaderValueCollection<string> VaryHeaders { get; private set; }
internal CacheEntry(PrimaryCacheKey key, HttpHeaderValueCollection<string> varyHeaders)
{
Key = key;
VaryHeaders = varyHeaders;
}
public string CreateSecondaryKey(HttpRequestMessage request)
{
var key = "";
foreach (var h in VaryHeaders.OrderBy(v => v)) // Sort the vary headers so that ordering doesn't generate different stored variants
{
if (h != "*")
{
key += h + ":" + String.Join(",", request.Headers.GetValues(h));
}
else
{
key += "*";
}
}
return key.ToLower();
}
public CacheContent CreateContent(HttpResponseMessage response)
{
return new CacheContent()
{
CacheEntry = this,
Key = CreateSecondaryKey(response.RequestMessage),
HasValidator = response.Headers.ETag != null || (response.Content != null && response.Content.Headers.LastModified != null),
Expires = HttpCache.GetExpireDate(response),
CacheControl = response.Headers.CacheControl ?? new CacheControlHeaderValue(),
Response = response,
};
}
}
}
|
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using ClientSamples.CachingTools;
namespace Tavis.PrivateCache
{
public class CacheEntry
{
public PrimaryCacheKey Key { get; private set; }
public HttpHeaderValueCollection<string> VaryHeaders { get; private set; }
internal CacheEntry(PrimaryCacheKey key, HttpHeaderValueCollection<string> varyHeaders)
{
Key = key;
VaryHeaders = varyHeaders;
}
public string CreateSecondaryKey(HttpRequestMessage request)
{
var key = new StringBuilder();
foreach (var h in VaryHeaders.OrderBy(v => v)) // Sort the vary headers so that ordering doesn't generate different stored variants
{
if (h != "*")
{
key.Append(h).Append(':');
bool addedOne = false;
foreach (var val in request.Headers.GetValues(h))
{
key.Append(val).Append(',');
addedOne = true;
}
if (addedOne)
{
key.Length--; // truncate trailing comma.
}
}
else
{
key.Append('*');
}
}
return key.ToString().ToLowerInvariant();
}
public CacheContent CreateContent(HttpResponseMessage response)
{
return new CacheContent()
{
CacheEntry = this,
Key = CreateSecondaryKey(response.RequestMessage),
HasValidator = response.Headers.ETag != null || (response.Content != null && response.Content.Headers.LastModified != null),
Expires = HttpCache.GetExpireDate(response),
CacheControl = response.Headers.CacheControl ?? new CacheControlHeaderValue(),
Response = response,
};
}
}
}
|
Switch to StringBuilder for speed.
|
Switch to StringBuilder for speed.
String concatenation of varying-count of items should almost always use StringBuilder.
|
C#
|
apache-2.0
|
tavis-software/Tavis.HttpCache
|
dfd12d7e1e9d7eac9ea968ed77a188391170243a
|
NBi.Xml/Items/Calculation/ExpressionXml.cs
|
NBi.Xml/Items/Calculation/ExpressionXml.cs
|
using NBi.Core.Evaluate;
using NBi.Core.ResultSet;
using NBi.Core.Transformation;
using NBi.Xml.Variables;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace NBi.Xml.Items.Calculation
{
[XmlType("")]
public class ExpressionXml: IColumnExpression
{
[Obsolete("Use the attribute Script in place of Value")]
[XmlText()]
public string Value
{
get => ShouldSerializeValue() ? Script.Code : null;
set => Script = new ScriptXml() { Language = LanguageType.NCalc, Code = value };
}
public bool ShouldSerializeValue() => Script?.Language == LanguageType.NCalc;
[XmlElement("script")]
public ScriptXml Script { get; set; }
public bool ShouldSerializeScript() => Script?.Language != LanguageType.NCalc;
[XmlIgnore()]
public LanguageType Language
{
get => ShouldSerializeValue() ? LanguageType.NCalc : Script.Language;
}
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("column-index")]
[DefaultValue(0)]
public int Column { get; set; }
[XmlAttribute("type")]
[DefaultValue(ColumnType.Text)]
public ColumnType Type { get; set; }
[XmlAttribute("tolerance")]
[DefaultValue("")]
public string Tolerance { get; set; }
}
}
|
using NBi.Core.Evaluate;
using NBi.Core.ResultSet;
using NBi.Core.Transformation;
using NBi.Xml.Variables;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace NBi.Xml.Items.Calculation
{
[XmlType("")]
public class ExpressionXml: IColumnExpression
{
[XmlText()]
public string Value
{
get => Script.Code;
set => Script.Code = value;
}
public bool ShouldSerializeValue() => Script.Language == LanguageType.NCalc;
[XmlElement("script")]
public ScriptXml Script { get; set; }
public bool ShouldSerializeScript() => Script.Language != LanguageType.NCalc;
[XmlIgnore()]
public LanguageType Language
{
get => ShouldSerializeValue() ? LanguageType.NCalc : Script.Language;
}
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("column-index")]
[DefaultValue(0)]
public int Column { get; set; }
[XmlAttribute("type")]
[DefaultValue(ColumnType.Text)]
public ColumnType Type { get; set; }
[XmlAttribute("tolerance")]
[DefaultValue("")]
public string Tolerance { get; set; }
public ExpressionXml()
{
Script = new ScriptXml() { Language = LanguageType.NCalc };
}
}
}
|
Fix some xml parsing issues
|
Fix some xml parsing issues
|
C#
|
apache-2.0
|
Seddryck/NBi,Seddryck/NBi
|
6fe663951dd2f889466f9ec65d33b834806389cd
|
test/WebSites/TagHelpersWebSite/Startup.cs
|
test/WebSites/TagHelpersWebSite/Startup.cs
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
namespace TagHelpersWebSite
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
var configuration = app.GetTestConfiguration();
app.UseServices(services =>
{
services.AddMvc(configuration);
});
app.UseMvc();
}
}
}
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
namespace TagHelpersWebSite
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
var configuration = app.GetTestConfiguration();
app.UsePerRequestServices(services =>
{
services.AddMvc(configuration);
});
app.UseMvc();
}
}
}
|
Update new test to use UsePerRequestServices
|
Update new test to use UsePerRequestServices
|
C#
|
apache-2.0
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
1026ad571f9507d276ede10ca84c97b76fccb493
|
VigilantCupcake/SubForms/AboutBox.cs
|
VigilantCupcake/SubForms/AboutBox.cs
|
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace VigilantCupcake.SubForms {
partial class AboutBox : Form {
public AboutBox() {
InitializeComponent();
Text = $"About {AssemblyTitle}";
labelProductName.Text = AssemblyTitle;
labelVersion.Text = AssemblyVersion;
lastUpdatedBox.Text = LastUpdatedDate.ToString();
linkLabel1.Text = Properties.Settings.Default.WebsiteUrl;
}
public string LatestVersionText {
set { latestBox.Text = value; }
}
public static string AssemblyTitle { get; } = "Vigilant Cupcake";
public static string AssemblyVersion {
get {
return Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public static DateTime LastUpdatedDate {
get {
return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
}
}
void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
this.linkLabel1.LinkVisited = true;
System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl);
}
}
}
|
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace VigilantCupcake.SubForms {
partial class AboutBox : Form {
public AboutBox() {
InitializeComponent();
Text = $"About {AssemblyTitle}";
labelProductName.Text = AssemblyTitle;
labelVersion.Text = AssemblyVersion;
lastUpdatedBox.Text = LastUpdatedDate.ToString();
linkLabel1.Text = Properties.Settings.Default.WebsiteUrl;
}
public string LatestVersionText {
set { latestBox.Text = value; }
}
public static string AssemblyTitle { get; } = "Vigilant Cupcake";
public static string AssemblyVersion {
get {
var version = Assembly.GetExecutingAssembly().GetName().Version;
return $"{version.Major}.{version.Minor}.{version.Revision}";
}
}
public static DateTime LastUpdatedDate {
get {
return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
}
}
void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
this.linkLabel1.LinkVisited = true;
System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl);
}
}
}
|
Reduce information displayed in about box
|
Reduce information displayed in about box
|
C#
|
mit
|
amweiss/vigilant-cupcake
|
106fca41a6267b34c4736d4c3dff6196152cc2a3
|
VigilantCupcake/SubForms/AboutBox.cs
|
VigilantCupcake/SubForms/AboutBox.cs
|
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace VigilantCupcake.SubForms {
partial class AboutBox : Form {
public AboutBox() {
InitializeComponent();
Text = $"About {AssemblyTitle}";
labelProductName.Text = AssemblyTitle;
labelVersion.Text = AssemblyVersion;
lastUpdatedBox.Text = LastUpdatedDate.ToString();
linkLabel1.Text = Properties.Settings.Default.WebsiteUrl;
}
public string LatestVersionText {
set { latestBox.Text = value; }
}
public static string AssemblyTitle { get; } = "Vigilant Cupcake";
public static string AssemblyVersion {
get {
var version = Assembly.GetExecutingAssembly().GetName().Version;
return $"{version.Major}.{version.Minor}.{version.Revision}";
}
}
public static DateTime LastUpdatedDate {
get {
return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
}
}
void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
this.linkLabel1.LinkVisited = true;
System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl);
}
}
}
|
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace VigilantCupcake.SubForms {
partial class AboutBox : Form {
public AboutBox() {
InitializeComponent();
Text = $"About {AssemblyTitle}";
labelProductName.Text = AssemblyTitle;
labelVersion.Text = AssemblyVersion;
lastUpdatedBox.Text = LastUpdatedDate.ToString();
linkLabel1.Text = Properties.Settings.Default.WebsiteUrl;
}
public string LatestVersionText {
set { latestBox.Text = value; }
}
public static string AssemblyTitle { get; } = "Vigilant Cupcake";
public static string AssemblyVersion {
get {
var version = Assembly.GetExecutingAssembly().GetName().Version;
return $"{version.Major}.{version.Minor}.{version.Build}";
}
}
public static DateTime LastUpdatedDate {
get {
return new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
}
}
void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
this.linkLabel1.LinkVisited = true;
System.Diagnostics.Process.Start(Properties.Settings.Default.WebsiteUrl);
}
}
}
|
Fix wrong attribute for about box
|
Fix wrong attribute for about box
|
C#
|
mit
|
amweiss/vigilant-cupcake
|
25b9850d6ae0c4ab2b89c7f357aa41a501d76147
|
Properties/AssemblyInfo.cs
|
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("Digital Color Meter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Digital Color Meter")]
[assembly: AssemblyCopyright("Copyright © 2014 Stian Hanger")]
[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("ca199dd4-2017-4ee7-808c-3747101e04b1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Digital Color Meter")]
[assembly: AssemblyDescription("Released under the MIT License")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Digital Color Meter")]
[assembly: AssemblyCopyright("Copyright © 2014 Stian Hanger")]
[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("ca199dd4-2017-4ee7-808c-3747101e04b1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Add license info in assembly.
|
Add license info in assembly.
|
C#
|
mit
|
nagilum/dcm
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.