commit
stringlengths 40
40
| subject
stringlengths 4
1.73k
| repos
stringlengths 5
127k
| old_file
stringlengths 2
751
| new_file
stringlengths 2
751
| new_contents
stringlengths 1
8.98k
| old_contents
stringlengths 0
6.59k
| license
stringclasses 13
values | lang
stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
a75401a8646b192ade7b690be1b43bf268379cd2
|
move default target definition to the correct place
|
adamralph/liteguard,adamralph/liteguard
|
targets/Program.cs
|
targets/Program.cs
|
using System;
using System.Threading.Tasks;
using SimpleExec;
using static Bullseye.Targets;
using static SimpleExec.Command;
internal class Program
{
public static Task Main(string[] args)
{
Target("build", () => RunAsync("dotnet", "build --configuration Release --nologo --verbosity quiet"));
Target(
"pack",
DependsOn("build"),
ForEach("LiteGuard.nuspec", "LiteGuard.Source.nuspec"),
async nuspec =>
{
await RunAsync("dotnet", "pack LiteGuard --configuration Release --no-build --nologo", configureEnvironment: env => env.Add("NUSPEC_FILE", nuspec));
});
Target(
"test",
DependsOn("build"),
() => RunAsync("dotnet", "test --configuration Release --no-build --nologo"));
Target("default", DependsOn("pack", "test"));
return RunTargetsAndExitAsync(args, ex => ex is NonZeroExitCodeException);
}
}
|
using System;
using System.Threading.Tasks;
using SimpleExec;
using static Bullseye.Targets;
using static SimpleExec.Command;
internal class Program
{
public static Task Main(string[] args)
{
Target("default", DependsOn("pack", "test"));
Target("build", () => RunAsync("dotnet", "build --configuration Release --nologo --verbosity quiet"));
Target(
"pack",
DependsOn("build"),
ForEach("LiteGuard.nuspec", "LiteGuard.Source.nuspec"),
async nuspec =>
{
await RunAsync("dotnet", "pack LiteGuard --configuration Release --no-build --nologo", configureEnvironment: env => env.Add("NUSPEC_FILE", nuspec));
});
Target(
"test",
DependsOn("build"),
() => RunAsync("dotnet", "test --configuration Release --no-build --nologo"));
return RunTargetsAndExitAsync(args, ex => ex is NonZeroExitCodeException);
}
}
|
mit
|
C#
|
09aa0d57c49fd567a4ade1b945c9428cc67d1c9b
|
优化性能。
|
noear/uwp-imageLoader
|
ImageLoader.UWP/ImageLoader.UWP/HttpClientImageDownloader.cs
|
ImageLoader.UWP/ImageLoader.UWP/HttpClientImageDownloader.cs
|
using System;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using Windows.Web.Http;
namespace Noear.UWP.Loader {
public class HttpClientImageDownloader : IImageDownloader {
public async Task<IBuffer> download(string url, object extra) {
return await new HttpClient().GetBufferAsync(new Uri(url));
}
}
}
|
using System;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using Windows.Web.Http;
namespace Noear.UWP.Loader {
public class HttpClientImageDownloader : IImageDownloader {
public virtual Task<IBuffer> download(string url, object extra) {
return new HttpClient().GetBufferAsync(new Uri(url)).AsTask();
}
}
}
|
apache-2.0
|
C#
|
59f2017a13672be09b527873470d528717d4ae70
|
Move BindValueChanged subscriptions to LoadComplete
|
smoogipoo/osu,smoogipoo/osu,peppy/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu
|
osu.Game/Screens/OnlinePlay/Multiplayer/CreateMultiplayerMatchButton.cs
|
osu.Game/Screens/OnlinePlay/Multiplayer/CreateMultiplayerMatchButton.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.OnlinePlay.Match.Components;
namespace osu.Game.Screens.OnlinePlay.Multiplayer
{
public class CreateMultiplayerMatchButton : PurpleTriangleButton
{
private IBindable<bool> isConnected;
private IBindable<bool> operationInProgress;
[Resolved]
private StatefulMultiplayerClient multiplayerClient { get; set; }
[Resolved]
private OngoingOperationTracker ongoingOperationTracker { get; set; }
[BackgroundDependencyLoader]
private void load()
{
Triangles.TriangleScale = 1.5f;
Text = "Create room";
isConnected = multiplayerClient.IsConnected.GetBoundCopy();
operationInProgress = ongoingOperationTracker.InProgress.GetBoundCopy();
}
protected override void LoadComplete()
{
base.LoadComplete();
isConnected.BindValueChanged(_ => updateState());
operationInProgress.BindValueChanged(_ => updateState(), true);
}
private void updateState() => Enabled.Value = isConnected.Value && !operationInProgress.Value;
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.OnlinePlay.Match.Components;
namespace osu.Game.Screens.OnlinePlay.Multiplayer
{
public class CreateMultiplayerMatchButton : PurpleTriangleButton
{
private IBindable<bool> isConnected;
private IBindable<bool> operationInProgress;
[Resolved]
private StatefulMultiplayerClient multiplayerClient { get; set; }
[Resolved]
private OngoingOperationTracker ongoingOperationTracker { get; set; }
[BackgroundDependencyLoader]
private void load()
{
Triangles.TriangleScale = 1.5f;
Text = "Create room";
isConnected = multiplayerClient.IsConnected.GetBoundCopy();
isConnected.BindValueChanged(_ => updateState());
operationInProgress = ongoingOperationTracker.InProgress.GetBoundCopy();
operationInProgress.BindValueChanged(_ => updateState(), true);
}
private void updateState() => Enabled.Value = isConnected.Value && !operationInProgress.Value;
}
}
|
mit
|
C#
|
fd894fb0c13f92fe88dae32585323f1cf6cef2e7
|
Rename FoundStringCallbacks to LineActions
|
mmoening/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,mmoening/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl
|
MatterControl.Printing/Communication/FoundStringCallBacks.cs
|
MatterControl.Printing/Communication/FoundStringCallBacks.cs
|
/*
Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
namespace MatterHackers.SerialPortCommunication
{
public class LineActions
{
public Dictionary<string, Action<string>> dictionaryOfCallbacks = new Dictionary<string, Action<string>>();
public void AddCallbackToKey(string key, Action<string> value)
{
if (dictionaryOfCallbacks.ContainsKey(key))
{
dictionaryOfCallbacks[key] += value;
}
else
{
dictionaryOfCallbacks.Add(key, value);
}
}
public void RemoveCallbackFromKey(string key, Action<string> value)
{
if (dictionaryOfCallbacks.ContainsKey(key))
{
if (dictionaryOfCallbacks[key] == null)
{
throw new Exception();
}
dictionaryOfCallbacks[key] -= value;
if (dictionaryOfCallbacks[key] == null)
{
dictionaryOfCallbacks.Remove(key);
}
}
else
{
throw new Exception();
}
}
}
public class FoundStringStartsWithCallbacks : LineActions
{
public void CheckForKeys(string s)
{
foreach (var pair in this.dictionaryOfCallbacks)
{
if (s.StartsWith(pair.Key))
{
pair.Value.Invoke(s);
}
}
}
}
public class FoundStringContainsCallbacks : LineActions
{
public void CheckForKeys(string s)
{
foreach (var pair in this.dictionaryOfCallbacks)
{
if (s.Contains(pair.Key))
{
pair.Value.Invoke(s);
}
}
}
}
}
|
/*
Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
namespace MatterHackers.SerialPortCommunication
{
public class FoundStringCallbacks
{
public Dictionary<string, Action<string>> dictionaryOfCallbacks = new Dictionary<string, Action<string>>();
public void AddCallbackToKey(string key, Action<string> value)
{
if (dictionaryOfCallbacks.ContainsKey(key))
{
dictionaryOfCallbacks[key] += value;
}
else
{
dictionaryOfCallbacks.Add(key, value);
}
}
public void RemoveCallbackFromKey(string key, Action<string> value)
{
if (dictionaryOfCallbacks.ContainsKey(key))
{
if (dictionaryOfCallbacks[key] == null)
{
throw new Exception();
}
dictionaryOfCallbacks[key] -= value;
if (dictionaryOfCallbacks[key] == null)
{
dictionaryOfCallbacks.Remove(key);
}
}
else
{
throw new Exception();
}
}
}
public class FoundStringStartsWithCallbacks : FoundStringCallbacks
{
public void CheckForKeys(string s)
{
foreach (var pair in this.dictionaryOfCallbacks)
{
if (s.StartsWith(pair.Key))
{
pair.Value.Invoke(s);
}
}
}
}
public class FoundStringContainsCallbacks : FoundStringCallbacks
{
public void CheckForKeys(string s)
{
foreach (var pair in this.dictionaryOfCallbacks)
{
if (s.Contains(pair.Key))
{
pair.Value.Invoke(s);
}
}
}
}
}
|
bsd-2-clause
|
C#
|
cbe2c6738ffc1e8636e99608fcde454cb49005a1
|
rename to invalidationUrls
|
signumsoftware/framework,signumsoftware/framework
|
Signum.Engine.Extensions/Cache/SimpleHttpCacheInvalidator.cs
|
Signum.Engine.Extensions/Cache/SimpleHttpCacheInvalidator.cs
|
using Azure.Messaging.ServiceBus;
using Azure.Messaging.ServiceBus.Administration;
using Npgsql;
using Signum.Engine.Json;
using Signum.Entities.Cache;
using Signum.Services;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Json;
namespace Signum.Engine.Cache;
public class SimpleHttpCacheInvalidator : ICacheMultiServerInvalidator {
HttpClient client = new HttpClient();
readonly string invalidationSecretHash;
readonly string[] invalidationUrls;
public SimpleHttpCacheInvalidator(string invalidationSecret, string[] invalidationUrls)
{
this.invalidationSecretHash = Convert.ToBase64String(Security.EncodePassword(invalidationSecret));
this.invalidationUrls = invalidationUrls;
}
public event Action<string>? ReceiveInvalidation;
public void Start()
{
}
//Called from Controller
public void InvalidateTable(InvalidateTableRequest request)
{
if (this.invalidationSecretHash != request.InvalidationSecretHash)
throw new InvalidOperationException("invalidationSecret does not match");
if (request.OriginMachineName == Environment.MachineName ||
request.OriginApplicationName == Schema.Current.ApplicationName)
return;
ReceiveInvalidation?.Invoke(request.CleanName);
}
public void SendInvalidation(string cleanName)
{
var request = new InvalidateTableRequest
{
CleanName = cleanName,
InvalidationSecretHash = this.invalidationSecretHash,
OriginMachineName = Environment.MachineName,
OriginApplicationName = Schema.Current.ApplicationName,
};
foreach (var url in invalidationUrls)
{
try
{
var fullUrl = url.TrimEnd('/') + "/api/cache/invalidateTable";
var json = JsonContent.Create(request, options: EntityJsonContext.FullJsonSerializerOptions /*SignumServer.JsonSerializerOptions*/);
var response = client.PostAsync(fullUrl, json).Result.EnsureSuccessStatusCode();
}
catch(Exception e)
{
e.LogException();
}
}
}
}
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public class InvalidateTableRequest
{
public string OriginMachineName;
public string OriginApplicationName;
public string CleanName;
public string InvalidationSecretHash;
}
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
using Azure.Messaging.ServiceBus;
using Azure.Messaging.ServiceBus.Administration;
using Npgsql;
using Signum.Engine.Json;
using Signum.Entities.Cache;
using Signum.Services;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Json;
namespace Signum.Engine.Cache;
public class SimpleHttpCacheInvalidator : ICacheMultiServerInvalidator {
HttpClient client = new HttpClient();
readonly string invalidationSecretHash;
readonly string[] invalidateUrls;
public SimpleHttpCacheInvalidator(string invalidationSecret, string[] invalidateUrls)
{
this.invalidationSecretHash = Convert.ToBase64String(Security.EncodePassword(invalidationSecret));
this.invalidateUrls = invalidateUrls;
}
public event Action<string>? ReceiveInvalidation;
public void Start()
{
}
//Called from Controller
public void InvalidateTable(InvalidateTableRequest request)
{
if (this.invalidationSecretHash != request.InvalidationSecretHash)
throw new InvalidOperationException("invalidationSecret does not match");
if (request.OriginMachineName == Environment.MachineName ||
request.OriginApplicationName == Schema.Current.ApplicationName)
return;
ReceiveInvalidation?.Invoke(request.CleanName);
}
public void SendInvalidation(string cleanName)
{
var request = new InvalidateTableRequest
{
CleanName = cleanName,
InvalidationSecretHash = this.invalidationSecretHash,
OriginMachineName = Environment.MachineName,
OriginApplicationName = Schema.Current.ApplicationName,
};
foreach (var url in invalidateUrls)
{
try
{
var fullUrl = url.TrimEnd('/') + "/api/cache/invalidateTable";
var json = JsonContent.Create(request, options: EntityJsonContext.FullJsonSerializerOptions /*SignumServer.JsonSerializerOptions*/);
var response = client.PostAsync(fullUrl, json).Result.EnsureSuccessStatusCode();
}
catch(Exception e)
{
e.LogException();
}
}
}
}
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public class InvalidateTableRequest
{
public string OriginMachineName;
public string OriginApplicationName;
public string CleanName;
public string InvalidationSecretHash;
}
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
|
mit
|
C#
|
f39586a90117c831b4d5f71801949e0dccc0225e
|
check for null
|
ZHZG/PropertyTools,ZHZG/PropertyTools,Mitch-Connor/PropertyTools,jogibear9988/PropertyTools,jogibear9988/PropertyTools,punker76/PropertyTools,LavishSoftware/PropertyTools,johnsonlu/PropertyTools,objorke/PropertyTools
|
Source/PropertyEditor/Converters/EnumDescriptionConverter.cs
|
Source/PropertyEditor/Converters/EnumDescriptionConverter.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Data;
namespace PropertyEditorLibrary
{
/// <summary>
/// The EnumDescriptionConverter gets the Description attribute for Enum values.
/// </summary>
[ValueConversion(typeof(object), typeof(string))]
public class EnumDescriptionConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// Default, non-converted result.
string result = value.ToString();
var field = value.GetType().GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public).FirstOrDefault(f => f.GetValue(null).Equals(value));
if (field != null)
{
var descriptionAttribute = field.GetCustomAttributes<DescriptionAttribute>(true).FirstOrDefault();
if (descriptionAttribute != null)
{
// Found the attribute, assign description
result = descriptionAttribute.Description;
}
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
public static class ReflectionExtensions
{
public static IEnumerable<T> GetCustomAttributes<T>(this FieldInfo fieldInfo, bool inherit)
{
return fieldInfo.GetCustomAttributes(typeof(T), inherit).Cast<T>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Data;
namespace PropertyEditorLibrary
{
/// <summary>
/// The EnumDescriptionConverter gets the Description attribute for Enum values.
/// </summary>
[ValueConversion(typeof(object), typeof(string))]
public class EnumDescriptionConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var enumType = value.GetType();
var field = enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public).First(f => f.GetValue(null).Equals(value));
var descriptionAttribute = field.GetCustomAttributes<DescriptionAttribute>(true).FirstOrDefault();
return descriptionAttribute != null ? descriptionAttribute.Description : value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
public static class ReflectionExtensions
{
public static IEnumerable<T> GetCustomAttributes<T>(this FieldInfo fieldInfo, bool inherit)
{
return fieldInfo.GetCustomAttributes(typeof(T), inherit).Cast<T>();
}
}
}
|
mit
|
C#
|
bfdf87c4937b8043aab1d50407e1e049ede63bd8
|
Fix unnecessarily-complex/wrong BackgroundGameHeadlessGameHost implementation
|
ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework
|
osu.Framework.Tests/IO/BackgroundGameHeadlessGameHost.cs
|
osu.Framework.Tests/IO/BackgroundGameHeadlessGameHost.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.Threading;
using System.Threading.Tasks;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests.IO
{
/// <summary>
/// A headless host for testing purposes. Contains an arbitrary game that is running after construction.
/// </summary>
public class BackgroundGameHeadlessGameHost : TestRunHeadlessGameHost
{
public BackgroundGameHeadlessGameHost(string gameName = null, bool bindIPC = false, bool realtime = true, bool portableInstallation = false)
: base(gameName, bindIPC, realtime, portableInstallation)
{
var testGame = new TestGame();
Task.Run(() => Run(testGame));
testGame.HasProcessed.Wait();
}
private class TestGame : Game
{
internal readonly ManualResetEventSlim HasProcessed = new ManualResetEventSlim(false);
protected override void Update()
{
base.Update();
HasProcessed.Set();
}
protected override void Dispose(bool isDisposing)
{
HasProcessed.Dispose();
base.Dispose(isDisposing);
}
}
protected override void Dispose(bool isDisposing)
{
if (ExecutionState != ExecutionState.Stopped)
Exit();
base.Dispose(isDisposing);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests.IO
{
/// <summary>
/// A headless host for testing purposes. Contains an arbitrary game that is running after construction.
/// </summary>
public class BackgroundGameHeadlessGameHost : TestRunHeadlessGameHost
{
private TestGame testGame;
public BackgroundGameHeadlessGameHost(string gameName = null, bool bindIPC = false, bool realtime = true, bool portableInstallation = false)
: base(gameName, bindIPC, realtime, portableInstallation)
{
using (var gameCreated = new ManualResetEventSlim(false))
{
Task.Run(() =>
{
try
{
testGame = new TestGame();
// ReSharper disable once AccessToDisposedClosure
gameCreated.Set();
Run(testGame);
}
catch
{
// may throw an unobserved exception if we don't handle here.
}
});
gameCreated.Wait();
testGame.HasProcessed.Wait();
}
}
private class TestGame : Game
{
internal readonly ManualResetEventSlim HasProcessed = new ManualResetEventSlim(false);
protected override void Update()
{
base.Update();
HasProcessed.Set();
}
protected override void Dispose(bool isDisposing)
{
HasProcessed.Dispose();
base.Dispose(isDisposing);
}
}
protected override void Dispose(bool isDisposing)
{
if (ExecutionState != ExecutionState.Stopped)
Exit();
base.Dispose(isDisposing);
}
}
}
|
mit
|
C#
|
04e4234e2aeb6830c38fe7a14b50586b6fa986d1
|
disable lmdb in tests for now, it fails as transactiosn can't be used across threads
|
ArsenShnurkov/BitSharp
|
BitSharp.Core.Test.Storage/StorageProviderTest.cs
|
BitSharp.Core.Test.Storage/StorageProviderTest.cs
|
using BitSharp.Common.ExtensionMethods;
using BitSharp.Esent.Test;
using BitSharp.Lmdb.Test;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace BitSharp.Core.Test.Storage
{
[TestClass]
public class StorageProviderTest
{
private readonly List<ITestStorageProvider> testStorageProviders =
new List<ITestStorageProvider>
{
new MemoryTestStorageProvider(),
new EsentTestStorageProvider(),
//new LmdbTestStorageProvider(),
};
// Run the specified test method against all providers
protected void RunTest(Action<ITestStorageProvider> testMethod)
{
foreach (var provider in testStorageProviders)
{
Debug.WriteLine("Testing provider: {0}".Format2(provider.Name));
provider.TestInitialize();
try
{
testMethod(provider);
}
finally
{
provider.TestCleanup();
}
}
}
}
}
|
using BitSharp.Common.ExtensionMethods;
using BitSharp.Esent.Test;
using BitSharp.Lmdb.Test;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace BitSharp.Core.Test.Storage
{
[TestClass]
public class StorageProviderTest
{
private readonly List<ITestStorageProvider> testStorageProviders =
new List<ITestStorageProvider>
{
new MemoryTestStorageProvider(),
new EsentTestStorageProvider(),
new LmdbTestStorageProvider(),
};
// Run the specified test method against all providers
protected void RunTest(Action<ITestStorageProvider> testMethod)
{
foreach (var provider in testStorageProviders)
{
Debug.WriteLine("Testing provider: {0}".Format2(provider.Name));
provider.TestInitialize();
try
{
testMethod(provider);
}
finally
{
provider.TestCleanup();
}
}
}
}
}
|
unlicense
|
C#
|
a186c86d03f560ed9973e47519be2bcd8bc8e397
|
Fix fail in RequireHigherRank
|
Yonom/CupCake
|
CupCake.DefaultCommands/Commands/CommandBase.cs
|
CupCake.DefaultCommands/Commands/CommandBase.cs
|
using System;
using CupCake.Command;
using CupCake.Command.Source;
using CupCake.Messages.User;
using CupCake.Permissions;
using CupCake.Players;
namespace CupCake.DefaultCommands.Commands
{
public abstract class CommandBase<T> : Command<T>
{
protected virtual string CommandName
{
get { return this.Labels[0]; }
}
protected virtual void RequireOwner()
{
if (this.RoomService.AccessRight < AccessRight.Owner)
throw new CommandException(String.Format("Bot must be world owner to be able to {0}.", this.CommandName));
}
protected virtual void RequireEdit()
{
if (this.RoomService.AccessRight < AccessRight.Edit)
throw new CommandException(String.Format("Bot must have edit rights to be able to {0}.",
this.CommandName));
}
protected void RequireSameRank(IInvokeSource source, Player player)
{
if (player.GetGroup() > source.Group)
throw new CommandException(String.Format("You may not {0} a player with a higher rank.",
this.CommandName));
}
protected void RequireHigherRank(IInvokeSource source, Player player)
{
if (player.GetGroup() >= source.Group)
throw new CommandException(String.Format("You may not {0} a player with an equal or higher rank.",
this.CommandName));
}
}
}
|
using System;
using CupCake.Command;
using CupCake.Command.Source;
using CupCake.Messages.User;
using CupCake.Permissions;
using CupCake.Players;
namespace CupCake.DefaultCommands.Commands
{
public abstract class CommandBase<T> : Command<T>
{
protected virtual string CommandName
{
get { return this.Labels[0]; }
}
protected virtual void RequireOwner()
{
if (this.RoomService.AccessRight < AccessRight.Owner)
throw new CommandException(String.Format("Bot must be world owner to be able to {0}.", this.CommandName));
}
protected virtual void RequireEdit()
{
if (this.RoomService.AccessRight < AccessRight.Edit)
throw new CommandException(String.Format("Bot must have edit rights to be able to {0}.",
this.CommandName));
}
protected void RequireSameRank(IInvokeSource source, Player player)
{
if (player.GetGroup() > source.Group)
throw new CommandException(String.Format("You may not {0} a player with a higher rank.",
this.CommandName));
}
protected void RequireHigherRank(IInvokeSource source, Player player)
{
if (player.GetGroup() > source.Group)
throw new CommandException(String.Format("You may not {0} a player with a higher rank.",
this.CommandName));
}
}
}
|
mit
|
C#
|
da1e8a518aa7d5762e1084eeacdc305f1a0a5f54
|
Add new contructor for TextEdit class
|
daviwil/PSScriptAnalyzer,dlwyatt/PSScriptAnalyzer,PowerShell/PSScriptAnalyzer
|
Engine/TextEdit.cs
|
Engine/TextEdit.cs
|
using System;
using System.Management.Automation.Language;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer
{
/// <summary>
/// Class to provide information about an edit
/// </summary>
public class TextEdit
{
public IScriptExtent ScriptExtent { get; private set; }
public int StartLineNumber { get { return ScriptExtent.StartLineNumber; } }
public int StartColumnNumber { get { return ScriptExtent.StartColumnNumber; } }
public int EndLineNumber { get { return ScriptExtent.EndLineNumber; } }
public int EndColumnNumber { get { return ScriptExtent.EndColumnNumber; } }
public string NewText { get; private set; }
/// <summary>
/// Creates an object of TextEdit.
/// </summary>
/// <param name="scriptExtent">Extent of script that needs to be replaced.</param>
/// <param name="newText">Text that will replace the region covered by scriptExtent.</param>
public TextEdit(IScriptExtent scriptExtent, string newText)
{
if (scriptExtent == null)
{
throw new ArgumentNullException(nameof(scriptExtent));
}
if (newText == null)
{
throw new ArgumentNullException(nameof(newText));
}
ScriptExtent = scriptExtent;
NewText = newText;
}
public TextEdit(
int startLineNumber,
int startColumnNumber,
int endLineNumber,
int endColumnNumber,
string newText)
: this(new ScriptExtent(
new ScriptPosition(null, startLineNumber, startColumnNumber, null),
new ScriptPosition(null, endLineNumber, endColumnNumber, null)),
newText)
{
}
}
}
|
using System;
using System.Management.Automation.Language;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer
{
/// <summary>
/// Class to provide information about an edit
/// </summary>
public class TextEdit
{
public IScriptExtent ScriptExtent { get; private set; }
public string NewText { get; private set; }
/// <summary>
/// Creates an object of TextEdit.
/// </summary>
/// <param name="scriptExtent">Extent of script that needs to be replaced.</param>
/// <param name="newText">Text that will replace the region covered by scriptExtent.</param>
public TextEdit(IScriptExtent scriptExtent, string newText)
{
if (scriptExtent == null)
{
throw new ArgumentNullException(nameof(scriptExtent));
}
if (newText == null)
{
throw new ArgumentNullException(nameof(newText));
}
ScriptExtent = scriptExtent;
NewText = newText;
}
}
}
|
mit
|
C#
|
ba1aa680b0e991bae9d8a5cf13d5a504acbcd771
|
change to Idictionary
|
danhaller/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,actionshrimp/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper,gregsochanik/SevenDigital.Api.Wrapper,raoulmillais/SevenDigital.Api.Wrapper,danbadge/SevenDigital.Api.Wrapper,mattgray/SevenDigital.Api.Wrapper,bnathyuw/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,knocte/SevenDigital.Api.Wrapper
|
src/SevenDigital.Api.Wrapper/EndpointResolution/DictionaryExtensions.cs
|
src/SevenDigital.Api.Wrapper/EndpointResolution/DictionaryExtensions.cs
|
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace SevenDigital.Api.Wrapper.EndpointResolution
{
public static class DictionaryExtensions
{
public static string ToQueryString(this IDictionary<string,string> collection)
{
var sb = new StringBuilder();
foreach (var key in collection.Keys)
{
sb.AppendFormat("{0}={1}&", key, collection[key]);
}
return sb.ToString().TrimEnd('&');
}
}
}
|
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace SevenDigital.Api.Wrapper.EndpointResolution
{
public static class DictionaryExtensions
{
public static string ToQueryString(this Dictionary<string,string> collection)
{
var sb = new StringBuilder();
foreach (var key in collection.Keys)
{
sb.AppendFormat("{0}={1}&", key, collection[key]);
}
return sb.ToString().TrimEnd('&');
}
}
}
|
mit
|
C#
|
31837ad049d0be83429f06ff7a976d5f6bb4b6d1
|
Test Cases
|
jefking/King.Service
|
King.Service.Tests/Scalability/QueueSimplifiedScalerTests.cs
|
King.Service.Tests/Scalability/QueueSimplifiedScalerTests.cs
|
namespace King.Service.Tests.Scalability
{
using System;
using King.Azure.Data;
using King.Service.Data;
using NSubstitute;
using NUnit.Framework;
using Service.Scalability;
[TestFixture]
public class QueueSimplifiedScalerTests
{
public class MyQScaler : QueueSimplifiedScaler
{
public MyQScaler(IQueueCount count, ITaskCreator creator)
: base(count, creator)
{
}
}
[Test]
public void Constructor()
{
var count = Substitute.For<IQueueCount>();
var creator = Substitute.For<ITaskCreator>();
new MyQScaler(count, creator);
}
[Test]
public void IsQueueAutoScaler()
{
var count = Substitute.For<IQueueCount>();
var creator = Substitute.For<ITaskCreator>();
Assert.IsNotNull(new MyQScaler(count, creator) as QueueAutoScaler<ITaskCreator>);
}
[Test]
public void ScaleUnit()
{
var count = Substitute.For<IQueueCount>();
var creator = Substitute.For<ITaskCreator>();
creator.Task.Returns((Func<IScalable>)null);
Assert.IsNotNull(new MyQScaler(count, creator) as QueueAutoScaler<ITaskCreator>);
creator.Task().Received();
}
}
}
|
namespace King.Service.Tests.Scalability
{
using King.Azure.Data;
using King.Service.Data;
using NSubstitute;
using NUnit.Framework;
using Service.Scalability;
[TestFixture]
public class QueueSimplifiedScalerTests
{
public class MyQScaler : QueueSimplifiedScaler
{
public MyQScaler(IQueueCount count, ITaskCreator creator)
: base(count, creator)
{
}
}
[Test]
public void Constructor()
{
var count = Substitute.For<IQueueCount>();
var creator = Substitute.For<ITaskCreator>();
new MyQScaler(count, creator);
}
[Test]
public void IsAutoScaler()
{
var count = Substitute.For<IQueueCount>();
var creator = Substitute.For<ITaskCreator>();
Assert.IsNotNull(new MyQScaler(count, creator) as QueueAutoScaler<ITaskCreator>);
}
}
}
|
mit
|
C#
|
28d7375b321c922e1e118645dc40b3d4552b1b2f
|
Change FloatPrecision value
|
bartlomiejwolk/AnimationPathAnimator
|
GlobalConstants.cs
|
GlobalConstants.cs
|
namespace ATP.AnimationPathTools {
public static class GlobalConstants {
public const float FloatPrecision = 0.0001f;
}
}
|
namespace ATP.AnimationPathTools {
public static class GlobalConstants {
public const float FloatPrecision = 0.001f;
}
}
|
mit
|
C#
|
3d9262e3c20a627e61e2d389bcf71d8d1fc1a909
|
Fix incorrect `DummyNativeTexture` implementation
|
peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework
|
osu.Framework/Graphics/Rendering/Dummy/DummyNativeTexture.cs
|
osu.Framework/Graphics/Rendering/Dummy/DummyNativeTexture.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Textures;
namespace osu.Framework.Graphics.Rendering.Dummy
{
/// <summary>
/// An <see cref="INativeTexture"/> that does nothing. May be used for tests that don't have a visual output.
/// </summary>
internal class DummyNativeTexture : INativeTexture
{
public IRenderer Renderer { get; }
public string Identifier => string.Empty;
public int MaxSize => 4096; // Sane default for testing purposes.
public int Width { get; set; } = 1;
public int Height { get; set; } = 1;
public bool Available => true;
public bool BypassTextureUploadQueueing { get; set; }
public bool UploadComplete => true;
public bool IsQueuedForUpload { get; set; }
ulong INativeTexture.TotalBindCount { get; set; }
public DummyNativeTexture(IRenderer renderer)
{
Renderer = renderer;
}
public void FlushUploads()
{
}
public void SetData(ITextureUpload upload)
{
}
public bool Upload() => true;
public bool Bind(int unit) => true;
public int GetByteSize() => 0;
public ulong BindCount => 0;
public void Dispose()
{
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.Textures;
namespace osu.Framework.Graphics.Rendering.Dummy
{
/// <summary>
/// An <see cref="INativeTexture"/> that does nothing. May be used for tests that don't have a visual output.
/// </summary>
internal class DummyNativeTexture : INativeTexture
{
public IRenderer Renderer { get; }
public string Identifier => string.Empty;
public int MaxSize => 4096; // Sane default for testing purposes.
public int Width { get; set; } = 1;
public int Height { get; set; } = 1;
public bool Available => true;
public bool BypassTextureUploadQueueing { get; set; }
public bool UploadComplete => true;
public bool IsQueuedForUpload { get; set; }
ulong INativeTexture.TotalBindCount
{
get => 0;
set => throw new System.NotImplementedException();
}
public DummyNativeTexture(IRenderer renderer)
{
Renderer = renderer;
}
public void FlushUploads()
{
}
public void SetData(ITextureUpload upload)
{
}
public bool Upload() => true;
public bool Bind(int unit) => true;
public int GetByteSize() => 0;
public ulong BindCount => 0;
public void Dispose()
{
}
}
}
|
mit
|
C#
|
fbf508d59a9a55f687716b4708df7f10628ce32c
|
change the controls for generating single buildings
|
AlexanderMazaletskiy/ProceduralBuildings,tkaretsos/ProceduralBuildings
|
Scripts/BuildingController.cs
|
Scripts/BuildingController.cs
|
using Thesis;
using UnityEngine;
public class BuildingController : MonoBehaviour
{
void Update ()
{
if (Input.GetKeyUp(KeyCode.F5))
{
BuildingManager.Instance.DestroyBuildings();
BuildingManager.Instance.CreateNeoclassical(BuildMode.Two);
}
if (Input.GetKeyUp(KeyCode.F6))
{
BuildingManager.Instance.DestroyBuildings();
BuildingManager.Instance.CreateNeoclassical(BuildMode.Three);
}
if (Input.GetKeyUp(KeyCode.F7))
{
BuildingManager.Instance.DestroyBuildings();
BuildingManager.Instance.CreateNeoclassical(BuildMode.Four);
}
if (Input.GetKeyUp(KeyCode.F8))
{
BuildingManager.Instance.DestroyBuildings();
BuildingManager.Instance.CreateNeoclassical(BuildMode.Five);
}
}
}
|
using Thesis;
using UnityEngine;
public class BuildingController : MonoBehaviour
{
void Update ()
{
if (Input.GetKeyUp(KeyCode.Alpha2))
{
BuildingManager.Instance.DestroyBuildings();
BuildingManager.Instance.CreateNeoclassical(BuildMode.Two);
}
if (Input.GetKeyUp(KeyCode.Alpha3))
{
BuildingManager.Instance.DestroyBuildings();
BuildingManager.Instance.CreateNeoclassical(BuildMode.Three);
}
if (Input.GetKeyUp(KeyCode.Alpha4))
{
BuildingManager.Instance.DestroyBuildings();
BuildingManager.Instance.CreateNeoclassical(BuildMode.Four);
}
if (Input.GetKeyUp(KeyCode.Alpha5))
{
BuildingManager.Instance.DestroyBuildings();
BuildingManager.Instance.CreateNeoclassical(BuildMode.Five);
}
}
}
|
mit
|
C#
|
6f5a385b6d35eeec984a22fb726ab18cffecf3d4
|
Fix typo in Adventure sample (#6496)
|
yevhen/orleans,hoopsomuah/orleans,amccool/orleans,ibondy/orleans,galvesribeiro/orleans,jason-bragg/orleans,waynemunro/orleans,dotnet/orleans,amccool/orleans,veikkoeeva/orleans,ElanHasson/orleans,ElanHasson/orleans,waynemunro/orleans,ibondy/orleans,yevhen/orleans,benjaminpetit/orleans,ReubenBond/orleans,hoopsomuah/orleans,dotnet/orleans,jthelin/orleans,galvesribeiro/orleans,amccool/orleans
|
Samples/2.0/Adventure/AdventureGrainInterfaces/IRoomGrain.cs
|
Samples/2.0/Adventure/AdventureGrainInterfaces/IRoomGrain.cs
|
using Orleans;
using System.Threading.Tasks;
namespace AdventureGrainInterfaces
{
/// <summary>
/// A room is any location in a game, including outdoor locations and
/// spaces that are arguably better described as moist, cold, caverns.
/// </summary>
public interface IRoomGrain : IGrainWithIntegerKey
{
// Rooms have a textual description
Task<string> Description(PlayerInfo whoisAsking);
Task SetInfo(RoomInfo info);
Task<IRoomGrain> ExitTo(string direction);
// Players can enter or exit a room
Task Enter(PlayerInfo player);
Task Exit(PlayerInfo player);
// Monsters can enter or exit a room
Task Enter(MonsterInfo monster);
Task Exit(MonsterInfo monster);
// Things can be dropped or taken from a room
Task Drop(Thing thing);
Task Take(Thing thing);
Task<Thing> FindThing(string name);
// Players and monsters can be killed, if you have the right weapon.
Task<PlayerInfo> FindPlayer(string name);
Task<MonsterInfo> FindMonster(string name);
}
}
|
using Orleans;
using System.Threading.Tasks;
namespace AdventureGrainInterfaces
{
/// <summary>
/// A room is any location in a game, including outdoor locations and
/// spaces that are arguably better described as moist, cold, caverns.
/// </summary>
public interface IRoomGrain : IGrainWithIntegerKey
{
// Rooms have a textual description
Task<string> Description(PlayerInfo whoisAsking);
Task SetInfo(RoomInfo info);
Task<IRoomGrain> ExitTo(string direction);
// Players can enter or exit a room
Task Enter(PlayerInfo player);
Task Exit(PlayerInfo player);
// Players can enter or exit a room
Task Enter(MonsterInfo monster);
Task Exit(MonsterInfo monster);
// Things can be dropped or taken from a room
Task Drop(Thing thing);
Task Take(Thing thing);
Task<Thing> FindThing(string name);
// Players and monsters can be killed, if you have the right weapon.
Task<PlayerInfo> FindPlayer(string name);
Task<MonsterInfo> FindMonster(string name);
}
}
|
mit
|
C#
|
3d2eb8dc1ee237de420aa680734e1ba3f6dc01b5
|
Rename connection to client
|
kevinta893/NetworkIt,kevinta893/NetworkIt,kevinta893/NetworkIt,kevinta893/NetworkIt,kevinta893/NetworkIt,kevinta893/NetworkIt,kevinta893/NetworkIt
|
NetworkItUnity/Assets/NetworkIt/Scripts/NetworkItEvents.cs
|
NetworkItUnity/Assets/NetworkIt/Scripts/NetworkItEvents.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NetworkIt;
using System;
public class NetworkItEvents : MonoBehaviour {
public string urlAddress = "";
public int port = 8000;
public string username = "demo_test_username";
public GameObject[] messageListeners;
private volatile LinkedList<Message> messageEvents = new LinkedList<Message>();
private Client client;
void Start() {
if (urlAddress == null || urlAddress.Length <= 0) {
Debug.LogError("URL or IP Address required.");
return;
}
if (username == null || username.Length <= 0) {
Debug.LogError("Username required.");
return;
}
client = new Client(username, urlAddress, port); //create and establish connection to server
client.StartConnection();
client.Connected += Connection_Connected;
client.Disconnected += Connection_Disconnected;
client.MessageReceived += Connection_MessageReceived;
client.Error += Connection_Error;
}
void Update()
{
ConsumeNetworkMessages();
}
//consume messages as they come in
private void ConsumeNetworkMessages()
{
if (messageEvents.Count <= 0)
{
return;
}
while (messageEvents.Count > 0)
{
Message m = messageEvents.First.Value;
foreach (GameObject g in messageListeners)
{
g.SendMessage("MessageReceived", m);
}
messageEvents.RemoveFirst();
}
}
private void Connection_MessageReceived(object sender, NetworkItMessageEventArgs e)
{
NotifyMessageListeners(e.ReceivedMessage);
}
private void Connection_Error(object sender, System.IO.ErrorEventArgs e)
{
}
private void Connection_Disconnected(object sender, System.EventArgs e)
{
}
private void Connection_Connected(object sender, System.EventArgs e)
{
}
//consumer producer pattern for threads
private void NotifyMessageListeners(Message recievedMessage)
{
messageEvents.AddLast(recievedMessage);
}
private void OnApplicationQuit()
{
client.CloseConnection();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using NetworkIt;
using System;
public class NetworkItEvents : MonoBehaviour {
public string urlAddress = "";
public int port = 8000;
public string username = "demo_test_username";
public GameObject[] messageListeners;
private volatile LinkedList<Message> messageEvents = new LinkedList<Message>();
private Client connection;
void Start() {
if (urlAddress == null || urlAddress.Length <= 0) {
Debug.LogError("URL or IP Address required.");
return;
}
if (username == null || username.Length <= 0) {
Debug.LogError("Username required.");
return;
}
connection = new Client(username, urlAddress, port); //create and establish connection to server
connection.StartConnection();
connection.Connected += Connection_Connected;
connection.Disconnected += Connection_Disconnected;
connection.MessageReceived += Connection_MessageReceived;
connection.Error += Connection_Error;
}
void Update()
{
ConsumeNetworkMessages();
}
//consume messages as they come in
private void ConsumeNetworkMessages()
{
if (messageEvents.Count <= 0)
{
return;
}
while (messageEvents.Count > 0)
{
Message m = messageEvents.First.Value;
foreach (GameObject g in messageListeners)
{
g.SendMessage("MessageReceived", m);
}
messageEvents.RemoveFirst();
}
}
private void Connection_MessageReceived(object sender, NetworkItMessageEventArgs e)
{
NotifyMessageListeners(e.ReceivedMessage);
}
private void Connection_Error(object sender, System.IO.ErrorEventArgs e)
{
}
private void Connection_Disconnected(object sender, System.EventArgs e)
{
}
private void Connection_Connected(object sender, System.EventArgs e)
{
}
//consumer producer pattern for threads
private void NotifyMessageListeners(Message recievedMessage)
{
messageEvents.AddLast(recievedMessage);
}
private void OnApplicationQuit()
{
connection.CloseConnection();
}
}
|
mit
|
C#
|
4bd480deb42d6b13b39ac7076f28c230bc4307d6
|
Add access to the RawProtobufValue converters (from/to).
|
r3c/Verse
|
Verse/src/Schemas/RawProtobuf/RawProtobufValue.cs
|
Verse/src/Schemas/RawProtobuf/RawProtobufValue.cs
|
namespace Verse.Schemas.RawProtobuf
{
public readonly struct RawProtobufValue
{
public readonly long Number;
public readonly RawProtobufStorage Storage;
public readonly string String;
public RawProtobufValue(long number, RawProtobufStorage storage)
{
this.Number = number;
this.Storage = storage;
this.String = default;
}
public RawProtobufValue(string value, RawProtobufStorage storage)
{
this.Number = default;
this.Storage = storage;
this.String = value;
}
private static readonly RawProtobufEncoderConverter converterFrom = new RawProtobufEncoderConverter();
private static readonly RawProtobufDecoderConverter converterTo = new RawProtobufDecoderConverter();
public static RawProtobufValue FromLong(long value)
{
return converterFrom.Get<long>()(value);
}
public static RawProtobufValue FromFloat(float value)
{
return converterFrom.Get<float>()(value);
}
public static RawProtobufValue FromDouble(double value)
{
return converterFrom.Get<double>()(value);
}
public static RawProtobufValue FromString(string value)
{
return converterFrom.Get<string>()(value);
}
public static long ToLong(RawProtobufValue value)
{
return converterTo.Get<long>()(value);
}
public static double ToDouble(RawProtobufValue value)
{
return converterTo.Get<double>()(value);
}
public static float ToFloat(RawProtobufValue value)
{
return converterTo.Get<float>()(value);
}
public static string ToString(RawProtobufValue value)
{
return converterTo.Get<string>()(value);
}
}
}
|
namespace Verse.Schemas.RawProtobuf
{
public readonly struct RawProtobufValue
{
public readonly long Number;
public readonly RawProtobufStorage Storage;
public readonly string String;
public RawProtobufValue(long number, RawProtobufStorage storage)
{
this.Number = number;
this.Storage = storage;
this.String = default;
}
public RawProtobufValue(string value, RawProtobufStorage storage)
{
this.Number = default;
this.Storage = storage;
this.String = value;
}
}
}
|
mit
|
C#
|
8c16d08a2a6346874443fc04e50782efa964276a
|
Fix name violation
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Gui/ManagedDialogs/ManagedFileChooserSources.cs
|
WalletWasabi.Gui/ManagedDialogs/ManagedFileChooserSources.cs
|
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
namespace WalletWasabi.Gui.ManagedDialogs
{
public class ManagedFileChooserSources
{
public Func<ManagedFileChooserNavigationItem[]> GetUserDirectories { get; set; }
= DefaultGetUserDirectories;
public Func<ManagedFileChooserNavigationItem[]> GetFileSystemRoots { get; set; }
= DefaultGetFileSystemRoots;
public Func<ManagedFileChooserSources, ManagedFileChooserNavigationItem[]> GetAllItemsDelegate { get; set; }
= DefaultGetAllItems;
public ManagedFileChooserNavigationItem[] GetAllItems() => GetAllItemsDelegate(this);
public static ManagedFileChooserNavigationItem[] DefaultGetAllItems(ManagedFileChooserSources sources)
{
return sources.GetUserDirectories().Concat(sources.GetFileSystemRoots()).ToArray();
}
private static Environment.SpecialFolder[] Folders = new[]
{
Environment.SpecialFolder.Desktop,
Environment.SpecialFolder.UserProfile,
Environment.SpecialFolder.MyDocuments,
Environment.SpecialFolder.MyMusic,
Environment.SpecialFolder.MyPictures,
Environment.SpecialFolder.MyVideos
};
public static ManagedFileChooserNavigationItem[] DefaultGetUserDirectories()
{
return Folders.Select(Environment.GetFolderPath).Distinct()
.Where(d => !string.IsNullOrWhiteSpace(d))
.Where(Directory.Exists)
.Select(d => new ManagedFileChooserNavigationItem
{
Path = d,
DisplayName = Path.GetFileName(d)
}).ToArray();
}
public static ManagedFileChooserNavigationItem[] DefaultGetFileSystemRoots()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return DriveInfo.GetDrives().Select(d => new ManagedFileChooserNavigationItem
{
DisplayName = d.Name,
Path = d.RootDirectory.FullName
}).ToArray();
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
var paths = Directory.GetDirectories("/Volumes");
return paths.Select(x => new ManagedFileChooserNavigationItem
{
DisplayName = Path.GetFileName(x),
Path = x
}).ToArray();
}
else
{
var paths = Directory.GetDirectories("/media/");
var drives = new ManagedFileChooserNavigationItem[]
{
new ManagedFileChooserNavigationItem
{
DisplayName = "File System",
Path = "/"
}
}.Concat(paths.Select(x => new ManagedFileChooserNavigationItem
{
DisplayName = Path.GetFileName(x),
Path = x
})).ToArray();
return drives;
}
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
namespace WalletWasabi.Gui.ManagedDialogs
{
public class ManagedFileChooserSources
{
public Func<ManagedFileChooserNavigationItem[]> GetUserDirectories { get; set; }
= DefaultGetUserDirectories;
public Func<ManagedFileChooserNavigationItem[]> GetFileSystemRoots { get; set; }
= DefaultGetFileSystemRoots;
public Func<ManagedFileChooserSources, ManagedFileChooserNavigationItem[]> GetAllItemsDelegate { get; set; }
= DefaultGetAllItems;
public ManagedFileChooserNavigationItem[] GetAllItems() => GetAllItemsDelegate(this);
public static ManagedFileChooserNavigationItem[] DefaultGetAllItems(ManagedFileChooserSources sources)
{
return sources.GetUserDirectories().Concat(sources.GetFileSystemRoots()).ToArray();
}
private static Environment.SpecialFolder[] s_folders = new[]
{
Environment.SpecialFolder.Desktop,
Environment.SpecialFolder.UserProfile,
Environment.SpecialFolder.MyDocuments,
Environment.SpecialFolder.MyMusic,
Environment.SpecialFolder.MyPictures,
Environment.SpecialFolder.MyVideos
};
public static ManagedFileChooserNavigationItem[] DefaultGetUserDirectories()
{
return s_folders.Select(Environment.GetFolderPath).Distinct()
.Where(d => !string.IsNullOrWhiteSpace(d))
.Where(Directory.Exists)
.Select(d => new ManagedFileChooserNavigationItem
{
Path = d,
DisplayName = Path.GetFileName(d)
}).ToArray();
}
public static ManagedFileChooserNavigationItem[] DefaultGetFileSystemRoots()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return DriveInfo.GetDrives().Select(d => new ManagedFileChooserNavigationItem
{
DisplayName = d.Name,
Path = d.RootDirectory.FullName
}).ToArray();
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
var paths = Directory.GetDirectories("/Volumes");
return paths.Select(x => new ManagedFileChooserNavigationItem
{
DisplayName = Path.GetFileName(x),
Path = x
}).ToArray();
}
else
{
var paths = Directory.GetDirectories("/media/");
var drives = new ManagedFileChooserNavigationItem[]
{
new ManagedFileChooserNavigationItem
{
DisplayName = "File System",
Path = "/"
}
}.Concat(paths.Select(x => new ManagedFileChooserNavigationItem
{
DisplayName = Path.GetFileName(x),
Path = x
})).ToArray();
return drives;
}
}
}
}
|
mit
|
C#
|
be76f9f7ddd13dac440d3130338315fe61a2df37
|
Add ResolveByName attribute to StyledElement property
|
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
|
src/Avalonia.Xaml.Interactions/Custom/RemoveClassAction.cs
|
src/Avalonia.Xaml.Interactions/Custom/RemoveClassAction.cs
|
using Avalonia.Controls;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// Removes a specified <see cref="RemoveClassAction.ClassName"/> from <see cref="IStyledElement.Classes"/> collection when invoked.
/// </summary>
public class RemoveClassAction : AvaloniaObject, IAction
{
/// <summary>
/// Identifies the <seealso cref="ClassName"/> avalonia property.
/// </summary>
public static readonly StyledProperty<string> ClassNameProperty =
AvaloniaProperty.Register<RemoveClassAction, string>(nameof(ClassName));
/// <summary>
/// Identifies the <seealso cref="StyledElement"/> avalonia property.
/// </summary>
public static readonly StyledProperty<IStyledElement?> StyledElementProperty =
AvaloniaProperty.Register<RemoveClassAction, IStyledElement?>(nameof(StyledElement));
/// <summary>
/// Gets or sets the class name that should be removed. This is a avalonia property.
/// </summary>
public string ClassName
{
get => GetValue(ClassNameProperty);
set => SetValue(ClassNameProperty, value);
}
/// <summary>
/// Gets or sets the target styled element that class name that should be removed from. This is a avalonia property.
/// </summary>
[ResolveByName]
public IStyledElement? StyledElement
{
get => GetValue(StyledElementProperty);
set => SetValue(StyledElementProperty, value);
}
/// <summary>
/// Executes the action.
/// </summary>
/// <param name="sender">The <see cref="object"/> that is passed to the action by the behavior. Generally this is <seealso cref="IBehavior.AssociatedObject"/> or a target object.</param>
/// <param name="parameter">The value of this parameter is determined by the caller.</param>
/// <returns>True if the class is successfully added; else false.</returns>
public object Execute(object? sender, object? parameter)
{
var target = GetValue(StyledElementProperty) is { } ? StyledElement : sender as IStyledElement;
if (target is null || string.IsNullOrEmpty(ClassName))
{
return false;
}
if (target.Classes.Contains(ClassName))
{
target.Classes.Remove(ClassName);
}
return true;
}
}
|
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// Removes a specified <see cref="RemoveClassAction.ClassName"/> from <see cref="IStyledElement.Classes"/> collection when invoked.
/// </summary>
public class RemoveClassAction : AvaloniaObject, IAction
{
/// <summary>
/// Identifies the <seealso cref="ClassName"/> avalonia property.
/// </summary>
public static readonly StyledProperty<string> ClassNameProperty =
AvaloniaProperty.Register<RemoveClassAction, string>(nameof(ClassName));
/// <summary>
/// Identifies the <seealso cref="StyledElement"/> avalonia property.
/// </summary>
public static readonly StyledProperty<IStyledElement?> StyledElementProperty =
AvaloniaProperty.Register<RemoveClassAction, IStyledElement?>(nameof(StyledElement));
/// <summary>
/// Gets or sets the class name that should be removed. This is a avalonia property.
/// </summary>
public string ClassName
{
get => GetValue(ClassNameProperty);
set => SetValue(ClassNameProperty, value);
}
/// <summary>
/// Gets or sets the target styled element that class name that should be removed from. This is a avalonia property.
/// </summary>
public IStyledElement? StyledElement
{
get => GetValue(StyledElementProperty);
set => SetValue(StyledElementProperty, value);
}
/// <summary>
/// Executes the action.
/// </summary>
/// <param name="sender">The <see cref="object"/> that is passed to the action by the behavior. Generally this is <seealso cref="IBehavior.AssociatedObject"/> or a target object.</param>
/// <param name="parameter">The value of this parameter is determined by the caller.</param>
/// <returns>True if the class is successfully added; else false.</returns>
public object Execute(object? sender, object? parameter)
{
var target = GetValue(StyledElementProperty) is { } ? StyledElement : sender as IStyledElement;
if (target is null || string.IsNullOrEmpty(ClassName))
{
return false;
}
if (target.Classes.Contains(ClassName))
{
target.Classes.Remove(ClassName);
}
return true;
}
}
|
mit
|
C#
|
73685275c4000c939bb3ccb5fb656863b492cb66
|
bump ver
|
AntonyCorbett/OnlyT,AntonyCorbett/OnlyT
|
SolutionInfo.cs
|
SolutionInfo.cs
|
using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.27")]
|
using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.26")]
|
mit
|
C#
|
8c8f87b435b0b028fb07d4ec013fa3a0e2a99ed3
|
Change Price type to double
|
kiyoaki/bitflyer-api-dotnet-client
|
src/BitFlyer.Apis/RequestData/SendChildOrderParameter.cs
|
src/BitFlyer.Apis/RequestData/SendChildOrderParameter.cs
|
using Newtonsoft.Json;
namespace BitFlyer.Apis
{
public class SendChildOrderParameter
{
[JsonProperty("product_code")]
public ProductCode ProductCode { get; set; }
[JsonProperty("child_order_type")]
public ChildOrderType ChildOrderType { get; set; }
[JsonProperty("side")]
public Side Side { get; set; }
[JsonProperty("price")]
public double Price { get; set; }
[JsonProperty("size")]
public double Size { get; set; }
[JsonProperty("minute_to_expire")]
public int MinuteToExpire { get; set; }
[JsonProperty("time_in_force")]
public TimeInForce TimeInForce { get; set; }
}
}
|
using Newtonsoft.Json;
namespace BitFlyer.Apis
{
public class SendChildOrderParameter
{
[JsonProperty("product_code")]
public ProductCode ProductCode { get; set; }
[JsonProperty("child_order_type")]
public ChildOrderType ChildOrderType { get; set; }
[JsonProperty("side")]
public Side Side { get; set; }
[JsonProperty("price")]
public int Price { get; set; }
[JsonProperty("size")]
public double Size { get; set; }
[JsonProperty("minute_to_expire")]
public int MinuteToExpire { get; set; }
[JsonProperty("time_in_force")]
public TimeInForce TimeInForce { get; set; }
}
}
|
mit
|
C#
|
40afae605eac22b02f60ea082d5befbd00e535af
|
Clean up Normalization code (dotnet/coreclr#9941)
|
ericstj/corefx,shimingsg/corefx,ericstj/corefx,ericstj/corefx,zhenlan/corefx,BrennanConroy/corefx,ViktorHofer/corefx,Jiayili1/corefx,ravimeda/corefx,Jiayili1/corefx,zhenlan/corefx,mmitche/corefx,ericstj/corefx,ravimeda/corefx,ViktorHofer/corefx,Ermiar/corefx,ptoonen/corefx,shimingsg/corefx,Jiayili1/corefx,shimingsg/corefx,zhenlan/corefx,zhenlan/corefx,wtgodbe/corefx,Ermiar/corefx,Jiayili1/corefx,ViktorHofer/corefx,ptoonen/corefx,ViktorHofer/corefx,ptoonen/corefx,shimingsg/corefx,mmitche/corefx,shimingsg/corefx,wtgodbe/corefx,Ermiar/corefx,wtgodbe/corefx,Ermiar/corefx,mmitche/corefx,Jiayili1/corefx,ravimeda/corefx,wtgodbe/corefx,ViktorHofer/corefx,zhenlan/corefx,ptoonen/corefx,BrennanConroy/corefx,ptoonen/corefx,ravimeda/corefx,zhenlan/corefx,wtgodbe/corefx,ravimeda/corefx,Ermiar/corefx,ericstj/corefx,Jiayili1/corefx,ericstj/corefx,ViktorHofer/corefx,ravimeda/corefx,ptoonen/corefx,mmitche/corefx,BrennanConroy/corefx,shimingsg/corefx,ptoonen/corefx,mmitche/corefx,wtgodbe/corefx,mmitche/corefx,Ermiar/corefx,Ermiar/corefx,ravimeda/corefx,wtgodbe/corefx,ViktorHofer/corefx,zhenlan/corefx,mmitche/corefx,ericstj/corefx,shimingsg/corefx,Jiayili1/corefx
|
src/Common/src/CoreLib/Interop/Windows/Interop.Errors.cs
|
src/Common/src/CoreLib/Interop/Windows/Interop.Errors.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
internal partial class Interop
{
internal partial class Errors
{
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_PATH_NOT_FOUND = 0x3;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int ERROR_INVALID_DRIVE = 0xF;
internal const int ERROR_NO_MORE_FILES = 0x12;
internal const int ERROR_NOT_READY = 0x15;
internal const int ERROR_SHARING_VIOLATION = 0x20;
internal const int ERROR_HANDLE_EOF = 0x26;
internal const int ERROR_FILE_EXISTS = 0x50;
internal const int ERROR_INVALID_PARAMETER = 0x57;
internal const int ERROR_BROKEN_PIPE = 0x6D;
internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A;
internal const int ERROR_INVALID_NAME = 0x7B;
internal const int ERROR_BAD_PATHNAME = 0xA1;
internal const int ERROR_ALREADY_EXISTS = 0xB7;
internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE;
internal const int ERROR_NO_DATA = 0xE8;
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_NO_MORE_ITEMS = 0x103;
internal const int ERROR_NOT_OWNER = 0x120;
internal const int ERROR_TOO_MANY_POSTS = 0x12A;
internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216;
internal const int ERROR_MUTANT_LIMIT_EXCEEDED = 0x24B;
internal const int ERROR_OPERATION_ABORTED = 0x3E3;
internal const int ERROR_IO_PENDING = 0x3E5;
internal const int ERROR_NO_UNICODE_TRANSLATION = 0x459;
internal const int ERROR_NOT_FOUND = 0x490;
internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542;
internal const int E_FILENOTFOUND = unchecked((int)0x80070002);
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
internal partial class Interop
{
internal partial class Errors
{
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_PATH_NOT_FOUND = 0x3;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int ERROR_INVALID_DRIVE = 0xF;
internal const int ERROR_NO_MORE_FILES = 0x12;
internal const int ERROR_NOT_READY = 0x15;
internal const int ERROR_SHARING_VIOLATION = 0x20;
internal const int ERROR_HANDLE_EOF = 0x26;
internal const int ERROR_FILE_EXISTS = 0x50;
internal const int ERROR_INVALID_PARAMETER = 0x57;
internal const int ERROR_BROKEN_PIPE = 0x6D;
internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A;
internal const int ERROR_INVALID_NAME = 0x7B;
internal const int ERROR_BAD_PATHNAME = 0xA1;
internal const int ERROR_ALREADY_EXISTS = 0xB7;
internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE;
internal const int ERROR_NO_DATA = 0xE8;
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_NO_MORE_ITEMS = 0x103;
internal const int ERROR_NOT_OWNER = 0x120;
internal const int ERROR_TOO_MANY_POSTS = 0x12A;
internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216;
internal const int ERROR_MUTANT_LIMIT_EXCEEDED = 0x24B;
internal const int ERROR_OPERATION_ABORTED = 0x3E3;
internal const int ERROR_IO_PENDING = 0x3E5;
internal const int ERROR_NOT_FOUND = 0x490;
internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542;
internal const int E_FILENOTFOUND = unchecked((int)0x80070002);
}
}
|
mit
|
C#
|
85d7fe3f160a144aa4430d4ad0fe14f00279d5fb
|
Fix setting color of text for ComboBoxCell
|
l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto
|
Source/Eto.Platform.Wpf/Forms/Cells/ComboBoxCellHandler.cs
|
Source/Eto.Platform.Wpf/Forms/Cells/ComboBoxCellHandler.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Eto.Forms;
using swc = System.Windows.Controls;
using swd = System.Windows.Data;
using sw = System.Windows;
using System.Collections;
namespace Eto.Platform.Wpf.Forms.Controls
{
public class ComboBoxCellHandler : CellHandler<swc.DataGridComboBoxColumn, ComboBoxCell>, IComboBoxCell
{
IListStore store;
string GetValue (object dataItem)
{
if (Widget.Binding != null) {
var val = Widget.Binding.GetValue (dataItem);
if (val != null)
return Convert.ToString (val);
}
return null;
}
void SetValue (object dataItem, object value)
{
if (Widget.Binding != null) {
Widget.Binding.SetValue (dataItem, Convert.ToString (value));
}
}
class Column : swc.DataGridComboBoxColumn
{
public ComboBoxCellHandler Handler { get; set; }
protected override sw.FrameworkElement GenerateElement (swc.DataGridCell cell, object dataItem)
{
var element = base.GenerateElement (cell, dataItem);
element.DataContextChanged += (sender, e) => {
var control = sender as swc.ComboBox;
control.SelectedValue = Handler.GetValue (control.DataContext);
Handler.FormatCell (control, cell, dataItem);
};
Handler.FormatCell (element, cell, dataItem);
return Handler.SetupCell (element);
}
protected override sw.FrameworkElement GenerateEditingElement (swc.DataGridCell cell, object dataItem)
{
var element = base.GenerateEditingElement (cell, dataItem);
element.Name = "control";
element.DataContextChanged += (sender, e) => {
var control = sender as swc.ComboBox;
control.SelectedValue = Handler.GetValue (control.DataContext);
Handler.FormatCell (control, cell, dataItem);
};
Handler.FormatCell (element, cell, dataItem);
return Handler.SetupCell (element);
}
protected override bool CommitCellEdit (sw.FrameworkElement editingElement)
{
var control = editingElement as swc.ComboBox ?? editingElement.FindChild<swc.ComboBox> ("control");
Handler.SetValue (control.DataContext, control.SelectedValue);
return true;
}
}
public ComboBoxCellHandler ()
{
Control = new Column {
Handler = this,
DisplayMemberPath = "Text",
SelectedValuePath = "Key"
};
}
public IListStore DataStore
{
get { return store; }
set
{
store = value;
Control.ItemsSource = store as IEnumerable ?? store.AsEnumerable();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Eto.Forms;
using swc = System.Windows.Controls;
using swd = System.Windows.Data;
using sw = System.Windows;
using System.Collections;
namespace Eto.Platform.Wpf.Forms.Controls
{
public class ComboBoxCellHandler : CellHandler<swc.DataGridComboBoxColumn, ComboBoxCell>, IComboBoxCell
{
IListStore store;
string GetValue (object dataItem)
{
if (Widget.Binding != null) {
var val = Widget.Binding.GetValue (dataItem);
if (val != null)
return Convert.ToString (val);
}
return null;
}
void SetValue (object dataItem, object value)
{
if (Widget.Binding != null) {
Widget.Binding.SetValue (dataItem, Convert.ToString (value));
}
}
class Column : swc.DataGridComboBoxColumn
{
public ComboBoxCellHandler Handler { get; set; }
protected override sw.FrameworkElement GenerateElement (swc.DataGridCell cell, object dataItem)
{
var element = base.GenerateElement (cell, dataItem);
element.DataContextChanged += (sender, e) => {
var control = sender as swc.ComboBox;
control.SelectedValue = Handler.GetValue (control.DataContext);
Handler.FormatCell (control, cell, dataItem);
};
return Handler.SetupCell(element);
}
protected override sw.FrameworkElement GenerateEditingElement (swc.DataGridCell cell, object dataItem)
{
var element = base.GenerateEditingElement (cell, dataItem);
element.Name = "control";
element.DataContextChanged += (sender, e) => {
var control = sender as swc.ComboBox;
control.SelectedValue = Handler.GetValue (control.DataContext);
Handler.FormatCell (control, cell, dataItem);
};
return Handler.SetupCell(element);
}
protected override bool CommitCellEdit (sw.FrameworkElement editingElement)
{
var control = editingElement as swc.ComboBox ?? editingElement.FindChild<swc.ComboBox> ("control");
Handler.SetValue (control.DataContext, control.SelectedValue);
return true;
}
}
public ComboBoxCellHandler ()
{
Control = new Column {
Handler = this,
DisplayMemberPath = "Text",
SelectedValuePath = "Key"
};
}
public IListStore DataStore
{
get { return store; }
set
{
store = value;
Control.ItemsSource = store as IEnumerable ?? store.AsEnumerable();
}
}
}
}
|
bsd-3-clause
|
C#
|
261f350eed6e5001bf3463a627600d66a8277279
|
remove unnescessary visibility setting in click event
|
github/VisualStudio,github/VisualStudio,github/VisualStudio
|
src/GitHub.VisualStudio.UI/UI/Controls/InfoPanel.xaml.cs
|
src/GitHub.VisualStudio.UI/UI/Controls/InfoPanel.xaml.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace GitHub.VisualStudio.UI.Controls
{
/// <summary>
/// Interaction logic for InfoPanel.xaml
/// </summary>
public partial class InfoPanel : UserControl
{
public static readonly DependencyProperty MessageProperty =
DependencyProperty.Register(nameof(Message), typeof(string), typeof(InfoPanel), new PropertyMetadata(null, UpdateVisibility));
public string Message
{
get { return (string)GetValue(MessageProperty); }
set { SetValue(MessageProperty, value); }
}
public InfoPanel()
{
InitializeComponent();
this.DataContext = this;
}
static void UpdateVisibility(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (InfoPanel)d;
control.Visibility = string.IsNullOrEmpty(control.Message) ? Visibility.Collapsed : Visibility.Visible;
}
void Button_Click(object sender, RoutedEventArgs e)
{
this.Message = string.Empty;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace GitHub.VisualStudio.UI.Controls
{
/// <summary>
/// Interaction logic for InfoPanel.xaml
/// </summary>
public partial class InfoPanel : UserControl
{
public static readonly DependencyProperty MessageProperty =
DependencyProperty.Register(nameof(Message), typeof(string), typeof(InfoPanel), new PropertyMetadata(null, UpdateVisibility));
public string Message
{
get { return (string)GetValue(MessageProperty); }
set { SetValue(MessageProperty, value); }
}
public InfoPanel()
{
InitializeComponent();
this.DataContext = this;
}
static void UpdateVisibility(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (InfoPanel)d;
control.Visibility = string.IsNullOrEmpty(control.Message) ? Visibility.Collapsed : Visibility.Visible;
}
void Button_Click(object sender, RoutedEventArgs e)
{
this.Visibility = Visibility.Collapsed;
this.Message = string.Empty;
}
}
}
|
mit
|
C#
|
3039c163fd48e6bcb25a684b95bf1ca0f79a2998
|
fix no Namespace cases in SignumControllerFactory
|
AlejandroCano/framework,AlejandroCano/framework,signumsoftware/framework,signumsoftware/framework,avifatal/framework,avifatal/framework
|
Signum.React/Facades/SignumControllerFactory.cs
|
Signum.React/Facades/SignumControllerFactory.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Signum.React.Facades;
using Signum.Utilities;
using System.Web.Http.Dispatcher;
using System.Web.Http.Controllers;
using System.Net.Http;
using System.Web.Http;
using System.Reflection;
using Signum.React.ApiControllers;
namespace Signum.React
{
public class SignumControllerFactory : DefaultHttpControllerSelector
{
public static HashSet<Type> AllowedControllers { get; private set; } = new HashSet<Type>();
public Assembly MainAssembly { get; set; }
public SignumControllerFactory(HttpConfiguration configuration, Assembly mainAssembly) : base(configuration)
{
this.MainAssembly = mainAssembly;
}
public static void RegisterController<T>()
{
AllowedControllers.Add(typeof(T));
}
public static void RegisterArea(MethodBase mb)
{
RegisterArea(mb.DeclaringType);
}
public static void RegisterArea(Type type)
{
AllowedControllers.AddRange(type.Assembly.ExportedTypes
.Where(c => (c.Namespace ?? "").StartsWith(type.Namespace) && typeof(ApiController).IsAssignableFrom(c)));
}
public override IDictionary<string, HttpControllerDescriptor> GetControllerMapping()
{
var dic = base.GetControllerMapping();
var result = dic.Where(a => a.Value.ControllerType.Assembly == MainAssembly || AllowedControllers.Contains(a.Value.ControllerType)).ToDictionary();
var removedControllers = dic.Keys.Except(result.Keys);//Just for debugging
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Signum.React.Facades;
using Signum.Utilities;
using System.Web.Http.Dispatcher;
using System.Web.Http.Controllers;
using System.Net.Http;
using System.Web.Http;
using System.Reflection;
using Signum.React.ApiControllers;
namespace Signum.React
{
public class SignumControllerFactory : DefaultHttpControllerSelector
{
public static HashSet<Type> AllowedControllers { get; private set; } = new HashSet<Type>();
public Assembly MainAssembly { get; set; }
public SignumControllerFactory(HttpConfiguration configuration, Assembly mainAssembly) : base(configuration)
{
this.MainAssembly = mainAssembly;
}
public static void RegisterController<T>()
{
AllowedControllers.Add(typeof(T));
}
public static void RegisterArea(MethodBase mb)
{
RegisterArea(mb.DeclaringType);
}
public static void RegisterArea(Type type)
{
AllowedControllers.AddRange(type.Assembly.ExportedTypes
.Where(c => c.Namespace.StartsWith(type.Namespace) && typeof(ApiController).IsAssignableFrom(c)));
}
public override IDictionary<string, HttpControllerDescriptor> GetControllerMapping()
{
var dic = base.GetControllerMapping();
var result = dic.Where(a => a.Value.ControllerType.Assembly == MainAssembly || AllowedControllers.Contains(a.Value.ControllerType)).ToDictionary();
var removedControllers = dic.Keys.Except(result.Keys);//Just for debugging
return result;
}
}
}
|
mit
|
C#
|
6593fea49839e1600892ce5fbf029382d0680ec0
|
Disable login redirect to dbbrowser.aspx forbidding redirects altogether
|
afortaleza/sitecore-linqpad
|
Sitecore.Linqpad/Server/CookieAwareWebClient.cs
|
Sitecore.Linqpad/Server/CookieAwareWebClient.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Sitecore.Linqpad.Server
{
public class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient(CookieContainer cookies = null)
{
this.Cookies = cookies ?? new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
var webRequest = base.GetWebRequest(address);
var request2 = webRequest as HttpWebRequest;
if (request2 != null)
{
request2.CookieContainer = this.Cookies;
request2.AllowAutoRedirect = false;
}
webRequest.Timeout = 300000;
return webRequest;
}
public CookieContainer Cookies { get; private set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Sitecore.Linqpad.Server
{
public class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient(CookieContainer cookies = null)
{
this.Cookies = cookies ?? new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
var webRequest = base.GetWebRequest(address);
var request2 = webRequest as HttpWebRequest;
if (request2 != null)
{
request2.CookieContainer = this.Cookies;
}
webRequest.Timeout = 300000;
return webRequest;
}
public CookieContainer Cookies { get; private set; }
}
}
|
mit
|
C#
|
0f18050e79f623e8b8aa35cc70af1bd80915249a
|
add FromBody
|
smbc-digital/iag-contentapi
|
src/StockportContentApi/Controllers/RedirectsController.cs
|
src/StockportContentApi/Controllers/RedirectsController.cs
|
using StockportContentApi.Repositories;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StockportContentApi.ContentfulModels;
namespace StockportContentApi.Controllers
{
[ApiExplorerSettings(IgnoreApi = true)]
public class RedirectsController : Controller
{
private readonly ResponseHandler _handler;
private readonly RedirectsRepository _repository;
private readonly ILogger<RedirectsController> _logger;
public RedirectsController(ResponseHandler handler,
RedirectsRepository repository,
ILogger<RedirectsController> logger)
{
_handler = handler;
_repository = repository;
_logger = logger;
}
[HttpGet]
[Route("redirects")]
[Route("v1/redirects")]
public async Task<IActionResult> GetRedirects(string businessId)
{
return await _handler.Get(() => _repository.GetRedirects());
}
[HttpPost]
[Route("update-redirects")]
public async Task<IActionResult> UpdateRedirects([FromBody]ContentfulRedirect body)
{
_logger.LogWarning($"RedirectsController:: UpdateRedirects body received: {JsonConvert.SerializeObject(body)}");
return Ok();
}
}
}
|
using StockportContentApi.Repositories;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StockportContentApi.ContentfulModels;
namespace StockportContentApi.Controllers
{
[ApiExplorerSettings(IgnoreApi = true)]
public class RedirectsController : Controller
{
private readonly ResponseHandler _handler;
private readonly RedirectsRepository _repository;
private readonly ILogger<RedirectsController> _logger;
public RedirectsController(ResponseHandler handler,
RedirectsRepository repository,
ILogger<RedirectsController> logger)
{
_handler = handler;
_repository = repository;
_logger = logger;
}
[HttpGet]
[Route("redirects")]
[Route("v1/redirects")]
public async Task<IActionResult> GetRedirects(string businessId)
{
return await _handler.Get(() => _repository.GetRedirects());
}
[HttpPost]
[Route("update-redirects")]
public async Task<IActionResult> UpdateRedirects(ContentfulRedirect body)
{
_logger.LogWarning($"RedirectsController:: UpdateRedirects body received: {JsonConvert.SerializeObject(body)}");
return Ok();
}
}
}
|
mit
|
C#
|
c5361ec54e309acfee206cca274cc6f5e4a35a37
|
Improve crop coordinate calculations
|
dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS
|
src/Umbraco.Web.Common/ImageProcessors/CropWebProcessor.cs
|
src/Umbraco.Web.Common/ImageProcessors/CropWebProcessor.cs
|
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Extensions.Logging;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Web;
using SixLabors.ImageSharp.Web.Commands;
using SixLabors.ImageSharp.Web.Processors;
namespace Umbraco.Cms.Web.Common.ImageProcessors
{
/// <summary>
/// Allows the cropping of images.
/// </summary>
public class CropWebProcessor : IImageWebProcessor
{
/// <summary>
/// The command constant for the crop coordinates.
/// </summary>
public const string Coordinates = "cc";
/// <inheritdoc/>
public IEnumerable<string> Commands { get; } = new[]
{
Coordinates
};
/// <inheritdoc/>
public FormattedImage Process(FormattedImage image, ILogger logger, IDictionary<string, string> commands, CommandParser parser, CultureInfo culture)
{
RectangleF? coordinates = GetCoordinates(commands, parser, culture);
if (coordinates != null)
{
// Convert the coordinates to a pixel based rectangle
int sourceWidth = image.Image.Width;
int sourceHeight = image.Image.Height;
int x = (int)MathF.Round(coordinates.Value.X * sourceWidth);
int y = (int)MathF.Round(coordinates.Value.Y * sourceHeight);
int width = (int)MathF.Round(coordinates.Value.Width * sourceWidth);
int height = (int)MathF.Round(coordinates.Value.Height * sourceHeight);
var cropRectangle = new Rectangle(x, y, width, height);
image.Image.Mutate(x => x.Crop(cropRectangle));
}
return image;
}
private static RectangleF? GetCoordinates(IDictionary<string, string> commands, CommandParser parser, CultureInfo culture)
{
float[] coordinates = parser.ParseValue<float[]>(commands.GetValueOrDefault(Coordinates), culture);
if (coordinates.Length != 4)
{
return null;
}
// The right and bottom values are actually the distance from those sides, so convert them into real coordinates
return RectangleF.FromLTRB(coordinates[0], coordinates[1], 1 - coordinates[2], 1 - coordinates[3]);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Extensions.Logging;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Web;
using SixLabors.ImageSharp.Web.Commands;
using SixLabors.ImageSharp.Web.Processors;
namespace Umbraco.Cms.Web.Common.ImageProcessors
{
/// <summary>
/// Allows the cropping of images.
/// </summary>
public class CropWebProcessor : IImageWebProcessor
{
/// <summary>
/// The command constant for the crop coordinates.
/// </summary>
public const string Coordinates = "cc";
/// <inheritdoc/>
public IEnumerable<string> Commands { get; } = new[]
{
Coordinates
};
/// <inheritdoc/>
public FormattedImage Process(FormattedImage image, ILogger logger, IDictionary<string, string> commands, CommandParser parser, CultureInfo culture)
{
RectangleF? coordinates = GetCoordinates(commands, parser, culture);
if (coordinates != null)
{
// Convert the percentage based model of left, top, right, bottom to x, y, width, height
int sourceWidth = image.Image.Width;
int sourceHeight = image.Image.Height;
int x = (int)MathF.Round(coordinates.Value.Left * sourceWidth);
int y = (int)MathF.Round(coordinates.Value.Top * sourceHeight);
int width = sourceWidth - (int)MathF.Round(coordinates.Value.Right * sourceWidth);
int height = sourceHeight - (int)MathF.Round(coordinates.Value.Bottom * sourceHeight);
var cropRectangle = new Rectangle(x, y, width, height);
image.Image.Mutate(x => x.Crop(cropRectangle));
}
return image;
}
private static RectangleF? GetCoordinates(IDictionary<string, string> commands, CommandParser parser, CultureInfo culture)
{
float[] coordinates = parser.ParseValue<float[]>(commands.GetValueOrDefault(Coordinates), culture);
if (coordinates.Length != 4)
{
return null;
}
return new RectangleF(coordinates[0], coordinates[1], coordinates[2], coordinates[3]);
}
}
}
|
mit
|
C#
|
2d2e318d5df5f22714cb940a8539b8b860e8556a
|
Change Remoting Summary to show top 50
|
Ampla/Ampla-Log-Reader
|
src/Ampla.LogReader/Reports/Pages/RemotingSummaryPage.cs
|
src/Ampla.LogReader/Reports/Pages/RemotingSummaryPage.cs
|
using System;
using System.Collections.Generic;
using Ampla.LogReader.Excel;
using Ampla.LogReader.Excel.Writer;
using Ampla.LogReader.Remoting;
using Ampla.LogReader.Statistics;
namespace Ampla.LogReader.Reports.Pages
{
public class RemotingSummaryPage : ReportPage<RemotingEntry>
{
private readonly RemotingSummaryStatistic summaryStatistic;
private readonly TopNStatistics<RemotingEntry> top50IdentityStats;
private readonly TopNStatistics<RemotingEntry> top50MethodStats;
public RemotingSummaryPage(IExcelSpreadsheet excelSpreadsheet, List<RemotingEntry> entries)
: base(excelSpreadsheet, entries, "Summary")
{
summaryStatistic = new RemotingSummaryStatistic("Summary");
top50IdentityStats = new TopNStatistics<RemotingEntry>
("Top 50 Identities", 50,
entry => entry.Identity,
entry => true);
top50MethodStats = new TopNStatistics<RemotingEntry>
("Top 50 Methods", 50,
entry => entry.Method,
entry => true);
}
protected override void RenderPage(IWorksheetWriter writer)
{
UpdateStatistics(new IStatistic<RemotingEntry>[] {summaryStatistic, top50IdentityStats, top50MethodStats});
writer.WriteRow("Summary of Remoting calls");
if (summaryStatistic.Count > 0)
{
writer.WriteRow("Count: ", summaryStatistic.Count);
writer.WriteRow("From: ", summaryStatistic.FirstEntry.ToLocalTime());
writer.WriteRow("To: ", summaryStatistic.LastEntry.ToLocalTime());
writer.WriteRow("Duration (hrs): ", summaryStatistic.LastEntry.Subtract(summaryStatistic.FirstEntry).TotalHours);
var current = writer.GetCurrentCell();
writer.WriteRow();
WriteStatistics(top50MethodStats, writer);
writer.MoveTo(current.Row, current.Column + 3);
writer.WriteRow();
WriteStatistics(top50IdentityStats, writer);
}
else
{
writer.WriteRow("Count:", "no entries");
}
}
}
}
|
using System;
using System.Collections.Generic;
using Ampla.LogReader.Excel;
using Ampla.LogReader.Excel.Writer;
using Ampla.LogReader.Remoting;
using Ampla.LogReader.Statistics;
namespace Ampla.LogReader.Reports.Pages
{
public class RemotingSummaryPage : ReportPage<RemotingEntry>
{
private readonly RemotingSummaryStatistic summaryStatistic;
private readonly TopNStatistics<RemotingEntry> top10IdentityStats;
private readonly TopNStatistics<RemotingEntry> top10MethodStats;
public RemotingSummaryPage(IExcelSpreadsheet excelSpreadsheet, List<RemotingEntry> entries)
: base(excelSpreadsheet, entries, "Summary")
{
summaryStatistic = new RemotingSummaryStatistic("Summary");
top10IdentityStats = new TopNStatistics<RemotingEntry>
("Top 20 Identities", 20,
entry => entry.Identity,
entry => true);
top10MethodStats = new TopNStatistics<RemotingEntry>
("Top 20 Methods", 20,
entry => entry.Method,
entry => true);
}
protected override void RenderPage(IWorksheetWriter writer)
{
UpdateStatistics(new IStatistic<RemotingEntry>[] {summaryStatistic, top10IdentityStats, top10MethodStats});
writer.WriteRow("Summary of Remoting calls");
if (summaryStatistic.Count > 0)
{
writer.WriteRow("Count: ", summaryStatistic.Count);
writer.WriteRow("From: ", summaryStatistic.FirstEntry.ToLocalTime());
writer.WriteRow("To: ", summaryStatistic.LastEntry.ToLocalTime());
writer.WriteRow("Duration (hrs): ", summaryStatistic.LastEntry.Subtract(summaryStatistic.FirstEntry).TotalHours);
var current = writer.GetCurrentCell();
writer.WriteRow();
WriteStatistics(top10MethodStats, writer);
writer.MoveTo(current.Row, current.Column + 3);
writer.WriteRow();
WriteStatistics(top10IdentityStats, writer);
}
else
{
writer.WriteRow("Count:", "no entries");
}
}
}
}
|
mit
|
C#
|
2f4c37915e51cffa549ce45a0ddeddccd05ef4ee
|
Revert "clean code a bit"
|
hazzik/Humanizer,MehdiK/Humanizer
|
src/Humanizer/Localisation/NumberToWords/FrenchNumberToWordsConverter.cs
|
src/Humanizer/Localisation/NumberToWords/FrenchNumberToWordsConverter.cs
|
using System.Collections.Generic;
namespace Humanizer.Localisation.NumberToWords
{
internal class FrenchNumberToWordsConverter : FrenchNumberToWordsConverterBase
{
protected override void CollectPartsUnderAHundred(ICollection<string> parts, ref int number, GrammaticalGender gender, bool pluralize)
{
if (number == 71)
parts.Add("soixante et onze");
else if (number == 80)
parts.Add(pluralize ? "quatre-vingts" : "quatre-vingt");
else if (number >= 70)
{
var @base = number < 80 ? 60 : 80;
int units = number - @base;
var tens = @base/10;
parts.Add(string.Format("{0}-{1}", GetTens(tens), GetUnits(units, gender)));
}
else
base.CollectPartsUnderAHundred(parts, ref number, gender, pluralize);
}
protected override string GetTens(int tens)
{
if (tens == 8)
return "quatre-vingt";
return base.GetTens(tens);
}
}
}
|
using System.Collections.Generic;
namespace Humanizer.Localisation.NumberToWords
{
internal class FrenchNumberToWordsConverter : FrenchNumberToWordsConverterBase
{
protected override void CollectPartsUnderAHundred(ICollection<string> parts, ref int number, GrammaticalGender gender, bool pluralize)
{
if (number == 71)
parts.Add("soixante et onze");
else if (number == 80)
parts.Add("quatre-vingt" + (pluralize ? "s" : string.Empty));
else if (number >= 70)
{
var @base = number < 80 ? 60 : 80;
int units = number - @base;
var tens = @base / 10;
parts.Add($"{GetTens(tens)}-{GetUnits(units, gender)}");
}
else
base.CollectPartsUnderAHundred(parts, ref number, gender, pluralize);
}
protected override string GetTens(int tens) => tens == 8 ? "quatre-vingt" : base.GetTens(tens);
}
}
|
mit
|
C#
|
13dd893446a674d4a01d6760f82bae3dd7e278ea
|
fix string localizer (#11838)
|
stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2
|
src/OrchardCore.Modules/OrchardCore.Templates/AdminTemplatesAdminMenu.cs
|
src/OrchardCore.Modules/OrchardCore.Templates/AdminTemplatesAdminMenu.cs
|
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Localization;
using OrchardCore.Navigation;
namespace OrchardCore.Templates
{
public class AdminTemplatesAdminMenu : INavigationProvider
{
private readonly IStringLocalizer S;
public AdminTemplatesAdminMenu(IStringLocalizer<AdminTemplatesAdminMenu> localizer)
{
S = localizer;
}
public Task BuildNavigationAsync(string name, NavigationBuilder builder)
{
if (!String.Equals(name, "admin", StringComparison.OrdinalIgnoreCase))
{
return Task.CompletedTask;
}
builder
.Add(S["Design"], design => design
.Add(S["Admin Templates"], S["Admin Templates"].PrefixPosition(), import => import
.Action("Admin", "Template", new { area = "OrchardCore.Templates" })
.Permission(AdminTemplatesPermissions.ManageAdminTemplates)
.LocalNav()
)
);
return Task.CompletedTask;
}
}
}
|
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Localization;
using OrchardCore.Navigation;
namespace OrchardCore.Templates
{
public class AdminTemplatesAdminMenu : INavigationProvider
{
private readonly IStringLocalizer S;
public AdminTemplatesAdminMenu(IStringLocalizer<AdminMenu> localizer)
{
S = localizer;
}
public Task BuildNavigationAsync(string name, NavigationBuilder builder)
{
if (!String.Equals(name, "admin", StringComparison.OrdinalIgnoreCase))
{
return Task.CompletedTask;
}
builder
.Add(S["Design"], design => design
.Add(S["Admin Templates"], S["Admin Templates"].PrefixPosition(), import => import
.Action("Admin", "Template", new { area = "OrchardCore.Templates" })
.Permission(AdminTemplatesPermissions.ManageAdminTemplates)
.LocalNav()
)
);
return Task.CompletedTask;
}
}
}
|
bsd-3-clause
|
C#
|
acf38d9f393b5e0037235b72e78f6940029f2bb9
|
Remove BOM from UTF8 encoder
|
RootAccessOrg/kynnaugh
|
kynnaugh/StringUtils.cs
|
kynnaugh/StringUtils.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace kynnaugh
{
class StringUtils
{
// By Hans Passant
// http://stackoverflow.com/a/10773988
public static IntPtr NativeUtf8FromString(string managedString)
{
int len = (new UTF8Encoding(false)).GetByteCount(managedString);
byte[] buffer = new byte[len + 1];
(new UTF8Encoding(false)).GetBytes(managedString, 0, managedString.Length, buffer, 0);
IntPtr nativeUtf8 = Marshal.AllocHGlobal(buffer.Length);
Marshal.Copy(buffer, 0, nativeUtf8, buffer.Length);
return nativeUtf8;
}
public static string StringFromNativeUtf8(IntPtr nativeUtf8)
{
int len = 0;
while (Marshal.ReadByte(nativeUtf8, len) != 0) ++len;
byte[] buffer = new byte[len];
Marshal.Copy(nativeUtf8, buffer, 0, buffer.Length);
return (new UTF8Encoding(false)).GetString(buffer);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace kynnaugh
{
class StringUtils
{
// By Hans Passant
// http://stackoverflow.com/a/10773988
public static IntPtr NativeUtf8FromString(string managedString)
{
int len = Encoding.UTF8.GetByteCount(managedString);
byte[] buffer = new byte[len + 1];
Encoding.UTF8.GetBytes(managedString, 0, managedString.Length, buffer, 0);
IntPtr nativeUtf8 = Marshal.AllocHGlobal(buffer.Length);
Marshal.Copy(buffer, 0, nativeUtf8, buffer.Length);
return nativeUtf8;
}
public static string StringFromNativeUtf8(IntPtr nativeUtf8)
{
int len = 0;
while (Marshal.ReadByte(nativeUtf8, len) != 0) ++len;
byte[] buffer = new byte[len];
Marshal.Copy(nativeUtf8, buffer, 0, buffer.Length);
return Encoding.UTF8.GetString(buffer);
}
}
}
|
apache-2.0
|
C#
|
fa837bcdb9273347564b2291c4aeea0b23f9f788
|
Update API version to 1.4.0
|
PyramidTechnologies/netPyramid-RS-232
|
Apex7000_BillValidator/Properties/AssemblyInfo.cs
|
Apex7000_BillValidator/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("NET Pyramid RS-232")]
[assembly: AssemblyDescription("RS-232 API by Pyramid Technologies")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Pyramid Technologies Inc")]
[assembly: AssemblyProduct("NET Pyramid RS-232")]
[assembly: AssemblyCopyright("© Pyramid Technologies Inc. 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("380ac9e2-635d-4547-a090-4e0e25663de9")]
// 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.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly : InternalsVisibleTo("PyramidNETRS232_Test")]
|
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("NET Pyramid RS-232")]
[assembly: AssemblyDescription("RS-232 API by Pyramid Technologies")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Pyramid Technologies Inc")]
[assembly: AssemblyProduct("NET Pyramid RS-232")]
[assembly: AssemblyCopyright("© Pyramid Technologies Inc. 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("380ac9e2-635d-4547-a090-4e0e25663de9")]
// 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.3.8.0")]
[assembly: AssemblyFileVersion("1.3.8.0")]
[assembly : InternalsVisibleTo("PyramidNETRS232_Test")]
|
mit
|
C#
|
c1d31926a11fbe432b7f52b5c26039b894402328
|
Add .AllRows to IUpdateWhereSyntax
|
modulexcite/fluentmigrator,istaheev/fluentmigrator,FabioNascimento/fluentmigrator,lcharlebois/fluentmigrator,lahma/fluentmigrator,swalters/fluentmigrator,jogibear9988/fluentmigrator,KaraokeStu/fluentmigrator,DefiSolutions/fluentmigrator,IRlyDontKnow/fluentmigrator,amroel/fluentmigrator,stsrki/fluentmigrator,KaraokeStu/fluentmigrator,schambers/fluentmigrator,wolfascu/fluentmigrator,stsrki/fluentmigrator,mstancombe/fluentmig,istaheev/fluentmigrator,akema-fr/fluentmigrator,istaheev/fluentmigrator,jogibear9988/fluentmigrator,alphamc/fluentmigrator,daniellee/fluentmigrator,swalters/fluentmigrator,bluefalcon/fluentmigrator,fluentmigrator/fluentmigrator,MetSystem/fluentmigrator,tommarien/fluentmigrator,MetSystem/fluentmigrator,vgrigoriu/fluentmigrator,DefiSolutions/fluentmigrator,amroel/fluentmigrator,fluentmigrator/fluentmigrator,daniellee/fluentmigrator,tommarien/fluentmigrator,drmohundro/fluentmigrator,mstancombe/fluentmigrator,daniellee/fluentmigrator,akema-fr/fluentmigrator,modulexcite/fluentmigrator,lcharlebois/fluentmigrator,FabioNascimento/fluentmigrator,barser/fluentmigrator,igitur/fluentmigrator,eloekset/fluentmigrator,mstancombe/fluentmig,IRlyDontKnow/fluentmigrator,drmohundro/fluentmigrator,dealproc/fluentmigrator,vgrigoriu/fluentmigrator,barser/fluentmigrator,itn3000/fluentmigrator,itn3000/fluentmigrator,tohagan/fluentmigrator,tohagan/fluentmigrator,dealproc/fluentmigrator,igitur/fluentmigrator,DefiSolutions/fluentmigrator,schambers/fluentmigrator,spaccabit/fluentmigrator,mstancombe/fluentmig,bluefalcon/fluentmigrator,lahma/fluentmigrator,mstancombe/fluentmigrator,eloekset/fluentmigrator,lahma/fluentmigrator,alphamc/fluentmigrator,wolfascu/fluentmigrator,tohagan/fluentmigrator,spaccabit/fluentmigrator
|
src/FluentMigrator/Builders/Update/IUpdateWhereSyntax.cs
|
src/FluentMigrator/Builders/Update/IUpdateWhereSyntax.cs
|
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace FluentMigrator.Builders.Update
{
public interface IUpdateWhereSyntax
{
void Where(object dataAsAnonymousType);
void AllRows();
}
}
|
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace FluentMigrator.Builders.Update
{
public interface IUpdateWhereSyntax
{
void Where(object dataAsAnonymousType);
}
}
|
apache-2.0
|
C#
|
75dab51f91b9d2bd267124e4e874282eb927fb11
|
add namespace
|
unity3d-jp/AngryChicken
|
Assets/Extra/TargetCount.cs
|
Assets/Extra/TargetCount.cs
|
using UnityEngine;
using System.Collections;
namespace AngryChicken2D
{
public class TargetCount : MonoBehaviour
{
public int count;
GameObject[] objects;
public float interval = 3;
float nextTime;
void Update()
{
if (Time.time > nextTime)
{
objects = GameObject.FindGameObjectsWithTag("Target");
count = objects.Length;
nextTime += interval;
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class TargetCount : MonoBehaviour
{
public int count;
GameObject[] objects;
public float interval = 3;
float nextTime;
void Update()
{
if (Time.time > nextTime)
{
objects = GameObject.FindGameObjectsWithTag("Target");
count = objects.Length;
nextTime += interval;
}
}
}
|
apache-2.0
|
C#
|
3506a2081507fb66467680f95234a8373209c844
|
Add GetStream to initial UploadedFile
|
mcintyre321/FormFactory,mcintyre321/FormFactory,mcintyre321/FormFactory
|
FormFactory/Mvc/UploadedFiles/AppDataFileStore.cs
|
FormFactory/Mvc/UploadedFiles/AppDataFileStore.cs
|
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using FormFactory.ValueTypes;
namespace FormFactory.Mvc.UploadedFiles
{
public class AppDataFileStore : IFileStore
{
public UploadedFile Store(HttpPostedFileBase httpPostedFileBase, ControllerContext controllerContext, ModelBindingContext modelBindingContext)
{
var dir = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/UploadedFiles");
Directory.CreateDirectory(dir);
var directoryName = Guid.NewGuid().ToString();
var relativePath = Path.Combine(directoryName, Path.GetFileName(httpPostedFileBase.FileName));
var fullPath = Path.Combine(dir, relativePath);
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
httpPostedFileBase.SaveAs(fullPath);
var uploadedFile = new UploadedFile()
{
ContentLength = httpPostedFileBase.ContentLength, ContentType = httpPostedFileBase.ContentType, FileName = Path.GetFileName(relativePath), Id = directoryName
};
var serializer = new JavaScriptSerializer();
var metadata = serializer.Serialize(uploadedFile);
File.WriteAllText(Path.Combine(StoreFolderPath, uploadedFile.Id, "metadata.json"), metadata);
uploadedFile.SetGetStream(() => File.OpenRead(Path.Combine(StoreFolderPath, uploadedFile.Id, uploadedFile.FileName)));
return uploadedFile;
}
public UploadedFile GetById(string id)
{
var serializer = new JavaScriptSerializer();
var filename = Path.Combine(StoreFolderPath, id, "metadata.json");
var uploadedFile = serializer.Deserialize<UploadedFile>(File.ReadAllText(filename));
uploadedFile.SetGetStream(() => File.OpenRead(Path.Combine(StoreFolderPath, id, uploadedFile.FileName)));
return uploadedFile;
}
private static string StoreFolderPath
{
get { return System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/UploadedFiles"); }
}
}
}
|
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using FormFactory.ValueTypes;
namespace FormFactory.Mvc.UploadedFiles
{
public class AppDataFileStore : IFileStore
{
public UploadedFile Store(HttpPostedFileBase httpPostedFileBase, ControllerContext controllerContext, ModelBindingContext modelBindingContext)
{
var dir = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/UploadedFiles");
Directory.CreateDirectory(dir);
var directoryName = Guid.NewGuid().ToString();
var relativePath = Path.Combine(directoryName, Path.GetFileName(httpPostedFileBase.FileName));
var fullPath = Path.Combine(dir, relativePath);
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
httpPostedFileBase.SaveAs(fullPath);
var uploadedFile = new UploadedFile()
{
ContentLength = httpPostedFileBase.ContentLength, ContentType = httpPostedFileBase.ContentType, FileName = Path.GetFileName(relativePath), Id = directoryName
};
var serializer = new JavaScriptSerializer();
var metadata = serializer.Serialize(uploadedFile);
File.WriteAllText(Path.Combine(StoreFolderPath, uploadedFile.Id, "metadata.json"), metadata);
return uploadedFile;
}
public UploadedFile GetById(string id)
{
var serializer = new JavaScriptSerializer();
var filename = Path.Combine(StoreFolderPath, id, "metadata.json");
var uploadedFile = serializer.Deserialize<UploadedFile>(File.ReadAllText(filename));
uploadedFile.SetGetStream(() => File.OpenRead(Path.Combine(StoreFolderPath, id, uploadedFile.FileName)));
return uploadedFile;
}
private static string StoreFolderPath
{
get { return System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/UploadedFiles"); }
}
}
}
|
mit
|
C#
|
970828b23a3128b11ae3206c19103f00001a4eed
|
Change Namespace
|
muhammedikinci/FuzzyCore
|
FuzzyCore/ConcreteCommands/GetPrograms_Command.cs
|
FuzzyCore/ConcreteCommands/GetPrograms_Command.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FuzzyCore.Server.Data;
namespace FuzzyCore.Server
{
public class GetPrograms_Command : Command
{
public GetPrograms_Command(JsonCommand comm) : base(comm)
{
}
public override void Execute()
{
Console.WriteLine(Comm.CommandType);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using fuzzyControl.Server.Data;
namespace fuzzyControl.Server
{
public class GetPrograms_Command : Command
{
public GetPrograms_Command(JsonCommand comm) : base(comm)
{
}
public override void Execute()
{
Console.WriteLine(Comm.CommandType);
}
}
}
|
mit
|
C#
|
7e1a82f833193e4b17afaf9d3df38ad0d203a5ee
|
Move tool writing to the end so we can accumulate the rules.
|
eriawan/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,genlu/roslyn,diryboy/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,ErikSchierboom/roslyn,aelij/roslyn,heejaechang/roslyn,genlu/roslyn,gafter/roslyn,agocke/roslyn,CyrusNajmabadi/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,jmarolf/roslyn,davkean/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,abock/roslyn,jasonmalinowski/roslyn,physhi/roslyn,eriawan/roslyn,tmat/roslyn,KevinRansom/roslyn,reaction1989/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,tannergooding/roslyn,dotnet/roslyn,stephentoub/roslyn,gafter/roslyn,sharwell/roslyn,genlu/roslyn,agocke/roslyn,physhi/roslyn,KevinRansom/roslyn,heejaechang/roslyn,dotnet/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,weltkante/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,dotnet/roslyn,stephentoub/roslyn,AmadeusW/roslyn,reaction1989/roslyn,panopticoncentral/roslyn,mavasani/roslyn,jmarolf/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,gafter/roslyn,davkean/roslyn,aelij/roslyn,wvdd007/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,agocke/roslyn,brettfo/roslyn,wvdd007/roslyn,mavasani/roslyn,mavasani/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,tannergooding/roslyn,abock/roslyn,jmarolf/roslyn,weltkante/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,weltkante/roslyn,davkean/roslyn,jasonmalinowski/roslyn,aelij/roslyn,panopticoncentral/roslyn,tmat/roslyn,KirillOsenkov/roslyn,physhi/roslyn,diryboy/roslyn,abock/roslyn,KirillOsenkov/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn
|
src/Compilers/Core/Portable/CommandLine/SarifV2ErrorLogger.cs
|
src/Compilers/Core/Portable/CommandLine/SarifV2ErrorLogger.cs
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Globalization;
using System.IO;
namespace Microsoft.CodeAnalysis
{
internal sealed class SarifV2ErrorLogger : StreamErrorLogger, IDisposable
{
private readonly string _toolName;
private readonly string _toolFileVersion;
private readonly Version _toolAssemblyVersion;
public SarifV2ErrorLogger(Stream stream, string toolName, string toolFileVersion, Version toolAssemblyVersion, CultureInfo culture)
: base(stream)
{
_toolName = toolName;
_toolFileVersion = toolFileVersion;
_toolAssemblyVersion = toolAssemblyVersion;
_writer.WriteObjectStart(); // root
_writer.Write("$schema", "http://json.schemastore.org/sarif-2.1.0");
_writer.Write("version", "2.1.0");
_writer.WriteArrayStart("runs");
_writer.WriteObjectStart(); // run
_writer.WriteArrayStart("results");
}
public override void LogDiagnostic(Diagnostic diagnostic)
{
_writer.WriteObjectStart(); // result
_writer.Write("ruleId", diagnostic.Id);
_writer.WriteObjectEnd(); // result
}
public override void Dispose()
{
_writer.WriteArrayEnd(); //results
WriteTool();
_writer.WriteObjectEnd(); // run
_writer.WriteArrayEnd(); // runs
_writer.WriteObjectEnd(); // root
base.Dispose();
}
private void WriteTool()
{
_writer.WriteObjectStart("tool");
_writer.WriteObjectStart("driver");
_writer.Write("name", _toolName);
_writer.Write("fileVersion", _toolFileVersion);
_writer.Write("version", _toolAssemblyVersion.ToString());
_writer.Write("semanticVersion", _toolAssemblyVersion.ToString(fieldCount: 3));
WriteRules();
_writer.WriteObjectEnd(); // driver
_writer.WriteObjectEnd(); // tool
}
private void WriteRules()
{
_writer.WriteArrayStart("rules");
_writer.WriteArrayEnd(); // rules
}
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Globalization;
using System.IO;
namespace Microsoft.CodeAnalysis
{
internal sealed class SarifV2ErrorLogger : StreamErrorLogger, IDisposable
{
public SarifV2ErrorLogger(Stream stream, string toolName, string toolFileVersion, Version toolAssemblyVersion, CultureInfo culture)
: base(stream)
{
_writer.WriteObjectStart(); // root
_writer.Write("$schema", "http://json.schemastore.org/sarif-2.1.0");
_writer.Write("version", "2.1.0");
_writer.WriteArrayStart("runs");
_writer.WriteObjectStart(); // run
_writer.WriteObjectStart("tool");
_writer.WriteObjectStart("driver");
_writer.Write("name", toolName);
_writer.Write("fileVersion", toolFileVersion);
_writer.Write("version", toolAssemblyVersion.ToString());
_writer.Write("semanticVersion", toolAssemblyVersion.ToString(fieldCount: 3));
WriteRules();
_writer.WriteObjectEnd(); // driver
_writer.WriteObjectEnd(); // tool
_writer.WriteArrayStart("results");
}
public override void LogDiagnostic(Diagnostic diagnostic)
{
_writer.WriteObjectStart(); // result
_writer.Write("ruleId", diagnostic.Id);
_writer.WriteObjectEnd(); // result
}
public override void Dispose()
{
_writer.WriteArrayEnd(); //results
_writer.WriteObjectEnd(); // run
_writer.WriteArrayEnd(); // runs
_writer.WriteObjectEnd(); // root
base.Dispose();
}
private void WriteRules()
{
_writer.WriteArrayStart("rules");
_writer.WriteArrayEnd(); // rules
}
}
}
|
mit
|
C#
|
dae5d519addef57d33da0d8fdadeb4a60b790866
|
Fix boolean operator.
|
harrison314/MassiveDynamicProxyGenerator,harrison314/MassiveDynamicProxyGenerator,harrison314/MassiveDynamicProxyGenerator
|
src/MassiveDynamicProxyGenerator.SimpleInjector/TypeHelper.cs
|
src/MassiveDynamicProxyGenerator.SimpleInjector/TypeHelper.cs
|
using System;
using System.Reflection;
namespace MassiveDynamicProxyGenerator.SimpleInjector
{
internal class TypeHelper
{
public static bool IsOpenGeneric(Type type)
{
return type.GetTypeInfo().IsGenericTypeDefinition;
}
public static bool IsGenericConstructedOf(Type genericDefinitionType, Type constructedType)
{
if (!genericDefinitionType.GetTypeInfo().IsGenericType || !constructedType.GetTypeInfo().IsGenericType)
{
return false;
}
return constructedType.GetGenericTypeDefinition() == genericDefinitionType;
}
public static bool IsPublicInterface(Type type)
{
return type.GetTypeInfo().IsPublic && type.GetTypeInfo().IsInterface;
}
}
}
|
using System;
using System.Reflection;
namespace MassiveDynamicProxyGenerator.SimpleInjector
{
internal class TypeHelper
{
public static bool IsOpenGeneric(Type type)
{
return type.GetTypeInfo().IsGenericTypeDefinition;
}
public static bool IsGenericConstructedOf(Type genericDefinitionType, Type constructedType)
{
if (!genericDefinitionType.GetTypeInfo().IsGenericType || !constructedType.GetTypeInfo().IsGenericType)
{
return false;
}
return constructedType.GetGenericTypeDefinition() == genericDefinitionType;
}
public static bool IsPublicInterface(Type type)
{
return type.GetTypeInfo().IsPublic || type.GetTypeInfo().IsInterface;
}
}
}
|
mit
|
C#
|
eae83932009770f726e2ec7b8af6ccbe5ee0dffa
|
add outcommented code to use cube as floorPlane
|
accu-rate/SumoVizUnity,accu-rate/SumoVizUnity
|
Assets/Scripts/sim/Floor.cs
|
Assets/Scripts/sim/Floor.cs
|
using UnityEngine;
using System.Collections.Generic;
using System;
public class Floor {
private List<Wall> walls = new List<Wall>();
private List<WunderZone> wunderZones = new List<WunderZone>();
private string floorId;
private int level;
internal float elevation;
private float height;
internal List<float> boundingPoints;
internal Floor(string floorId) {
this.floorId = floorId;
}
internal void addWunderZone(WunderZone wz) {
wunderZones.Add(wz);
}
internal void addWall(Wall wall) {
walls.Add(wall);
}
internal void printGeometryElements() {
Debug.Log("Floor " + floorId);
foreach(var wz in wunderZones) {
Debug.Log(" WunderZone: " + wz.getId());
}
foreach (var wall in walls) {
Debug.Log(" Wall: " + wall.getId());
}
}
internal void setMetaData(int level, float height, float elevation, List<float> boundingPoints) {
this.level = level;
this.height = height;
this.elevation = elevation;
this.boundingPoints = boundingPoints;
}
internal void createObjects() {
List<Vector2> plane = new List<Vector2>();
float minX = boundingPoints[0],
minY = boundingPoints[1],
maxX = boundingPoints[2],
maxY = boundingPoints[3];
plane.Add(new Vector2(minX, minY));
plane.Add(new Vector2(minX, maxY));
plane.Add(new Vector2(maxX, maxY));
plane.Add(new Vector2(maxX, minY));
AreaGeometry.createOriginTarget(floorId + "_ground", plane, new Color(1.0f, 1.0f, 1.0f, 0.3f), elevation - 0.01f);
/*
float planeHeight = 0.2f;
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = "FloorPlane_" + floorId;
Material floorPlaneMaterial = Resources.Load("Materials/FloorPlaneMaterial.mat", typeof(Material)) as Material;
cube.GetComponent<Renderer>().sharedMaterial = floorPlaneMaterial;
//floorPlaneMaterial.shader = Shader.Find("Standard");
cube.transform.position = new Vector3((minX + maxX) / 2, elevation - planeHeight / 2 - 0.01f, (minY + maxY) / 2);
cube.transform.localScale = new Vector3(minX + maxX, planeHeight, minY + maxY);
GeometryLoader gl = GameObject.Find("GeometryLoader").GetComponent<GeometryLoader>();
gl.setWorldAsParent(cube);
*/
foreach (WunderZone wz in wunderZones) {
wz.createObject();
}
foreach (Wall wall in walls) {
wall.createObject();
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
using System;
public class Floor {
private List<Wall> walls = new List<Wall>();
private List<WunderZone> wunderZones = new List<WunderZone>();
private string floorId;
private int level;
internal float elevation;
private float height;
internal List<float> boundingPoints;
internal Floor(string floorId) {
this.floorId = floorId;
}
internal void addWunderZone(WunderZone wz) {
wunderZones.Add(wz);
}
internal void addWall(Wall wall) {
walls.Add(wall);
}
internal void printGeometryElements() {
Debug.Log("Floor " + floorId);
foreach(var wz in wunderZones) {
Debug.Log(" WunderZone: " + wz.getId());
}
foreach (var wall in walls) {
Debug.Log(" Wall: " + wall.getId());
}
}
internal void setMetaData(int level, float height, float elevation, List<float> boundingPoints) {
this.level = level;
this.height = height;
this.elevation = elevation;
this.boundingPoints = boundingPoints;
}
internal void createObjects() {
List<Vector2> plane = new List<Vector2>();
float minX = boundingPoints[0],
minY = boundingPoints[1],
maxX = boundingPoints[2],
maxY = boundingPoints[3];
plane.Add(new Vector2(minX, minY));
plane.Add(new Vector2(minX, maxY));
plane.Add(new Vector2(maxX, maxY));
plane.Add(new Vector2(maxX, minY));
AreaGeometry.createOriginTarget(floorId + "_ground", plane, new Color(1.0f, 1.0f, 1.0f, 0.3f), elevation - 0.01f);
foreach (WunderZone wz in wunderZones) {
wz.createObject();
}
foreach (Wall wall in walls) {
wall.createObject();
}
}
}
|
mit
|
C#
|
7fdafe3717f1dd3c49f00fa21e388fb11a41e965
|
Allow redefining already defined symbols
|
escamilla/squirrel
|
squirrel/Environment.cs
|
squirrel/Environment.cs
|
using System.Collections.Generic;
using Squirrel.Nodes;
namespace Squirrel
{
public class Environment
{
private readonly Environment _parent;
private readonly Dictionary<string, INode> _definitions = new Dictionary<string, INode>();
public Environment(Environment parent)
{
_parent = parent;
}
public Environment() : this(null)
{
}
public void Put(string key, INode value) => _definitions[key] = value;
public void PutOuter(string key, INode value) => _parent.Put(key, value);
public INode Get(string key)
{
if (_parent == null)
{
return GetShallow(key);
}
return GetShallow(key) ?? _parent.Get(key);
}
private INode GetShallow(string key) => _definitions.ContainsKey(key) ? _definitions[key] : null;
public void Extend(Environment env)
{
foreach (var definition in env._definitions)
{
Put(definition.Key, definition.Value);
}
}
}
}
|
using System.Collections.Generic;
using Squirrel.Nodes;
namespace Squirrel
{
public class Environment
{
private readonly Environment _parent;
private readonly Dictionary<string, INode> _definitions = new Dictionary<string, INode>();
public Environment(Environment parent)
{
_parent = parent;
}
public Environment() : this(null)
{
}
public void Put(string key, INode value) => _definitions.Add(key, value);
public void PutOuter(string key, INode value) => _parent.Put(key, value);
public INode Get(string key)
{
if (_parent == null)
{
return GetShallow(key);
}
return GetShallow(key) ?? _parent.Get(key);
}
private INode GetShallow(string key) => _definitions.ContainsKey(key) ? _definitions[key] : null;
public void Extend(Environment env)
{
foreach (var definition in env._definitions)
{
Put(definition.Key, definition.Value);
}
}
}
}
|
mit
|
C#
|
5d7455005e1179f8fccbf325edea78f15caaa9b7
|
Add optional date field to RemoteMedia
|
dukemiller/anime-downloader
|
anime-downloader/Models/Abstract/RemoteMedia.cs
|
anime-downloader/Models/Abstract/RemoteMedia.cs
|
using System;
using System.Linq;
using System.Text.RegularExpressions;
using anime_downloader.Classes;
namespace anime_downloader.Models.Abstract
{
/// <summary>
/// A representation of something that can be initiated
/// in some way to retrieve a file.
/// </summary>
public abstract class RemoteMedia
{
/// <summary>
/// The quantified name of the retrievable file.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The given contextually dependant remote accesser (download link, irc message, ...).
/// </summary>
public string Remote { get; set; }
/// <summary>
/// The date published of the remote accessor, if available.
/// </summary>
public DateTime? Date { get; set; }
/// <summary>
/// Returns the subgroup from the name of the file.
/// </summary>
public string Subgroup()
{
return (from Match match in Regex.Matches(Name, @"\[([A-Za-z0-9_µ\s\-]+)\]+")
select match.Groups[1].Value).FirstOrDefault(result => result.All(c => !char.IsNumber(c)));
}
/// <summary>
/// A check if the subgroup exists.
/// </summary>
public bool HasSubgroup() => Subgroup() != null;
public string StrippedName => Methods.Strip(Name);
public string StrippedWithNoEpisode => Methods.Strip(Name, true);
/// <summary>
/// A simple representation of the important attributes of a Nyaa object.
/// </summary>
/// <returns>
/// Summary of torrent providers' values
/// </returns>
public override string ToString() => $"{GetType().Name}<name={Name}, remote={Remote}>";
}
}
|
using System.Linq;
using System.Text.RegularExpressions;
using anime_downloader.Classes;
namespace anime_downloader.Models.Abstract
{
/// <summary>
/// A representation of something that can be initiated
/// in some way to retrieve a file.
/// </summary>
public abstract class RemoteMedia
{
/// <summary>
/// The quantified name of the retrievable file.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The given contextually dependant remote accesser (download link, irc message, ...).
/// </summary>
public string Remote { get; set; }
/// <summary>
/// Returns the subgroup from the name of the file.
/// </summary>
public string Subgroup()
{
return (from Match match in Regex.Matches(Name, @"\[([A-Za-z0-9_µ\s\-]+)\]+")
select match.Groups[1].Value).FirstOrDefault(result => result.All(c => !char.IsNumber(c)));
}
/// <summary>
/// A check if the subgroup exists.
/// </summary>
public bool HasSubgroup() => Subgroup() != null;
public string StrippedName => Methods.Strip(Name);
public string StrippedWithNoEpisode => Methods.Strip(Name, true);
/// <summary>
/// A simple representation of the important attributes of a Nyaa object.
/// </summary>
/// <returns>
/// Summary of torrent providers' values
/// </returns>
public override string ToString() => $"{GetType().Name}<name={Name}, remote={Remote}>";
}
}
|
apache-2.0
|
C#
|
e0a4826e1d705eb14c782b6a9fffd2b9a1ac60ce
|
Correct argument validation
|
YeastFx/Yeast
|
src/Yeast.Multitenancy/Extensions/TenantContextExtensions.cs
|
src/Yeast.Multitenancy/Extensions/TenantContextExtensions.cs
|
using Microsoft.Extensions.DependencyInjection;
using Yeast.Core.Helpers;
namespace Yeast.Multitenancy
{
public static class TenantContextExtensions
{
/// <summary>
/// Extensions method to create service scope on <paramref name="tenantContext"/>.
/// </summary>
/// <param name="tenantContext">Created <see cref="IServiceScope"/></param>
/// <returns></returns>
public static IServiceScope CreateServiceScope(this TenantContext tenantContext)
{
Ensure.Argument.NotNull(tenantContext, nameof(tenantContext));
return tenantContext.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
}
}
}
|
using Microsoft.Extensions.DependencyInjection;
using Yeast.Core.Helpers;
namespace Yeast.Multitenancy
{
public static class TenantContextExtensions
{
/// <summary>
/// Extensions method to create service scope on <paramref name="tenantContext"/>.
/// </summary>
/// <param name="tenantContext">Created <see cref="IServiceScope"/></param>
/// <returns></returns>
public static IServiceScope CreateServiceScope(this TenantContext tenantContext)
{
Ensure.NotNull(tenantContext, nameof(tenantContext));
return tenantContext.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
}
}
}
|
mit
|
C#
|
5b729321e59afe769553af4fccd9a23d170b7557
|
Remove lazy loading of configuration
|
timclipsham/tfs-hipchat
|
TfsHipChat/Configuration/ConfigurationProvider.cs
|
TfsHipChat/Configuration/ConfigurationProvider.cs
|
using System.IO;
using Newtonsoft.Json;
using TfsHipChat.Properties;
namespace TfsHipChat.Configuration
{
public class ConfigurationProvider : IConfigurationProvider
{
public ConfigurationProvider()
{
using (var reader = new JsonTextReader(new StreamReader(Settings.Default.DefaultConfigPath)))
{
Config = (new JsonSerializer()).Deserialize<TfsHipChatConfig>(reader);
}
}
public TfsHipChatConfig Config { get; private set; }
}
}
|
using System.IO;
using Newtonsoft.Json;
namespace TfsHipChat.Configuration
{
public class ConfigurationProvider : IConfigurationProvider
{
private TfsHipChatConfig _tfsHipChatConfig;
public TfsHipChatConfig Config
{
get
{
if (_tfsHipChatConfig == null)
{
using (var reader = new JsonTextReader(new StreamReader(Properties.Settings.Default.DefaultConfigPath)))
{
_tfsHipChatConfig = (new JsonSerializer()).Deserialize<TfsHipChatConfig>(reader);
}
}
return _tfsHipChatConfig;
}
}
}
}
|
mit
|
C#
|
fb85020fe6231eefb50c21081576000d5c4a9876
|
Fix failing test by setting the host object
|
rschiefer/templating,seancpeters/templating,danroth27/templating,lambdakris/templating,lambdakris/templating,mlorbetske/templating,rschiefer/templating,seancpeters/templating,danroth27/templating,rschiefer/templating,mlorbetske/templating,lambdakris/templating,danroth27/templating,seancpeters/templating,seancpeters/templating
|
test/Microsoft.TemplateEngine.Core.UnitTests/TestBase.cs
|
test/Microsoft.TemplateEngine.Core.UnitTests/TestBase.cs
|
using System;
using System.IO;
using System.Text;
using Microsoft.TemplateEngine.Core.Contracts;
using Microsoft.TemplateEngine.Utils;
using Xunit;
namespace Microsoft.TemplateEngine.Core.UnitTests
{
public abstract class TestBase
{
protected TestBase()
{
EngineEnvironmentSettings.Host = new DefaultTemplateEngineHost("TestRunner", Version.Parse("1.0.0.0"), "en-US");
}
protected static void RunAndVerify(string originalValue, string expectedValue, IProcessor processor, int bufferSize, bool? changeOverride = null)
{
byte[] valueBytes = Encoding.UTF8.GetBytes(originalValue);
MemoryStream input = new MemoryStream(valueBytes);
MemoryStream output = new MemoryStream();
bool changed = processor.Run(input, output, bufferSize);
Verify(Encoding.UTF8, output, changed, originalValue, expectedValue, changeOverride);
}
protected static void Verify(Encoding encoding, Stream output, bool changed, string source, string expected, bool? changeOverride = null)
{
output.Position = 0;
byte[] resultBytes = new byte[output.Length];
output.Read(resultBytes, 0, resultBytes.Length);
string actual = encoding.GetString(resultBytes);
Assert.Equal(expected, actual);
bool expectedChange = changeOverride ?? !string.Equals(expected, source, StringComparison.Ordinal);
string modifier = expectedChange ? "" : "not ";
if (expectedChange ^ changed)
{
Assert.False(true, $"Expected value to {modifier} be changed");
}
}
}
}
|
using System;
using System.IO;
using System.Text;
using Microsoft.TemplateEngine.Core.Contracts;
using Xunit;
namespace Microsoft.TemplateEngine.Core.UnitTests
{
public abstract class TestBase
{
protected static void RunAndVerify(string originalValue, string expectedValue, IProcessor processor, int bufferSize, bool? changeOverride = null)
{
byte[] valueBytes = Encoding.UTF8.GetBytes(originalValue);
MemoryStream input = new MemoryStream(valueBytes);
MemoryStream output = new MemoryStream();
bool changed = processor.Run(input, output, bufferSize);
Verify(Encoding.UTF8, output, changed, originalValue, expectedValue, changeOverride);
}
protected static void Verify(Encoding encoding, Stream output, bool changed, string source, string expected, bool? changeOverride = null)
{
output.Position = 0;
byte[] resultBytes = new byte[output.Length];
output.Read(resultBytes, 0, resultBytes.Length);
string actual = encoding.GetString(resultBytes);
Assert.Equal(expected, actual);
bool expectedChange = changeOverride ?? !string.Equals(expected, source, StringComparison.Ordinal);
string modifier = expectedChange ? "" : "not ";
if (expectedChange ^ changed)
{
Assert.False(true, $"Expected value to {modifier} be changed");
}
}
}
}
|
mit
|
C#
|
1671f9477fcbe54dd2e59294982aaa677f9e760f
|
Add /GET for a single website resource
|
RockstarLabs/GeoToast,RockstarLabs/GeoToast,RockstarLabs/GeoToast
|
src/GeoToast/Controllers/WebsiteController.cs
|
src/GeoToast/Controllers/WebsiteController.cs
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using GeoToast.Data;
using GeoToast.Data.Models;
using GeoToast.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace GeoToast.Controllers
{
//[Authorize]
[Route("api/website")]
public class WebsiteController : Controller
{
private readonly GeoToastDbContext _dbContext;
private readonly IMapper _mapper;
public WebsiteController(GeoToastDbContext dbContext, IMapper mapper)
{
_dbContext = dbContext;
_mapper = mapper;
}
[HttpGet]
public IEnumerable<WebsiteReadModel> Get()
{
// TODO: Only select websites for current User
return _mapper.Map<List<WebsiteReadModel>>(_dbContext.Websites);
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var website = await _dbContext.Websites.FirstOrDefaultAsync(w => w.Id == id);
if (website == null)
return NotFound();
return Ok(_mapper.Map<WebsiteReadModel>(website));
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]WebsiteCreateModel model)
{
if (ModelState.IsValid)
{
// TODO: Set User ID
var website = _mapper.Map<Website>(model);
_dbContext.Websites.Add(website);
await _dbContext.SaveChangesAsync();
return CreatedAtAction("Get", new { id = website.Id }, _mapper.Map<WebsiteReadModel>(website));
}
return BadRequest();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using GeoToast.Data;
using GeoToast.Data.Models;
using GeoToast.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace GeoToast.Controllers
{
//[Authorize]
[Route("api/[controller]")]
public class WebsiteController : Controller
{
private readonly GeoToastDbContext _dbContext;
private readonly IMapper _mapper;
public WebsiteController(GeoToastDbContext dbContext, IMapper mapper)
{
_dbContext = dbContext;
_mapper = mapper;
}
[HttpGet]
public IEnumerable<WebsiteReadModel> Get()
{
// TODO: Only select websites for current User
return _mapper.Map<List<WebsiteReadModel>>(_dbContext.Websites);
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]WebsiteCreateModel model)
{
if (ModelState.IsValid)
{
// TODO: Set User ID
var website = _mapper.Map<Website>(model);
_dbContext.Websites.Add(website);
await _dbContext.SaveChangesAsync();
return CreatedAtAction("Get", website.Id);
}
return BadRequest();
}
}
}
|
mit
|
C#
|
c45944f935fbb79799a05a193eabbc278d51e78e
|
Fix the scenarios
|
ludwigjossieaux/pickles,dirkrombauts/pickles,dirkrombauts/pickles,picklesdoc/pickles,picklesdoc/pickles,magicmonty/pickles,ludwigjossieaux/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,dirkrombauts/pickles,picklesdoc/pickles,magicmonty/pickles,dirkrombauts/pickles,magicmonty/pickles,magicmonty/pickles
|
src/Pickles/Pickles/StrikeMarkdownProvider.cs
|
src/Pickles/Pickles/StrikeMarkdownProvider.cs
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StrikeMarkdownProvider.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using Strike;
using Strike.Jint;
namespace PicklesDoc.Pickles
{
public class StrikeMarkdownProvider : IMarkdownProvider
{
private readonly Markdownify markdownify;
public StrikeMarkdownProvider()
{
this.markdownify = new Markdownify(
new Options { Xhtml = true },
new RenderMethods());
}
public string Transform(string text)
{
return this.markdownify.Transform(text);
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StrikeMarkdownProvider.cs" company="PicklesDoc">
// Copyright 2011 Jeffrey Cameron
// Copyright 2012-present PicklesDoc team and community contributors
//
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using Strike.Jint;
namespace PicklesDoc.Pickles
{
public class StrikeMarkdownProvider : IMarkdownProvider
{
private readonly Markdownify markdownify;
public StrikeMarkdownProvider()
{
this.markdownify = new Markdownify();
}
public string Transform(string text)
{
return this.markdownify.Transform(text);
}
}
}
|
apache-2.0
|
C#
|
2139554cfbc06bab62c9d66a3968ae59563ddb33
|
remove any extra double quotes from parsed string literals
|
damianh/fluent-command-line-parser,ghstahl/fluent-command-line-parser,EricSB/fluent-command-line-parser,spzSource/fluent-command-line-parser
|
FluentCommandLineParser/Internals/Parsers/StringCommandLineOptionParser.cs
|
FluentCommandLineParser/Internals/Parsers/StringCommandLineOptionParser.cs
|
#region License
// StringCommandLineOptionParser.cs
// Copyright (c) 2013, Simon Williams
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provide
// d that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
// the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using Fclp.Internals.Extensions;
namespace Fclp.Internals.Parsers
{
/// <summary>
/// Parser used to convert to <see cref="System.String"/>.
/// </summary>
public class StringCommandLineOptionParser : ICommandLineOptionParser<string>
{
/// <summary>
/// Parses the specified <see cref="System.String"/> into a <see cref="System.String"/>.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public string Parse(string value)
{
return value.TrimStart('"').TrimEnd('"');
}
/// <summary>
/// Determines whether the specified <see cref="System.String"/> can be parsed by this <see cref="ICommandLineOptionParser{T}"/>.
/// </summary>
/// <param name="value">The <see cref="System.String"/> to check.</param>
/// <returns><c>true</c> if the specified <see cref="System.String"/> can be parsed by this <see cref="ICommandLineOptionParser{T}"/>; otherwise <c>false</c>.</returns>
public bool CanParse(string value)
{
return !value.IsNullOrWhiteSpace();
}
}
}
|
#region License
// StringCommandLineOptionParser.cs
// Copyright (c) 2013, Simon Williams
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provide
// d that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
// the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using Fclp.Internals.Extensions;
namespace Fclp.Internals.Parsers
{
/// <summary>
/// Parser used to convert to <see cref="System.String"/>.
/// </summary>
public class StringCommandLineOptionParser : ICommandLineOptionParser<string>
{
/// <summary>
/// Parses the specified <see cref="System.String"/> into a <see cref="System.String"/>.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public string Parse(string value)
{
return value;
}
/// <summary>
/// Determines whether the specified <see cref="System.String"/> can be parsed by this <see cref="ICommandLineOptionParser{T}"/>.
/// </summary>
/// <param name="value">The <see cref="System.String"/> to check.</param>
/// <returns><c>true</c> if the specified <see cref="System.String"/> can be parsed by this <see cref="ICommandLineOptionParser{T}"/>; otherwise <c>false</c>.</returns>
public bool CanParse(string value)
{
return !value.IsNullOrWhiteSpace();
}
}
}
|
bsd-2-clause
|
C#
|
0c738b3d6ce4c9de8a2959431ed1e76e6a0fa3a2
|
Fix test with better assert.
|
JohanLarsson/Gu.Localization
|
Gu.Localization.Analyzers.Tests/GULOC08DuplicateNeutralTests/Diagnostic.cs
|
Gu.Localization.Analyzers.Tests/GULOC08DuplicateNeutralTests/Diagnostic.cs
|
namespace Gu.Localization.Analyzers.Tests.GULOC08DuplicateNeutralTests
{
using System.IO;
using System.Linq;
using Gu.Localization.Analyzers.Tests.Helpers;
using Gu.Roslyn.Asserts;
using Microsoft.CodeAnalysis.Diagnostics;
using NUnit.Framework;
internal class Diagnostic
{
private static readonly DiagnosticAnalyzer Analyzer = new ResourceAnalyzer();
private FileInfo projectFile;
private DirectoryInfo directory;
[SetUp]
public void SetUp()
{
var original = ProjectFile.Find("Gu.Localization.TestStub.csproj");
this.directory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), original.Directory.Name));
if (this.directory.Exists)
{
this.directory.Delete(recursive: true);
}
original.Directory.CopyTo(this.directory);
this.projectFile = this.directory.FindFile(original.Name);
}
[Test]
public void WhenDupe()
{
this.directory.FindFile("Properties\\Resources.resx").ReplaceText(
"<value>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</value>",
$"<value>Value</value>");
var sln = CodeFactory.CreateSolution(this.projectFile, MetadataReferences.FromAttributes());
var diagnostics = Analyze.GetDiagnostics(sln, Analyzer).Single();
Assert.AreEqual(4, diagnostics.Length);
CollectionAssert.AreEquivalent(new[] { "GULOC07", "GULOC07", "GULOC08", "GULOC08" }, diagnostics.Select(x => x.Id).ToArray());
CollectionAssert.AreEquivalent(new[] { "Resources.Designer.cs", "Resources.Designer.cs", "Resources.Designer.cs", "Resources.Designer.cs" }, diagnostics.Select(x => Path.GetFileName(x.Location.SourceTree.FilePath)).ToArray());
}
}
}
|
namespace Gu.Localization.Analyzers.Tests.GULOC08DuplicateNeutralTests
{
using System.IO;
using System.Linq;
using Gu.Localization.Analyzers.Tests.Helpers;
using Gu.Roslyn.Asserts;
using Microsoft.CodeAnalysis.Diagnostics;
using NUnit.Framework;
internal class Diagnostic
{
private static readonly DiagnosticAnalyzer Analyzer = new ResourceAnalyzer();
private FileInfo projectFile;
private DirectoryInfo directory;
[SetUp]
public void SetUp()
{
var original = ProjectFile.Find("Gu.Localization.TestStub.csproj");
this.directory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), original.Directory.Name));
if (this.directory.Exists)
{
this.directory.Delete(recursive: true);
}
original.Directory.CopyTo(this.directory);
this.projectFile = this.directory.FindFile(original.Name);
}
[Test]
public void WhenDupe()
{
this.directory.FindFile("Properties\\Resources.resx").ReplaceText(
"<value>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</value>",
$"<value>Value</value>");
var sln = CodeFactory.CreateSolution(this.projectFile, MetadataReferences.FromAttributes());
var diagnostics = Analyze.GetDiagnostics(sln, Analyzer).Single();
Assert.AreEqual(4, diagnostics.Length);
Assert.AreEqual("GULOC07", diagnostics[0].Id);
StringAssert.EndsWith("Resources.Designer.cs", diagnostics[0].Location.SourceTree.FilePath);
Assert.AreEqual("GULOC08", diagnostics[1].Id);
StringAssert.EndsWith("Resources.Designer.cs", diagnostics[1].Location.SourceTree.FilePath);
Assert.AreEqual("GULOC07", diagnostics[2].Id);
StringAssert.EndsWith("Resources.Designer.cs", diagnostics[2].Location.SourceTree.FilePath);
Assert.AreEqual("GULOC08", diagnostics[3].Id);
StringAssert.EndsWith("Resources.Designer.cs", diagnostics[3].Location.SourceTree.FilePath);
}
}
}
|
mit
|
C#
|
331a19b58605c78ada1c6b232f7d040d3a2e48d7
|
Update SimpleBinaryBondSerializer.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Serialization/Bond/SimpleBinaryBondSerializer.cs
|
TIKSN.Core/Serialization/Bond/SimpleBinaryBondSerializer.cs
|
using Bond.IO.Safe;
using Bond.Protocols;
namespace TIKSN.Serialization.Bond
{
public class SimpleBinaryBondSerializer : SerializerBase<byte[]>
{
protected override byte[] SerializeInternal<T>(T obj)
{
var output = new OutputBuffer();
var writer = new SimpleBinaryWriter<OutputBuffer>(output);
global::Bond.Serialize.To(writer, obj);
return output.Data.Array;
}
}
}
|
using Bond.IO.Safe;
using Bond.Protocols;
namespace TIKSN.Serialization.Bond
{
public class SimpleBinaryBondSerializer : SerializerBase<byte[]>
{
protected override byte[] SerializeInternal(object obj)
{
var output = new OutputBuffer();
var writer = new SimpleBinaryWriter<OutputBuffer>(output);
global::Bond.Serialize.To(writer, obj);
return output.Data.Array;
}
}
}
|
mit
|
C#
|
882ca1d2471fde5a6ec385f4ca5764705e8b81ec
|
Remove redundant Invoke.
|
dotless/dotless,rytmis/dotless,r2i-sitecore/dotless,rytmis/dotless,rytmis/dotless,modulexcite/dotless,NickCraver/dotless,modulexcite/dotless,dotless/dotless,rytmis/dotless,modulexcite/dotless,r2i-sitecore/dotless,NickCraver/dotless,NickCraver/dotless,r2i-sitecore/dotless,r2i-sitecore/dotless,modulexcite/dotless,modulexcite/dotless,NickCraver/dotless,rytmis/dotless,rytmis/dotless,rytmis/dotless,r2i-sitecore/dotless,modulexcite/dotless,r2i-sitecore/dotless,r2i-sitecore/dotless,modulexcite/dotless
|
src/dotless.Core/engine/LessNodes/Selector.cs
|
src/dotless.Core/engine/LessNodes/Selector.cs
|
/* Copyright 2009 dotless project, http://www.dotlesscss.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
namespace dotless.Core.engine
{
using System;
using System.Collections.Generic;
public class Selectors : Dictionary<string, Func<Selector>>
{
public Selectors()
{
Add("", () => new Descendant());
Add(">", () => new Child());
Add("+", () => new Adjacent());
Add(":", () => new PseudoClass());
Add("::", () => new PseudoElement());
Add("~", () => new Sibling());
}
}
public class Selector : Entity
{
private static readonly Selectors Selectors = new Selectors();
public static Selector Get(string key)
{
return Selectors[key]();
}
}
public class Descendant : Selector
{
public override string ToCss()
{
return " ";
}
}
public class Child : Selector
{
public override string ToCss()
{
return " > ";
}
}
public class Adjacent : Selector
{
public override string ToCss()
{
return " + ";
}
}
public class Sibling : Selector
{
public override string ToCss()
{
return " ~ ";
}
}
public class PseudoClass : Selector
{
public override string ToCss()
{
return ":";
}
}
public class PseudoElement : Selector
{
public override string ToCss()
{
return "::";
}
}
}
|
/* Copyright 2009 dotless project, http://www.dotlesscss.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
namespace dotless.Core.engine
{
using System;
using System.Collections.Generic;
public class Selectors : Dictionary<string, Func<Selector>>
{
public Selectors()
{
Add("", () => new Descendant());
Add(">", () => new Child());
Add("+", () => new Adjacent());
Add(":", () => new PseudoClass());
Add("::", () => new PseudoElement());
Add("~", () => new Sibling());
}
}
public class Selector : Entity
{
private static readonly Selectors Selectors = new Selectors();
public static Selector Get(string key)
{
return Selectors[key].Invoke();
}
}
public class Descendant : Selector
{
public override string ToCss()
{
return " ";
}
}
public class Child : Selector
{
public override string ToCss()
{
return " > ";
}
}
public class Adjacent : Selector
{
public override string ToCss()
{
return " + ";
}
}
public class Sibling : Selector
{
public override string ToCss()
{
return " ~ ";
}
}
public class PseudoClass : Selector
{
public override string ToCss()
{
return ":";
}
}
public class PseudoElement : Selector
{
public override string ToCss()
{
return "::";
}
}
}
|
apache-2.0
|
C#
|
705f946de908f76adf5e157c142a697d87a88f21
|
add param
|
EamonNerbonne/ExpressionToCode
|
ExpressionToCodeLib/ObjectToCode.cs
|
ExpressionToCodeLib/ObjectToCode.cs
|
namespace ExpressionToCodeLib;
/// <summary>
/// If you wish to override some formatting aspects of these methods, set
/// ExpressionToCodeConfiguration.GlobalCodeGetConfiguration.
/// </summary>
public static class ObjectToCode
{
public static string ComplexObjectToPseudoCode(object? val)
=> ObjectToCodeImpl.ComplexObjectToPseudoCode(ExpressionToCodeConfiguration.GlobalCodeGenConfiguration, val, 0);
public static string ComplexObjectToPseudoCode(this ExpressionToCodeConfiguration config, object? val)
=> ObjectToCodeImpl.ComplexObjectToPseudoCode(config, val, 0);
public static string? PlainObjectToCode(object? val)
=> ObjectStringifyImpl.PlainObjectToCode(ExpressionToCodeConfiguration.GlobalCodeGenConfiguration, val, val?.GetType());
public static string? PlainObjectToCode(object? val, Type? type)
=> ObjectStringifyImpl.PlainObjectToCode(ExpressionToCodeConfiguration.GlobalCodeGenConfiguration, val, type);
public static string ToCSharpFriendlyTypeName(this Type type)
=> new CSharpFriendlyTypeName { IncludeGenericTypeArgumentNames = true, }.GetTypeName(type);
public static string ToCSharpFriendlyTypeName(this Type type, ExpressionToCodeConfiguration config)
=> type.ToCSharpFriendlyTypeName(config.UseFullyQualifiedTypeNames, true);
public static string ToCSharpFriendlyTypeName(this Type type, bool useFullyQualifiedTypeNames, bool includeGenericTypeArgumentNames)
=> new CSharpFriendlyTypeName { IncludeGenericTypeArgumentNames = includeGenericTypeArgumentNames, UseFullyQualifiedTypeNames = useFullyQualifiedTypeNames, }.GetTypeName(type);
}
|
namespace ExpressionToCodeLib;
/// <summary>
/// If you wish to override some formatting aspects of these methods, set
/// ExpressionToCodeConfiguration.GlobalCodeGetConfiguration.
/// </summary>
public static class ObjectToCode
{
public static string ComplexObjectToPseudoCode(object? val)
=> ObjectToCodeImpl.ComplexObjectToPseudoCode(ExpressionToCodeConfiguration.GlobalCodeGenConfiguration, val, 0);
public static string ComplexObjectToPseudoCode(this ExpressionToCodeConfiguration config, object? val)
=> ObjectToCodeImpl.ComplexObjectToPseudoCode(config, val, 0);
public static string? PlainObjectToCode(object? val)
=> ObjectStringifyImpl.PlainObjectToCode(ExpressionToCodeConfiguration.GlobalCodeGenConfiguration, val, val?.GetType());
public static string? PlainObjectToCode(object? val, Type? type)
=> ObjectStringifyImpl.PlainObjectToCode(ExpressionToCodeConfiguration.GlobalCodeGenConfiguration, val, type);
public static string ToCSharpFriendlyTypeName(this Type type)
=> new CSharpFriendlyTypeName { IncludeGenericTypeArgumentNames = true, }.GetTypeName(type);
public static string ToCSharpFriendlyTypeName(this Type type, ExpressionToCodeConfiguration config)
=> type.ToCSharpFriendlyTypeName(config.UseFullyQualifiedTypeNames);
public static string ToCSharpFriendlyTypeName(this Type type, bool useFullyQualifiedTypeNames)
=> new CSharpFriendlyTypeName { IncludeGenericTypeArgumentNames = true, UseFullyQualifiedTypeNames = useFullyQualifiedTypeNames, }.GetTypeName(type);
}
|
apache-2.0
|
C#
|
151c3d073475d27ab4bffd7a3e3bd6e13fcaef7f
|
Build fix
|
mikescandy/BottomNavigationBarXF,thrive-now/BottomNavigationBarXF
|
example-xaml/BottomBarXFExampleXaml/App.xaml.cs
|
example-xaml/BottomBarXFExampleXaml/App.xaml.cs
|
using Xamarin.Forms;
namespace BottomBarXFExampleXaml
{
public partial class App : Application
{
public App ()
{
InitializeComponent ();
MainPage = new BarPage();
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
}
}
|
using Xamarin.Forms;
namespace BottomBarXFExample
{
public partial class App : Application
{
public App ()
{
InitializeComponent ();
MainPage = new BarPage();
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
}
}
|
mit
|
C#
|
0e69e8aa1578be9af3b6dfa16346df2018faa944
|
Fix code smell S3881.
|
rosolko/WebDriverManager.Net
|
IntegrationTests/DriverManagerTests/CustomServiceTests.cs
|
IntegrationTests/DriverManagerTests/CustomServiceTests.cs
|
using System;
using IntegrationTests.BrowserTests;
using OpenQA.Selenium;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
using WebDriverManager.Services.Impl;
using Xunit;
namespace IntegrationTests.DriverManagerTests
{
public sealed class CustomServiceTests: IDisposable
{
private IWebDriver _webDriver;
private readonly BinaryService _customBinaryService;
private readonly VariableService _customVariableService;
private string _driverExe;
public CustomServiceTests()
{
_customBinaryService = new BinaryService();
_customVariableService = new VariableService();
}
[Fact, Trait("Category", "Browser")]
public void CustomServiceTest()
{
_driverExe = "geckodriver";
new DriverManager(_customBinaryService, _customVariableService).SetUpDriver(new FirefoxConfig());
_webDriver = new DriverCreator().Create(DriverType.Firefox);
_webDriver.Navigate().GoToUrl("https://www.wikipedia.org");
Assert.Equal("Wikipedia", _webDriver.Title);
}
public void Dispose()
{
try
{
_webDriver.Close();
_webDriver.Quit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message, ex);
}
finally
{
Helper.KillProcesses(_driverExe);
}
}
}
}
|
using System;
using IntegrationTests.BrowserTests;
using OpenQA.Selenium;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
using WebDriverManager.Services.Impl;
using Xunit;
namespace IntegrationTests.DriverManagerTests
{
public class CustomServiceTests: IDisposable
{
private IWebDriver _webDriver;
private readonly BinaryService _customBinaryService;
private readonly VariableService _customVariableService;
private string _driverExe;
public CustomServiceTests()
{
_customBinaryService = new BinaryService();
_customVariableService = new VariableService();
}
[Fact, Trait("Category", "Browser")]
protected void CustomServiceTest()
{
_driverExe = "geckodriver";
new DriverManager(_customBinaryService, _customVariableService).SetUpDriver(new FirefoxConfig());
_webDriver = new DriverCreator().Create(DriverType.Firefox);
_webDriver.Navigate().GoToUrl("https://www.wikipedia.org");
Assert.Equal("Wikipedia", _webDriver.Title);
}
public void Dispose()
{
try
{
_webDriver.Close();
_webDriver.Quit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message, ex);
}
finally
{
Helper.KillProcesses(_driverExe);
}
}
}
}
|
mit
|
C#
|
ca4a9c3146e1d1430c036cb2e1e6b0331a52ef4b
|
Remove unused variable in SmsModel.
|
jeremycook/PickupMailViewer,jeremycook/PickupMailViewer
|
PickupMailViewer/Models/SmsModel.cs
|
PickupMailViewer/Models/SmsModel.cs
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace PickupMailViewer.Models
{
public class SmsModel : MessageModel
{
private class SmsData
{
public string To { get; set; }
public string From { get; set; }
public string Text { get; set; }
}
readonly SmsData loadedData;
readonly DateTime sentOn;
public SmsModel(string path)
{
loadedData = JsonConvert.DeserializeObject<SmsData>(File.ReadAllText(path));
sentOn = File.GetCreationTime(path);
}
override public string FromAddress
{
get
{
return loadedData.From;
}
}
override public DateTime SentOn
{
get
{
return sentOn;
}
}
override public string Subject
{
get
{
return loadedData.Text;
}
}
override public string ToAddress
{
get
{
return loadedData.To;
}
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace PickupMailViewer.Models
{
public class SmsModel : MessageModel
{
private class SmsData
{
public string To { get; set; }
public string From { get; set; }
public string Text { get; set; }
}
readonly SmsData loadedData;
readonly DateTime sentOn;
public SmsModel(string path)
{
int failCount = 0;
loadedData = JsonConvert.DeserializeObject<SmsData>(File.ReadAllText(path));
sentOn = File.GetCreationTime(path);
}
override public string FromAddress
{
get
{
return loadedData.From;
}
}
override public DateTime SentOn
{
get
{
return sentOn;
}
}
override public string Subject
{
get
{
return loadedData.Text;
}
}
override public string ToAddress
{
get
{
return loadedData.To;
}
}
}
}
|
mit
|
C#
|
40a810565aa87aacf04ab5b8c4a96fddbbf1f600
|
Add comment numbering
|
yskatsumata/resharper-workshop,yskatsumata/resharper-workshop,yskatsumata/resharper-workshop
|
CSharp/04-Refactoring/Refactoring/21-Pull_up_and_push_down.cs
|
CSharp/04-Refactoring/Refactoring/21-Pull_up_and_push_down.cs
|
using System;
namespace JetBrains.ReSharper.Koans.Refactoring
{
// Pull Members Up
//
// Pulls members up the inheritance chain from the current type to the base type.
// Moves members from a derived type to a base type
//
// No keyboard shortcut. Invoke via Refactor This menu
// Ctrl+Shift+R
// Push Members Down
//
// Pushes members down the inheritance chain from the current type to inheriting types.
// Moves members from a base type to a derived type
//
// No keyboard shortcut. Invoke via Refactor This menu
// Ctrl+Shift+R
namespace PullUp
{
public class Base
{
}
public class Derived : Base
{
}
// 1. Pull members up to base type
// Invoke Refactor This → Pull Members Up on Derived
// Choose the base type to move to (Derived or Base)
// Choose the members to move
public class MostDerived : Derived
{
public string PropertyOnDerived { get; set; }
}
}
namespace PushDown
{
// 2. Push members down from Base to inheriting types
// Invoke Refactor This → Push Members Down on Base
// Choose which inheriting types to push to
// Choose which members to push down
public class Base
{
public string PropertyOnBase { get; set; }
// 3. Push members down on property that is in use
// Invoke Refactor This → Push Members Down on Base
// Choose which inheriting types to push to
// Choose UsedPropertyOnBase
// ReSharper warns that UsedPropertyOnBase cannot be moved
public string UsedPropertyOnBase { get; set; }
}
public class Derived : Base
{
}
public class Derived2 : Base
{
}
public class Consumer
{
public void Method()
{
var @base = new Base();
Console.WriteLine(@base.UsedPropertyOnBase);
}
}
}
}
|
using System;
namespace JetBrains.ReSharper.Koans.Refactoring
{
// Pull Members Up
//
// Pulls members up the inheritance chain from the current type to the base type.
// Moves members from a derived type to a base type
//
// No keyboard shortcut. Invoke via Refactor This menu
// Ctrl+Shift+R
// Push Members Down
//
// Pushes members down the inheritance chain from the current type to inheriting types.
// Moves members from a base type to a derived type
//
// No keyboard shortcut. Invoke via Refactor This menu
// Ctrl+Shift+R
namespace PullUp
{
public class Base
{
}
public class Derived : Base
{
}
// 1. Pull members up to base type
// Invoke Refactor This → Pull Members Up on Derived
// Choose the base type to move to (Derived or Base)
// Choose the members to move
public class MostDerived : Derived
{
public string PropertyOnDerived { get; set; }
}
}
namespace PushDown
{
// x. Push members down from Base to inheriting types
// Invoke Refactor This → Push Members Down on Base
// Choose which inheriting types to push to
// Choose which members to push down
public class Base
{
public string PropertyOnBase { get; set; }
// x. Push members down on property that is in use
// Invoke Refactor This → Push Members Down on Base
// Choose which inheriting types to push to
// Choose UsedPropertyOnBase
// ReSharper warns that UsedPropertyOnBase cannot be moved
public string UsedPropertyOnBase { get; set; }
}
public class Derived : Base
{
}
public class Derived2 : Base
{
}
public class Consumer
{
public void Method()
{
var @base = new Base();
Console.WriteLine(@base.UsedPropertyOnBase);
}
}
}
}
|
apache-2.0
|
C#
|
608c38f5d3d00de005a859c5f7e112c7fe2120b1
|
Add note for Not Compiled to indicate ignoring case
|
markaschell/SoftwareThresher
|
code/SoftwareThresher/SoftwareThresher/Tasks/NotCompiled.cs
|
code/SoftwareThresher/SoftwareThresher/Tasks/NotCompiled.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SoftwareThresher.Configurations;
using SoftwareThresher.Observations;
using SoftwareThresher.Settings.Search;
namespace SoftwareThresher.Tasks {
[UsageNote("Ignores case when matching names")]
public class NotCompiled : Task {
public string Directory { get; set; }
public string CompileConfigurationFileSearchPattern { get; set; }
public string TextSearchPattern { get; set; }
public override string DefaultReportHeaderText => "Not Compiled";
readonly Search search;
public NotCompiled(Search search) {
this.search = search;
}
public override List<Observation> Execute(List<Observation> observations) {
observations.ForEach(o => o.Failed = true);
var observationsLookup = observations.ToLookup(o => o.Location);
search.GetObservations(Directory, CompileConfigurationFileSearchPattern).ForEach(o => MarkObservationsPassedForFile(observationsLookup, o));
return observations;
}
void MarkObservationsPassedForFile(ILookup<string, Observation> observations, Observation observation) {
var observationsWithSameDirectory = observations.Where(o => o.Key.StartsWith(observation.Location)).SelectMany(g => g).ToLookup(o => o.Location);
var referenceLines = search.GetReferenceLine(observation, TextSearchPattern);
referenceLines.ForEach(r => MarkObservationsPassedForReference(observationsWithSameDirectory, observation.Location, r));
}
void MarkObservationsPassedForReference(ILookup<string, Observation> observations, string fileDirectory, string reference) {
var referenceObject = reference.Substring(reference.IndexOf(TextSearchPattern) + TextSearchPattern.Length).Split(' ', '\t', '"').First();
if (string.IsNullOrEmpty(referenceObject))
return;
var referenceObservation = new FileObservation(referenceObject, null);
var directory = Path.Combine(fileDirectory, referenceObservation.Location);
observations.Where(o => string.Equals(o.Key, directory, StringComparison.CurrentCultureIgnoreCase))
.SelectMany(g => g).Where(o => string.Equals(referenceObservation.Name, o.Name, StringComparison.CurrentCultureIgnoreCase)).ToList()
.ForEach(o => o.Failed = false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SoftwareThresher.Observations;
using SoftwareThresher.Settings.Search;
namespace SoftwareThresher.Tasks {
// TODO - add note to a task
// Note: ignores case
// TODO - should we be ignoring case other places?
public class NotCompiled : Task {
public string Directory { get; set; }
public string CompileConfigurationFileSearchPattern { get; set; }
public string TextSearchPattern { get; set; }
public override string DefaultReportHeaderText => "Not Compiled";
readonly Search search;
public NotCompiled(Search search) {
this.search = search;
}
public override List<Observation> Execute(List<Observation> observations) {
observations.ForEach(o => o.Failed = true);
var observationsLookup = observations.ToLookup(o => o.Location);
search.GetObservations(Directory, CompileConfigurationFileSearchPattern).ForEach(o => MarkObservationsPassedForFile(observationsLookup, o));
return observations;
}
void MarkObservationsPassedForFile(ILookup<string, Observation> observations, Observation observation) {
var observationsWithSameDirectory = observations.Where(o => o.Key.StartsWith(observation.Location)).SelectMany(g => g).ToLookup(o => o.Location);
var referenceLines = search.GetReferenceLine(observation, TextSearchPattern);
referenceLines.ForEach(r => MarkObservationsPassedForReference(observationsWithSameDirectory, observation.Location, r));
}
void MarkObservationsPassedForReference(ILookup<string, Observation> observations, string fileDirectory, string reference) {
var referenceObject = reference.Substring(reference.IndexOf(TextSearchPattern) + TextSearchPattern.Length).Split(' ', '\t', '"').First();
if (string.IsNullOrEmpty(referenceObject))
return;
var referenceObservation = new FileObservation(referenceObject, null);
var directory = Path.Combine(fileDirectory, referenceObservation.Location);
observations.Where(o => string.Equals(o.Key, directory, StringComparison.CurrentCultureIgnoreCase))
.SelectMany(g => g).Where(o => string.Equals(referenceObservation.Name, o.Name, StringComparison.CurrentCultureIgnoreCase)).ToList()
.ForEach(o => o.Failed = false);
}
}
}
|
mit
|
C#
|
4b1b73690ed2d0a52ed2f46b822e4a5835310ace
|
Remove curlies Case 176 (https://github.com/MehdiK/Humanizer/issues/176)
|
kikoanis/Humanizer,micdenny/Humanizer,aloisdg/Humanizer,MehdiK/Humanizer,schalpat/Humanizer,preetksingh80/Humanizer,preetksingh80/Humanizer,thunsaker/Humanizer,HalidCisse/Humanizer,mrchief/Humanizer,preetksingh80/Humanizer,hazzik/Humanizer,HalidCisse/Humanizer,llehouerou/Humanizer,CodeFromJordan/Humanizer,mrchief/Humanizer,HalidCisse/Humanizer,CodeFromJordan/Humanizer,CodeFromJordan/Humanizer,ErikSchierboom/Humanizer,mrchief/Humanizer,Flatlineato/Humanizer,kikoanis/Humanizer,jaxx-rep/Humanizer,ErikSchierboom/Humanizer,micdenny/Humanizer,thunsaker/Humanizer,schalpat/Humanizer,llehouerou/Humanizer,llehouerou/Humanizer,thunsaker/Humanizer,Flatlineato/Humanizer
|
src/Humanizer/Truncation/FixedNumberOfCharactersTruncator.cs
|
src/Humanizer/Truncation/FixedNumberOfCharactersTruncator.cs
|
using System;
using System.Linq;
namespace Humanizer
{
/// <summary>
/// Truncate a string to a fixed number of letters or digits
/// </summary>
class FixedNumberOfCharactersTruncator : ITruncator
{
public string Truncate(string value, int length, string truncationString, TruncateFrom truncateFrom = TruncateFrom.Right)
{
if (value == null)
return null;
if (value.Length == 0)
return value;
if (truncationString == null || truncationString.Length > length)
{
return truncateFrom == TruncateFrom.Right ? value.Substring(0, length) : value.Substring(value.Length - length);
}
var alphaNumericalCharactersProcessed = 0;
if (value.ToCharArray().Count(Char.IsLetterOrDigit) <= length)
return value;
if (truncateFrom == TruncateFrom.Left)
{
for (var i = value.Length - 1; i > 0; i--)
{
if (Char.IsLetterOrDigit(value[i]))
alphaNumericalCharactersProcessed++;
if (alphaNumericalCharactersProcessed + truncationString.Length == length)
return truncationString + value.Substring(i);
}
}
for (var i = 0; i < value.Length - truncationString.Length; i++)
{
if (Char.IsLetterOrDigit(value[i]))
alphaNumericalCharactersProcessed++;
if (alphaNumericalCharactersProcessed + truncationString.Length == length)
return value.Substring(0, i + 1) + truncationString;
}
return value;
}
}
}
|
using System;
using System.Linq;
namespace Humanizer
{
/// <summary>
/// Truncate a string to a fixed number of letters or digits
/// </summary>
class FixedNumberOfCharactersTruncator : ITruncator
{
public string Truncate(string value, int length, string truncationString, TruncateFrom truncateFrom = TruncateFrom.Right)
{
if (value == null)
return null;
if (value.Length == 0)
return value;
if (truncationString == null || truncationString.Length > length)
{
return truncateFrom == TruncateFrom.Right ? value.Substring(0, length) : value.Substring(value.Length - length);
}
var alphaNumericalCharactersProcessed = 0;
if (value.ToCharArray().Count(Char.IsLetterOrDigit) <= length)
{
return value;
}
if (truncateFrom == TruncateFrom.Left)
{
for (var i = value.Length - 1; i > 0; i--)
{
if (Char.IsLetterOrDigit(value[i]))
alphaNumericalCharactersProcessed++;
if (alphaNumericalCharactersProcessed + truncationString.Length == length)
return truncationString + value.Substring(i);
}
}
for (var i = 0; i < value.Length - truncationString.Length; i++)
{
if (Char.IsLetterOrDigit(value[i]))
alphaNumericalCharactersProcessed++;
if (alphaNumericalCharactersProcessed + truncationString.Length == length)
return value.Substring(0, i + 1) + truncationString;
}
return value;
}
}
}
|
mit
|
C#
|
02f1a39b1cf6c2a953323660ce645d151688b2c1
|
Include Sage
|
johnnyreilly/proverb-api-core
|
src/Proverb.Data.EntityFramework/CommandQuery/SayingQuery.cs
|
src/Proverb.Data.EntityFramework/CommandQuery/SayingQuery.cs
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Proverb.Data.EntityFramework.Models;
namespace Proverb.Data.EntityFramework.CommandQuery
{
public interface ISayingQuery
{
Task<ICollection<Saying>> GetAllAsync();
Task<Saying> GetByIdAsync(int id);
Task<ICollection<Saying>> GetBySageIdAsync(int sageId);
}
public class SayingQuery : BaseCommandQuery, ISayingQuery
{
public SayingQuery(ProverbContext dbContext) : base(dbContext) { }
public async Task<ICollection<Saying>> GetAllAsync()
{
var sayings = await DbContext.Saying
.Include(saying => saying.Sage)
.ToListAsync();
return sayings;
}
public async Task<Saying> GetByIdAsync(int id)
{
var sayings = await DbContext.Saying.FindAsync(id);
return sayings;
}
public async Task<ICollection<Saying>> GetBySageIdAsync(int sageId)
{
var sayings = await DbContext.Saying.Where(x => x.SageId == sageId).ToListAsync();
return sayings;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Proverb.Data.EntityFramework.Models;
namespace Proverb.Data.EntityFramework.CommandQuery
{
public interface ISayingQuery
{
Task<ICollection<Saying>> GetAllAsync();
Task<Saying> GetByIdAsync(int id);
Task<ICollection<Saying>> GetBySageIdAsync(int sageId);
}
public class SayingQuery : BaseCommandQuery, ISayingQuery
{
public SayingQuery(ProverbContext dbContext) : base(dbContext) { }
public async Task<ICollection<Saying>> GetAllAsync()
{
var sayings = await DbContext.Saying.ToListAsync();
return sayings;
}
public async Task<Saying> GetByIdAsync(int id)
{
var sayings = await DbContext.Saying.FindAsync(id);
return sayings;
}
public async Task<ICollection<Saying>> GetBySageIdAsync(int sageId)
{
var sayings = await DbContext.Saying.Where(x => x.SageId == sageId).ToListAsync();
return sayings;
}
}
}
|
mit
|
C#
|
a7ed0ae488305cbca13bed3475e46517e3dc89ef
|
add ConfigureMackineKeyForSessionTokens helper
|
jbn566/Thinktecture.IdentityModel.45,shashwatchandra/Thinktecture.IdentityModel.45,nguyenbanguyen/Thinktecture.IdentityModel.45,darraghoriordan/Thinktecture.IdentityModel.45,IdentityModel/Thinktecture.IdentityModel.45,rmorris8812/Thinktecture.IdentityModel.45,yonglehou/Thinktecture.IdentityModel.45
|
IdentityModel/Thinktecture.IdentityModel/Web/PassiveSessionConfiguration.cs
|
IdentityModel/Thinktecture.IdentityModel/Web/PassiveSessionConfiguration.cs
|
using System;
using System.Collections.Generic;
using System.IdentityModel.Services;
using System.IdentityModel.Services.Tokens;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Thinktecture.IdentityModel.Web
{
public static class PassiveSessionConfiguration
{
public static void ConfigureSessionCache(ITokenCacheRepositoryFactory factory)
{
if (!(FederatedAuthentication.FederationConfiguration.IdentityConfiguration.Caches.SessionSecurityTokenCache is PassiveRepositorySessionSecurityTokenCache))
{
FederatedAuthentication.FederationConfiguration.IdentityConfiguration.Caches.SessionSecurityTokenCache = new PassiveRepositorySessionSecurityTokenCache(factory);
}
}
public static void ConfigureDefaultSessionDuration(TimeSpan sessionDuration)
{
var handler = (SessionSecurityTokenHandler)FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[typeof(SessionSecurityToken)];
if (handler != null)
{
handler.TokenLifetime = sessionDuration;
}
}
public static void ConfigureMackineKeyForSessionTokens()
{
var handler = (SessionSecurityTokenHandler)FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[typeof(SessionSecurityToken)];
if (!(handler is MachineKeySessionSecurityTokenHandler))
{
var mkssth = new MachineKeySessionSecurityTokenHandler();
if (handler != null) mkssth.TokenLifetime = handler.TokenLifetime;
FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers.AddOrReplace(mkssth);
}
}
public static void ConfigurePersistentSessions(TimeSpan persistentDuration)
{
FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.PersistentCookiesOnPassiveRedirects = true;
FederatedAuthentication.FederationConfiguration.CookieHandler.PersistentSessionLifetime = persistentDuration;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IdentityModel.Services;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Thinktecture.IdentityModel.Web
{
public static class PassiveSessionConfiguration
{
public static void ConfigureSessionCache(ITokenCacheRepositoryFactory factory)
{
if (!(FederatedAuthentication.FederationConfiguration.IdentityConfiguration.Caches.SessionSecurityTokenCache is PassiveRepositorySessionSecurityTokenCache))
{
FederatedAuthentication.FederationConfiguration.IdentityConfiguration.Caches.SessionSecurityTokenCache = new PassiveRepositorySessionSecurityTokenCache(factory);
}
}
public static void ConfigureDefaultSessionDuration(TimeSpan sessionDuration)
{
var handler = (SessionSecurityTokenHandler)FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[typeof(SessionSecurityToken)];
if (handler != null)
{
handler.TokenLifetime = sessionDuration;
}
}
public static void ConfigurePersistentSessions(TimeSpan persistentDuration)
{
FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.PersistentCookiesOnPassiveRedirects = true;
FederatedAuthentication.FederationConfiguration.CookieHandler.PersistentSessionLifetime = persistentDuration;
}
}
}
|
bsd-3-clause
|
C#
|
91d7bbc60787989e4bfc82e3db01d6a5dd83f3c3
|
Update ShapeStateFlags.cs
|
wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
|
src/Core2D/Model/Renderer/ShapeStateFlags.cs
|
src/Core2D/Model/Renderer/ShapeStateFlags.cs
|
using System;
namespace Core2D.Renderer
{
/// <summary>
/// Specifies shape state flags.
/// </summary>
[Flags]
public enum ShapeStateFlags
{
/// <summary>
/// Default shape state.
/// </summary>
Default = 0,
/// <summary>
/// Shape is visible.
/// </summary>
Visible = 1,
/// <summary>
/// Shape is printable.
/// </summary>
Printable = 2,
/// <summary>
/// Shape position is locked.
/// </summary>
Locked = 4,
/// <summary>
/// Shape size is scaled.
/// </summary>
Size = 8,
/// <summary>
/// Shape thickness is scaled.
/// </summary>
Thickness = 16,
/// <summary>
/// Shape is connector.
/// </summary>
Connector = 32,
/// <summary>
/// Shape in none.
/// </summary>
None = 64,
/// <summary>
/// Shape is standalone.
/// </summary>
Standalone = 128,
/// <summary>
/// Shape is an input.
/// </summary>
Input = 256,
/// <summary>
/// Shape is and output.
/// </summary>
Output = 512
}
}
|
using System;
namespace Core2D.Renderer
{
/// <summary>
/// Specifies shape state flags.
/// </summary>
[Flags]
public enum ShapeStateFlags
{
/// <summary>
/// Default shape state.
/// </summary>
Default = 0,
/// <summary>
/// Shape is visible.
/// </summary>
Visible = 1,
/// <summary>
/// Shape is printable.
/// </summary>
Printable = 2,
/// <summary>
/// Shape position is locked.
/// </summary>
Locked = 4,
/// <summary>
/// Shape is connector.
/// </summary>
Connector = 8,
/// <summary>
/// Shape in none.
/// </summary>
None = 16,
/// <summary>
/// Shape is standalone.
/// </summary>
Standalone = 32,
/// <summary>
/// Shape is an input.
/// </summary>
Input = 64,
/// <summary>
/// Shape is and output.
/// </summary>
Output = 128
}
}
|
mit
|
C#
|
2594f15937f4cc81fc0cb5e073aa324a678cd7cc
|
Remove custom constructor from WheelOfFortune class.
|
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
|
src/MitternachtBot/Modules/Gambling/Common/WheelOfFortune/WheelOfFortune.cs
|
src/MitternachtBot/Modules/Gambling/Common/WheelOfFortune/WheelOfFortune.cs
|
using System.Collections.Immutable;
using Mitternacht.Common;
namespace Mitternacht.Modules.Gambling.Common.WheelOfFortune {
public class WheelOfFortune {
private static readonly NadekoRandom _rng = new NadekoRandom();
private static readonly ImmutableArray<string> _emojis = new string[] {
"⬆",
"↖",
"⬅",
"↙",
"⬇",
"↘",
"➡",
"↗" }.ToImmutableArray();
public static readonly ImmutableArray<float> Multipliers = new float[] {
1.7f,
1.5f,
0.2f,
0.1f,
0.3f,
0.5f,
1.2f,
2.4f,
}.ToImmutableArray();
public readonly int Result = _rng.Next(0, 8);
public string Emoji => _emojis[Result];
public float Multiplier => Multipliers[Result];
}
}
|
using System.Collections.Immutable;
using Mitternacht.Common;
namespace Mitternacht.Modules.Gambling.Common.WheelOfFortune {
public class WheelOfFortune {
private static readonly NadekoRandom _rng = new NadekoRandom();
private static readonly ImmutableArray<string> _emojis = new string[] {
"⬆",
"↖",
"⬅",
"↙",
"⬇",
"↘",
"➡",
"↗" }.ToImmutableArray();
public static readonly ImmutableArray<float> Multipliers = new float[] {
1.7f,
1.5f,
0.2f,
0.1f,
0.3f,
0.5f,
1.2f,
2.4f,
}.ToImmutableArray();
public int Result { get; }
public string Emoji => _emojis[Result];
public float Multiplier => Multipliers[Result];
public WheelOfFortune() {
this.Result = _rng.Next(0, 8);
}
}
}
|
mit
|
C#
|
c856b3df05dc95a3cb563804e755eb0efdc37768
|
Add comment noting tight-coupling of a-vs-an scanner and query
|
EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an
|
A-vs-An/WikipediaAvsAnTrieExtractor/RegexTextUtils.ExtractWordsAfterAOrAn.cs
|
A-vs-An/WikipediaAvsAnTrieExtractor/RegexTextUtils.ExtractWordsAfterAOrAn.cs
|
using System.Text.RegularExpressions;
using System.Linq;
using System;
using System.Collections.Generic;
namespace WikipediaAvsAnTrieExtractor {
public partial class RegexTextUtils {
//Note: regexes are NOT static and shared because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex
//This code is bottlenecked by regexes, so this really matters, here.
//If you change this, keep WordQuery char-skipping in Query in sync!
readonly Regex followingAn = new Regex(@"(^(?<article>An?)|[\s""()‘’“”](?<article>an?)) [""‘’“”$']*(?<word>[^\s""()‘’“”$-]+(?<!'))", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
//general notes:
//words consist of anything BUT spaces and delimiters "()‘’“”-
//dash is a word delimiter in pronunciation, which is all we care about here
//$ isn't a delimiter, but its an unpronounced prefix ($3 is "three dollars"), so
//we exclude $ from words too.
//Some tricky corner-cases:
//watch out for dashes *before* "A" because of things like "Triple-A annotation"
//Be careful of words like Chang'an - ' is not a separator here.
//Prefer a few false negatives over false positives when it comes to article detection.
//In particular, some symbolic math and logic expressions use the word "a" followed by things
//like parentheses and that throws the statistics a little (but enough in rarely occuring
//prefixes to matter). Therefore, don't detect a/an + word when separated by "(".
public IEnumerable<AvsAnSighting> ExtractWordsPrecededByAOrAn(string text) {
//TODO: ignore uppercase "A" -it's just too hard to get right.
return
from Match m in followingAn.Matches(text)
select new AvsAnSighting { Word = m.Groups["word"].Value, PrecededByAn = m.Groups["article"].Value.Length == 2 };
}
}
}
|
using System.Text.RegularExpressions;
using System.Linq;
using System;
using System.Collections.Generic;
namespace WikipediaAvsAnTrieExtractor {
public partial class RegexTextUtils {
//Note: regexes are NOT static and shared because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex
//This code is bottlenecked by regexes, so this really matters, here.
readonly Regex followingAn = new Regex(@"(^(?<article>An?)|[\s""()‘’“”](?<article>an?)) [""‘’“”$']*(?<word>[^\s""()‘’“”$-]+(?<!'))", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
//general notes:
//words consist of anything BUT spaces and delimiters "()‘’“”-
//dash is a word delimiter in pronunciation, which is all we care about here
//$ isn't a delimiter, but its an unpronounced prefix ($3 is "three dollars"), so
//we exclude $ from words too.
//Some tricky corner-cases:
//watch out for dashes *before* "A" because of things like "Triple-A annotation"
//Be careful of words like Chang'an - ' is not a separator here.
//Prefer a few false negatives over false positives when it comes to article detection.
//In particular, some symbolic math and logic expressions use the word "a" followed by things
//like parentheses and that throws the statistics a little (but enough in rarely occuring
//prefixes to matter). Therefore, don't detect a/an + word when separated by "(".
public IEnumerable<AvsAnSighting> ExtractWordsPrecededByAOrAn(string text) {
//TODO: ignore uppercase "A" -it's just too hard to get right.
return
from Match m in followingAn.Matches(text)
select new AvsAnSighting { Word = m.Groups["word"].Value, PrecededByAn = m.Groups["article"].Value.Length == 2 };
}
}
}
|
apache-2.0
|
C#
|
ce80c8ff87f528f248e5d7d734b711bc788e44a1
|
Allow statically bound Razor templates to be output cached
|
kamsar/Blade
|
Source/Blade/Views/RazorTemplate.cs
|
Source/Blade/Views/RazorTemplate.cs
|
using System.Web.UI;
using Sitecore.Web.UI;
using Blade.Razor;
using Blade.Utility;
using Sitecore.Diagnostics;
namespace Blade.Views
{
/// <summary>
/// Allows statically binding a Razor template as if it were a WebControl
/// </summary>
public class RazorTemplate : WebControl
{
/// <summary>
/// Virtual path to the Razor file to render
/// </summary>
public string Path { get; set; }
/// <summary>
/// The Model for the Razor view. The model will be null if this is unset.
/// </summary>
public object Model { get; set; }
protected override void DoRender(HtmlTextWriter output)
{
using (new RenderingDiagnostics(output, Path + " (statically bound)", Cacheable, VaryByData, VaryByDevice, VaryByLogin, VaryByParm, VaryByQueryString, VaryByUser, ClearOnIndexUpdate, GetCachingID()))
{
Assert.IsNotNull(Path, "Path was null or empty, and must point to a valid virtual path to a Razor rendering.");
var renderer = new ViewRenderer();
var result = renderer.RenderPartialViewToString(Path, Model);
output.Write(result);
}
}
protected override string GetCachingID()
{
return Path;
}
}
}
|
using System.Web.UI;
using Sitecore.Web.UI;
using Blade.Razor;
using Blade.Utility;
using Sitecore.Diagnostics;
namespace Blade.Views
{
/// <summary>
/// Allows statically binding a Razor template as if it were a WebControl
/// </summary>
public class RazorTemplate : WebControl
{
/// <summary>
/// Virtual path to the Razor file to render
/// </summary>
public string Path { get; set; }
/// <summary>
/// The Model for the Razor view. The model will be null if this is unset.
/// </summary>
public object Model { get; set; }
protected override void DoRender(HtmlTextWriter output)
{
using (new RenderingDiagnostics(output, Path + " (statically bound)", Cacheable, VaryByData, VaryByDevice, VaryByLogin, VaryByParm, VaryByQueryString, VaryByUser, ClearOnIndexUpdate, GetCachingID()))
{
Assert.IsNotNull(Path, "Path was null or empty, and must point to a valid virtual path to a Razor rendering.");
var renderer = new ViewRenderer();
var result = renderer.RenderPartialViewToString(Path, Model);
output.Write(result);
}
}
}
}
|
mit
|
C#
|
1f4ac958f423c76561667937fd5b52256558baa0
|
Remove incorrect comment
|
DotNetAnalyzers/StyleCopAnalyzers
|
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/Lightup/StackAllocArrayCreationExpressionSyntaxExtensionsTests.cs
|
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/Lightup/StackAllocArrayCreationExpressionSyntaxExtensionsTests.cs
|
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp7.Lightup
{
using Microsoft.CodeAnalysis.CSharp;
using StyleCop.Analyzers.Lightup;
using Xunit;
public class StackAllocArrayCreationExpressionSyntaxExtensionsTests
{
[Fact]
public void TestInitializer()
{
var stackAllocSyntax = SyntaxFactory.StackAllocArrayCreationExpression(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)))
.WithInitializer(SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression));
Assert.NotNull(StackAllocArrayCreationExpressionSyntaxExtensions.Initializer(stackAllocSyntax));
Assert.Equal(SyntaxKind.ArrayInitializerExpression, StackAllocArrayCreationExpressionSyntaxExtensions.Initializer(stackAllocSyntax).Kind());
}
[Fact]
public void TestWithInitializer()
{
var stackAllocSyntax = SyntaxFactory.StackAllocArrayCreationExpression(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)));
var stackAllocWithDefaultInitializer = StackAllocArrayCreationExpressionSyntaxExtensions.WithInitializer(stackAllocSyntax, null);
Assert.Null(StackAllocArrayCreationExpressionSyntaxExtensions.Initializer(stackAllocWithDefaultInitializer));
var initializer = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression);
var stackAllocWithInitializer = StackAllocArrayCreationExpressionSyntaxExtensions.WithInitializer(stackAllocSyntax, initializer);
Assert.NotNull(stackAllocWithInitializer.Initializer);
Assert.Equal(SyntaxKind.ArrayInitializerExpression, stackAllocWithInitializer.Initializer.Kind());
Assert.True(stackAllocWithInitializer.Initializer.IsEquivalentTo(initializer));
}
}
}
|
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp7.Lightup
{
using Microsoft.CodeAnalysis.CSharp;
using StyleCop.Analyzers.Lightup;
using Xunit;
public class StackAllocArrayCreationExpressionSyntaxExtensionsTests
{
[Fact]
public void TestInitializer()
{
var stackAllocSyntax = SyntaxFactory.StackAllocArrayCreationExpression(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)))
.WithInitializer(SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression));
Assert.NotNull(StackAllocArrayCreationExpressionSyntaxExtensions.Initializer(stackAllocSyntax));
Assert.Equal(SyntaxKind.ArrayInitializerExpression, StackAllocArrayCreationExpressionSyntaxExtensions.Initializer(stackAllocSyntax).Kind());
}
[Fact]
public void TestWithInitializer()
{
var stackAllocSyntax = SyntaxFactory.StackAllocArrayCreationExpression(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)));
// With default value is allowed
var stackAllocWithDefaultInitializer = StackAllocArrayCreationExpressionSyntaxExtensions.WithInitializer(stackAllocSyntax, null);
Assert.Null(StackAllocArrayCreationExpressionSyntaxExtensions.Initializer(stackAllocWithDefaultInitializer));
// Non-default throws an exception
var initializer = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression);
var stackAllocWithInitializer = StackAllocArrayCreationExpressionSyntaxExtensions.WithInitializer(stackAllocSyntax, initializer);
Assert.NotNull(stackAllocWithInitializer.Initializer);
Assert.Equal(SyntaxKind.ArrayInitializerExpression, stackAllocWithInitializer.Initializer.Kind());
Assert.True(stackAllocWithInitializer.Initializer.IsEquivalentTo(initializer));
}
}
}
|
mit
|
C#
|
bd0a329912802376ed3426bf2b914a9890d14dcb
|
Simplify format logic
|
AntiTcb/Discord.Net,RogueException/Discord.Net,Confruggy/Discord.Net,LassieME/Discord.Net
|
src/Discord.Net.Core/CDN.cs
|
src/Discord.Net.Core/CDN.cs
|
namespace Discord
{
public static class CDN
{
public static string GetApplicationIconUrl(ulong appId, string iconId)
=> iconId != null ? $"{DiscordConfig.CDNUrl}app-icons/{appId}/{iconId}.jpg" : null;
public static string GetUserAvatarUrl(ulong userId, string avatarId, ushort size, AvatarFormat format)
{
if (avatarId == null)
return null;
if (format == AvatarFormat.Auto)
format = avatarId.StartsWith("a_") ? AvatarFormat.Gif : AvatarFormat.Png;
return $"{DiscordConfig.CDNUrl}avatars/{userId}/{avatarId}.{format.ToString().ToLower()}?size={size}";
}
public static string GetGuildIconUrl(ulong guildId, string iconId)
=> iconId != null ? $"{DiscordConfig.CDNUrl}icons/{guildId}/{iconId}.jpg" : null;
public static string GetGuildSplashUrl(ulong guildId, string splashId)
=> splashId != null ? $"{DiscordConfig.CDNUrl}splashes/{guildId}/{splashId}.jpg" : null;
public static string GetChannelIconUrl(ulong channelId, string iconId)
=> iconId != null ? $"{DiscordConfig.CDNUrl}channel-icons/{channelId}/{iconId}.jpg" : null;
public static string GetEmojiUrl(ulong emojiId)
=> $"{DiscordConfig.CDNUrl}emojis/{emojiId}.png";
}
}
|
namespace Discord
{
public static class CDN
{
public static string GetApplicationIconUrl(ulong appId, string iconId)
=> iconId != null ? $"{DiscordConfig.CDNUrl}app-icons/{appId}/{iconId}.jpg" : null;
public static string GetUserAvatarUrl(ulong userId, string avatarId, ushort size, AvatarFormat format)
{
if (avatarId == null)
return null;
var baseUrl = $"{DiscordConfig.CDNUrl}avatars/{userId}/{avatarId}";
if (format == AvatarFormat.Auto)
return baseUrl + (avatarId.StartsWith("a_") ? "gif" : "png") + $"?size={size}";
else
return baseUrl + format.ToString().ToLower() + $"?size={size}";
}
public static string GetGuildIconUrl(ulong guildId, string iconId)
=> iconId != null ? $"{DiscordConfig.CDNUrl}icons/{guildId}/{iconId}.jpg" : null;
public static string GetGuildSplashUrl(ulong guildId, string splashId)
=> splashId != null ? $"{DiscordConfig.CDNUrl}splashes/{guildId}/{splashId}.jpg" : null;
public static string GetChannelIconUrl(ulong channelId, string iconId)
=> iconId != null ? $"{DiscordConfig.CDNUrl}channel-icons/{channelId}/{iconId}.jpg" : null;
public static string GetEmojiUrl(ulong emojiId)
=> $"{DiscordConfig.CDNUrl}emojis/{emojiId}.png";
}
}
|
mit
|
C#
|
be08460bea4c10391dd980b2d437a5ee4364e248
|
Fix formatting issues
|
ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu
|
osu.Game/Users/Drawables/DrawableAvatar.cs
|
osu.Game/Users/Drawables/DrawableAvatar.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Game.Online.API;
namespace osu.Game.Users.Drawables
{
[LongRunningLoad]
public class DrawableAvatar : Sprite
{
private readonly User user;
[Resolved(CanBeNull = true)]
private IAPIProvider api { get; set; }
/// <summary>
/// A simple, non-interactable avatar sprite for the specified user.
/// </summary>
/// <param name="user">The user. A null value will get a placeholder avatar.</param>
public DrawableAvatar(User user = null)
{
this.user = user;
RelativeSizeAxes = Axes.Both;
FillMode = FillMode.Fit;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
[BackgroundDependencyLoader]
private void load(LargeTextureStore textures)
{
if (api != null && user?.AvatarUrl != null)
Texture = textures.Get(user.AvatarUrl.StartsWith('/') ? $"{api.WebsiteRootUrl}{user.AvatarUrl}" : user.AvatarUrl);
else if (user != null && user.Id > 1)
Texture = textures.Get($@"https://a.ppy.sh/{user.Id}");
Texture ??= textures.Get(@"Online/avatar-guest");
}
protected override void LoadComplete()
{
base.LoadComplete();
this.FadeInFromZero(300, Easing.OutQuint);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Game.Online.API;
namespace osu.Game.Users.Drawables
{
[LongRunningLoad]
public class DrawableAvatar : Sprite
{
private readonly User user;
[Resolved(CanBeNull=true)]
private IAPIProvider api { get; set; }
/// <summary>
/// A simple, non-interactable avatar sprite for the specified user.
/// </summary>
/// <param name="user">The user. A null value will get a placeholder avatar.</param>
public DrawableAvatar(User user = null)
{
this.user = user;
RelativeSizeAxes = Axes.Both;
FillMode = FillMode.Fit;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
}
[BackgroundDependencyLoader]
private void load(LargeTextureStore textures)
{
if (api != null && user?.AvatarUrl != null)
Texture = textures.Get(user.AvatarUrl.StartsWith('/') ? $"{api.WebsiteRootUrl}{user.AvatarUrl}" : user.AvatarUrl);
else if (user != null && user.Id > 1)
Texture = textures.Get($@"https://a.ppy.sh/{user.Id}");
Texture ??= textures.Get(@"Online/avatar-guest");
}
protected override void LoadComplete()
{
base.LoadComplete();
this.FadeInFromZero(300, Easing.OutQuint);
}
}
}
|
mit
|
C#
|
eda818710739ebb1a5a460d6793978b01d61d2e9
|
Fix TesterDiagnosticProvider not actually providing any document diagnostics
|
DotNetAnalyzers/StyleCopAnalyzers
|
StyleCop.Analyzers/StyleCopTester/TesterDiagnosticProvider.cs
|
StyleCop.Analyzers/StyleCopTester/TesterDiagnosticProvider.cs
|
namespace StyleCopTester
{
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
internal sealed class TesterDiagnosticProvider : FixAllContext.DiagnosticProvider
{
private ImmutableArray<Diagnostic> diagnostics;
private TesterDiagnosticProvider(ImmutableArray<Diagnostic> diagnostics)
{
this.diagnostics = diagnostics;
}
public override Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken)
{
return Task.FromResult<IEnumerable<Diagnostic>>(this.diagnostics);
}
public override Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken)
{
return Task.FromResult(this.diagnostics.Where(i => i.Location.GetLineSpan().Path == document.FilePath));
}
public override Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken)
{
return Task.FromResult(this.diagnostics.Where(i => !i.Location.IsInSource));
}
internal static TesterDiagnosticProvider Create(ImmutableArray<Diagnostic> diagnostics)
{
return new TesterDiagnosticProvider(diagnostics);
}
}
}
|
namespace StyleCopTester
{
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
internal sealed class TesterDiagnosticProvider : FixAllContext.DiagnosticProvider
{
private ImmutableArray<Diagnostic> diagnostics;
private TesterDiagnosticProvider(ImmutableArray<Diagnostic> diagnostics)
{
this.diagnostics = diagnostics;
}
public override Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken)
{
return Task.FromResult<IEnumerable<Diagnostic>>(this.diagnostics);
}
public override Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken)
{
return Task.FromResult(this.diagnostics.Where(i => i.Location.GetLineSpan().Path == document.Name));
}
public override Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken)
{
return Task.FromResult(this.diagnostics.Where(i => !i.Location.IsInSource));
}
internal static TesterDiagnosticProvider Create(ImmutableArray<Diagnostic> diagnostics)
{
return new TesterDiagnosticProvider(diagnostics);
}
}
}
|
mit
|
C#
|
217554f587d40582ce51b2c5630c8a0e4402791d
|
Remove redundant interface
|
smoogipoo/osu,Frontear/osuKyzer,UselessToucan/osu,smoogipoo/osu,naoey/osu,johnneijzen/osu,UselessToucan/osu,DrabWeb/osu,2yangk23/osu,ZLima12/osu,Drezi126/osu,johnneijzen/osu,peppy/osu,DrabWeb/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,ppy/osu,EVAST9919/osu,peppy/osu-new,2yangk23/osu,Nabile-Rahmani/osu,DrabWeb/osu,naoey/osu,naoey/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,ZLima12/osu,EVAST9919/osu,ppy/osu,NeoAdonis/osu
|
osu.Game/Rulesets/Mods/ModPerfect.cs
|
osu.Game/Rulesets/Mods/ModPerfect.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModPerfect : ModSuddenDeath
{
public override string Name => "Perfect";
public override string ShortenedName => "PF";
public override string Description => "SS or quit.";
protected override bool FailCondition(ScoreProcessor scoreProcessor) => scoreProcessor.Accuracy.Value != 1;
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModPerfect : ModSuddenDeath, IApplicableToScoreProcessor
{
public override string Name => "Perfect";
public override string ShortenedName => "PF";
public override string Description => "SS or quit.";
protected override bool FailCondition(ScoreProcessor scoreProcessor) => scoreProcessor.Accuracy.Value != 1;
}
}
|
mit
|
C#
|
7649ff2cccbe06a44c6ee5ab5a77b658018adef1
|
Remove unnecessary Console.WriteLine in C# library
|
john29917958/Cpp-Call-CSharp-Example,john29917958/Cpp-Call-CSharp-Example
|
CSharpLibrary/Calculator.cs
|
CSharpLibrary/Calculator.cs
|
using System;
namespace CSharpLibrary
{
public class Calculator : ICalculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Subtract(int a, int b)
{
return a - b;
}
public int Multiply(int a, int b)
{
return a * b;
}
public int Divide(int a, int b)
{
if (b == 0)
{
Console.WriteLine("Divide by zero is invalid!");
}
return a / b;
}
public int ToNumber(string number)
{
int result = 0;
try
{
result = int.Parse(number);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return result;
}
}
}
|
using System;
namespace CSharpLibrary
{
public class Calculator : ICalculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Subtract(int a, int b)
{
return a - b;
}
public int Multiply(int a, int b)
{
return a * b;
}
public int Divide(int a, int b)
{
if (b == 0)
{
Console.WriteLine("Divide by zero is invalid!");
}
return a / b;
}
public int ToNumber(string number)
{
int result = 0;
try
{
result = int.Parse(number);
}
catch (Exception e)
{
Console.WriteLine(number);
Console.WriteLine(e.Message);
}
return result;
}
}
}
|
mit
|
C#
|
c5de2a7187d9f0912f541a22ab6c01eb13ea0c38
|
Update Program.cs
|
informedcitizenry/6502.Net
|
6502.Net/Program.cs
|
6502.Net/Program.cs
|
//-----------------------------------------------------------------------------
// Copyright (c) 2017 Nate Burnett <informedcitizenry@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
using System;
namespace Asm6502.Net
{
class Program
{
static void Main(string[] args)
{
try
{
IAssemblyController asm = new Asm6502Controller(); asm.Assemble(args);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
|
//-----------------------------------------------------------------------------
// Copyright (c) 2017 Nate Burnett <informedcitizenry@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
namespace Asm6502.Net
{
class Program
{
static void Main(string[] args)
{
try
{
IAssemblyController asm = new Asm6502Controller(); asm.Assemble(args);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
|
mit
|
C#
|
1e776561a1ee37e9dea88afce06117c53baaf0d0
|
Update InclusionChecker.cs
|
Fody/Virtuosity
|
Virtuosity.Fody/InclusionChecker.cs
|
Virtuosity.Fody/InclusionChecker.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
public partial class ModuleWeaver
{
public Func<TypeDefinition, bool> ShouldIncludeType;
List<LineMatcher> lineMatchers;
public void ProcessIncludesExcludes()
{
if (ExcludeNamespaces.Any())
{
lineMatchers = GetLines(ExcludeNamespaces).ToList();
ShouldIncludeType = definition => lineMatchers.All(lineMatcher => !lineMatcher.Match(definition.Namespace)) && !ContainsIgnoreAttribute(definition);
return;
}
if (IncludeNamespaces.Any())
{
lineMatchers = GetLines(IncludeNamespaces).ToList();
ShouldIncludeType = definition => lineMatchers.Any(lineMatcher => lineMatcher.Match(definition.Namespace)) && !ContainsIgnoreAttribute(definition);
return;
}
ShouldIncludeType = definition => !ContainsIgnoreAttribute(definition);
}
bool ContainsIgnoreAttribute(TypeDefinition typeDefinition)
{
return typeDefinition.CustomAttributes.ContainsAttribute("DoNotVirtualizeAttribute");
}
public static IEnumerable<LineMatcher> GetLines(List<string> namespaces)
{
return namespaces.Select(BuildLineMatcher);
}
public static LineMatcher BuildLineMatcher(string line)
{
var starStart = false;
if (line.StartsWith("*"))
{
starStart = true;
line = line.Substring(1);
}
var starEnd = false;
if (line.EndsWith("*"))
{
starEnd = true;
line = line.Substring(0, line.Length - 1);
}
ValidateLine(line);
return new LineMatcher
{
Line = line,
StarStart = starStart,
StarEnd = starEnd,
};
}
// ReSharper disable once UnusedParameter.Local
static void ValidateLine(string line)
{
if (line.Contains("*"))
{
throw new Exception("Namespaces can't only start or end with '*'.");
}
if (line.Contains(" "))
{
throw new Exception("Namespaces cant contain spaces.");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
public partial class ModuleWeaver
{
public Func<TypeDefinition, bool> ShouldIncludeType;
List<LineMatcher> lineMatchers;
public void ProcessIncludesExcludes()
{
if (ExcludeNamespaces.Any())
{
lineMatchers = GetLines(ExcludeNamespaces).ToList();
ShouldIncludeType = definition => lineMatchers.All(lineMatcher => !lineMatcher.Match(definition.Namespace)) && !ContainsIgnoreAttribute(definition);
return;
}
if (IncludeNamespaces.Any())
{
lineMatchers = GetLines(IncludeNamespaces).ToList();
ShouldIncludeType = definition => lineMatchers.Any(lineMatcher => lineMatcher.Match(definition.Namespace)) && !ContainsIgnoreAttribute(definition);
return;
}
ShouldIncludeType = definition => !ContainsIgnoreAttribute(definition);
}
bool ContainsIgnoreAttribute(TypeDefinition typeDefinition)
{
return typeDefinition.CustomAttributes.ContainsAttribute("DoNotVirtualizeAttribute");
}
public static IEnumerable<LineMatcher> GetLines(List<string> namespaces)
{
return namespaces.Select(BuildLineMatcher);
}
public static LineMatcher BuildLineMatcher(string line)
{
var starStart = false;
if (line.StartsWith("*"))
{
starStart = true;
line = line.Substring(1);
}
var starEnd = false;
if (line.EndsWith("*"))
{
starEnd = true;
line = line.Substring(0, line.Length - 1);
}
ValidateLine(line);
return new LineMatcher
{
Line = line,
StarStart = starStart,
StarEnd = starEnd,
};
}
// ReSharper disable once UnusedParameter.Local
static void ValidateLine(string line)
{
if (line.Contains("*"))
{
throw new Exception("Namespaces can't only start or end with '*'.");
}
if (line.Contains(" "))
{
throw new Exception("Namespaces cant contain spaces.");
}
}
}
|
mit
|
C#
|
d4adf9fb30813ec4a02d70f024e0441d6778388e
|
add null check
|
TakeAsh/cs-WpfUtility
|
WpfUtility/BrushExtensionMethods.cs
|
WpfUtility/BrushExtensionMethods.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Media3D;
namespace WpfUtility {
public static class BrushExtensionMethods {
public static Material ToMaterial(this Brush brush) {
return brush == null ?
null :
new DiffuseMaterial(brush);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Media3D;
namespace WpfUtility {
public static class BrushExtensionMethods {
public static Material ToMaterial(this Brush brush) {
return new DiffuseMaterial(brush);
}
}
}
|
mit
|
C#
|
5328b096373bbfa215a2a026fc59fbbe7e0360f1
|
Implement RunServerCompilation in portable build task
|
pdelvo/roslyn,pdelvo/roslyn,jamesqo/roslyn,AlekseyTs/roslyn,mattscheffer/roslyn,jhendrixMSFT/roslyn,natgla/roslyn,bbarry/roslyn,KevinRansom/roslyn,brettfo/roslyn,CaptainHayashi/roslyn,MichalStrehovsky/roslyn,MattWindsor91/roslyn,CyrusNajmabadi/roslyn,khellang/roslyn,weltkante/roslyn,drognanar/roslyn,KevinRansom/roslyn,SeriaWei/roslyn,Hosch250/roslyn,eriawan/roslyn,gafter/roslyn,MattWindsor91/roslyn,vcsjones/roslyn,jcouv/roslyn,davkean/roslyn,ErikSchierboom/roslyn,jcouv/roslyn,a-ctor/roslyn,MattWindsor91/roslyn,amcasey/roslyn,ErikSchierboom/roslyn,jhendrixMSFT/roslyn,ValentinRueda/roslyn,basoundr/roslyn,mgoertz-msft/roslyn,yeaicc/roslyn,jasonmalinowski/roslyn,khyperia/roslyn,rgani/roslyn,wvdd007/roslyn,balajikris/roslyn,KirillOsenkov/roslyn,AnthonyDGreen/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,jeffanders/roslyn,ljw1004/roslyn,MichalStrehovsky/roslyn,panopticoncentral/roslyn,mattscheffer/roslyn,CyrusNajmabadi/roslyn,agocke/roslyn,Shiney/roslyn,jhendrixMSFT/roslyn,Pvlerick/roslyn,KiloBravoLima/roslyn,jeffanders/roslyn,bkoelman/roslyn,bbarry/roslyn,SeriaWei/roslyn,abock/roslyn,heejaechang/roslyn,mavasani/roslyn,KiloBravoLima/roslyn,budcribar/roslyn,swaroop-sridhar/roslyn,lorcanmooney/roslyn,panopticoncentral/roslyn,paulvanbrenk/roslyn,sharwell/roslyn,aelij/roslyn,jmarolf/roslyn,akrisiun/roslyn,khyperia/roslyn,dotnet/roslyn,tmeschter/roslyn,jasonmalinowski/roslyn,natidea/roslyn,Giftednewt/roslyn,xasx/roslyn,KiloBravoLima/roslyn,xasx/roslyn,AmadeusW/roslyn,OmarTawfik/roslyn,wvdd007/roslyn,wvdd007/roslyn,mattwar/roslyn,jkotas/roslyn,tvand7093/roslyn,nguerrera/roslyn,mattwar/roslyn,michalhosala/roslyn,ljw1004/roslyn,ErikSchierboom/roslyn,physhi/roslyn,aelij/roslyn,tmat/roslyn,mmitche/roslyn,diryboy/roslyn,reaction1989/roslyn,leppie/roslyn,rgani/roslyn,Pvlerick/roslyn,mattwar/roslyn,VSadov/roslyn,jcouv/roslyn,basoundr/roslyn,leppie/roslyn,vslsnap/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,paulvanbrenk/roslyn,AlekseyTs/roslyn,srivatsn/roslyn,rgani/roslyn,Giftednewt/roslyn,Hosch250/roslyn,KevinRansom/roslyn,basoundr/roslyn,tmat/roslyn,vcsjones/roslyn,KevinH-MS/roslyn,a-ctor/roslyn,AnthonyDGreen/roslyn,xasx/roslyn,jkotas/roslyn,brettfo/roslyn,mmitche/roslyn,natidea/roslyn,jaredpar/roslyn,mavasani/roslyn,khellang/roslyn,yeaicc/roslyn,srivatsn/roslyn,AArnott/roslyn,tvand7093/roslyn,genlu/roslyn,khyperia/roslyn,zooba/roslyn,AnthonyDGreen/roslyn,robinsedlaczek/roslyn,swaroop-sridhar/roslyn,jamesqo/roslyn,jmarolf/roslyn,dpoeschl/roslyn,paulvanbrenk/roslyn,mattscheffer/roslyn,Shiney/roslyn,dotnet/roslyn,pdelvo/roslyn,balajikris/roslyn,srivatsn/roslyn,xoofx/roslyn,cston/roslyn,dpoeschl/roslyn,stephentoub/roslyn,TyOverby/roslyn,ljw1004/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,MichalStrehovsky/roslyn,lorcanmooney/roslyn,tmat/roslyn,bartdesmet/roslyn,DustinCampbell/roslyn,sharadagrawal/Roslyn,DustinCampbell/roslyn,swaroop-sridhar/roslyn,KevinH-MS/roslyn,sharwell/roslyn,bkoelman/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,AmadeusW/roslyn,kelltrick/roslyn,ericfe-ms/roslyn,akrisiun/roslyn,KevinH-MS/roslyn,lorcanmooney/roslyn,natidea/roslyn,jkotas/roslyn,KirillOsenkov/roslyn,bbarry/roslyn,drognanar/roslyn,OmarTawfik/roslyn,dpoeschl/roslyn,orthoxerox/roslyn,Shiney/roslyn,genlu/roslyn,dotnet/roslyn,jaredpar/roslyn,natgla/roslyn,ValentinRueda/roslyn,robinsedlaczek/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,VSadov/roslyn,reaction1989/roslyn,tannergooding/roslyn,khellang/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,agocke/roslyn,xoofx/roslyn,vslsnap/roslyn,MatthieuMEZIL/roslyn,VSadov/roslyn,xoofx/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,CaptainHayashi/roslyn,reaction1989/roslyn,DustinCampbell/roslyn,sharadagrawal/Roslyn,heejaechang/roslyn,tmeschter/roslyn,bartdesmet/roslyn,leppie/roslyn,zooba/roslyn,tannergooding/roslyn,sharwell/roslyn,physhi/roslyn,davkean/roslyn,physhi/roslyn,mavasani/roslyn,panopticoncentral/roslyn,tvand7093/roslyn,cston/roslyn,orthoxerox/roslyn,genlu/roslyn,brettfo/roslyn,jamesqo/roslyn,CyrusNajmabadi/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,MatthieuMEZIL/roslyn,michalhosala/roslyn,AmadeusW/roslyn,drognanar/roslyn,diryboy/roslyn,gafter/roslyn,TyOverby/roslyn,CaptainHayashi/roslyn,bkoelman/roslyn,ValentinRueda/roslyn,stephentoub/roslyn,kelltrick/roslyn,jeffanders/roslyn,amcasey/roslyn,SeriaWei/roslyn,davkean/roslyn,robinsedlaczek/roslyn,aelij/roslyn,nguerrera/roslyn,kelltrick/roslyn,a-ctor/roslyn,jaredpar/roslyn,amcasey/roslyn,AArnott/roslyn,MattWindsor91/roslyn,balajikris/roslyn,mmitche/roslyn,zooba/roslyn,budcribar/roslyn,TyOverby/roslyn,Hosch250/roslyn,vcsjones/roslyn,stephentoub/roslyn,natgla/roslyn,eriawan/roslyn,MatthieuMEZIL/roslyn,budcribar/roslyn,agocke/roslyn,yeaicc/roslyn,AArnott/roslyn,mgoertz-msft/roslyn,abock/roslyn,ericfe-ms/roslyn,vslsnap/roslyn,gafter/roslyn,KirillOsenkov/roslyn,OmarTawfik/roslyn,Pvlerick/roslyn,cston/roslyn,tannergooding/roslyn,Giftednewt/roslyn,akrisiun/roslyn,orthoxerox/roslyn,nguerrera/roslyn,sharadagrawal/Roslyn,abock/roslyn,tmeschter/roslyn,michalhosala/roslyn,ericfe-ms/roslyn
|
src/Compilers/Core/MSBuildTask/Portable/BuildClientShim.cs
|
src/Compilers/Core/MSBuildTask/Portable/BuildClientShim.cs
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CommandLine;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.BuildTasks
{
internal static class BuildClientShim
{
public static Task<BuildResponse> RunServerCompilation(
RequestLanguage language,
List<string> arguments,
BuildPaths buildPaths,
string keepAlive,
string libEnvVariable,
CancellationToken cancellationToken) => Task.FromResult<BuildResponse>(null);
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CommandLine;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.BuildTasks
{
internal static class BuildClientShim
{
public static Task<BuildResponse> RunServerCompilation(
RequestLanguage language,
List<string> arguments,
BuildPaths buildPaths,
string keepAlive,
string libEnvVariable,
CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
}
}
|
mit
|
C#
|
9802d8ab1133d33e267afcb173efac0da82579e0
|
Rename setting
|
EVAST9919/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,johnneijzen/osu,smoogipooo/osu,UselessToucan/osu,2yangk23/osu,peppy/osu,NeoAdonis/osu,johnneijzen/osu,ppy/osu,ppy/osu,ZLima12/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,2yangk23/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,ZLima12/osu
|
osu.Game.Rulesets.Osu/UI/OsuSettingsSubsection.cs
|
osu.Game.Rulesets.Osu/UI/OsuSettingsSubsection.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Osu.Configuration;
namespace osu.Game.Rulesets.Osu.UI
{
public class OsuSettingsSubsection : RulesetSettingsSubsection
{
protected override string Header => "osu!";
public OsuSettingsSubsection(Ruleset ruleset)
: base(ruleset)
{
}
[BackgroundDependencyLoader]
private void load()
{
var config = (OsuRulesetConfigManager)Config;
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = "Snaking in sliders",
Bindable = config.GetBindable<bool>(OsuRulesetSetting.SnakingInSliders)
},
new SettingsCheckbox
{
LabelText = "Snaking out sliders",
Bindable = config.GetBindable<bool>(OsuRulesetSetting.SnakingOutSliders)
},
new SettingsCheckbox
{
LabelText = "Cursor trail",
Bindable = config.GetBindable<bool>(OsuRulesetSetting.ShowCursorTrail)
},
};
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Osu.Configuration;
namespace osu.Game.Rulesets.Osu.UI
{
public class OsuSettingsSubsection : RulesetSettingsSubsection
{
protected override string Header => "osu!";
public OsuSettingsSubsection(Ruleset ruleset)
: base(ruleset)
{
}
[BackgroundDependencyLoader]
private void load()
{
var config = (OsuRulesetConfigManager)Config;
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = "Snaking in sliders",
Bindable = config.GetBindable<bool>(OsuRulesetSetting.SnakingInSliders)
},
new SettingsCheckbox
{
LabelText = "Snaking out sliders",
Bindable = config.GetBindable<bool>(OsuRulesetSetting.SnakingOutSliders)
},
new SettingsCheckbox
{
LabelText = "Show cursor trail",
Bindable = config.GetBindable<bool>(OsuRulesetSetting.ShowCursorTrail)
},
};
}
}
}
|
mit
|
C#
|
c409b893f67780dbf0a85774094e26c9c6b53109
|
Update comments for ServiceName property in ZipkinExporterOptions (#1539)
|
open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet
|
src/OpenTelemetry.Exporter.Zipkin/ZipkinExporterOptions.cs
|
src/OpenTelemetry.Exporter.Zipkin/ZipkinExporterOptions.cs
|
// <copyright file="ZipkinExporterOptions.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// 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.
// </copyright>
using System;
using System.Diagnostics;
namespace OpenTelemetry.Exporter.Zipkin
{
/// <summary>
/// Zipkin trace exporter options.
/// </summary>
public sealed class ZipkinExporterOptions
{
internal const string DefaultServiceName = "OpenTelemetry Exporter";
#if !NET452
internal const int DefaultMaxPayloadSizeInBytes = 4096;
#endif
/// <summary>
/// Gets or sets the name of the service reporting telemetry. If the `Resource` associated with the telemetry
/// has "service.name" defined, then it'll be preferred over this option.
/// </summary>
public string ServiceName { get; set; } = DefaultServiceName;
/// <summary>
/// Gets or sets Zipkin endpoint address. See https://zipkin.io/zipkin-api/#/default/post_spans.
/// Typically https://zipkin-server-name:9411/api/v2/spans.
/// </summary>
public Uri Endpoint { get; set; } = new Uri("http://localhost:9411/api/v2/spans");
/// <summary>
/// Gets or sets a value indicating whether short trace id should be used.
/// </summary>
public bool UseShortTraceIds { get; set; }
#if !NET452
/// <summary>
/// Gets or sets the maximum payload size in bytes. Default value: 4096.
/// </summary>
public int? MaxPayloadSizeInBytes { get; set; } = DefaultMaxPayloadSizeInBytes;
#endif
/// <summary>
/// Gets or sets the export processor type to be used with Zipkin Exporter.
/// </summary>
public ExportProcessorType ExportProcessorType { get; set; } = ExportProcessorType.Batch;
/// <summary>
/// Gets or sets the BatchExportProcessor options. Ignored unless ExportProcessorType is BatchExporter.
/// </summary>
public BatchExportProcessorOptions<Activity> BatchExportProcessorOptions { get; set; } = new BatchExportProcessorOptions<Activity>();
}
}
|
// <copyright file="ZipkinExporterOptions.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// 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.
// </copyright>
using System;
using System.Diagnostics;
namespace OpenTelemetry.Exporter.Zipkin
{
/// <summary>
/// Zipkin trace exporter options.
/// </summary>
public sealed class ZipkinExporterOptions
{
internal const string DefaultServiceName = "OpenTelemetry Exporter";
#if !NET452
internal const int DefaultMaxPayloadSizeInBytes = 4096;
#endif
/// <summary>
/// Gets or sets the name of the service reporting telemetry.
/// </summary>
public string ServiceName { get; set; } = DefaultServiceName;
/// <summary>
/// Gets or sets Zipkin endpoint address. See https://zipkin.io/zipkin-api/#/default/post_spans.
/// Typically https://zipkin-server-name:9411/api/v2/spans.
/// </summary>
public Uri Endpoint { get; set; } = new Uri("http://localhost:9411/api/v2/spans");
/// <summary>
/// Gets or sets a value indicating whether short trace id should be used.
/// </summary>
public bool UseShortTraceIds { get; set; }
#if !NET452
/// <summary>
/// Gets or sets the maximum payload size in bytes. Default value: 4096.
/// </summary>
public int? MaxPayloadSizeInBytes { get; set; } = DefaultMaxPayloadSizeInBytes;
#endif
/// <summary>
/// Gets or sets the export processor type to be used with Zipkin Exporter.
/// </summary>
public ExportProcessorType ExportProcessorType { get; set; } = ExportProcessorType.Batch;
/// <summary>
/// Gets or sets the BatchExportProcessor options. Ignored unless ExportProcessorType is BatchExporter.
/// </summary>
public BatchExportProcessorOptions<Activity> BatchExportProcessorOptions { get; set; } = new BatchExportProcessorOptions<Activity>();
}
}
|
apache-2.0
|
C#
|
c130400cb502ec002c8919e8996e693eb505552e
|
Set PATH to influence DLL load path
|
boumenot/Wapiti.NET
|
src/Wapiti/Wapiti.cs
|
src/Wapiti/Wapiti.cs
|
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
namespace Wapiti
{
public class Wapiti
{
static Wapiti()
{
Wapiti.SetPathForNativeDllResolution();
}
private static string GetExecutingAssemblyPath()
{
var assemblyFullName = new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath;
var assemblyPath = Path.GetDirectoryName(assemblyFullName);
return assemblyPath;
}
private static void SetPathForNativeDllResolution()
{
if (IntPtr.Size != 8)
{
const string message = "Wapiti.NET only support 64-bit processes!";
throw new ArgumentOutOfRangeException(message);
}
var assemblyPath = Wapiti.GetExecutingAssemblyPath();
var nativeDllPath = Path.Combine(assemblyPath, "native", "x64");
const string PATH = "PATH";
var newPath = string.Format("{0};{1}",
nativeDllPath,
Environment.GetEnvironmentVariable(PATH));
Environment.SetEnvironmentVariable(PATH, newPath);
}
private Wapiti() {}
public string Label(WapitiModel model, string path)
{
using (var stream = File.OpenRead(path))
{
return this.Label(model, stream);
}
}
public string Label(WapitiModel model, Stream stream)
{
var lines = new StreamReader(stream).ReadAllLines();
return this.Label(model, lines);
}
public string Label(WapitiModel model, string[] lines)
{
int i = 0;
WapitiNative.gets_cb gets_cb = () => i >= lines.Length ? null : lines[i++];
var sb = new StringBuilder();
WapitiNative.write_cb write_cb = (ptr, length) =>
{
byte[] strbuf = new byte[length];
Marshal.Copy(ptr, strbuf, 0, length);
var data = Encoding.UTF8.GetString(strbuf);
WapitiNative.xfree(ptr);
sb.Append(data);
};
var iol = WapitiNative.iol_new3(gets_cb, write_cb);
WapitiNative.tag_label(model.Model, iol);
WapitiNative.iol_free(iol);
return sb.ToString();
}
public static Wapiti Create()
{
return new Wapiti();
}
}
}
|
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Wapiti
{
public class Wapiti
{
private Wapiti() {}
public string Label(WapitiModel model, string path)
{
using (var stream = File.OpenRead(path))
{
return this.Label(model, stream);
}
}
public string Label(WapitiModel model, Stream stream)
{
var lines = new StreamReader(stream).ReadAllLines();
return this.Label(model, lines);
}
public string Label(WapitiModel model, string[] lines)
{
int i = 0;
WapitiNative.gets_cb gets_cb = () => i >= lines.Length ? null : lines[i++];
var sb = new StringBuilder();
WapitiNative.write_cb write_cb = (ptr, length) =>
{
byte[] strbuf = new byte[length];
Marshal.Copy(ptr, strbuf, 0, length);
var data = Encoding.UTF8.GetString(strbuf);
WapitiNative.xfree(ptr);
sb.Append(data);
};
var iol = WapitiNative.iol_new3(gets_cb, write_cb);
WapitiNative.tag_label(model.Model, iol);
WapitiNative.iol_free(iol);
return sb.ToString();
}
public static Wapiti Create()
{
return new Wapiti();
}
}
}
|
apache-2.0
|
C#
|
964ff36c2a3a4816b4bc78ebc5bf274ced9854e1
|
Fix copy/paste bug related to changeset a06f6c6cd5ab
|
burningice2866/CompositeC1Contrib.Email,burningice2866/CompositeC1Contrib.Email
|
Email/C1Console/Workflows/EditConfigurableSystemNetMailClientQueueWorkflow.cs
|
Email/C1Console/Workflows/EditConfigurableSystemNetMailClientQueueWorkflow.cs
|
using System;
using System.Collections.Generic;
using System.Net.Mail;
namespace CompositeC1Contrib.Email.C1Console.Workflows
{
public sealed class EditConfigurableSystemNetMailClientQueueWorkflow : EditMailQueueWorkflow
{
public EditConfigurableSystemNetMailClientQueueWorkflow() : base("\\InstalledPackages\\CompositeC1Contrib.Email\\EditConfigurableSystemNetMailClientQueue.xml") { }
public static IEnumerable<string> GetNetworkDeliveryOptions()
{
return Enum.GetNames(typeof(SmtpDeliveryMethod));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Mail;
using Composite.C1Console.Workflow;
namespace CompositeC1Contrib.Email.C1Console.Workflows
{
[AllowPersistingWorkflow(WorkflowPersistingType.Idle)]
public sealed class EditConfigurableSystemNetMailClientQueueWorkflow : EditMailQueueWorkflow
{
public EditConfigurableSystemNetMailClientQueueWorkflow() : base("\\InstalledPackages\\CompositeC1Contrib.Email\\EditConfigurableSystemNetMailClientQueue.xml") { }
public static IEnumerable<string> GetNetworkDeliveryOptions()
{
return Enum.GetNames(typeof(SmtpDeliveryMethod));
}
}
}
|
mit
|
C#
|
d7bf46072312dd0c6f270b11c29fd37134b0b134
|
Update AbpCoreEf6SampleEntityFrameworkModule.cs
|
aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples,aspnetboilerplate/aspnetboilerplate-samples
|
AbpCoreEf6Sample/aspnet-core/src/AbpCoreEf6Sample.EntityFrameworkCore/EntityFrameworkCore/AbpCoreEf6SampleEntityFrameworkModule.cs
|
AbpCoreEf6Sample/aspnet-core/src/AbpCoreEf6Sample.EntityFrameworkCore/EntityFrameworkCore/AbpCoreEf6SampleEntityFrameworkModule.cs
|
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Zero.EntityFramework;
using System.Data.Entity;
namespace AbpCoreEf6Sample.EntityFrameworkCore
{
[DependsOn(
typeof(AbpCoreEf6SampleCoreModule),
typeof(AbpZeroCoreEntityFrameworkModule))]
public class AbpCoreEf6SampleEntityFrameworkModule : AbpModule
{
public override void PreInitialize()
{
Database.SetInitializer(new CreateDatabaseIfNotExists<AbpCoreEf6SampleDbContext>());
Configuration.DefaultNameOrConnectionString = "Default";
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(AbpCoreEf6SampleEntityFrameworkModule).GetAssembly());
}
}
}
|
using Abp.EntityFrameworkCore.Configuration;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Zero.EntityFramework;
using AbpCoreEf6Sample.EntityFrameworkCore.Seed;
namespace AbpCoreEf6Sample.EntityFrameworkCore
{
[DependsOn(
typeof(AbpCoreEf6SampleCoreModule),
typeof(AbpZeroCoreEntityFrameworkCoreModule))]
public class AbpCoreEf6SampleEntityFrameworkModule : AbpModule
{
/* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */
public bool SkipDbContextRegistration { get; set; }
public bool SkipDbSeed { get; set; }
public override void PreInitialize()
{
if (!SkipDbContextRegistration)
{
Configuration.Modules.AbpEfCore().AddDbContext<AbpCoreEf6SampleDbContext>(options =>
{
if (options.ExistingConnection != null)
{
AbpCoreEf6SampleDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
}
else
{
AbpCoreEf6SampleDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
}
});
}
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(AbpCoreEf6SampleEntityFrameworkModule).GetAssembly());
}
public override void PostInitialize()
{
if (!SkipDbSeed)
{
SeedHelper.SeedHostDb(IocManager);
}
}
}
}
|
mit
|
C#
|
66112e6b391bf56d3d3e5bb398a3f392b20a09bf
|
Fix bug with test cases not working with different timezone
|
stranne/Vasttrafik.NET,stranne/Vasttrafik.NET
|
src/Stranne.VasttrafikNET.Tests/JsonParsing/HistoricalAvailabilityJsonTest.cs
|
src/Stranne.VasttrafikNET.Tests/JsonParsing/HistoricalAvailabilityJsonTest.cs
|
using System;
using System.Collections.Generic;
using Stranne.VasttrafikNET.ApiModels.CommuterParking;
using Stranne.VasttrafikNET.Tests.Json;
using Xunit;
namespace Stranne.VasttrafikNET.Tests.JsonParsing
{
public class HistoricalAvailabilityJsonTest : BaseJsonTest
{
protected override string Json => HistoricalAvailabilityJson.Json;
public static TheoryData TestParameters => new TheoryData<string, object>
{
{ "", 5 },
{ "[0].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 8, 0, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"), TimeZoneInfo.Local) },
{ "[0].FreeSpaces",79 },
{ "[1].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 8, 15, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"), TimeZoneInfo.Local) },
{ "[1].FreeSpaces", 78 },
{ "[2].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 8, 30, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"), TimeZoneInfo.Local) },
{ "[2].FreeSpaces", 71 },
{ "[3].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 8, 45, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"), TimeZoneInfo.Local) },
{ "[3].FreeSpaces", 70 },
{ "[4].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 9, 0, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time"), TimeZoneInfo.Local) },
{ "[4].FreeSpaces", 67 }
};
[Theory, MemberData(nameof(TestParameters))]
public void HistoricalAvailabilityJsonParsing(string property, object expected)
{
TestValue<IEnumerable<HistoricalAvailability>>(property, expected);
}
}
}
|
using System;
using System.Collections.Generic;
using Stranne.VasttrafikNET.ApiModels.CommuterParking;
using Stranne.VasttrafikNET.Tests.Json;
using Xunit;
namespace Stranne.VasttrafikNET.Tests.JsonParsing
{
public class HistoricalAvailabilityJsonTest : BaseJsonTest
{
protected override string Json => HistoricalAvailabilityJson.Json;
public static TheoryData TestParameters => new TheoryData<string, object>
{
{ "", 5 },
{ "[0].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 8, 0, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")) },
{ "[0].FreeSpaces",79 },
{ "[1].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 8, 15, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")) },
{ "[1].FreeSpaces", 78 },
{ "[2].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 8, 30, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")) },
{ "[2].FreeSpaces", 71 },
{ "[3].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 8, 45, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")) },
{ "[3].FreeSpaces", 70 },
{ "[4].DateTime", TimeZoneInfo.ConvertTime(new DateTime(2016, 8, 1, 9, 0, 0), TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")) },
{ "[4].FreeSpaces", 67 }
};
[Theory, MemberData(nameof(TestParameters))]
public void HistoricalAvailabilityJsonParsing(string property, object expected)
{
TestValue<IEnumerable<HistoricalAvailability>>(property, expected);
}
}
}
|
mit
|
C#
|
8f6baad5c3bf9737447c41c20ff88beac274004f
|
Revert `IUniform` accessibility change
|
peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework
|
osu.Framework/Graphics/Shaders/IUniform.cs
|
osu.Framework/Graphics/Shaders/IUniform.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 disable
namespace osu.Framework.Graphics.Shaders
{
/// <summary>
/// Represents an updateable shader uniform.
/// </summary>
internal interface IUniform
{
/// <summary>
/// The shader which this uniform was declared in.
/// </summary>
IShader Owner { get; }
/// <summary>
/// The name of this uniform as declared by the shader, or <see cref="GlobalPropertyManager"/> for global uniforms.
/// </summary>
string Name { get; }
/// <summary>
/// The location of this uniform in relation to all other uniforms in the shader.
/// </summary>
/// <remarks>
/// Depending on the renderer used, this could either be zero-based index number or location in bytes.
/// </remarks>
int Location { get; }
/// <summary>
/// Updates the renderer with the current value of this uniform.
/// </summary>
void Update();
}
}
|
// 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 disable
namespace osu.Framework.Graphics.Shaders
{
/// <summary>
/// Represents an updateable shader uniform.
/// </summary>
public interface IUniform
{
/// <summary>
/// The shader which this uniform was declared in.
/// </summary>
IShader Owner { get; }
/// <summary>
/// The name of this uniform as declared by the shader, or <see cref="GlobalPropertyManager"/> for global uniforms.
/// </summary>
string Name { get; }
/// <summary>
/// The location of this uniform in relation to all other uniforms in the shader.
/// </summary>
/// <remarks>
/// Depending on the renderer used, this could either be zero-based index number or location in bytes.
/// </remarks>
int Location { get; }
/// <summary>
/// Updates the renderer with the current value of this uniform.
/// </summary>
void Update();
}
}
|
mit
|
C#
|
f6cb97fa6a0bdea8f2e7c442733a3a8f5c92228f
|
Add missing content for the Nubbin
|
ethanmoffat/EndlessClient
|
EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs
|
EndlessClient/Rendering/Chat/ChatBubbleTextureProvider.cs
|
// Original Work Copyright (c) Ethan Moffat 2014-2017
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Collections.Generic;
using EndlessClient.Content;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace EndlessClient.Rendering.Chat
{
public class ChatBubbleTextureProvider : IChatBubbleTextureProvider
{
private readonly IContentManagerProvider _contentManagerProvider;
private readonly Dictionary<ChatBubbleTexture, Texture2D> _chatBubbleTextures;
public IReadOnlyDictionary<ChatBubbleTexture, Texture2D> ChatBubbleTextures => _chatBubbleTextures;
public ChatBubbleTextureProvider(IContentManagerProvider contentManagerProvider)
{
_contentManagerProvider = contentManagerProvider;
_chatBubbleTextures = new Dictionary<ChatBubbleTexture, Texture2D>();
}
public void LoadContent()
{
_chatBubbleTextures.Add(ChatBubbleTexture.TopLeft, Content.Load<Texture2D>("ChatBubble\\TL"));
_chatBubbleTextures.Add(ChatBubbleTexture.TopMiddle, Content.Load<Texture2D>("ChatBubble\\TM"));
_chatBubbleTextures.Add(ChatBubbleTexture.TopRight, Content.Load<Texture2D>("ChatBubble\\TR"));
_chatBubbleTextures.Add(ChatBubbleTexture.MiddleLeft, Content.Load<Texture2D>("ChatBubble\\ML"));
_chatBubbleTextures.Add(ChatBubbleTexture.MiddleMiddle, Content.Load<Texture2D>("ChatBubble\\MM"));
_chatBubbleTextures.Add(ChatBubbleTexture.MiddleRight, Content.Load<Texture2D>("ChatBubble\\MR"));
//todo: change the first 'R' to a 'B' (for bottom)
_chatBubbleTextures.Add(ChatBubbleTexture.BottomLeft, Content.Load<Texture2D>("ChatBubble\\RL"));
_chatBubbleTextures.Add(ChatBubbleTexture.BottomMiddle, Content.Load<Texture2D>("ChatBubble\\RM"));
_chatBubbleTextures.Add(ChatBubbleTexture.BottomRight, Content.Load<Texture2D>("ChatBubble\\RR"));
_chatBubbleTextures.Add(ChatBubbleTexture.Nubbin, Content.Load<Texture2D>("ChatBubble\\NUB"));
}
private ContentManager Content => _contentManagerProvider.Content;
}
public interface IChatBubbleTextureProvider
{
IReadOnlyDictionary<ChatBubbleTexture, Texture2D> ChatBubbleTextures { get; }
void LoadContent();
}
}
|
// Original Work Copyright (c) Ethan Moffat 2014-2017
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Collections.Generic;
using EndlessClient.Content;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace EndlessClient.Rendering.Chat
{
public class ChatBubbleTextureProvider : IChatBubbleTextureProvider
{
private readonly IContentManagerProvider _contentManagerProvider;
private readonly Dictionary<ChatBubbleTexture, Texture2D> _chatBubbleTextures;
public IReadOnlyDictionary<ChatBubbleTexture, Texture2D> ChatBubbleTextures => _chatBubbleTextures;
public ChatBubbleTextureProvider(IContentManagerProvider contentManagerProvider)
{
_contentManagerProvider = contentManagerProvider;
_chatBubbleTextures = new Dictionary<ChatBubbleTexture, Texture2D>();
}
public void LoadContent()
{
_chatBubbleTextures.Add(ChatBubbleTexture.TopLeft, Content.Load<Texture2D>("ChatBubble\\TL"));
_chatBubbleTextures.Add(ChatBubbleTexture.TopMiddle, Content.Load<Texture2D>("ChatBubble\\TM"));
_chatBubbleTextures.Add(ChatBubbleTexture.TopRight, Content.Load<Texture2D>("ChatBubble\\TR"));
_chatBubbleTextures.Add(ChatBubbleTexture.MiddleLeft, Content.Load<Texture2D>("ChatBubble\\ML"));
_chatBubbleTextures.Add(ChatBubbleTexture.MiddleMiddle, Content.Load<Texture2D>("ChatBubble\\MM"));
_chatBubbleTextures.Add(ChatBubbleTexture.MiddleRight, Content.Load<Texture2D>("ChatBubble\\MR"));
//todo: change the first 'R' to a 'B' (for bottom)
_chatBubbleTextures.Add(ChatBubbleTexture.BottomLeft, Content.Load<Texture2D>("ChatBubble\\RL"));
_chatBubbleTextures.Add(ChatBubbleTexture.BottomMiddle, Content.Load<Texture2D>("ChatBubble\\RM"));
_chatBubbleTextures.Add(ChatBubbleTexture.BottomRight, Content.Load<Texture2D>("ChatBubble\\RR"));
}
private ContentManager Content => _contentManagerProvider.Content;
}
public interface IChatBubbleTextureProvider
{
IReadOnlyDictionary<ChatBubbleTexture, Texture2D> ChatBubbleTextures { get; }
void LoadContent();
}
}
|
mit
|
C#
|
b6e464f873a2b8ff06b4c33630c55199e25f19f2
|
Fix issue with skidmarks.
|
jongallant/CarSimulator
|
Assets/Scripts/Tire.cs
|
Assets/Scripts/Tire.cs
|
using UnityEngine;
public class Tire : MonoBehaviour {
public float RestingWeight { get; set; }
public float ActiveWeight { get; set; }
public float Grip { get; set; }
public float FrictionForce { get; set; }
public float AngularVelocity { get; set; }
public float Torque { get; set; }
public float Radius = 0.5f;
float TrailDuration = 5;
bool TrailActive;
GameObject Skidmark;
public void SetTrailActive(bool active) {
if (active && !TrailActive) {
// These should be pooled and re-used
Skidmark = GameObject.Instantiate (Resources.Load ("Skidmark") as GameObject);
//Fix issue where skidmarks draw at 0,0,0 at slow speeds
Skidmark.GetComponent<TrailRenderer>().Clear();
Skidmark.GetComponent<TrailRenderer> ().time = TrailDuration;
Skidmark.GetComponent<TrailRenderer> ().sortingOrder = 0;
Skidmark.transform.parent = this.transform;
Skidmark.transform.localPosition = Vector2.zero;
} else if (!active && TrailActive) {
Skidmark.transform.parent = null;
GameObject.Destroy (Skidmark.gameObject, TrailDuration);
}
TrailActive = active;
}
}
|
using UnityEngine;
public class Tire : MonoBehaviour {
public float RestingWeight { get; set; }
public float ActiveWeight { get; set; }
public float Grip { get; set; }
public float FrictionForce { get; set; }
public float AngularVelocity { get; set; }
public float Torque { get; set; }
public float Radius = 0.5f;
float TrailDuration = 5;
bool TrailActive;
GameObject Skidmark;
public void SetTrailActive(bool active) {
if (active && !TrailActive) {
// These should be pooled and re-used
Skidmark = GameObject.Instantiate (Resources.Load ("Skidmark") as GameObject);
Skidmark.GetComponent<TrailRenderer> ().time = TrailDuration;
Skidmark.GetComponent<TrailRenderer> ().sortingOrder = 0;
Skidmark.transform.parent = this.transform;
Skidmark.transform.localPosition = Vector2.zero;
} else if (!active && TrailActive) {
Skidmark.transform.parent = null;
GameObject.Destroy (Skidmark.gameObject, TrailDuration);
}
TrailActive = active;
}
}
|
mit
|
C#
|
5fb6ff6bd5b969ddb8cbb81997906564b1cd2ba9
|
increase version
|
tinohager/Nager.AmazonProductAdvertising,tinohager/Nager.AmazonProductAdvertising
|
Nager.AmazonProductAdvertising/Properties/AssemblyInfo.cs
|
Nager.AmazonProductAdvertising/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("Nager.AmazonProductAdvertising")]
[assembly: AssemblyDescription("Amazon ProductAdvertising")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("nager.at")]
[assembly: AssemblyProduct("Nager.AmazonProductAdvertising")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("026a9ee3-9a48-48a1-9026-1573f2e8a85e")]
// 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.18.0")]
[assembly: AssemblyFileVersion("1.0.18.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("Nager.AmazonProductAdvertising")]
[assembly: AssemblyDescription("Amazon ProductAdvertising")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("nager.at")]
[assembly: AssemblyProduct("Nager.AmazonProductAdvertising")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("026a9ee3-9a48-48a1-9026-1573f2e8a85e")]
// 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.17.0")]
[assembly: AssemblyFileVersion("1.0.17.0")]
|
mit
|
C#
|
72a9b01e842cee71bc46bdf1ce761d7cb3833ad0
|
Remove unused code
|
blaise-braye/my-accounts
|
Operations.Classification.WpfUi.Tests/Accounts/Wrapper.cs
|
Operations.Classification.WpfUi.Tests/Accounts/Wrapper.cs
|
namespace Operations.Classification.WpfUi.Tests.Accounts
{
/// <summary>
/// this wrapper is used as a trick to fool the test explorer.
/// Without this mecanism, some tests could be written with the autofixture style
/// </summary>
/// <typeparam name="T"></typeparam>
public class Wrapper<T>
{
public T Value { get; }
public Wrapper(T value)
{
Value = value;
}
public override string ToString()
{
return typeof(T).ToString();
}
public static implicit operator T(Wrapper<T> wrapper)
{
return wrapper.Value;
}
}
}
|
namespace Operations.Classification.WpfUi.Tests.Accounts
{
public class Wrapper<T>
{
public T Value { get; }
public Wrapper(T value)
{
Value = value;
}
public override string ToString()
{
return typeof(T).ToString();
}
public static implicit operator Wrapper<T>(T val)
{
return new Wrapper<T>(val);
}
public static implicit operator T(Wrapper<T> wrapper)
{
return wrapper.Value;
}
}
}
|
mit
|
C#
|
3aadcba27e92bc3714102bd0d5961cc34b9e0304
|
Include isasync
|
FlorianRappl/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp
|
AngleSharp/Html/LinkRels/ImportLinkRelation.cs
|
AngleSharp/Html/LinkRels/ImportLinkRelation.cs
|
namespace AngleSharp.Html.LinkRels
{
using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using AngleSharp.Extensions;
using AngleSharp.Network;
using AngleSharp.Parser.Html;
using System;
using System.Threading;
using System.Threading.Tasks;
class ImportLinkRelation : BaseLinkRelation
{
#region Fields
IDocument _import;
#endregion
#region ctor
public ImportLinkRelation(IHtmlLinkElement link)
: base(link)
{
}
#endregion
#region Properties
public IDocument Import
{
get { return _import; }
}
#endregion
#region Methods
public override async Task LoadAsync(IConfiguration configuration, IResourceLoader loader, CancellationToken cancel)
{
var link = Link;
var request = link.CreateRequestFor(Url);
var isasync = link.HasAttribute(AttributeNames.Async);
using (var response = await loader.FetchAsync(request, cancel).ConfigureAwait(false))
{
if (response != null)
{
var parser = new HtmlParser(configuration);
_import = await parser.ParseAsync(response.Content, cancel).ConfigureAwait(false);
}
}
}
#endregion
}
}
|
namespace AngleSharp.Html.LinkRels
{
using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using AngleSharp.Extensions;
using AngleSharp.Network;
using AngleSharp.Parser.Html;
using System.Threading;
using System.Threading.Tasks;
class ImportLinkRelation : BaseLinkRelation
{
#region Fields
IDocument _import;
#endregion
#region ctor
public ImportLinkRelation(IHtmlLinkElement link)
: base(link)
{
}
#endregion
#region Properties
public IDocument Import
{
get { return _import; }
}
#endregion
#region Methods
public override async Task LoadAsync(IConfiguration configuration, IResourceLoader loader, CancellationToken cancel)
{
var link = Link;
var request = link.CreateRequestFor(Url);
using (var response = await loader.FetchAsync(request, cancel).ConfigureAwait(false))
{
if (response != null)
{
var parser = new HtmlParser(configuration);
_import = await parser.ParseAsync(response.Content, cancel).ConfigureAwait(false);
}
}
}
#endregion
}
}
|
mit
|
C#
|
2415201cb611745a8556c4410695289b0d517a8c
|
Rename vars
|
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
|
R7.University/Commands/UpdateEduProgramDivisionCommand.cs
|
R7.University/Commands/UpdateEduProgramDivisionCommand.cs
|
using System.Collections.Generic;
using R7.Dnn.Extensions.Models;
using R7.University.EditModels;
using R7.University.ModelExtensions;
using R7.University.Models;
namespace R7.University.Commands
{
public class UpdateEduProgramDivisionsCommand
{
protected readonly IModelContext ModelContext;
public UpdateEduProgramDivisionsCommand (IModelContext modelContext)
{
ModelContext = modelContext;
}
public void Update (IEnumerable<IEditModel<EduProgramDivisionInfo>> epDivs, ModelType modelType, int itemId)
{
foreach (var epDiv in epDivs) {
var epd = epDiv.CreateModel ();
switch (epDiv.EditState) {
case ModelEditState.Added:
epd.SetModelId (modelType, itemId);
ModelContext.Add (epd);
break;
case ModelEditState.Modified:
ModelContext.UpdateExternal (epd);
break;
case ModelEditState.Deleted:
ModelContext.RemoveExternal (epd);
break;
}
}
}
}
}
|
//
// UpdateEduProgramDivisionsCommand.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2017-2018 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System.Collections.Generic;
using R7.Dnn.Extensions.Models;
using R7.University.EditModels;
using R7.University.ModelExtensions;
using R7.University.Models;
namespace R7.University.Commands
{
public class UpdateEduProgramDivisionsCommand
{
protected readonly IModelContext ModelContext;
public UpdateEduProgramDivisionsCommand (IModelContext modelContext)
{
ModelContext = modelContext;
}
public void Update (IEnumerable<IEditModel<EduProgramDivisionInfo>> epDocs, ModelType modelType, int itemId)
{
foreach (var epDoc in epDocs) {
var epd = epDoc.CreateModel ();
switch (epDoc.EditState) {
case ModelEditState.Added:
epd.SetModelId (modelType, itemId);
ModelContext.Add (epd);
break;
case ModelEditState.Modified:
ModelContext.UpdateExternal (epd);
break;
case ModelEditState.Deleted:
ModelContext.RemoveExternal (epd);
break;
}
}
}
}
}
|
agpl-3.0
|
C#
|
3a5813f0e305a7661b9daf388140585b7b162f30
|
Update class that was missed in the last commit
|
peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype
|
src/Glimpse.Agent.AspNet.Mvc/Messages/AfterActionMessage.cs
|
src/Glimpse.Agent.AspNet.Mvc/Messages/AfterActionMessage.cs
|
namespace Glimpse.Agent.AspNet.Mvc.Messages
{
public class AfterActionMessage
{
public string ActionId { get; set; }
public Timing Timing { get; set; }
}
}
|
namespace Glimpse.Agent.AspNet.Mvc.Messages
{
public class ActionInvokedMessage
{
public string ActionId { get; set; }
public Timing Timing { get; set; }
}
}
|
mit
|
C#
|
72c01439185b3ec9e50a160920ee56df892189ef
|
Add check for BGA
|
fanoI/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,zarlo/Cosmos,tgiphil/Cosmos,jp2masa/Cosmos,jp2masa/Cosmos,fanoI/Cosmos,trivalik/Cosmos,fanoI/Cosmos,tgiphil/Cosmos,zarlo/Cosmos,trivalik/Cosmos,CosmosOS/Cosmos,trivalik/Cosmos,jp2masa/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,tgiphil/Cosmos
|
source/Cosmos.HAL/Drivers/VBEDriver.cs
|
source/Cosmos.HAL/Drivers/VBEDriver.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cosmos.HAL.Drivers
{
public class VBEDriver
{
private Core.IOGroup.VBE IO = Core.Global.BaseIOGroups.VBE;
private void vbe_write(ushort index, ushort value)
{
IO.VbeIndex.Word = index;
IO.VbeData.Word = value;
}
public void vbe_set(ushort xres, ushort yres, ushort bpp)
{
if (Cosmos.HAL.PCI.GetDevice(1234, 1111) == null){
throw new Exception("No BGA adapter found..");
}
//Disable Display
vbe_write(0x4, 0x00);
//Set Display Xres
vbe_write(0x1, xres);
//SetDisplay Yres
vbe_write(0x2, yres);
//SetDisplay bpp
vbe_write(0x3, bpp);
//Enable Display and LFB
vbe_write(0x4, (ushort)(0x01 | 0x40));
}
public void set_vram(uint index, byte value)
{
IO.VGAMemoryBlock[index] = value;
}
public byte get_vram(uint index)
{
return IO.VGAMemoryBlock[index];
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cosmos.HAL.Drivers
{
public class VBEDriver
{
private Core.IOGroup.VBE IO = Core.Global.BaseIOGroups.VBE;
private void vbe_write(ushort index, ushort value)
{
IO.VbeIndex.Word = index;
IO.VbeData.Word = value;
}
public void vbe_set(ushort xres, ushort yres, ushort bpp)
{
//Disable Display
vbe_write(0x4, 0x00);
//Set Display Xres
vbe_write(0x1, xres);
//SetDisplay Yres
vbe_write(0x2, yres);
//SetDisplay bpp
vbe_write(0x3, bpp);
//Enable Display and LFB
vbe_write(0x4, (ushort)(0x01 | 0x40));
}
public void set_vram(uint index, byte value)
{
IO.VGAMemoryBlock[index] = value;
}
public byte get_vram(uint index)
{
return IO.VGAMemoryBlock[index];
}
}
}
|
bsd-3-clause
|
C#
|
5038c6241efe904f65dcb0578bc704c1bc70ab24
|
Fix the ugly checkbox
|
LodewijkSioen/ExitStrategy,LodewijkSioen/ExitStrategy
|
src/TestWebsite/Views/Shared/EditorTemplates/Boolean.cshtml
|
src/TestWebsite/Views/Shared/EditorTemplates/Boolean.cshtml
|
@model Boolean?
<div class="checkbox">
<label>
@Html.CheckBox("", @Model.GetValueOrDefault(false))
</label>
</div>
|
@model Boolean?
<label>
@Html.CheckBox("", @Model.GetValueOrDefault(false), new {@class="form-control check-box checkbox-inline"})
</label>
|
mit
|
C#
|
45a6db2f799cf4e3909a33958e63be9858db517a
|
Bump version.
|
bchavez/SharpFlame,bchavez/SharpFlame
|
source/SharpFlame/Constants.cs
|
source/SharpFlame/Constants.cs
|
internal static class Constants
{
public const string ProgramName = "SharpFlame";
public const string ProgramVersionNumber = "0.24";
#if Mono
public const string ProgramPlatform = "Mono 0.24";
#else
public const string ProgramPlatform = "Windows";
#endif
public const int PlayerCountMax = 10;
public const int GameTypeCount = 3;
public const int DefaultHeightMultiplier = 2;
public const int MinimapDelay = 100;
public const int SectorTileSize = 8;
public const int MaxDroidWeapons = 3;
public const int WzMapMaxSize = 250;
public const int MapMaxSize = 512;
public const int MinimapMaxSize = 512;
public const int INIRotationMax = 65536;
public const int TileTypeNum_Water = 7;
public const int TileTypeNum_Cliff = 8;
public const int TerrainGridSpacing = 128;
}
|
internal static class Constants
{
public const string ProgramName = "SharpFlame";
public const string ProgramVersionNumber = "0.23";
#if Mono
public const string ProgramPlatform = "Mono 0.23";
#else
public const string ProgramPlatform = "Windows";
#endif
public const int PlayerCountMax = 10;
public const int GameTypeCount = 3;
public const int DefaultHeightMultiplier = 2;
public const int MinimapDelay = 100;
public const int SectorTileSize = 8;
public const int MaxDroidWeapons = 3;
public const int WzMapMaxSize = 250;
public const int MapMaxSize = 512;
public const int MinimapMaxSize = 512;
public const int INIRotationMax = 65536;
public const int TileTypeNum_Water = 7;
public const int TileTypeNum_Cliff = 8;
public const int TerrainGridSpacing = 128;
}
|
mit
|
C#
|
fdcd03be21f8e6218cba43d34f633cf134c08c68
|
Fix feature FootprintY having FootprintX value
|
MHeasell/Mappy,MHeasell/Mappy
|
Mappy/Data/FeatureRecord.cs
|
Mappy/Data/FeatureRecord.cs
|
namespace Mappy.Data
{
using Mappy.Util;
using TAUtil.Tdf;
public class FeatureRecord
{
public string Name { get; set; }
public string World { get; set; }
public string Category { get; set; }
public int FootprintX { get; set; }
public int FootprintY { get; set; }
public string AnimFileName { get; set; }
public string SequenceName { get; set; }
public string ObjectName { get; set; }
public static FeatureRecord FromTdfNode(TdfNode n)
{
return new FeatureRecord
{
Name = n.Name,
World = n.Entries.GetOrDefault("world", string.Empty),
Category = n.Entries.GetOrDefault("category", string.Empty),
FootprintX = TdfConvert.ToInt32(n.Entries.GetOrDefault("footprintx", "0")),
FootprintY = TdfConvert.ToInt32(n.Entries.GetOrDefault("footprintz", "0")),
AnimFileName = n.Entries.GetOrDefault("filename", string.Empty),
SequenceName = n.Entries.GetOrDefault("seqname", string.Empty),
ObjectName = n.Entries.GetOrDefault("object", string.Empty)
};
}
}
}
|
namespace Mappy.Data
{
using Mappy.Util;
using TAUtil.Tdf;
public class FeatureRecord
{
public string Name { get; set; }
public string World { get; set; }
public string Category { get; set; }
public int FootprintX { get; set; }
public int FootprintY { get; set; }
public string AnimFileName { get; set; }
public string SequenceName { get; set; }
public string ObjectName { get; set; }
public static FeatureRecord FromTdfNode(TdfNode n)
{
return new FeatureRecord
{
Name = n.Name,
World = n.Entries.GetOrDefault("world", string.Empty),
Category = n.Entries.GetOrDefault("category", string.Empty),
FootprintX = TdfConvert.ToInt32(n.Entries.GetOrDefault("footprintx", "0")),
FootprintY = TdfConvert.ToInt32(n.Entries.GetOrDefault("footprintx", "0")),
AnimFileName = n.Entries.GetOrDefault("filename", string.Empty),
SequenceName = n.Entries.GetOrDefault("seqname", string.Empty),
ObjectName = n.Entries.GetOrDefault("object", string.Empty)
};
}
}
}
|
mit
|
C#
|
c193330a2d3fdffb5e0a3d760f8ddb8352366f51
|
Add missing '.' to /// comment
|
martincostello/api,martincostello/api,martincostello/api
|
src/API/Controllers/ErrorController.cs
|
src/API/Controllers/ErrorController.cs
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ErrorController.cs" company="https://martincostello.com/">
// Martin Costello (c) 2016
// </copyright>
// <summary>
// ErrorController.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace MartinCostello.Api.Controllers
{
using Microsoft.AspNetCore.Mvc;
/// <summary>
/// A class representing the controller for the <c>/error</c> resource.
/// </summary>
public class ErrorController : Controller
{
/// <summary>
/// Gets the view for the error page.
/// </summary>
/// <param name="id">The optional HTTP status code associated with the error.</param>
/// <returns>
/// The view for the error page.
/// </returns>
[HttpGet]
public IActionResult Index(int? id) => View("Error", id ?? 500);
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ErrorController.cs" company="https://martincostello.com/">
// Martin Costello (c) 2016
// </copyright>
// <summary>
// ErrorController.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace MartinCostello.Api.Controllers
{
using Microsoft.AspNetCore.Mvc;
/// <summary>
/// A class representing the controller for the <c>/error</c> resource.
/// </summary>
public class ErrorController : Controller
{
/// <summary>
/// Gets the view for the error page.
/// </summary>
/// <param name="id">The optional HTTP status code associated with the error</param>
/// <returns>
/// The view for the error page.
/// </returns>
[HttpGet]
public IActionResult Index(int? id) => View("Error", id ?? 500);
}
}
|
mit
|
C#
|
ec3ed56c700cf8a605426bd77b38543fa9420b47
|
Set environment variable configuration to the passed in parameter
|
appharbor/appharbor-cli
|
src/AppHarbor/Commands/LoginCommand.cs
|
src/AppHarbor/Commands/LoginCommand.cs
|
using System;
namespace AppHarbor.Commands
{
public class LoginCommand : ICommand
{
private readonly AppHarborApi _appHarborApi;
private readonly EnvironmentVariableConfiguration _environmentVariableConfiguration;
public LoginCommand(AppHarborApi appHarborApi, EnvironmentVariableConfiguration environmentVariableConfiguration)
{
_appHarborApi = appHarborApi;
_environmentVariableConfiguration = environmentVariableConfiguration;
}
public void Execute(string[] arguments)
{
Console.WriteLine("Username:");
var username = Console.ReadLine();
Console.WriteLine("Password:");
var password = Console.ReadLine();
}
}
}
|
using System;
namespace AppHarbor.Commands
{
public class LoginCommand : ICommand
{
private readonly AppHarborApi _appHarborApi;
private readonly EnvironmentVariableConfiguration _environmentVariableConfiguration;
public LoginCommand(AppHarborApi appHarborApi, EnvironmentVariableConfiguration environmentVariableConfiguration)
{
_appHarborApi = appHarborApi;
_environmentVariableConfiguration = _environmentVariableConfiguration;
}
public void Execute(string[] arguments)
{
Console.WriteLine("Username:");
var username = Console.ReadLine();
Console.WriteLine("Password:");
var password = Console.ReadLine();
}
}
}
|
mit
|
C#
|
6f5278f8cfb6907f2f2924a17392035b8f3a37d1
|
Fix Registry Name
|
Tulpep/Network-AutoSwitch
|
Tulpep.NetworkAutoSwitch.ProxyService/ManageProxyState.cs
|
Tulpep.NetworkAutoSwitch.ProxyService/ManageProxyState.cs
|
using Microsoft.Win32;
using System;
using System.Management;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using Tulpep.NetworkAutoSwitch.NetworkStateLibrary;
using Tulpep.NetworkAutoSwitch.UtilityLibrary;
namespace Tulpep.NetworkAutoSwitch.ProxyService
{
public class ManageProxyState
{
public static void AnalyzeNow(Priority priority)
{
NetworkState networkState = NetworkStateService.RefreshNetworkState(priority);
Logging.WriteMessage("Wireless: {0} | Wired: {1}" , networkState.WirelessStatus, networkState.WiredStatus);
if(networkState.WiredStatus == OperationalStatus.Up && networkState.WirelessStatus == OperationalStatus.Down)
{
ModifyProxyState(priority == Priority.Wired);
}
else if (networkState.WirelessStatus == OperationalStatus.Up && networkState.WiredStatus == OperationalStatus.Down)
{
ModifyProxyState(priority == Priority.Wireless);
}
else if (networkState.WirelessStatus == OperationalStatus.Up && networkState.WiredStatus == OperationalStatus.Up)
{
ModifyProxyState(true);
}
else if (networkState.WirelessStatus == OperationalStatus.Down && networkState.WiredStatus == OperationalStatus.Down)
{
ModifyProxyState(false);
}
}
[DllImport("wininet.dll")]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
public const int INTERNET_OPTION_REFRESH = 37;
public const string REGISTRY_KEY_IS = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
public static void SetProxyState(bool proxyEnabled)
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey(REGISTRY_KEY_IS, true);
registry.SetValue("ProxyEnable", proxyEnabled ? 1 : 0);
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
}
public static void ModifyProxyState(bool EnableProxy)
{
SetProxyState(EnableProxy);
Logging.WriteMessage((EnableProxy ? "Enable" : "Disable") + " Proxy Server");
}
}
}
|
using Microsoft.Win32;
using System;
using System.Management;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using Tulpep.NetworkAutoSwitch.NetworkStateLibrary;
using Tulpep.NetworkAutoSwitch.UtilityLibrary;
namespace Tulpep.NetworkAutoSwitch.ProxyService
{
public class ManageProxyState
{
public static void AnalyzeNow(Priority priority)
{
NetworkState networkState = NetworkStateService.RefreshNetworkState(priority);
Logging.WriteMessage("Wireless: {0} | Wired: {1}" , networkState.WirelessStatus, networkState.WiredStatus);
if(networkState.WiredStatus == OperationalStatus.Up && networkState.WirelessStatus == OperationalStatus.Down)
{
ModifyProxyState(priority == Priority.Wired);
}
else if (networkState.WirelessStatus == OperationalStatus.Up && networkState.WiredStatus == OperationalStatus.Down)
{
ModifyProxyState(priority == Priority.Wireless);
}
else if (networkState.WirelessStatus == OperationalStatus.Up && networkState.WiredStatus == OperationalStatus.Up)
{
ModifyProxyState(true);
}
else if (networkState.WirelessStatus == OperationalStatus.Down && networkState.WiredStatus == OperationalStatus.Down)
{
ModifyProxyState(false);
}
}
[DllImport("wininet.dll")]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
public const int INTERNET_OPTION_REFRESH = 37;
public const string REGISTRY_KEY_IS = "\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
public static void SetProxyState(bool proxyEnabled)
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey(REGISTRY_KEY_IS, true);
registry.SetValue("ProxyEnable", proxyEnabled ? 1 : 0);
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
}
public static void ModifyProxyState(bool EnableProxy)
{
SetProxyState(EnableProxy);
Logging.WriteMessage((EnableProxy ? "Enable" : "Disable") + " Proxy Server");
}
}
}
|
mit
|
C#
|
c78821c6347f73b1015161b4dd205c5a89c04be4
|
Fix CanvasCellViewBackend.QueueDraw()
|
sevoku/xwt
|
Xwt.WPF/Xwt.WPFBackend.CellViews/CanvasCellViewBackend.cs
|
Xwt.WPF/Xwt.WPFBackend.CellViews/CanvasCellViewBackend.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using Xwt.Backends;
namespace Xwt.WPFBackend
{
class CanvasCellViewBackend: CellViewBackend, ICanvasCellViewBackend
{
public void QueueDraw()
{
CurrentElement.InvalidateVisual ();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using Xwt.Backends;
namespace Xwt.WPFBackend
{
class CanvasCellViewBackend: CellViewBackend, ICanvasCellViewBackend
{
public void QueueDraw()
{
}
}
}
|
mit
|
C#
|
eb6256f3f3c5f7a499e9f64d72e33c0fb08b544f
|
Fix fake client
|
MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net
|
Mindscape.Raygun4Net.NetCore.Tests/Model/FakeRaygunClient.cs
|
Mindscape.Raygun4Net.NetCore.Tests/Model/FakeRaygunClient.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework.Internal;
namespace Mindscape.Raygun4Net.NetCore.Tests
{
public class FakeRaygunClient : RaygunClient
{
public FakeRaygunClient()
: base(string.Empty)
{
}
public FakeRaygunClient(string apiKey)
: base(apiKey)
{
}
public RaygunMessage ExposeBuildMessage(Exception exception, [Optional] IList<string> tags, [Optional] IDictionary userCustomData, [Optional] RaygunIdentifierMessage user)
{
var task = BuildMessage(exception, tags, userCustomData, user);
task.Wait();
return task.Result;
}
public bool ExposeValidateApiKey()
{
return ValidateApiKey();
}
public bool ExposeOnSendingMessage(RaygunMessage raygunMessage)
{
return OnSendingMessage(raygunMessage);
}
public bool ExposeCanSend(Exception exception)
{
return CanSend(exception);
}
public void ExposeFlagAsSent(Exception exception)
{
FlagAsSent(exception);
}
public IEnumerable<Exception> ExposeStripWrapperExceptions(Exception exception)
{
return StripWrapperExceptions(exception);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework.Internal;
namespace Mindscape.Raygun4Net.NetCore.Tests
{
public class FakeRaygunClient : RaygunClient
{
public FakeRaygunClient()
: base(string.Empty)
{
}
public FakeRaygunClient(string apiKey)
: base(apiKey)
{
}
public RaygunMessage ExposeBuildMessage(Exception exception, [Optional] IList<string> tags, [Optional] IDictionary userCustomData)
{
var task = BuildMessage(exception, tags, userCustomData);
task.Wait();
return task.Result;
}
public bool ExposeValidateApiKey()
{
return ValidateApiKey();
}
public bool ExposeOnSendingMessage(RaygunMessage raygunMessage)
{
return OnSendingMessage(raygunMessage);
}
public bool ExposeCanSend(Exception exception)
{
return CanSend(exception);
}
public void ExposeFlagAsSent(Exception exception)
{
FlagAsSent(exception);
}
public IEnumerable<Exception> ExposeStripWrapperExceptions(Exception exception)
{
return StripWrapperExceptions(exception);
}
}
}
|
mit
|
C#
|
1baf30e5d2a95bc34862727419887d7b0591e5d1
|
add implement yield keyword
|
jongfeel/OOP_Review_2017_1
|
OOP_Review_2017_1/OOP_Review_2017_2/Program.cs
|
OOP_Review_2017_1/OOP_Review_2017_2/Program.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOP_Review_2017_2
{
class Program
{
// Declare delegate
public delegate void DelegateAction();
// Difference DelegateAction and DelegateActionMethod
public static void DelegateActionMethod()
{
Console.WriteLine("Called DelegateActionMethod!");
}
static void Main(string[] args)
{
// Create delegate object
// DelegateAction parameter: intellisense "void () target", what is mean?
DelegateAction da = new DelegateAction(DelegateActionMethod);
da.Invoke();
// Lambda
DelegateAction da2 = () => Console.WriteLine("Called da2 delegate variable.");
// yield
foreach (var item in GetNames)
{
if (item != null)
{
Console.WriteLine("AOA member: " + item);
}
}
}
public static IEnumerable GetNames
{
get
{
yield return "Seolhyun";
yield return null;
yield return "Cho-a";
yield break;
// yield return "Chou Tzu-yu"; // no meaning
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOP_Review_2017_2
{
class Program
{
// Declare delegate
public delegate void DelegateAction();
// Difference DelegateAction and DelegateActionMethod
public static void DelegateActionMethod()
{
Console.WriteLine("Called DelegateActionMethod!");
}
static void Main(string[] args)
{
// Create delegate object
// DelegateAction parameter: intellisense "void () target", what is mean?
DelegateAction da = new DelegateAction(DelegateActionMethod);
da.Invoke();
// Lambda
DelegateAction da2 = () => Console.WriteLine("Called da2 delegate variable.");
}
}
}
|
mit
|
C#
|
66d2d5ec55163ce5900f3b1195ef8688cc1b46af
|
test ocmmit
|
g0rdan/g0rdan.MvvmCross.Plugins
|
samples/MvvmCross.Plugins/MvvmCross.Plugins.Windows/Properties/AssemblyInfo.cs
|
samples/MvvmCross.Plugins/MvvmCross.Plugins.Windows/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("MvvmCross.Plugins.Windows")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MvvmCross.Plugins.Windows")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)]
|
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("MvvmCross.Plugins.Windows")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MvvmCross.Plugins.Windows")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)]
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.