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 |
|---|---|---|---|---|---|---|---|---|
0f4b9e1b1df4162b808569acdb2fdbb0d018ef99 | Fix getting categories | xobed/RohlikAPI,xobed/RohlikAPI,xobed/RohlikAPI,xobed/RohlikAPI,notdev/RohlikAPI | RohlikAPI/Categories.cs | RohlikAPI/Categories.cs | using System;
using System.Collections.Generic;
using System.Linq;
using HtmlAgilityPack;
namespace RohlikAPI
{
internal class Categories
{
private readonly PersistentSessionHttpClient httpClient;
internal Categories(PersistentSessionHttpClient httpClient)
{
this.httpClient = httpClient;
}
public IEnumerable<string> GetAllCategories()
{
var rohlikDomain = "https://www.rohlik.cz/";
var rohlikFrontString = httpClient.Get(rohlikDomain);
var rohlikFrontDocument = new HtmlDocument();
rohlikFrontDocument.LoadHtml(rohlikFrontString);
var categoryNodes = rohlikFrontDocument.DocumentNode.SelectNodes("//div[@class='Menu__sortimentLinkWrapper']/a");
var categoryHrefs = categoryNodes.Select(c => c.Attributes["href"].Value);
foreach (var categoryHref in categoryHrefs)
{
// strip any parameters
string hrefWithoutParameters = StripUrlParameters(categoryHref);
if (hrefWithoutParameters.Contains(rohlikDomain))
{
yield return hrefWithoutParameters.Replace(rohlikDomain, "");
}
else
{
yield return hrefWithoutParameters.Substring(1);
}
}
}
private string StripUrlParameters(string categoryHref)
{
var questionMarkIndex = categoryHref.IndexOf("?", StringComparison.Ordinal);
return questionMarkIndex != -1 ? categoryHref.Substring(0,questionMarkIndex) : categoryHref;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using HtmlAgilityPack;
namespace RohlikAPI
{
internal class Categories
{
private readonly PersistentSessionHttpClient httpClient;
internal Categories(PersistentSessionHttpClient httpClient)
{
this.httpClient = httpClient;
}
public IEnumerable<string> GetAllCategories()
{
var rohlikDomain = "https://www.rohlik.cz/";
var rohlikFrontString = httpClient.Get(rohlikDomain);
var rohlikFrontDocument = new HtmlDocument();
rohlikFrontDocument.LoadHtml(rohlikFrontString);
var categoryNodes = rohlikFrontDocument.DocumentNode.SelectNodes("//div[contains(@class,'sortiment')]//div[contains(@class,'rootcat')]/div/a");
var categoryHrefs = categoryNodes.Select(c => c.Attributes["href"].Value);
foreach (var categoryHref in categoryHrefs)
{
// strip any parameters
string hrefWithoutParameters = StripUrlParameters(categoryHref);
if (hrefWithoutParameters.Contains(rohlikDomain))
{
yield return hrefWithoutParameters.Replace(rohlikDomain, "");
}
else
{
yield return hrefWithoutParameters.Substring(1);
}
}
}
private string StripUrlParameters(string categoryHref)
{
var questionMarkIndex = categoryHref.IndexOf("?", StringComparison.Ordinal);
return questionMarkIndex != -1 ? categoryHref.Substring(0,questionMarkIndex) : categoryHref;
}
}
} | mit | C# |
491bb013a854b313ab13be93280cb8799e896160 | Add SignPath to known words | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/Utilities/String.KnownWords.cs | source/Nuke.Common/Utilities/String.KnownWords.cs | // Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
namespace Nuke.Common.Utilities
{
public static partial class StringExtensions
{
private static readonly string[] KnownWords =
{
"DotNet",
"GitHub",
"GitVersion",
"MSBuild",
"NuGet",
"ReSharper",
"AppVeyor",
"TeamCity",
"GitLab",
"SignPath"
};
}
}
| // Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
namespace Nuke.Common.Utilities
{
public static partial class StringExtensions
{
private static readonly string[] KnownWords =
{
"DotNet",
"GitHub",
"GitVersion",
"MSBuild",
"NuGet",
"ReSharper",
"AppVeyor",
"TeamCity",
"GitLab"
};
}
}
| mit | C# |
66bfb3d648779d18464d692ca17015d2c7e94c07 | Update Assets/MixedRealityToolkit.Examples/Demos/HandTracking/Script/LaunchUri.cs | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MixedRealityToolkit.Examples/Demos/HandTracking/Script/LaunchUri.cs | Assets/MixedRealityToolkit.Examples/Demos/HandTracking/Script/LaunchUri.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Examples.Demos
{
public class LaunchUri : MonoBehaviour
{
/// <summary>
/// Launch a UWP slate app. In most cases, your experience can continue running while the
/// launched app renders on top.
/// </summary>
/// <param name="uri">Url of the web page or app to launch. See https://docs.microsoft.com/en-us/windows/uwp/launch-resume/launch-default-app
/// for more information about the protocols that can be used when launching apps.</param>
public void Launch(string uri)
{
Debug.Log($"LaunchUri: Launching {uri}");
#if WINDOWS_UWP
UnityEngine.WSA.Application.InvokeOnUIThread(async () =>
{
bool result = await global::Windows.System.Launcher.LaunchUriAsync(new System.Uri(uri));
if (!result)
{
Debug.LogError("Launching URI failed to launch.");
}
}, false);
#else
Application.OpenURL(uri);
#endif
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Examples.Demos
{
public class LaunchUri : MonoBehaviour
{
/// <summary>
/// Launch a UWP slate app. In most cases, your experience can continue running while the
/// launched app renders on top.
/// </summary>
/// <param name="uri">Url of the web page or app to launch. See https://docs.microsoft.com/en-us/windows/uwp/launch-resume/launch-default-app
/// for more information about the protocols that can be used when launching apps.</param>
public void Launch(string uri)
{
Debug.Log($"LaunchUri: Launching {uri}");
#if WINDOWS_UWP
UnityEngine.WSA.Application.InvokeOnUIThread(async () =>
{
bool result = await global::Windows.System.Launcher.LaunchUriAsync(new System.Uri(uri));
if (!result)
{
Debug.LogError("Browser failed to launch.");
}
}, false);
#else
Application.OpenURL(uri);
#endif
}
}
}
| mit | C# |
39fc7454a469936fe0840883f01a41fb947daf74 | fix build | vkhorikov/CSharpFunctionalExtensions | CSharpFunctionalExtensions/Result/Methods/Extensions/OnFailure.Task.Right.cs | CSharpFunctionalExtensions/Result/Methods/Extensions/OnFailure.Task.Right.cs | using System;
using System.ComponentModel;
using System.Threading.Tasks;
namespace CSharpFunctionalExtensions
{
public static partial class ResultExtensions
{
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<Result<T>> OnFailure<T>(this Result<T> result, Func<Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<Result<T, E>> OnFailure<T, E>(this Result<T, E> result, Func<Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<Result> OnFailure(this Result result, Func<Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<Result> OnFailure(this Result result, Func<string, Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<UnitResult<E>> OnFailure<E>(this UnitResult<E> result, Func<Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<UnitResult<E>> OnFailure<E>(this UnitResult<E> result, Func<E, Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<Result<T>> OnFailure<T>(this Result<T> result, Func<string, Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<Result<T, E>> OnFailure<T, E>(this Result<T, E> result, Func<E, Task> func)
=> result.TapError(func);
}
}
| using System;
using System.ComponentModel;
using System.Threading.Tasks;
namespace CSharpFunctionalExtensions
{
public static partial class ResultExtensions
{
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<Result<T>> OnFailure<T>(this Result<T> result, Func<Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<Result<T, E>> OnFailure<T, E>(this Result<T, E> result, Func<Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<Result> OnFailure(this Result result, Func<Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<Result> OnFailure(this Result result, Func<string, Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<UnitResult<E>> OnFailure<E>(this UnitResult<E> result, Func<Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<UnitResult<E>> OnFailure<E>(this UnitResult<E> result, Func<E, Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<Result<T>> OnFailure<T>(this Result<T> result, Func<string, Task> func)
=> result.TapError(func);
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use TapError() instead.")]
public static Task<Result<T, E>> OnFailure<T, E>(this Result<T, E> result, Func<E, Task> func)
=> result.TapError(func);
}
| mit | C# |
ce69fd266f2247f7224032df8285309e63aded48 | Fix build | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/GameObjects/EntitySystems/GameMode/SuspicionEndTimerSystem.cs | Content.Server/GameObjects/EntitySystems/GameMode/SuspicionEndTimerSystem.cs | using System;
using System.Linq;
using Content.Server.Interfaces.GameTicking;
using Content.Shared.GameObjects.EntitySystemMessages;
using Content.Shared.GameTicking;
using JetBrains.Annotations;
using Robust.Server.Player;
using Robust.Shared.Enums;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Timing;
#nullable enable
namespace Content.Server.GameObjects.EntitySystems.GameMode
{
[UsedImplicitly]
public sealed class SuspicionEndTimerSystem : EntitySystem, IResettingEntitySystem
{
[Dependency] private readonly IPlayerManager _playerManager = null!;
private TimeSpan? _endTime;
public TimeSpan? EndTime
{
get => _endTime;
set
{
_endTime = value;
SendUpdateToAll();
}
}
public override void Initialize()
{
base.Initialize();
_playerManager.PlayerStatusChanged += PlayerManagerOnPlayerStatusChanged;
}
public override void Shutdown()
{
base.Shutdown();
_playerManager.PlayerStatusChanged -= PlayerManagerOnPlayerStatusChanged;
}
private void PlayerManagerOnPlayerStatusChanged(object? sender, SessionStatusEventArgs e)
{
if (e.NewStatus == SessionStatus.InGame)
{
SendUpdateTimerMessage(e.Session);
}
}
private void SendUpdateToAll()
{
foreach (var player in _playerManager.GetAllPlayers().Where(p => p.Status == SessionStatus.InGame))
{
SendUpdateTimerMessage(player);
}
}
private void SendUpdateTimerMessage(IPlayerSession player)
{
var msg = new SuspicionMessages.SetSuspicionEndTimerMessage
{
EndTime = EndTime
};
EntityManager.EntityNetManager?.SendSystemNetworkMessage(msg, player.ConnectedClient);
}
void IResettingEntitySystem.Reset()
{
EndTime = null;
}
}
}
| using System;
using System.Linq;
using Content.Server.Interfaces.GameTicking;
using Content.Shared.GameObjects.EntitySystemMessages;
using Content.Shared.GameTicking;
using JetBrains.Annotations;
using Robust.Server.Player;
using Robust.Shared.Enums;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Timing;
#nullable enable
namespace Content.Server.GameObjects.EntitySystems.GameMode
{
[UsedImplicitly]
public sealed class SuspicionEndTimerSystem : EntitySystem, IResettingEntitySystem
{
[Dependency] private readonly IPlayerManager _playerManager = null!;
private TimeSpan? _endTime;
public TimeSpan? EndTime
{
get => _endTime;
set
{
_endTime = value;
SendUpdateToAll();
}
}
public override void Initialize()
{
base.Initialize();
_playerManager.PlayerStatusChanged += PlayerManagerOnPlayerStatusChanged;
}
public override void Shutdown()
{
base.Shutdown();
_playerManager.PlayerStatusChanged -= PlayerManagerOnPlayerStatusChanged;
}
private void PlayerManagerOnPlayerStatusChanged(object? sender, SessionStatusEventArgs e)
{
if (e.NewStatus == SessionStatus.InGame)
{
SendUpdateTimerMessage(e.Session);
}
}
private void SendUpdateToAll()
{
foreach (var player in _playerManager.GetAllPlayers().Where(p => p.Status == SessionStatus.InGame))
{
SendUpdateTimerMessage(player);
}
}
private void SendUpdateTimerMessage(IPlayerSession player)
{
var msg = new SuspicionMessages.SetSuspicionEndTimerMessage
{
EndTime = EndTime
};
EntityManager.EntityNetworkManager?.SendSystemNetworkMessage(msg, player.ConnectedClient);
}
void IResettingEntitySystem.Reset()
{
EndTime = null;
}
}
}
| mit | C# |
752b3f760f56a6d8f097230e5cb9cd39f322c647 | Apply angular velocity to asteroids | iridinite/shiftdrive | Client/Asteroid.cs | Client/Asteroid.cs | /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using System;
using Microsoft.Xna.Framework;
namespace ShiftDrive {
/// <summary>
/// A <seealso cref="GameObject"/> representing a single asteroid.
/// </summary>
internal sealed class Asteroid : GameObject {
private float angularVelocity;
public Asteroid() {
type = ObjectType.Asteroid;
facing = Utils.RNG.Next(0, 360);
spritename = "map/asteroid";
color = Color.White;
bounding = 7f;
}
public override void Update(GameState world, float deltaTime) {
base.Update(world, deltaTime);
facing += angularVelocity * deltaTime;
angularVelocity *= (float)Math.Pow(0.8f, deltaTime);
}
protected override void OnCollision(GameObject other, Vector2 normal, float penetration) {
base.OnCollision(other, normal, penetration);
// spin around!
angularVelocity += (1f + penetration * 4f) * (float)(Utils.RNG.NextDouble() * 2.0 - 1.0);
// asteroids shouldn't move so much if ships bump into them, because
// they should look heavy and sluggish
if (other.type == ObjectType.AIShip || other.type == ObjectType.PlayerShip)
this.velocity *= 0.8f;
}
public override bool IsTerrain() {
return true;
}
}
} | /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using Microsoft.Xna.Framework;
namespace ShiftDrive {
/// <summary>
/// A <seealso cref="GameObject"/> representing a single asteroid.
/// </summary>
internal sealed class Asteroid : GameObject {
public Asteroid() {
type = ObjectType.Asteroid;
facing = Utils.RNG.Next(0, 360);
spritename = "map/asteroid";
color = Color.White;
bounding = 7f;
}
public override void Update(GameState world, float deltaTime) {
base.Update(world, deltaTime);
}
protected override void OnCollision(GameObject other, Vector2 normal, float penetration) {
base.OnCollision(other, normal, penetration);
// asteroids shouldn't move so much if ships bump into them, because
// they should look heavy and sluggish
if (other.type == ObjectType.AIShip || other.type == ObjectType.PlayerShip)
this.velocity *= 0.8f;
}
public override bool IsTerrain() {
return true;
}
}
} | bsd-3-clause | C# |
5bb4d359826f2df850a167c502bda25408edd1f0 | Make RealmWrapper nullable enabled | peppy/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu-new,ppy/osu,peppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu | osu.Game/Database/RealmWrapper.cs | osu.Game/Database/RealmWrapper.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Threading;
using Realms;
#nullable enable
namespace osu.Game.Database
{
public class RealmWrapper<T> : IEquatable<RealmWrapper<T>>
where T : RealmObject, IHasGuidPrimaryKey
{
public Guid ID { get; }
private readonly ThreadLocal<T> threadValues;
public readonly IRealmFactory ContextFactory;
public RealmWrapper(T original, IRealmFactory contextFactory)
{
ContextFactory = contextFactory;
ID = original.Guid;
var originalContext = original.Realm;
threadValues = new ThreadLocal<T>(() =>
{
var context = ContextFactory.Get();
if (context == null || originalContext?.IsSameInstance(context) != false)
return original;
return context.Find<T>(ID);
});
}
public T Get() => threadValues.Value;
public RealmWrapper<TChild> WrapChild<TChild>(Func<T, TChild> lookup)
where TChild : RealmObject, IHasGuidPrimaryKey => new RealmWrapper<TChild>(lookup(Get()), ContextFactory);
public void PerformUpdate(Action<T> perform)
{
using (ContextFactory.GetForWrite())
perform(Get());
}
public static implicit operator T?(RealmWrapper<T>? wrapper)
=> wrapper?.Get().Detach();
public static implicit operator RealmWrapper<T>(T obj) => obj.WrapAsUnmanaged();
public bool Equals(RealmWrapper<T>? other) => other != null && other.ID == ID;
public override string ToString() => Get().ToString();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Threading;
using Realms;
namespace osu.Game.Database
{
public class RealmWrapper<T> : IEquatable<RealmWrapper<T>>
where T : RealmObject, IHasGuidPrimaryKey
{
public Guid ID { get; }
private readonly ThreadLocal<T> threadValues;
public readonly IRealmFactory ContextFactory;
public RealmWrapper(T original, IRealmFactory contextFactory)
{
ContextFactory = contextFactory;
ID = original.Guid;
var originalContext = original.Realm;
threadValues = new ThreadLocal<T>(() =>
{
var context = ContextFactory?.Get();
if (context == null || originalContext?.IsSameInstance(context) != false)
return original;
return context.Find<T>(ID);
});
}
public T Get() => threadValues.Value;
public RealmWrapper<TChild> WrapChild<TChild>(Func<T, TChild> lookup)
where TChild : RealmObject, IHasGuidPrimaryKey => new RealmWrapper<TChild>(lookup(Get()), ContextFactory);
public void PerformUpdate(Action<T> perform)
{
using (ContextFactory.GetForWrite())
perform(this);
}
// ReSharper disable once CA2225
public static implicit operator T(RealmWrapper<T> wrapper)
=> wrapper?.Get().Detach();
// ReSharper disable once CA2225
public static implicit operator RealmWrapper<T>(T obj) => obj.WrapAsUnmanaged();
public bool Equals(RealmWrapper<T> other) => other != null && other.ID == ID;
public override string ToString() => Get().ToString();
}
}
| mit | C# |
2cc91eb56e1226ee05d316862c121944356ef5ec | add tiles yay :D | windowsphonehacker/SparklrWP | SparklrWP/Utils/Task.cs | SparklrWP/Utils/Task.cs | using Microsoft.Phone.Scheduler;
using System;
namespace SparklrWP.Utils
{
public class Task
{
PeriodicTask periodicTask;
string periodicTaskName = "Sparklr";
public Task()
{
periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
#if DEBUG
if (periodicTask != null)
{
ScheduledActionService.Remove(periodicTaskName);
periodicTask = null;
}
#endif
if (periodicTask == null)
{
periodicTask = new PeriodicTask(periodicTaskName);
periodicTask.Description = "Sparklr notification agent";
try
{
ScheduledActionService.Add(periodicTask);
}
catch (Exception)
{
}
}
// If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if DEBUG
ScheduledActionService.LaunchForTest("Sparklr", new TimeSpan(1));
#endif
}
}
}
| using Microsoft.Phone.Scheduler;
using System;
namespace SparklrWP.Utils
{
public class Task
{
PeriodicTask periodicTask;
string periodicTaskName = "Sparklr";
public Task()
{
periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
#if DEBUG
if (periodicTask != null)
{
ScheduledActionService.Remove(periodicTaskName);
periodicTask = null;
}
#endif
if (periodicTask == null)
{
periodicTask = new PeriodicTask(periodicTaskName);
periodicTask.Description = "Sparklr notification agent";
try
{
ScheduledActionService.Add(periodicTask);
}
catch (Exception)
{
}
}
// If debugging is enabled, use LaunchForTest to launch the agent in one minute.
}
}
}
| mit | C# |
bfa98b583ce5603c25b5847175f22e6f89279dbb | improve FakeTestFixture. | jwChung/Experimentalism,jwChung/Experimentalism | test/ExperimentUnitTest/FakeTestFixture.cs | test/ExperimentUnitTest/FakeTestFixture.cs | using System;
namespace Jwc.Experiment
{
public class FakeTestFixture : ITestFixture
{
private readonly string _stringValue = Guid.NewGuid().ToString();
private readonly string _intValue = Guid.NewGuid().ToString();
public string StringValue
{
get
{
return _stringValue;
}
}
public string IntValue
{
get
{
return _intValue;
}
}
public object Create(object request)
{
var type = request as Type;
if (type != null)
{
if (type == typeof(string))
{
return _stringValue;
}
if (type == typeof(int))
{
return _intValue;
}
}
throw new NotSupportedException();
}
}
} | using System;
namespace Jwc.Experiment
{
public class FakeTestFixture : ITestFixture
{
private readonly string _stringValue = Guid.NewGuid().ToString();
private readonly string _intValue = Guid.NewGuid().ToString();
private readonly Func<object, object> _onCreate;
public FakeTestFixture()
{
_onCreate = r =>
{
var type = r as Type;
if (type != null)
{
if (type == typeof(string))
{
return _stringValue;
}
if (type == typeof(int))
{
return _intValue;
}
}
throw new NotSupportedException();
};
}
public string StringValue
{
get
{
return _stringValue;
}
}
public string IntValue
{
get
{
return _intValue;
}
}
public object Create(object request)
{
return _onCreate(request);
}
}
} | mit | C# |
3858647e8b0413c75196ba262d1336354ed1a309 | Make search for users case insensitive | erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner | Oogstplanner.Data/UserRepository.cs | Oogstplanner.Data/UserRepository.cs | using System.Linq;
using System.Collections.Generic;
using Oogstplanner.Common;
using Oogstplanner.Models;
namespace Oogstplanner.Data
{
public class UserRepository : EntityFrameworkRepository<User>, IUserRepository
{
public UserRepository(IOogstplannerContext db)
: base(db)
{ }
public User GetUserByUserName(string name)
{
var user = DbSet.SingleOrDefault(u => u.Name == name);
if (user == null)
{
throw new UserNotFoundException("The user with the specified name does not exist.");
}
return user;
}
public int GetUserIdByEmail(string email)
{
var user = DbSet.SingleOrDefault(u => u.Email == email);
if (user == null)
{
throw new UserNotFoundException("The user with the specified email does not exist.");
}
return user.Id;
}
public int GetUserIdByName(string name)
{
var user = DbSet.SingleOrDefault(u => u.Name == name);
if (user == null)
{
throw new UserNotFoundException("The user with the specified name does not exist.");
}
return user.Id;
}
public IEnumerable<User> GetRecentlyActiveUsers(int count)
{
return DbSet.Where(u => u.AuthenticationStatus == AuthenticatedStatus.Authenticated)
.OrderByDescending(u => u.LastActive).Take(count).ToList();
}
public IEnumerable<User> SearchUsers(string searchTerm)
{
return DbSet.Where(u =>
u.AuthenticationStatus == AuthenticatedStatus.Authenticated
&& (u.Name.ToLower().Contains(searchTerm) || u.FullName.ToLower().Contains(searchTerm)))
.OrderByDescending(u => u.LastActive);
}
}
}
| using System.Linq;
using System.Collections.Generic;
using Oogstplanner.Common;
using Oogstplanner.Models;
namespace Oogstplanner.Data
{
public class UserRepository : EntityFrameworkRepository<User>, IUserRepository
{
public UserRepository(IOogstplannerContext db)
: base(db)
{ }
public User GetUserByUserName(string name)
{
var user = DbSet.SingleOrDefault(u => u.Name == name);
if (user == null)
{
throw new UserNotFoundException("The user with the specified name does not exist.");
}
return user;
}
public int GetUserIdByEmail(string email)
{
var user = DbSet.SingleOrDefault(u => u.Email == email);
if (user == null)
{
throw new UserNotFoundException("The user with the specified email does not exist.");
}
return user.Id;
}
public int GetUserIdByName(string name)
{
var user = DbSet.SingleOrDefault(u => u.Name == name);
if (user == null)
{
throw new UserNotFoundException("The user with the specified name does not exist.");
}
return user.Id;
}
public IEnumerable<User> GetRecentlyActiveUsers(int count)
{
return DbSet.Where(u => u.AuthenticationStatus == AuthenticatedStatus.Authenticated)
.OrderByDescending(u => u.LastActive).Take(count).ToList();
}
public IEnumerable<User> SearchUsers(string searchTerm)
{
return DbSet.Where(u =>
u.AuthenticationStatus == AuthenticatedStatus.Authenticated
&& (u.Name.Contains(searchTerm) || u.FullName.Contains(searchTerm)))
.OrderByDescending(u => u.LastActive);
}
}
}
| mit | C# |
bcda3c5062923736ccf0cca838ec176f7fe29827 | Remove obsolete attribute | KodrAus/elasticsearch-net,cstlaurent/elasticsearch-net,elastic/elasticsearch-net,faisal00813/elasticsearch-net,geofeedia/elasticsearch-net,ststeiger/elasticsearch-net,Grastveit/NEST,RossLieberman/NEST,SeanKilleen/elasticsearch-net,gayancc/elasticsearch-net,junlapong/elasticsearch-net,abibell/elasticsearch-net,RossLieberman/NEST,KodrAus/elasticsearch-net,adam-mccoy/elasticsearch-net,KodrAus/elasticsearch-net,NickCraver/NEST,gayancc/elasticsearch-net,robertlyson/elasticsearch-net,amyzheng424/elasticsearch-net,azubanov/elasticsearch-net,DavidSSL/elasticsearch-net,cstlaurent/elasticsearch-net,robertlyson/elasticsearch-net,amyzheng424/elasticsearch-net,wawrzyn/elasticsearch-net,LeoYao/elasticsearch-net,starckgates/elasticsearch-net,jonyadamit/elasticsearch-net,SeanKilleen/elasticsearch-net,NickCraver/NEST,geofeedia/elasticsearch-net,alanprot/elasticsearch-net,ststeiger/elasticsearch-net,adam-mccoy/elasticsearch-net,NickCraver/NEST,LeoYao/elasticsearch-net,LeoYao/elasticsearch-net,starckgates/elasticsearch-net,CSGOpenSource/elasticsearch-net,mac2000/elasticsearch-net,starckgates/elasticsearch-net,joehmchan/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,gayancc/elasticsearch-net,wawrzyn/elasticsearch-net,RossLieberman/NEST,ststeiger/elasticsearch-net,junlapong/elasticsearch-net,TheFireCookie/elasticsearch-net,alanprot/elasticsearch-net,DavidSSL/elasticsearch-net,TheFireCookie/elasticsearch-net,azubanov/elasticsearch-net,junlapong/elasticsearch-net,UdiBen/elasticsearch-net,tkirill/elasticsearch-net,UdiBen/elasticsearch-net,Grastveit/NEST,amyzheng424/elasticsearch-net,robrich/elasticsearch-net,alanprot/elasticsearch-net,mac2000/elasticsearch-net,SeanKilleen/elasticsearch-net,jonyadamit/elasticsearch-net,UdiBen/elasticsearch-net,faisal00813/elasticsearch-net,abibell/elasticsearch-net,elastic/elasticsearch-net,robertlyson/elasticsearch-net,geofeedia/elasticsearch-net,Grastveit/NEST,DavidSSL/elasticsearch-net,abibell/elasticsearch-net,faisal00813/elasticsearch-net,robrich/elasticsearch-net,mac2000/elasticsearch-net,tkirill/elasticsearch-net,joehmchan/elasticsearch-net,cstlaurent/elasticsearch-net,alanprot/elasticsearch-net,jonyadamit/elasticsearch-net,robrich/elasticsearch-net,wawrzyn/elasticsearch-net,tkirill/elasticsearch-net,azubanov/elasticsearch-net,CSGOpenSource/elasticsearch-net,joehmchan/elasticsearch-net,TheFireCookie/elasticsearch-net | src/Nest/Domain/Analysis/Analyzers/CustomAnalyzer.cs | src/Nest/Domain/Analysis/Analyzers/CustomAnalyzer.cs | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Nest
{
/// <summary>
/// An analyzer of type custom that allows to combine a Tokenizer with zero or more Token Filters, and zero or more Char Filters.
/// <para>The custom analyzer accepts a logical/registered name of the tokenizer to use, and a list of logical/registered names of token filters.</para>
/// </summary>
public class CustomAnalyzer : AnalyzerBase
{
public CustomAnalyzer(string type)
{
Type = type;
}
public CustomAnalyzer() : this("custom") {}
[JsonProperty("tokenizer")]
public string Tokenizer { get; set; }
[JsonProperty("filter")]
public IList<string> Filter { get; set; }
[JsonProperty("char_filter")]
public IList<string> CharFilter { get; set; }
}
} | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Nest
{
/// <summary>
/// An analyzer of type custom that allows to combine a Tokenizer with zero or more Token Filters, and zero or more Char Filters.
/// <para>The custom analyzer accepts a logical/registered name of the tokenizer to use, and a list of logical/registered names of token filters.</para>
/// </summary>
public class CustomAnalyzer : AnalyzerBase
{
public CustomAnalyzer(string type)
{
Type = type;
}
[Obsolete("ctor(string) is preferred")]
public CustomAnalyzer() : this("custom") {}
[JsonProperty("tokenizer")]
public string Tokenizer { get; set; }
[JsonProperty("filter")]
public IList<string> Filter { get; set; }
[JsonProperty("char_filter")]
public IList<string> CharFilter { get; set; }
}
} | apache-2.0 | C# |
36f5efded812109f6f26963b4703ae8411db16f7 | add ability to authenticate with a specific username/password in windows authenticator | jonnii/SpeakEasy | src/SpeakEasy/Authenticators/WindowsAuthenticator.cs | src/SpeakEasy/Authenticators/WindowsAuthenticator.cs | using System.Net;
namespace SpeakEasy.Authenticators
{
/// <summary>
/// The windows authenticator will authenticate
/// an http request with windows credentials
/// </summary>
public class WindowsAuthenticator : IAuthenticator
{
private readonly ICredentials credentials;
/// <summary>
/// Creates a windows authenticator with the default credentials
/// </summary>
public WindowsAuthenticator()
: this(CredentialCache.DefaultCredentials)
{
}
/// <summary>
/// Creates a windows authenticator with a specific username
/// and password
/// </summary>
/// <param name="username">The username to authenticate with</param>
/// <param name="password">The password to authenticate with</param>
public WindowsAuthenticator(string username, string password)
: this(new NetworkCredential(username, password))
{
}
/// <summary>
/// Creates a windows authenticator with a specific credentials
/// </summary>
/// <param name="credentials">The credentials to authenticate with</param>
public WindowsAuthenticator(ICredentials credentials)
{
this.credentials = credentials;
}
public void Authenticate(IHttpRequest httpRequest)
{
httpRequest.Credentials = credentials;
}
}
} | using System.Net;
namespace SpeakEasy.Authenticators
{
public class WindowsAuthenticator : IAuthenticator
{
public void Authenticate(IHttpRequest httpRequest)
{
httpRequest.Credentials = CredentialCache.DefaultCredentials;
}
}
} | apache-2.0 | C# |
5c03aeef9c265752c2c0ad6e722ab3ca9e772783 | Add properties (BestFitness, BestPosition, Current Iteration, CurrentFunctionEvaluations) in IOptimizationAlgorithm interface. | geoem/MSolve,geoem/MSolve | ISAAR.MSolve.Analyzers/Optimization/IOptimizationAlgorithm.cs | ISAAR.MSolve.Analyzers/Optimization/IOptimizationAlgorithm.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ISAAR.MSolve.Analyzers.Optimization
{
public interface IOptimizationAlgorithm
{
double BestFitness
{
get;
}
double[] BestPosition
{
get;
}
int CurrentIteration
{
get;
}
double CurrentFunctionEvaluations
{
get;
}
void Solve();
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ISAAR.MSolve.Analyzers.Optimization
{
public interface IOptimizationAlgorithm
{
void Solve();
}
} | apache-2.0 | C# |
3879d7f51c0ac3325508236cc308592d337c8570 | make GraphTypeTypeRegistry thread safe (#1327) | graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet | src/GraphQL/Utilities/GraphTypeTypeRegistry.cs | src/GraphQL/Utilities/GraphTypeTypeRegistry.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Numerics;
using GraphQL.Types;
namespace GraphQL.Utilities
{
public static class GraphTypeTypeRegistry
{
static readonly ConcurrentDictionary<Type, Type> _entries;
static GraphTypeTypeRegistry()
{
_entries = new ConcurrentDictionary<Type, Type>
{
[typeof(int)] = typeof(IntGraphType),
[typeof(long)] = typeof(LongGraphType),
[typeof(BigInteger)] = typeof(BigIntGraphType),
[typeof(double)] = typeof(FloatGraphType),
[typeof(float)] = typeof(FloatGraphType),
[typeof(decimal)] = typeof(DecimalGraphType),
[typeof(string)] = typeof(StringGraphType),
[typeof(bool)] = typeof(BooleanGraphType),
[typeof(DateTime)] = typeof(DateGraphType),
[typeof(DateTimeOffset)] = typeof(DateTimeOffsetGraphType),
[typeof(TimeSpan)] = typeof(TimeSpanSecondsGraphType),
[typeof(Guid)] = typeof(IdGraphType),
[typeof(short)] = typeof(ShortGraphType),
[typeof(ushort)] = typeof(UShortGraphType),
[typeof(ulong)] = typeof(ULongGraphType),
[typeof(uint)] = typeof(UIntGraphType),
[typeof(byte)] = typeof(ByteGraphType),
[typeof(sbyte)] = typeof(SByteGraphType),
};
}
public static void Register<T, TGraph>() where TGraph : GraphType
{
Register(typeof(T), typeof(TGraph));
}
public static void Register(Type clrType, Type graphType)
{
_entries[clrType ?? throw new ArgumentNullException(nameof(clrType))] = graphType ?? throw new ArgumentNullException(nameof(graphType));
}
public static Type Get<TClr>() => Get(typeof(TClr));
public static Type Get(Type clrType) => _entries.TryGetValue(clrType, out var graphType) ? graphType : null;
public static bool Contains(Type clrType) => _entries.ContainsKey(clrType);
}
}
| using System;
using System.Collections.Generic;
using System.Numerics;
using GraphQL.Types;
namespace GraphQL.Utilities
{
public static class GraphTypeTypeRegistry
{
static readonly Dictionary<Type, Type> _entries;
static GraphTypeTypeRegistry()
{
_entries = new Dictionary<Type, Type>
{
[typeof(int)] = typeof(IntGraphType),
[typeof(long)] = typeof(LongGraphType),
[typeof(BigInteger)] = typeof(BigIntGraphType),
[typeof(double)] = typeof(FloatGraphType),
[typeof(float)] = typeof(FloatGraphType),
[typeof(decimal)] = typeof(DecimalGraphType),
[typeof(string)] = typeof(StringGraphType),
[typeof(bool)] = typeof(BooleanGraphType),
[typeof(DateTime)] = typeof(DateGraphType),
[typeof(DateTimeOffset)] = typeof(DateTimeOffsetGraphType),
[typeof(TimeSpan)] = typeof(TimeSpanSecondsGraphType),
[typeof(Guid)] = typeof(IdGraphType),
[typeof(short)] = typeof(ShortGraphType),
[typeof(ushort)] = typeof(UShortGraphType),
[typeof(ulong)] = typeof(ULongGraphType),
[typeof(uint)] = typeof(UIntGraphType),
[typeof(byte)] = typeof(ByteGraphType),
[typeof(sbyte)] = typeof(SByteGraphType),
};
}
public static void Register<T, TGraph>() where TGraph : GraphType
{
Register(typeof(T), typeof(TGraph));
}
public static void Register(Type clrType, Type graphType)
{
_entries[clrType ?? throw new ArgumentNullException(nameof(clrType))] = graphType ?? throw new ArgumentNullException(nameof(graphType));
}
public static Type Get<TClr>() => Get(typeof(TClr));
public static Type Get(Type clrType) => _entries.TryGetValue(clrType, out var graphType) ? graphType : null;
public static bool Contains(Type clrType) => _entries.ContainsKey(clrType);
}
}
| mit | C# |
5046c2d34e364a36620fb82bc1e4fc49f467305e | Use body length for Service Bus binary messages. | oliver-feng/azure-webjobs-sdk,vasanthangel4/azure-webjobs-sdk,brendankowitz/azure-webjobs-sdk,gibwar/azure-webjobs-sdk,Azure/azure-webjobs-sdk,oaastest/azure-webjobs-sdk,shrishrirang/azure-webjobs-sdk,oliver-feng/azure-webjobs-sdk,oliver-feng/azure-webjobs-sdk,shrishrirang/azure-webjobs-sdk,shrishrirang/azure-webjobs-sdk,oaastest/azure-webjobs-sdk,gibwar/azure-webjobs-sdk,vasanthangel4/azure-webjobs-sdk,vasanthangel4/azure-webjobs-sdk,brendankowitz/azure-webjobs-sdk,gibwar/azure-webjobs-sdk,Azure/azure-webjobs-sdk,oaastest/azure-webjobs-sdk,brendankowitz/azure-webjobs-sdk | src/Microsoft.Azure.Jobs.ServiceBus/Triggers/BrokeredMessageValueProvider.cs | src/Microsoft.Azure.Jobs.ServiceBus/Triggers/BrokeredMessageValueProvider.cs | using System;
using System.IO;
using System.Text;
using Microsoft.Azure.Jobs.Host.Bindings;
using Microsoft.ServiceBus.Messaging;
namespace Microsoft.Azure.Jobs.ServiceBus.Triggers
{
internal class BrokeredMessageValueProvider : IValueProvider
{
private readonly object _value;
private readonly Type _valueType;
private readonly string _invokeString;
public BrokeredMessageValueProvider(BrokeredMessage clone, object value, Type valueType)
{
if (value != null && !valueType.IsAssignableFrom(value.GetType()))
{
throw new InvalidOperationException("value is not of the correct type.");
}
_value = value;
_valueType = valueType;
_invokeString = CreateInvokeString(clone);
}
public Type Type
{
get { return _valueType; }
}
public object GetValue()
{
return _value;
}
public string ToInvokeString()
{
return _invokeString;
}
private static string CreateInvokeString(BrokeredMessage message)
{
using (MemoryStream outputStream = new MemoryStream())
{
using (Stream inputStream = message.GetBody<Stream>())
{
if (inputStream == null)
{
return null;
}
inputStream.CopyTo(outputStream);
byte[] bytes = outputStream.ToArray();
try
{
return StrictEncodings.Utf8.GetString(bytes);
}
catch (DecoderFallbackException)
{
return "byte[" + bytes.Length + "]";
}
}
}
}
}
}
| using System;
using System.IO;
using System.Text;
using Microsoft.Azure.Jobs.Host.Bindings;
using Microsoft.ServiceBus.Messaging;
namespace Microsoft.Azure.Jobs.ServiceBus.Triggers
{
internal class BrokeredMessageValueProvider : IValueProvider
{
private readonly object _value;
private readonly Type _valueType;
private readonly string _invokeString;
public BrokeredMessageValueProvider(BrokeredMessage clone, object value, Type valueType)
{
if (value != null && !valueType.IsAssignableFrom(value.GetType()))
{
throw new InvalidOperationException("value is not of the correct type.");
}
_value = value;
_valueType = valueType;
_invokeString = CreateInvokeString(clone);
}
public Type Type
{
get { return _valueType; }
}
public object GetValue()
{
return _value;
}
public string ToInvokeString()
{
return _invokeString;
}
private static string CreateInvokeString(BrokeredMessage message)
{
using (MemoryStream outputStream = new MemoryStream())
{
using (Stream inputStream = message.GetBody<Stream>())
{
if (inputStream == null)
{
return null;
}
inputStream.CopyTo(outputStream);
try
{
return StrictEncodings.Utf8.GetString(outputStream.ToArray());
}
catch (DecoderFallbackException)
{
return "byte[" + message.Size + "]";
}
}
}
}
}
}
| mit | C# |
5f0c0594c6b566eeb210a3716cfdef6f81340715 | Update existing documentation for show images. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Objects/Get/Shows/TraktShowImages.cs | Source/Lib/TraktApiSharp/Objects/Get/Shows/TraktShowImages.cs | namespace TraktApiSharp.Objects.Get.Shows
{
using Basic;
using Newtonsoft.Json;
/// <summary>A collection of images and image sets for a Trakt show.</summary>
public class TraktShowImages
{
/// <summary>Gets or sets the fan art image set.</summary>
[JsonProperty(PropertyName = "fanart")]
public TraktImageSet FanArt { get; set; }
/// <summary>Gets or sets the poster image set.</summary>
[JsonProperty(PropertyName = "poster")]
public TraktImageSet Poster { get; set; }
/// <summary>Gets or sets the loge image.</summary>
[JsonProperty(PropertyName = "logo")]
public TraktImage Logo { get; set; }
/// <summary>Gets or sets the clear art image.</summary>
[JsonProperty(PropertyName = "clearart")]
public TraktImage ClearArt { get; set; }
/// <summary>Gets or sets the banner image.</summary>
[JsonProperty(PropertyName = "banner")]
public TraktImage Banner { get; set; }
/// <summary>Gets or sets the thumb image.</summary>
[JsonProperty(PropertyName = "thumb")]
public TraktImage Thumb { get; set; }
}
}
| namespace TraktApiSharp.Objects.Get.Shows
{
using Basic;
using Newtonsoft.Json;
/// <summary>
/// A collection of images for a Trakt show.
/// </summary>
public class TraktShowImages
{
/// <summary>
/// A fanart image set for various sizes.
/// </summary>
[JsonProperty(PropertyName = "fanart")]
public TraktImageSet FanArt { get; set; }
/// <summary>
/// A poster image set for various sizes.
/// </summary>
[JsonProperty(PropertyName = "poster")]
public TraktImageSet Poster { get; set; }
/// <summary>
/// A logo image.
/// </summary>
[JsonProperty(PropertyName = "logo")]
public TraktImage Logo { get; set; }
/// <summary>
/// A clearart image.
/// </summary>
[JsonProperty(PropertyName = "clearart")]
public TraktImage ClearArt { get; set; }
/// <summary>
/// A banner image.
/// </summary>
[JsonProperty(PropertyName = "banner")]
public TraktImage Banner { get; set; }
/// <summary>
/// A thumbnail image.
/// </summary>
[JsonProperty(PropertyName = "thumb")]
public TraktImage Thumb { get; set; }
}
}
| mit | C# |
7d4a8bebaec5c417ce05cc8ae3eab0e061399abf | Update MessagePackSerializer.cs | tiksn/TIKSN-Framework | TIKSN.Core/Serialization/MessagePack/MessagePackSerializer.cs | TIKSN.Core/Serialization/MessagePack/MessagePackSerializer.cs | using System.IO;
using MsgPack.Serialization;
namespace TIKSN.Serialization.MessagePack
{
public class MessagePackSerializer : SerializerBase<byte[]>
{
private readonly SerializationContext _serializationContext;
public MessagePackSerializer(SerializationContext serializationContext) =>
this._serializationContext = serializationContext;
protected override byte[] SerializeInternal<T>(T obj)
{
var serializer = this._serializationContext.GetSerializer<T>();
using (var stream = new MemoryStream())
{
serializer.Pack(stream, obj);
return stream.ToArray();
}
}
}
}
| using MsgPack.Serialization;
using System.IO;
namespace TIKSN.Serialization.MessagePack
{
public class MessagePackSerializer : SerializerBase<byte[]>
{
private readonly SerializationContext _serializationContext;
public MessagePackSerializer(SerializationContext serializationContext)
{
_serializationContext = serializationContext;
}
protected override byte[] SerializeInternal<T>(T obj)
{
var serializer = _serializationContext.GetSerializer<T>();
using (var stream = new MemoryStream())
{
serializer.Pack(stream, obj);
return stream.ToArray();
}
}
}
} | mit | C# |
f4f70ec54c0dd34958ba9f91b1b833faf5e1ead0 | add instructors link for admins | ucdavis/Badges,ucdavis/Badges | Badges/Areas/Admin/Views/Landing/Index.cshtml | Badges/Areas/Admin/Views/Landing/Index.cshtml | @model dynamic
@{
ViewBag.Title = "Admin Homepage";
}
<h2>Admin Homepage</h2>
<ul class="nav nav-pills nav-stacked">
<li>@Html.ActionLink("Manage Titles", "Index", "Title")</li>
<li>@Html.ActionLink("Manage Organizations", "Index", "Organization")</li>
<li>@Html.ActionLink("Manage Instructors", "Index", "Instructor")</li>
</ul> | @model dynamic
@{
ViewBag.Title = "Admin Homepage";
}
<h2>Admin Homepage</h2>
<ul class="nav nav-pills nav-stacked">
<li>@Html.ActionLink("Manage Titles", "Index", "Title")</li>
<li>@Html.ActionLink("Manage Organizations", "Index", "Organization")</li>
</ul> | mpl-2.0 | C# |
847dc00d91b60934f82e4d3922cb323da8d41424 | fix typo | apache/npanday,apache/npanday,apache/npanday,apache/npanday | dotnet/assemblies/NPanday.ProjectImporter/Engine/src/test/csharp/ImporterTests/AzureImportSDKVersionTest.cs | dotnet/assemblies/NPanday.ProjectImporter/Engine/src/test/csharp/ImporterTests/AzureImportSDKVersionTest.cs | //
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace NPanday.ProjectImporter.ImporterTests
{
[TestFixture]
public class AzureImportSDKVersionTest : AbstractAzureImportTest
{
public override void CheckFrameworkVersion()
{
if (Environment.Version.Major < 4)
{
Assert.Ignore("Test only runs on .NET 4.0, but is: " + Environment.Version.ToString());
}
}
public override string SolutionFileRelativePath
{
get { return @"NPANDAY_571\NPANDAY_571_AzureSDKVersionTest.sln"; }
}
[Test]
public override void ShouldGenerateTheExpectedNumberOfPoms()
{
ProjectImporterAssertions.AssertPomCount(3, GeneratedPomFiles);
}
public override bool UseMsDeploy
{
get { return true; }
}
public override string TestResourcePath
{
get { return @"src\test\resource\NPANDAY_571\"; }
}
}
}
| //
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace NPanday.ProjectImporter.ImporterTests
{
[TestFixture]
public class AzureImporSDKVersionTest : AbstractAzureImportTest
{
public override void CheckFrameworkVersion()
{
if (Environment.Version.Major < 4)
{
Assert.Ignore("Test only runs on .NET 4.0, but is: " + Environment.Version.ToString());
}
}
public override string SolutionFileRelativePath
{
get { return @"NPANDAY_571\NPANDAY_571_AzureSDKVersionTest.sln"; }
}
[Test]
public override void ShouldGenerateTheExpectedNumberOfPoms()
{
ProjectImporterAssertions.AssertPomCount(3, GeneratedPomFiles);
}
public override bool UseMsDeploy
{
get { return true; }
}
public override string TestResourcePath
{
get { return @"src\test\resource\NPANDAY_571\"; }
}
}
}
| apache-2.0 | C# |
0bb0949bfba8b76fc97e12672646b61f58099c0b | Make consistent. | agocke/roslyn,genlu/roslyn,MichalStrehovsky/roslyn,DustinCampbell/roslyn,swaroop-sridhar/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,abock/roslyn,stephentoub/roslyn,heejaechang/roslyn,xasx/roslyn,xasx/roslyn,ErikSchierboom/roslyn,genlu/roslyn,jcouv/roslyn,gafter/roslyn,wvdd007/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,VSadov/roslyn,VSadov/roslyn,gafter/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,sharwell/roslyn,davkean/roslyn,dotnet/roslyn,brettfo/roslyn,KevinRansom/roslyn,tannergooding/roslyn,wvdd007/roslyn,heejaechang/roslyn,sharwell/roslyn,physhi/roslyn,MichalStrehovsky/roslyn,eriawan/roslyn,jmarolf/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,reaction1989/roslyn,brettfo/roslyn,VSadov/roslyn,agocke/roslyn,weltkante/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,aelij/roslyn,jmarolf/roslyn,dotnet/roslyn,tannergooding/roslyn,diryboy/roslyn,KevinRansom/roslyn,nguerrera/roslyn,AlekseyTs/roslyn,dotnet/roslyn,sharwell/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,abock/roslyn,genlu/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,brettfo/roslyn,weltkante/roslyn,AmadeusW/roslyn,mavasani/roslyn,nguerrera/roslyn,davkean/roslyn,abock/roslyn,DustinCampbell/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,reaction1989/roslyn,reaction1989/roslyn,tannergooding/roslyn,davkean/roslyn,eriawan/roslyn,swaroop-sridhar/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,diryboy/roslyn,xasx/roslyn,tmat/roslyn,AlekseyTs/roslyn,MichalStrehovsky/roslyn,nguerrera/roslyn,stephentoub/roslyn,diryboy/roslyn,aelij/roslyn,eriawan/roslyn,agocke/roslyn,wvdd007/roslyn,panopticoncentral/roslyn,jcouv/roslyn,weltkante/roslyn,gafter/roslyn,physhi/roslyn,heejaechang/roslyn,mavasani/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,jcouv/roslyn,swaroop-sridhar/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,tmat/roslyn,DustinCampbell/roslyn,aelij/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn | src/Workspaces/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexEmbeddedLanguage.cs | src/Workspaces/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexEmbeddedLanguage.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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification.Classifiers;
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices
{
internal class RegexEmbeddedLanguage : IEmbeddedLanguage
{
public readonly EmbeddedLanguageInfo Info;
public ISyntaxClassifier Classifier { get; }
public RegexEmbeddedLanguage(EmbeddedLanguageInfo info)
{
Info = info;
Classifier = new RegexSyntaxClassifier(info);
}
internal async Task<(RegexTree tree, SyntaxToken token)> TryGetTreeAndTokenAtPositionAsync(
Document document, int position, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(position);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
if (RegexPatternDetector.IsDefinitelyNotPattern(token, syntaxFacts))
{
return default;
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var detector = RegexPatternDetector.TryGetOrCreate(semanticModel, this.Info);
var tree = detector?.TryParseRegexPattern(token, cancellationToken);
return tree == null ? default : (tree, token);
}
internal async Task<RegexTree> TryGetTreeAtPositionAsync(
Document document, int position, CancellationToken cancellationToken)
{
var (tree, _) = await TryGetTreeAndTokenAtPositionAsync(
document, position, cancellationToken).ConfigureAwait(false);
return tree;
}
}
}
| // 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification.Classifiers;
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices
{
internal class RegexEmbeddedLanguage : IEmbeddedLanguage
{
public readonly EmbeddedLanguageInfo Info;
public ISyntaxClassifier Classifier { get; }
public RegexEmbeddedLanguage(EmbeddedLanguageInfo info)
{
this.Info = info;
Classifier = new RegexSyntaxClassifier(info);
}
internal async Task<(RegexTree tree, SyntaxToken token)> TryGetTreeAndTokenAtPositionAsync(
Document document, int position, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(position);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
if (RegexPatternDetector.IsDefinitelyNotPattern(token, syntaxFacts))
{
return default;
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var detector = RegexPatternDetector.TryGetOrCreate(semanticModel, this.Info);
var tree = detector?.TryParseRegexPattern(token, cancellationToken);
return tree == null ? default : (tree, token);
}
internal async Task<RegexTree> TryGetTreeAtPositionAsync(
Document document, int position, CancellationToken cancellationToken)
{
var (tree, _) = await TryGetTreeAndTokenAtPositionAsync(
document, position, cancellationToken).ConfigureAwait(false);
return tree;
}
}
}
| mit | C# |
f771a4155cdfef08da87310b92d722191e7565c8 | Update tests. | DropNet/DropNet | DropNet.Tests/TestVariables.cs | DropNet.Tests/TestVariables.cs |
namespace DropNet.Tests
{
public static class TestVariables
{
//Insert yo stuff here to run the tests
public static string ApiKey = "APIKEY";
public static string ApiSecret = "APISECRET";
public static string ApiKey_Sandbox = "SANDBOXKEY";
public static string ApiSecret_Sandbox = "SANDBOXSECRET";
public static string Email = "EMAIL";
public static string Password = "PASSWORD";
public static string Token = "TOKEN";
public static string Secret = "SECRET";
public static string Token_Sandbox = "SANDBOXTOKEN";
public static string Secret_Sandbox = "SANDBOXSECRET";
}
}
|
namespace DropNet.Tests
{
public static class TestVariables
{
//Insert yo stuff here to run the tests
public static string ApiKey = "qgy5kj76jb5mxto";
public static string ApiSecret = "3dkrpzwdw2eyeqn";
public static string ApiKey_Sandbox = "ni2xys08hyzl0l1";
public static string ApiSecret_Sandbox = "ia62ljd7uj9rf9k";
public static string Email = "EMAIL";
public static string Password = "PASSWORD";
public static string Token = "8566cynlt782l9o";
public static string Secret = "0y1u9a5mofwkrwj";
public static string Token_Sandbox = "lf8nt6xf1xyid3u";
public static string Secret_Sandbox = "upffd03b69v9i3b";
}
}
| apache-2.0 | C# |
88410ff87d6beab871b6e2970aee59adb6126ee9 | Update NumberChainValidator.cs | kenshinthebattosai/KenChainer | KenChainer/Validators/NumberChainValidator.cs | KenChainer/Validators/NumberChainValidator.cs | using System.Linq;
using System.Text.RegularExpressions;
using KenChainer.Core;
namespace KenChainer.Validators
{
/// <summary>
/// Default rules for the problem go here.
/// Currently there are 4 rules:
/// Only 7 numbers
/// Only 6 operators
/// All 4 operators must be used
/// 2 operators must be used twice
/// </summary>
public class NumberChainValidator : INumberChainValidator
{
private static readonly Regex Operators = new Regex("\\+|\\-|x|\\/",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline);
public bool IsValid(NumberChain numberChain)
{
try
{
// Only seven numbers
if (numberChain.Length != 7)
return false;
var operators =
Operators.Matches(numberChain.ToString()).Cast<object>().Select(x => x.ToString()).ToList();
// Only 6 operators
if (operators.Count != 6) return false;
// All 4 operators should be used
var grouped = operators.GroupBy(x => x);
if (grouped.Count() != 4) return false;
// Maximum of 2 operators can be used twice
var groupedByCount = grouped.GroupBy(x => x.Count());
var countOfOperatorsUsedTwice = groupedByCount.FirstOrDefault(x => x.Key == 2)?.Count();
if (countOfOperatorsUsedTwice != 2)
return false;
// Validated
return true;
}
catch
{
return false;
}
}
}
}
| using System.Linq;
using System.Text.RegularExpressions;
using KenChainer.Core;
namespace KenChainer.Validators
{
/// <summary>
/// Default rules for the problem go here.
/// Currently there are 3 rules:
/// Only 7 numbers
/// Only 6 operators
/// All 4 operators must be used
/// 2 operators must be used twice
/// </summary>
public class NumberChainValidator : INumberChainValidator
{
private static readonly Regex Operators = new Regex("\\+|\\-|x|\\/",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline);
public bool IsValid(NumberChain numberChain)
{
try
{
// Only seven numbers
if (numberChain.Length != 7)
return false;
var operators =
Operators.Matches(numberChain.ToString()).Cast<object>().Select(x => x.ToString()).ToList();
// Only 6 operators
if (operators.Count != 6) return false;
// All 4 operators should be used
var grouped = operators.GroupBy(x => x);
if (grouped.Count() != 4) return false;
// Maximum of 2 operators can be used twice
var groupedByCount = grouped.GroupBy(x => x.Count());
var countOfOperatorsUsedTwice = groupedByCount.FirstOrDefault(x => x.Key == 2)?.Count();
if (countOfOperatorsUsedTwice != 2)
return false;
// Validated
return true;
}
catch
{
return false;
}
}
}
}
| mit | C# |
24d4bec699d7d3b6a080ab2566597045fe7f9911 | Include the Table namespace into Hangman | 12joan/hangman | hangman.cs | hangman.cs | using System;
using Table;
public class Hangman {
public static void Main(string[] args) {
Console.WriteLine("Hello, World!");
Console.WriteLine("You entered the following {0} command line arguments:",
args.Length );
for (int i=0; i < args.Length; i++) {
Console.WriteLine("{0}", args[i]);
}
}
}
| using System;
public class Hangman {
public static void Main(string[] args) {
Console.WriteLine("Hello, World!");
Console.WriteLine("You entered the following {0} command line arguments:",
args.Length );
for (int i=0; i < args.Length; i++) {
Console.WriteLine("{0}", args[i]);
}
}
}
| unlicense | C# |
c509dd9723c9a24339d1b096023df34beeee0fea | Fix safety net emits sound only when ball is slowed down. | gbudiman/glass | Gloria_Huixin_Glass/Assets/Networking/SafetyNet.cs | Gloria_Huixin_Glass/Assets/Networking/SafetyNet.cs | using UnityEngine;
using System.Collections;
public class SafetyNet : MonoBehaviour {
BoxCollider2D bcl;
SpriteRenderer sr;
PhotonView photon_view;
AudioSource audio_source;
public AudioClip clip_slow_down;
const float base_duration = 8f;
float timer;
bool is_enabled = false;
// Use this for initialization
void Start () {
bcl = GetComponent<BoxCollider2D>();
sr = GetComponentInChildren<SpriteRenderer>();
photon_view = GetComponent<PhotonView>();
audio_source = GetComponent<AudioSource>();
audio_source.clip = clip_slow_down;
}
// Update is called once per frame
void Update () {
TickDuration();
}
void TickDuration() {
if (!is_enabled) { return; }
timer -= Time.deltaTime;
float clamped_alpha = Mathf.Clamp01(timer / base_duration * 1.0f + 0.33f);
sr.color = new Color(sr.color.r, sr.color.g, sr.color.b, clamped_alpha);
if (timer < 0) {
SetEnable(false);
}
}
[PunRPC]
void UpdateSafetyNetOverNetwork() {
if (!photon_view.isMine) {
SetEnable(true);
}
}
void OnTriggerEnter2D(Collider2D other) {
if (other.GetComponent<GlassBall>() != null) {
Rigidbody2D other_rb = other.GetComponent<GlassBall>().GetComponent<Rigidbody2D>();
if (PhotonNetwork.connected) {
if (PhotonNetwork.isMasterClient && photon_view.isMine ||
!PhotonNetwork.isMasterClient && !photon_view.isMine) {
if (other_rb.velocity.y > 0) {
audio_source.Play();
other_rb.velocity *= 0.5f;
}
} else {
if (other_rb.velocity.y < 0) {
audio_source.Play();
other_rb.velocity *= 0.5f;
}
}
} else {
if (other_rb.velocity.y < 0) {
audio_source.Play();
other_rb.velocity *= 0.5f;
}
}
}
}
public void SetEnable(bool enable) {
bcl.enabled = enable;
sr.enabled = enable;
is_enabled = true;
if (enable) {
timer = base_duration;
if (PhotonNetwork.connected) {
photon_view.RPC("UpdateSafetyNetOverNetwork", PhotonTargets.Others);
}
}
}
}
| using UnityEngine;
using System.Collections;
public class SafetyNet : MonoBehaviour {
BoxCollider2D bcl;
SpriteRenderer sr;
PhotonView photon_view;
AudioSource audio_source;
public AudioClip clip_slow_down;
const float base_duration = 8f;
float timer;
bool is_enabled = false;
// Use this for initialization
void Start () {
bcl = GetComponent<BoxCollider2D>();
sr = GetComponentInChildren<SpriteRenderer>();
photon_view = GetComponent<PhotonView>();
audio_source = GetComponent<AudioSource>();
audio_source.clip = clip_slow_down;
}
// Update is called once per frame
void Update () {
TickDuration();
}
void TickDuration() {
if (!is_enabled) { return; }
timer -= Time.deltaTime;
float clamped_alpha = Mathf.Clamp01(timer / base_duration * 1.0f + 0.33f);
sr.color = new Color(sr.color.r, sr.color.g, sr.color.b, clamped_alpha);
if (timer < 0) {
SetEnable(false);
}
}
[PunRPC]
void UpdateSafetyNetOverNetwork() {
if (!photon_view.isMine) {
SetEnable(true);
}
}
void OnTriggerEnter2D(Collider2D other) {
if (other.GetComponent<GlassBall>() != null) {
audio_source.Play();
Rigidbody2D other_rb = other.GetComponent<GlassBall>().GetComponent<Rigidbody2D>();
if (PhotonNetwork.connected) {
if (PhotonNetwork.isMasterClient && photon_view.isMine ||
!PhotonNetwork.isMasterClient && !photon_view.isMine) {
if (other_rb.velocity.y > 0) {
other_rb.velocity *= 0.5f;
}
} else {
if (other_rb.velocity.y < 0) {
other_rb.velocity *= 0.5f;
}
}
} else {
if (other_rb.velocity.y < 0) {
other_rb.velocity *= 0.5f;
}
}
}
}
public void SetEnable(bool enable) {
bcl.enabled = enable;
sr.enabled = enable;
is_enabled = true;
if (enable) {
timer = base_duration;
if (PhotonNetwork.connected) {
photon_view.RPC("UpdateSafetyNetOverNetwork", PhotonTargets.Others);
}
}
}
}
| mit | C# |
2116aa572ff979b2b8ba23cf771995465d634146 | Add vote method to voting service | Branimir123/PhotoLife,Branimir123/PhotoLife,Branimir123/PhotoLife | PhotoLife/PhotoLife.Services/VotingService.cs | PhotoLife/PhotoLife.Services/VotingService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PhotoLife.Data.Contracts;
using PhotoLife.Factories;
using PhotoLife.Models;
using PhotoLife.Services.Contracts;
namespace PhotoLife.Services
{
public class VotingService
{
private readonly IRepository<Vote> voteRepository;
private readonly IUnitOfWork unitOfWork;
private readonly IVoteFactory voteFactory;
private readonly IPostService postService;
public VotingService(IRepository<Vote> voteRepository, IUnitOfWork unitOfWork, IVoteFactory voteFactory, IPostService postService)
{
if (voteRepository == null)
{
throw new ArgumentNullException(nameof(voteRepository));
}
if (unitOfWork == null)
{
throw new ArgumentNullException(nameof(unitOfWork));
}
if (postService == null)
{
throw new ArgumentNullException(nameof(postService));
}
if (voteFactory == null)
{
throw new ArgumentNullException(nameof(voteFactory));
}
this.voteRepository = voteRepository;
this.unitOfWork = unitOfWork;
this.postService = postService;
this.voteFactory = voteFactory;
}
public int Vote(int postId, string userId)
{
var userVoteOnLog = this.voteRepository
.GetAll
.FirstOrDefault(v => v.PostId.Equals(postId) && v.UserId.Equals(userId));
var notVoted = (userVoteOnLog == null);
if (notVoted)
{
var log = this.postService.GetPostById(postId);
if (log != null)
{
var vote = this.voteFactory.CreateVote(postId, userId);
this.voteRepository.Add(vote);
this.unitOfWork.Commit();
return log.Votes.Count;
}
}
return -1;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PhotoLife.Services
{
class VotingService
{
}
}
| mit | C# |
f1e630edcfd72b8b731a3583e62347f48920a881 | Increment version 0.1.3 -> 0.1.4 | genius394/PogoLocationFeeder,5andr0/PogoLocationFeeder,5andr0/PogoLocationFeeder | PogoLocationFeeder/Properties/AssemblyInfo.cs | PogoLocationFeeder/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PogoLocationFeeder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PogoLocationFeeder")]
[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("76f6eeef-e89f-4e43-aa9d-1567cbc1420b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.4.0")]
[assembly: AssemblyFileVersion("0.1.4.0")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PogoLocationFeeder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PogoLocationFeeder")]
[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("76f6eeef-e89f-4e43-aa9d-1567cbc1420b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.3.0")]
[assembly: AssemblyFileVersion("0.1.3.0")] | agpl-3.0 | C# |
2cab11682e5358d3ad5859d3004ddfeae5fb2081 | Load main screen within content view on first load | AlexStefan/template-app | TemplateMenu/Template.Droid/Views/RootView.cs | TemplateMenu/Template.Droid/Views/RootView.cs | using Android.App;
using Android.OS;
using Android.Support.V4.Widget;
using Android.Widget;
using MvvmCross.Droid.Support.V7.AppCompat;
using TemplateMenu.Core.ViewModels;
using TemplateMenu.Droid.Custom;
namespace TemplateMenu.Droid.Views
{
[Activity(Label = "Template Menu", MainLauncher = true)]
public class RootView : MvxCachingFragmentCompatActivity
{
private DrawerLayout drawerLayout;
private LinearLayout drawerMenu;
private CustomDrawerToggle drawerToggle;
public new RootViewModel ViewModel
{
get { return (RootViewModel)base.ViewModel; }
set { base.ViewModel = value; }
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.NavigationDrawer);
Init();
SetMenu();
}
private void Init()
{
drawerLayout = FindViewById<DrawerLayout>(Resource.Id.DrawerLayout);
drawerMenu = FindViewById<LinearLayout>(Resource.Id.LeftMenu);
var Toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
if (Toolbar != null)
SetActionBar(Toolbar);
drawerToggle = new CustomDrawerToggle(this, drawerLayout, 0, 0);
drawerLayout.AddDrawerListener(drawerToggle);
drawerToggle.SyncState();
drawerLayout.CloseDrawer(drawerMenu);
ViewModel.MainScreenCommand.Execute(null);
}
private void SetMenu()
{
var home = drawerLayout.FindViewById<LinearLayout>(Resource.Id.lytHome);
home.Click += (sender, e) => {
ViewModel.MainScreenCommand.Execute(null);
drawerLayout.CloseDrawer(drawerMenu);
};
var second = drawerLayout.FindViewById<LinearLayout>(Resource.Id.lytSecondView);
second.Click += (sender, e) => {
ViewModel.SecondScreenCommand.Execute(null);
drawerLayout.CloseDrawer(drawerMenu);
};
}
}
} | using Android.App;
using Android.OS;
using Android.Support.V4.Widget;
using Android.Widget;
using MvvmCross.Droid.Support.V7.AppCompat;
using TemplateMenu.Core.ViewModels;
using TemplateMenu.Droid.Custom;
namespace TemplateMenu.Droid.Views
{
[Activity(Label = "Template Menu", MainLauncher = true)]
public class RootView : MvxCachingFragmentCompatActivity
{
private DrawerLayout drawerLayout;
private LinearLayout drawerMenu;
private CustomDrawerToggle drawerToggle;
public new RootViewModel ViewModel
{
get { return (RootViewModel)base.ViewModel; }
set { base.ViewModel = value; }
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.NavigationDrawer);
Init();
SetMenu();
}
private void Init()
{
drawerLayout = FindViewById<DrawerLayout>(Resource.Id.DrawerLayout);
drawerMenu = FindViewById<LinearLayout>(Resource.Id.LeftMenu);
var Toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
if (Toolbar != null)
SetActionBar(Toolbar);
drawerToggle = new CustomDrawerToggle(this, drawerLayout, 0, 0);
drawerLayout.AddDrawerListener(drawerToggle);
drawerToggle.SyncState();
drawerLayout.CloseDrawer(drawerMenu);
}
private void SetMenu()
{
var home = drawerLayout.FindViewById<LinearLayout>(Resource.Id.lytHome);
home.Click += (sender, e) => {
ViewModel.MainScreenCommand.Execute(null);
drawerLayout.CloseDrawer(drawerMenu);
};
var second = drawerLayout.FindViewById<LinearLayout>(Resource.Id.lytSecondView);
second.Click += (sender, e) => {
ViewModel.SecondScreenCommand.Execute(null);
drawerLayout.CloseDrawer(drawerMenu);
};
}
}
} | mit | C# |
cd598c82a60f48053e8d4346a8a4572ac6b1000b | rollback to previous version | eriforce/PureLib | trunk/PureLib/Common/Entities/Arguments.cs | trunk/PureLib/Common/Entities/Arguments.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
namespace PureLib.Common.Entities {
/// <summary>
/// A structure of the startup arguments from command-line.
/// </summary>
[Serializable]
public class Arguments : Dictionary<string, List<string>> {
/// <summary>
/// Initializes a new instance of Arguments.
/// </summary>
/// <param name="args"></param>
public Arguments(string[] args) : base(StringComparer.OrdinalIgnoreCase) {
if ((args == null) || (args.Length == 0))
return;
const string argumentName = "name";
string argumentNamePattern = @"^(/|\-{{1,2}})(?<{0}>\w+)$".FormatWith(argumentName);
string currentName = null;
foreach (string arg in args) {
Match m = Regex.Match(arg, argumentNamePattern);
if (m.Success) {
currentName = m.Groups[argumentName].Value;
Add(currentName, new List<string>());
}
else if (!currentName.IsNullOrEmpty())
this[currentName].Add(arg);
}
}
/// <summary>
/// Initializes a new instance of Arguments with serialized data.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected Arguments(SerializationInfo info, StreamingContext context)
: base(info, context) {
}
/// <summary>
/// Gets the value by provided key.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetValue(string key) {
if (!ContainsKey(key))
throw new ApplicationException("The key cannot be found in arguments.");
return this[key].FirstOrDefault();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
namespace PureLib.Common.Entities {
/// <summary>
/// A structure of the startup arguments from command-line.
/// </summary>
[Serializable]
public class Arguments : Dictionary<string, List<string>> {
/// <summary>
/// Initializes a new instance of Arguments.
/// </summary>
/// <param name="args"></param>
public Arguments(string[] args) : base(StringComparer.OrdinalIgnoreCase) {
if ((args == null) || (args.Length == 0))
return;
const string argumentName = "name";
string argumentNamePattern = @"^(/|\-{{1,2}})(?<{0}>\w+)$".FormatWith(argumentName);
string currentName = null;
foreach (string arg in args) {
Match m = Regex.Match(arg, argumentNamePattern);
if (m.Success) {
currentName = m.Groups[argumentName].Value;
Add(currentName, new List<string>());
}
else if (!currentName.IsNullOrEmpty())
this[currentName].Add(arg.Replace("\"", string.Empty));
}
}
/// <summary>
/// Initializes a new instance of Arguments with serialized data.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected Arguments(SerializationInfo info, StreamingContext context)
: base(info, context) {
}
/// <summary>
/// Gets the value by provided key.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetValue(string key) {
if (!ContainsKey(key))
throw new ApplicationException("The key cannot be found in arguments.");
return this[key].FirstOrDefault();
}
}
}
| mit | C# |
167b92bf2e99ab99aca8bc66604fbc944bca9ae6 | fix MainThreadDispatcher ourUIThread | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | unity/EditorPlugin/MainThreadDispatcher.cs | unity/EditorPlugin/MainThreadDispatcher.cs | using System;
using System.Collections.Generic;
using System.Threading;
using JetBrains.Platform.RdFramework;
using JetBrains.Util;
using JetBrains.Util.Logging;
using UnityEditor;
namespace JetBrains.Rider.Unity.Editor
{
public class MainThreadDispatcher : IScheduler
{
private static Thread ourUIThread;
internal static readonly MainThreadDispatcher Instance = new MainThreadDispatcher();
/// <summary>
/// The queue of tasks that are being requested for the next time DispatchTasks is called
/// </summary>
private readonly Queue<Action> myTaskQueue = new Queue<Action>();
private MainThreadDispatcher()
{
EditorApplication.update += DispatchTasks;
}
/// <summary>
/// Dispatches the specified action delegate.
/// </summary>
/// <param name="action">Action being requested</param>
public void Queue(Action action)
{
if (Thread.CurrentThread == ourUIThread)
{
action();
return;
}
lock (myTaskQueue)
{
myTaskQueue.Enqueue(action);
}
}
/// <summary>
/// Dispatches the tasks that has been requested since the last call to this function
/// </summary>
private void DispatchTasks()
{
ourUIThread = Thread.CurrentThread;
if (myTaskQueue.Count == 0)
return;
while (true)
{
try
{
if (myTaskQueue.Count == 0)
return;
var task = myTaskQueue.Dequeue();
task();
}
catch (Exception e)
{
Log.GetLog<MainThreadDispatcher>().Error(e);
}
}
}
public static void AssertThread()
{
Assertion.Require(ourUIThread == null || ourUIThread == Thread.CurrentThread, "Not a UI thread");
}
/// <summary>
/// Indicates whether there are tasks available for dispatching
/// </summary>
/// <value>
/// <c>true</c> if there are tasks available for dispatching; otherwise, <c>false</c>.
/// </value>
public bool IsActive => ourUIThread == null || ourUIThread == Thread.CurrentThread;
public bool OutOfOrderExecution => false;
}
} | using System;
using System.Collections.Generic;
using System.Threading;
using JetBrains.Platform.RdFramework;
using JetBrains.Util;
using JetBrains.Util.Logging;
using UnityEditor;
namespace JetBrains.Rider.Unity.Editor
{
public class MainThreadDispatcher : IScheduler
{
internal static readonly MainThreadDispatcher Instance = new MainThreadDispatcher();
private static Thread ourUIThread;
private MainThreadDispatcher()
{
ourUIThread = Thread.CurrentThread;
EditorApplication.update += DispatchTasks;
}
/// <summary>
/// The queue of tasks that are being requested for the next time DispatchTasks is called
/// </summary>
private readonly Queue<Action> myTaskQueue = new Queue<Action>();
/// <summary>
/// Dispatches the specified action delegate.
/// </summary>
/// <param name="action">Action being requested</param>
public void Queue(Action action)
{
if (Thread.CurrentThread == ourUIThread)
{
action();
return;
}
lock (myTaskQueue)
{
myTaskQueue.Enqueue(action);
}
}
/// <summary>
/// Dispatches the tasks that has been requested since the last call to this function
/// </summary>
private void DispatchTasks()
{
if (myTaskQueue.Count == 0)
return;
while (true)
{
try
{
if (myTaskQueue.Count == 0)
return;
var task = myTaskQueue.Dequeue();
task();
}
catch (Exception e)
{
Log.GetLog<MainThreadDispatcher>().Error(e);
}
}
}
public static void AssertThread()
{
Assertion.Require(ourUIThread == null || ourUIThread == Thread.CurrentThread, "Not not UI thread");
}
/// <summary>
/// Indicates whether there are tasks available for dispatching
/// </summary>
/// <value>
/// <c>true</c> if there are tasks available for dispatching; otherwise, <c>false</c>.
/// </value>
public bool IsActive => ourUIThread == null || ourUIThread == Thread.CurrentThread;
public bool OutOfOrderExecution => false;
}
} | apache-2.0 | C# |
636b7dd011a598350d567b0ab6342b464367b2fc | Increase the page size for the logs polling. (#1419) | googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,evildour/google-cloud-dotnet,benwulfe/google-cloud-dotnet,googleapis/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,chrisdunelm/gcloud-dotnet,evildour/google-cloud-dotnet,evildour/google-cloud-dotnet,iantalarico/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/gcloud-dotnet,benwulfe/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,iantalarico/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,benwulfe/google-cloud-dotnet,iantalarico/google-cloud-dotnet | apis/Google.Cloud.Diagnostics.Common/Google.Cloud.Diagnostics.Common.IntegrationTests/Logging/LogEntryPolling.cs | apis/Google.Cloud.Diagnostics.Common/Google.Cloud.Diagnostics.Common.IntegrationTests/Logging/LogEntryPolling.cs | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.Diagnostics.Common.Tests;
using Google.Cloud.Logging.V2;
using System;
using System.Collections.Generic;
using System.Xml;
namespace Google.Cloud.Diagnostics.Common.IntegrationTests
{
/// <summary>
/// An implementation of <see cref="BaseEntryPolling{T}"/> for <see cref="LogEntry"/>s.
/// </summary>
internal class LogEntryPolling : BaseEntryPolling<LogEntry>
{
/// <summary>Project id to run the test on.</summary>
private readonly string _projectId = Utils.GetProjectIdFromEnvironment();
/// <summary>Client to use to send RPCs.</summary>
private readonly LoggingServiceV2Client _client = LoggingServiceV2Client.Create();
/// <summary>
/// Gets log entries that contain the passed in testId in the log message. Will poll
/// and wait for the entries to appear.
/// </summary>
/// <param name="startTime">The earliest log entry time that will be looked at.</param>
/// <param name="testId">The test id to filter log entries on.</param>
/// <param name="minEntries">The minimum number of logs entries that should be waited for.
/// If minEntries is zero this method will wait the full timeout before checking for the
/// entries.</param>
public IEnumerable<LogEntry> GetEntries(DateTime startTime, string testId, int minEntries)
{
return GetEntries(minEntries, () =>
{
// Convert the time to RFC3339 UTC format.
string time = XmlConvert.ToString(startTime, XmlDateTimeSerializationMode.Utc);
var request = new ListLogEntriesRequest
{
ResourceNames = { $"projects/{_projectId}" },
Filter = $"timestamp >= \"{time}\" AND textPayload:{testId}",
PageSize = 1000,
};
return _client.ListLogEntries(request);
});
}
}
}
| // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.Diagnostics.Common.Tests;
using Google.Cloud.Logging.V2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
namespace Google.Cloud.Diagnostics.Common.IntegrationTests
{
/// <summary>
/// An implementation of <see cref="BaseEntryPolling{T}"/> for <see cref="LogEntry"/>s.
/// </summary>
internal class LogEntryPolling : BaseEntryPolling<LogEntry>
{
/// <summary>Project id to run the test on.</summary>
private readonly string _projectId = Utils.GetProjectIdFromEnvironment();
/// <summary>Client to use to send RPCs.</summary>
private readonly LoggingServiceV2Client _client = LoggingServiceV2Client.Create();
/// <summary>
/// Gets log entries that contain the passed in testId in the log message. Will poll
/// and wait for the entries to appear.
/// </summary>
/// <param name="startTime">The earliest log entry time that will be looked at.</param>
/// <param name="testId">The test id to filter log entries on.</param>
/// <param name="minEntries">The minimum number of logs entries that should be waited for.
/// If minEntries is zero this method will wait the full timeout before checking for the
/// entries.</param>
public IEnumerable<LogEntry> GetEntries(DateTime startTime, string testId, int minEntries)
{
return GetEntries(minEntries, () =>
{
// Convert the time to RFC3339 UTC format.
string time = XmlConvert.ToString(startTime, XmlDateTimeSerializationMode.Utc);
var request = new ListLogEntriesRequest
{
ResourceNames = { $"projects/{_projectId}" },
Filter = $"timestamp >= \"{time}\" AND textPayload:{testId}",
PageSize = 250,
};
return _client.ListLogEntries(request);
});
}
}
}
| apache-2.0 | C# |
e057cf1f91da41169bd580507be690d56ed660e6 | Fix Nupkg Version | MassTransit/MassTransit,MassTransit/MassTransit,phatboyg/MassTransit,phatboyg/MassTransit | build/version.cake | build/version.cake | public class BuildVersion
{
public string Prefix { get; set; }
public string Suffix { get; set; }
public static BuildVersion Calculate(ICakeContext context, BuildParameters buildParameters)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var buildSystem = context.BuildSystem();
var prefix = context.XmlPeek(buildParameters.Paths.Files.VersionProperties, "/Project/PropertyGroup/VersionPrefix/text()");
string suffix = "alpha.9999";
if(!buildParameters.IsLocalBuild)
{
var commitHash = buildSystem.AppVeyor.Environment.Repository.Commit.Id;
suffix =
buildParameters.IsMasterBranch ? null
: buildParameters.IsDevelopBranch ? "develop"
: "beta";
if(suffix != null)
suffix += "." + buildSystem.AppVeyor.Environment.Build.Number + "+sha." + commitHash.Substring(0,Math.Min(commitHash.Length,7));
}
return new BuildVersion
{
Prefix = prefix,
Suffix = suffix
};
}
}
| public class BuildVersion
{
public string Prefix { get; set; }
public string Suffix { get; set; }
public static BuildVersion Calculate(ICakeContext context, BuildParameters buildParameters)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var buildSystem = context.BuildSystem();
var prefix = context.XmlPeek(buildParameters.Paths.Files.VersionProperties, "/Project/PropertyGroup/VersionPrefix/text()");
string suffix = "alpha.9999";
if(!buildParameters.IsLocalBuild)
{
suffix =
buildParameters.IsMasterBranch ? null
: buildParameters.IsDevelopBranch ? "preview"
: "beta";
if(suffix != null)
suffix += "." + buildSystem.AppVeyor.Environment.Build.Number + "+git.hash" + buildSystem.AppVeyor.Environment.Repository.Commit.Id;
}
return new BuildVersion
{
Prefix = prefix,
Suffix = suffix
};
}
}
| apache-2.0 | C# |
a1dec59b014ef5fddcd64ef709d59c299c931d13 | Set DateFormat in RestSharp so DateTimes would deserialize with correct DateTime.Kind. | crdeutsch/Agvise-Api-DotNet | Agvise.Api/AgviseClient.cs | Agvise.Api/AgviseClient.cs | using Agvise.Api.Models;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Agvise.Api
{
public class AgviseClient
{
public static string BaseUrl = "https://submit.agvise.com/api/";
public static string Resource = "content/item.js?nonce={nonce}";
private readonly RestClient _client;
public AgviseClient(string apiKey)
{
_client = new RestClient(BaseUrl);
_client.Authenticator = new HttpBasicAuthenticator(apiKey, null);
}
public SubmittedSampleOrder GetSampleSubmission(long sampleOrderID)
{
var request = new RestRequest("samples/submit/{id}");
request.RequestFormat = DataFormat.Json;
request.DateFormat = "yyyy-MM-ddTHH:mm:ssZ"; // do this so we get the right timezone
request.AddUrlSegment("id", sampleOrderID.ToString());
request.Method = Method.GET;
var response = _client.Execute<ApiResponse<SubmittedSampleOrder>>(request);
response.ThrowExceptionsForErrors<SubmittedSampleOrder>();
return response.Data.Data;
}
public SubmittedSampleOrder SubmitSample(SampleOrder sampleOrder)
{
var request = new RestRequest("samples/submit");
request.RequestFormat = DataFormat.Json;
request.DateFormat = "yyyy-MM-ddTHH:mm:ssZ"; // do this so we get the right timezone
request.Method = Method.POST;
request.AddBody(sampleOrder);
var response = _client.Execute<ApiResponse<SubmittedSampleOrder>>(request);
response.ThrowExceptionsForErrors<SubmittedSampleOrder>();
return response.Data.Data;
}
public RestClient RestClient
{
get
{
return _client;
}
}
}
}
| using Agvise.Api.Models;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Agvise.Api
{
public class AgviseClient
{
public static string BaseUrl = "https://submit.agvise.com/api/";
public static string Resource = "content/item.js?nonce={nonce}";
private readonly RestClient _client;
public AgviseClient(string apiKey)
{
_client = new RestClient(BaseUrl);
_client.Authenticator = new HttpBasicAuthenticator(apiKey, null);
}
public SubmittedSampleOrder GetSampleSubmission(long sampleOrderID)
{
var request = new RestRequest("samples/submit/{id}");
request.RequestFormat = DataFormat.Json;
request.AddUrlSegment("id", sampleOrderID.ToString());
request.Method = Method.GET;
var response = _client.Execute<ApiResponse<SubmittedSampleOrder>>(request);
response.ThrowExceptionsForErrors<SubmittedSampleOrder>();
return response.Data.Data;
}
public SubmittedSampleOrder SubmitSample(SampleOrder sampleOrder)
{
var request = new RestRequest("samples/submit");
request.RequestFormat = DataFormat.Json;
request.Method = Method.POST;
request.AddBody(sampleOrder);
var response = _client.Execute<ApiResponse<SubmittedSampleOrder>>(request);
response.ThrowExceptionsForErrors<SubmittedSampleOrder>();
return response.Data.Data;
}
public RestClient RestClient
{
get
{
return _client;
}
}
}
}
| mit | C# |
988165871d5da363ff99fa03ae63924b06cf82fa | Revert "Added option in Parallel to enforce a unanimous success or fail state condition in children before returning." | caseydedore/BehaviorEngine | BehaviorEngine/Nodes/Composites/Parallel.cs | BehaviorEngine/Nodes/Composites/Parallel.cs |
using System.Collections;
using System;
using System.Collections.Generic;
namespace BehaviorEngine
{
public class Parallel : ANodeComposite
{
private int index = 0;
public override void Update()
{
if (Children.Count <= 0)
{
Status = NodeState.Error;
return;
}
for (index = 0; index < Children.Count; index++)
{
if (Children[index].Status != NodeState.Active)
{
Children[index].Start();
}
Children[index].Update();
Status = Children[index].Status;
if (Status == NodeState.Failure)
{
Children[index].End();
return;
}
else if (Status == NodeState.Successful)
{
Children[index].End();
return;
}
}
}
}
}
|
namespace BehaviorEngine
{
public class Parallel : ANodeComposite
{
public bool ChildrenMustAllSucceed { get; set; }
public bool ChildrenMustAllFail { get; set; }
private int index = 0;
private int childrenSucceeded = 0,
childrenFailed = 0;
public Parallel()
{
ChildrenMustAllSucceed = false;
ChildrenMustAllFail = false;
}
public override void Update()
{
if (Children.Count <= 0)
{
Status = NodeState.Error;
return;
}
for (index = 0; index < Children.Count; index++)
{
if (Children[index].Status != NodeState.Active)
{
Children[index].Start();
}
Children[index].Update();
Status = Children[index].Status;
if (Status == NodeState.Failure)
{
Children[index].End();
childrenFailed++;
if (ChildrenMustAllFail && childrenFailed < Children.Count) Status = NodeState.Active;
return;
}
else if (Status == NodeState.Successful)
{
Children[index].End();
if(ChildrenMustAllSucceed && childrenSucceeded < Children.Count) Status = NodeState.Active;
return;
}
}
}
}
}
| mit | C# |
946390627a6821373df6d4d595cf50c1e09205b2 | Simplify C# list removal algorithm | btmills/PartitionableArray,btmills/PartitionableArray,btmills/PartitionableArray | C#/PartitionableArray/PartitionableArray.cs | C#/PartitionableArray/PartitionableArray.cs | using System;
//using System.Collections.Generic;
//using System.Linq.Expressions;
namespace PartitionableArray
{
public class PartitionableArray<T>
{
private class Element
{
public T value;
public readonly int index;
public Element prev;
public Element next;
public Element(int i) { index = i; }
}
public delegate bool EvalFn(T val);
private EvalFn test;
private Element[] arr;
private Element interesting = null;
public T this[int index] {
get { return arr[index].value; }
set {
arr[index].value = value;
if(test(value)) { // Is interesting
if(!(arr[index].prev != null
|| arr[index].next != null)) { // Is not already in list
// Add to interesting list
if(interesting != null) {
interesting.prev = arr[index];
arr[index].next = interesting;
}
interesting = arr[index];
}
} else { // Is not interesting
if(interesting != null
&& interesting.index == index) { // Is list head
// Remove list head
interesting = arr[index].next;
arr[index].next = null;
if(interesting != null) { // List is not empty
interesting.prev = null;
}
} else if(arr[index].prev != null) { // Elsewhere in list
// Remove from list
arr[index].prev.next = arr[index].next;
if(arr[index].next != null) { // Is not tail
arr[index].next.prev = arr[index].prev;
arr[index].next = null;
}
arr[index].prev = null;
}
}
}
}
public PartitionableArray (EvalFn fn, int capacity)
{
test = fn;
arr = new Element[capacity];
for (int i = 0; i < capacity; i++) {
arr [i] = new Element (i);
}
}
public bool IsInteresting()
{
return interesting != null;
}
public int InterestingElement()
{
return interesting.index;
}
}
}
| using System;
//using System.Collections.Generic;
//using System.Linq.Expressions;
namespace PartitionableArray
{
public class PartitionableArray<T>
{
private class Element
{
public T value;
public readonly int index;
public Element prev;
public Element next;
public Element(int i) { index = i; }
}
public delegate bool EvalFn(T val);
private EvalFn test;
private Element[] arr;
private Element interesting = null;
public T this[int index] {
get { return arr[index].value; }
set {
arr[index].value = value;
if(test(value)) { // Is interesting
if(!(arr[index].prev != null
|| arr[index].next != null)) { // Is not already in list
// Add to interesting list
if(interesting != null) {
interesting.prev = arr[index];
arr[index].next = interesting;
}
interesting = arr[index];
}
} else { // Is not interesting
if(arr[index].prev != null
|| arr[index].next != null
|| (interesting != null && interesting.index == index)) { // Is in list
// Remove from interesting list
if(interesting.index == index) { // Is head
interesting = arr[index].next;
arr[index].next = null;
if(interesting != null) {
interesting.prev = null;
}
} else { // Is not head
arr[index].prev.next = arr[index].next;
if(arr[index].next != null) { // Is not tail
arr[index].next.prev = arr[index].prev;
arr[index].next = null;
}
arr[index].prev = null;
}
}
}
}
}
public PartitionableArray (EvalFn fn, int capacity)
{
test = fn;
arr = new Element[capacity];
for (int i = 0; i < capacity; i++) {
arr [i] = new Element (i);
}
}
public bool IsInteresting()
{
return interesting != null;
}
public int InterestingElement()
{
return interesting.index;
}
}
}
| mit | C# |
043490bb70e5715b785e3e47c94528d4514d5f54 | fix project | Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode | CSharp7/CSharp7/7.1/2.DefaultExpressions.cs | CSharp7/CSharp7/7.1/2.DefaultExpressions.cs | using System.Linq;
using static System.Console;
namespace CSharp7
{
public sealed class DefaultExpressions
{
public DefaultExpressions()
{
int? DoSomeWorkAndGetResult(int a = default, string s = default)
{
if (s == default
// || s is default // starting from C# 8 it is not valid
)
{
return default;
}
switch(a)
{
// case (default): break; // starting from C# 8 it is not valid
default: break;
}
int? result = default;
var array = new[] { default, a, s.Length };
if (array.Sum() > 0)
{
result = array.Sum();
}
return result;
}
WriteLine(DoSomeWorkAndGetResult(default, string.Empty));
}
}
}
| using System.Linq;
using static System.Console;
namespace CSharp7
{
public sealed class DefaultExpressions
{
public DefaultExpressions()
{
int? DoSomeWorkAndGetResult(int a = default, string s = default)
{
if (s == default || s is default)
{
return default;
}
switch(a)
{
case (default): break;
default: break;
}
int? result = default;
var array = new[] { default, a, s.Length };
if (array.Sum() > 0)
{
result = array.Sum();
}
return result;
}
WriteLine(DoSomeWorkAndGetResult(default, string.Empty));
}
}
}
| mit | C# |
5b97c2b01f1fd08a2becd592d293d5165a9e31c2 | Update version information | SerialKeyManager/SKGL-Extension-for-dot-NET,artemlos/SKGL-Extension-for-dot-NET | SKM/Properties/AssemblyInfo.cs | SKM/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("SKM Client API")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Cryptolens AB")]
[assembly: AssemblyProduct("SKM")]
[assembly: AssemblyCopyright("Copyright © 2014-2018 Cryptolens AB, All rights reserved")]
[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("0f5e191b-dbc9-4a6b-8b55-7d9de286c2fd")]
// 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("4.0.3.1")]
[assembly: AssemblyFileVersion("4.0.3.1")]
| 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("SKM Client API")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Artem Los")]
[assembly: AssemblyProduct("SKM")]
[assembly: AssemblyCopyright("Copyright © 2014-2017 Artem Los, All rights reserved")]
[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("0f5e191b-dbc9-4a6b-8b55-7d9de286c2fd")]
// 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("4.0.2.6")]
[assembly: AssemblyFileVersion("4.0.2.6")]
| bsd-3-clause | C# |
a586225b172d111a1b4083e79ce8cb45e389548d | fix typo | olegsmetanin/apinet-server,olegsmetanin/apinet-server,olegsmetanin/apinet-server | AGO.Tasks/Controllers/Extensions.cs | AGO.Tasks/Controllers/Extensions.cs | using System;
using System.Linq;
using System.Linq.Expressions;
using AGO.Core.Filters.Metadata;
using AGO.Core;
namespace AGO.Tasks.Controllers
{
public static class Extensions
{
public static string EnumDisplayValue<TModel, TEnum>(
this IModelMetadata meta, Expression<Func<TModel, TEnum>> property, TEnum value)
{
var name = property.PropertyInfoFromExpression().Name;
var prop = meta.PrimitiveProperties.FirstOrDefault(p => p.Name == name);
if (prop == null)
throw new ArgumentException("Invalid property for retrive enum display value", "property");
return prop.PossibleValues[value.ToString()];
}
}
} | using System;
using System.Linq;
using System.Linq.Expressions;
using AGO.Core.Filters.Metadata;
using AGO.Core;
namespace AGO.Tasks.Controllers
{
public static class Extensions
{
public static string EnumDisplayValue<TModel, TEnum>(
this IModelMetadata meta, Expression<Func<TModel, TEnum>> property, TEnum value)
{
var name = property.PropertyInfoFromExpression().Name;
var prop = meta.PrimitiveProperties.FirstOrDefault(p => p.Name == name);
if (prop == null)
throw new ArgumentException("Invalid property for retriev enum display value", "property");
return prop.PossibleValues[value.ToString()];
}
}
} | mit | C# |
72e5dff1dbe3e163beab75e252a756656218a8f1 | Implement MediaExtractor for iOS | martijn00/XamarinMediaManager,bubavanhalen/XamarinMediaManager,mike-rowley/XamarinMediaManager,modplug/XamarinMediaManager,martijn00/XamarinMediaManager,mike-rowley/XamarinMediaManager | MediaManager/Plugin.MediaManager.iOS/MediaExtractorImplementation.cs | MediaManager/Plugin.MediaManager.iOS/MediaExtractorImplementation.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AVFoundation;
using Foundation;
using Plugin.MediaManager.Abstractions;
using UIKit;
namespace Plugin.MediaManager
{
public class MediaExtractorImplementation : IMediaExtractor
{
public async Task<IMediaFile> ExtractMediaInfo(IMediaFile mediaFile)
{
try
{
var assetsToLoad = new List<string>
{
AVMetadata.CommonKeyArtist,
AVMetadata.CommonKeyTitle,
AVMetadata.CommonKeyArtwork
};
var nsUrl = new NSUrl(mediaFile.Url);
// Default title to filename
mediaFile.Title = nsUrl.LastPathComponent;
var asset = AVAsset.FromUrl(nsUrl);
await asset.LoadValuesTaskAsync(assetsToLoad.ToArray());
foreach (var avMetadataItem in asset.CommonMetadata)
{
if (avMetadataItem.CommonKey == AVMetadata.CommonKeyArtist)
{
mediaFile.Artist = ((NSString) avMetadataItem.Value).ToString();
}
else if (avMetadataItem.CommonKey == AVMetadata.CommonKeyTitle)
{
mediaFile.Title = ((NSString) avMetadataItem.Value).ToString();
}
else if (avMetadataItem.CommonKey == AVMetadata.CommonKeyArtwork)
{
var image = UIImage.LoadFromData(avMetadataItem.DataValue);
mediaFile.Cover = image;
}
}
return mediaFile;
}
catch (Exception)
{
return mediaFile;
}
}
}
} | using System;
using System.Threading.Tasks;
using Plugin.MediaManager.Abstractions;
namespace Plugin.MediaManager
{
public class MediaExtractorImplementation : IMediaExtractor
{
public Task<IMediaFile> ExtractMediaInfo(IMediaFile mediaFile)
{
return Task.FromResult(mediaFile);
}
}
}
| mit | C# |
71222dc427bbd392cf2e3a148c1e9e050b5c4e36 | Store temp files from different processes in different folders | liddictm/BrawlManagers,libertyernie/BrawlManagers,liddictm/BrawlManagers,libertyernie/BrawlManagers | BrawlManagerLib/TempFiles.cs | BrawlManagerLib/TempFiles.cs | using BrawlLib.IO;
using BrawlLib.SSBB.ResourceNodes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace BrawlManagerLib {
public class TempFileCleanupException : AggregateException {
public TempFileCleanupException(IEnumerable<Exception> exceptions)
: base("One or more errors occured while attempting to remove BrawlManagerLib's temporary files.", exceptions) { }
}
public class TempFiles {
public static readonly string SUBDIR = "BrawlManagerLib-" + Guid.NewGuid();
static TempFiles() {
string p = Path.Combine(Path.GetTempPath(), SUBDIR);
if (Directory.Exists(p)) {
try {
Directory.Delete(p, true);
} catch (IOException) {
Console.WriteLine("could not clear out " + p + " (files probably in use)");
}
}
Directory.CreateDirectory(p);
}
/// <summary>
/// Creates a temporary file in the BrawlManagerLib subdirectory of the system temporary folder.
/// This function can be used for image files. For files that can be opened as a ResourceNode, consider using the MakeTempNode function instead.
/// </summary>
public static string Create(string extension) {
if (!extension.StartsWith(".")) extension = "." + extension;
return Path.Combine(Path.GetTempPath(), SUBDIR, Guid.NewGuid() + extension);
}
/// <summary>
/// Deletes all files created by the Create function (but not those created by MakeTempNode.)
/// </summary>
public static void DeleteAll() {
List<Exception> exceptions = new List<Exception>();
foreach (string s in Directory.EnumerateFiles(Path.Combine(Path.GetTempPath(), SUBDIR))) {
try {
File.Delete(s);
} catch (Exception e) {
exceptions.Add(e);
}
}
if (exceptions.Count == 0) {
try {
Directory.Delete(Path.Combine(Path.GetTempPath(), SUBDIR));
} catch (Exception e) {
exceptions.Add(e);
}
}
if (exceptions.Count > 0) {
throw new TempFileCleanupException(exceptions);
}
}
/// <summary>
/// Creates a ResourceNode from a temporary file using FileMap.FromTempFile. The file will be deleted when the underlying FileMap's stream is closed.
/// </summary>
public static ResourceNode MakeTempNode(string path) {
byte[] data = File.ReadAllBytes(path);
FileMap map = FileMap.FromTempFile(data.Length);
Console.WriteLine(path + " -> FromTempFile -> " + map.FilePath);
Marshal.Copy(data, 0, map.Address, data.Length);
return NodeFactory.FromSource(null, new DataSource(map));
}
}
}
| using BrawlLib.IO;
using BrawlLib.SSBB.ResourceNodes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace BrawlManagerLib {
public class TempFiles {
static TempFiles() {
string p = Path.Combine(Path.GetTempPath(), "BrawlManagerLib");
if (Directory.Exists(p)) {
try {
Directory.Delete(p, true);
} catch (IOException) {
Console.WriteLine("could not clear out " + p + " (files probably in use)");
}
}
Directory.CreateDirectory(p);
}
/// <summary>
/// Creates a temporary file in the BrawlManagerLib subdirectory of the system temporary folder.
/// This function can be used for image files. For files that can be opened as a ResourceNode, consider using the MakeTempNode function instead.
/// </summary>
public static string Create(string extension) {
if (!extension.StartsWith(".")) extension = "." + extension;
return Path.Combine(Path.GetTempPath(), "BrawlManagerLib", Guid.NewGuid() + extension);
}
/// <summary>
/// Deletes all files created by the Create function (but not those created by MakeTempNode.)
/// </summary>
public static void DeleteAll() {
List<Exception> exceptions = new List<Exception>();
foreach (string s in Directory.EnumerateFiles(Path.Combine(Path.GetTempPath(), "BrawlManagerLib"))) {
try {
File.Delete(s);
} catch (Exception e) {
exceptions.Add(e);
}
}
if (exceptions.Count == 0) {
Directory.Delete(Path.Combine(Path.GetTempPath(), "BrawlManagerLib"));
} else if (exceptions.Count == 1) {
throw exceptions[0];
} else {
throw new AggregateException(exceptions);
}
}
/// <summary>
/// Creates a ResourceNode from a temporary file using FileMap.FromTempFile. The file will be deleted when the underlying FileMap's stream is closed.
/// </summary>
public static ResourceNode MakeTempNode(string path) {
byte[] data = File.ReadAllBytes(path);
FileMap map = FileMap.FromTempFile(data.Length);
Console.WriteLine(path + " -> FromTempFile -> " + map.FilePath);
Marshal.Copy(data, 0, map.Address, data.Length);
return NodeFactory.FromSource(null, new DataSource(map));
}
}
}
| mit | C# |
9dbad29e3d249a1ee737dec729837c35aa23736c | add missing public declaration | humsp/uebersetzerbauSWP | Twee2Z/ObjectTree/Expressions/Base/Values/Functions/TurnsFunction.cs | Twee2Z/ObjectTree/Expressions/Base/Values/Functions/TurnsFunction.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Twee2Z.ObjectTree.Expressions.Base.Values.Functions
{
public class TurnsFunction : FunctionValue
{
public TurnsFunction()
: base(FunctionTypeEnum.Turns)
{ }
public override int MaxArgCount
{
get { return 0; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Twee2Z.ObjectTree.Expressions.Base.Values.Functions
{
class TurnsFunction : FunctionValue
{
public TurnsFunction()
: base(FunctionTypeEnum.Turns)
{ }
public override int MaxArgCount
{
get { return 0; }
}
}
}
| mit | C# |
6e93dd6453e1fbc002077bb53dfde27b01063e0c | Bump version number for 5.0.0 | csf-dev/CSF.Security | Common/CommonAssemblyInfo.cs | Common/CommonAssemblyInfo.cs | //
// CommonAssemblyInfo.cs
//
// Author:
// Craig Fowler <craig@csf-dev.com>
//
// Copyright (c) 2015 CSF Software Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyCompany("CSF Software Limited")]
[assembly: AssemblyProduct("CSF Software Utilities")]
[assembly: AssemblyCopyright("CSF Software Limited")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("5.0.0")]
| //
// CommonAssemblyInfo.cs
//
// Author:
// Craig Fowler <craig@csf-dev.com>
//
// Copyright (c) 2015 CSF Software Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyCompany("CSF Software Limited")]
[assembly: AssemblyProduct("CSF Software Utilities")]
[assembly: AssemblyCopyright("CSF Software Limited")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("4.1.1")]
| mit | C# |
d95eb569af06e598925287f80b1cbc03787441d3 | FIx TimeEntry | sochix/TogglAPI.Net | Toggl/DataObjects/TimeEntry.cs | Toggl/DataObjects/TimeEntry.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Toggl.DataObjects;
namespace Toggl
{
public class TimeEntry : BaseDataObject
{
[JsonProperty(PropertyName = "id")]
public long? Id { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "wid")]
public long? WorkspaceId { get; set; }
[JsonProperty(PropertyName = "pid")]
public long? ProjectId { get; set; }
[JsonProperty(PropertyName = "tid")]
public long? TaskId { get; set; }
[JsonProperty(PropertyName = "task")]
public string TaskName { get; set; }
[JsonProperty(PropertyName = "billable")]
public bool? IsBillable { get; set; }
[JsonProperty(PropertyName = "start")]
//[JsonConverter(typeof(IsoDateTimeConverter))]
//public DateTime? Start { get; set; }
public string Start { get; set; }
[JsonProperty(PropertyName = "stop")]
//[JsonConverter(typeof(IsoDateTimeConverter))]
//public DateTime? Stop { get; set; }
public string Stop { get; set; }
[JsonProperty(PropertyName = "duration")]
public long? Duration { get; set; }
[JsonProperty(PropertyName = "created_with")]
public string CreatedWith { get; set; }
[JsonProperty(PropertyName = "tags")]
public List<string> TagNames { get; set; }
[JsonProperty(PropertyName = "duronly")]
public bool? ShowDurationOnly { get; set; }
[JsonProperty(PropertyName = "at")]
public DateTime? UpdatedOn { get; set; }
public override string ToString()
{
return string.Format("Id: {0}, Start: {1}, Stop: {2}, TaskId: {3}", this.Id, this.Start, this.Stop, this.TaskId);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Toggl.DataObjects;
namespace Toggl
{
public class TimeEntry : BaseDataObject
{
[JsonProperty(PropertyName = "id")]
public long? Id { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "wid")]
public long? WorkspaceId { get; set; }
[JsonProperty(PropertyName = "pid")]
public long? ProjectId { get; set; }
[JsonProperty(PropertyName = "project")]
public string ProjectName { get; set; }
[JsonProperty(PropertyName = "client")]
public string ClientName { get; set; }
[JsonProperty(PropertyName = "tid")]
public long? TaskId { get; set; }
[JsonProperty(PropertyName = "task")]
public string TaskName { get; set; }
[JsonProperty(PropertyName = "billable")]
public bool? IsBillable { get; set; }
[JsonProperty(PropertyName = "start")]
//[JsonConverter(typeof(IsoDateTimeConverter))]
//public DateTime? Start { get; set; }
public string Start { get; set; }
[JsonProperty(PropertyName = "stop")]
//[JsonConverter(typeof(IsoDateTimeConverter))]
//public DateTime? Stop { get; set; }
public string Stop { get; set; }
[JsonProperty(PropertyName = "duration")]
public long? Duration { get; set; }
[JsonProperty(PropertyName = "created_with")]
public string CreatedWith { get; set; }
[JsonProperty(PropertyName = "tags")]
public List<string> TagNames { get; set; }
[JsonProperty(PropertyName = "duronly")]
public bool? ShowDurationOnly { get; set; }
[JsonProperty(PropertyName = "at")]
public DateTime? UpdatedOn { get; set; }
public override string ToString()
{
return string.Format("Id: {0}, Start: {1}, Stop: {2}, TaskId: {3}", this.Id, this.Start, this.Stop, this.TaskId);
}
}
}
| mit | C# |
4889892976708e8ad43834f6071f7839fcad5588 | Add missing test | mattolenik/winston,mattolenik/winston,mattolenik/winston | Winston.Test/InstallerTests.cs | Winston.Test/InstallerTests.cs | using System;
using FluentAssertions;
using Xunit;
namespace Winston.Test
{
public class InstallerTests
{
[Fact(Skip="Work in progress")]
public void BootstrapsCorrectly()
{
var path = Paths.GetDirectory(typeof(Winmain).Assembly.Location);
using (var installer = new Winstall(path))
{
var res = installer.Bootstrap();
res.Should().Be(0);
}
}
}
} | using System;
using FluentAssertions;
using Xunit;
namespace Winston.Test
{
class InstallerTests
{
[Fact]
public void BootstrapsCorrectly()
{
var path = Paths.GetDirectory(typeof(Winmain).Assembly.Location);
using (var installer = new Winstall(path))
{
var res = installer.Bootstrap();
res.Should().Be(0);
}
}
}
} | mit | C# |
4f0d0dd99e76dab3b1443f9954bc077432a532f5 | Test version of binary dependency | BenPhegan/NuGet.Extensions | NuGet.Extensions.Tests/MSBuild/ProjectAdapterTests.cs | NuGet.Extensions.Tests/MSBuild/ProjectAdapterTests.cs | using System;
using System.Linq;
using Microsoft.Build.Evaluation;
using NuGet.Extensions.MSBuild;
using NuGet.Extensions.Tests.TestData;
using NUnit.Framework;
namespace NuGet.Extensions.Tests.MSBuild
{
[TestFixture]
public class ProjectAdapterTests
{
private const string _expectedBinaryDependencyAssemblyName = "Newtonsoft.Json";
private const string _expectedBinaryDependencyVersion = "6.0.0.0";
[Test]
public void ProjectWithDependenciesAssemblyNameIsProjectWithDependencies()
{
var projectAdapter = CreateProjectAdapter(Paths.ProjectWithDependencies);
Assert.That(projectAdapter.AssemblyName, Is.EqualTo("ProjectWithDependencies"));
}
[Test]
public void ProjectWithDependenciesDependsOnNewtonsoftJson()
{
var projectAdapter = CreateProjectAdapter(Paths.ProjectWithDependencies);
var binaryReferences = projectAdapter.GetBinaryReferences();
var binaryReferenceIncludeNames = binaryReferences.Select(r => r.IncludeName).ToList();
Assert.That(binaryReferenceIncludeNames, Contains.Item(_expectedBinaryDependencyAssemblyName));
}
[Test]
public void ProjectWithDependenciesDependsOnNewtonsoftJson6000()
{
var projectAdapter = CreateProjectAdapter(Paths.ProjectWithDependencies);
var binaryReferences = projectAdapter.GetBinaryReferences();
var newtonsoft = binaryReferences.Single(r => r.IncludeName == _expectedBinaryDependencyAssemblyName);
Assert.That(newtonsoft.IncludeVersion, Is.EqualTo(_expectedBinaryDependencyVersion));
}
private static ProjectAdapter CreateProjectAdapter(string projectWithDependencies)
{
var msBuildProject = new Project(projectWithDependencies, null, null);
var projectAdapter = new ProjectAdapter(msBuildProject, "packages.config");
return projectAdapter;
}
}
}
| using System;
using System.Linq;
using Microsoft.Build.Evaluation;
using NuGet.Extensions.MSBuild;
using NuGet.Extensions.Tests.TestData;
using NUnit.Framework;
namespace NuGet.Extensions.Tests.MSBuild
{
[TestFixture]
public class ProjectAdapterTests
{
[Test]
public void ProjectWithDependenciesAssemblyNameIsProjectWithDependencies()
{
var projectAdapter = CreateProjectAdapter(Paths.ProjectWithDependencies);
Assert.That(projectAdapter.AssemblyName, Is.EqualTo("ProjectWithDependencies"));
}
[Test]
public void ProjectWithDependenciesDependsOnNewtonsoftJson()
{
var projectAdapter = CreateProjectAdapter(Paths.ProjectWithDependencies);
var binaryReferences = projectAdapter.GetBinaryReferences();
var binaryReferenceIncludeNames = binaryReferences.Select(r => r.IncludeName).ToList();
Assert.That(binaryReferenceIncludeNames, Contains.Item("Newtonsoft.Json"));
}
private static ProjectAdapter CreateProjectAdapter(string projectWithDependencies)
{
var msBuildProject = new Project(projectWithDependencies, null, null);
var projectAdapter = new ProjectAdapter(msBuildProject, "packages.config");
return projectAdapter;
}
}
}
| mit | C# |
a984ca1f145a5dc411234ecb607a63a07e8033b2 | return null | octoblu/meshblu-connector-skype,octoblu/meshblu-connector-skype | src/csharp/start-video.cs | src/csharp/start-video.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using Microsoft.Lync.Model.Conversation.AudioVideo;
using Microsoft.Lync.Model.Extensibility;
public class Startup
{
public Conversation GetConversation()
{
return LyncClient.GetClient().ConversationManager.Conversations.FirstOrDefault();
}
public Task WaitToConnect()
{
var conversation = GetConversation();
var avModality = ((AVModality)conversation.Modalities[ModalityTypes.AudioVideo]);
var tcs = new TaskCompletionSource<bool>();
EventHandler<ModalityStateChangedEventArgs> handler = null;
handler = (sender, e) => {
if (e.NewState != ModalityState.Connected) return;
avModality.ModalityStateChanged -= handler;
tcs.TrySetResult(true);
};
avModality.ModalityStateChanged += handler;
return tcs.Task;
}
public async Task<VideoChannel> GetVideoChannel()
{
var conversation = GetConversation();
if (conversation == null) throw new System.InvalidOperationException("Cannot start video on non-extant conversation");
var avModality = ((AVModality)conversation.Modalities[ModalityTypes.AudioVideo]);
if (avModality.State != ModalityState.Connected) {
await WaitToConnect();
}
return avModality.VideoChannel;
}
public async Task<object> Invoke(string ignored)
{
var videoChannel = await GetVideoChannel();
await Task.Factory.FromAsync(videoChannel.BeginStart, videoChannel.EndStart, null);
return null;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using Microsoft.Lync.Model.Conversation.AudioVideo;
using Microsoft.Lync.Model.Extensibility;
public class Startup
{
public Conversation GetConversation()
{
return LyncClient.GetClient().ConversationManager.Conversations.FirstOrDefault();
}
public Task WaitToConnect()
{
var conversation = GetConversation();
var avModality = ((AVModality)conversation.Modalities[ModalityTypes.AudioVideo]);
var tcs = new TaskCompletionSource<bool>();
EventHandler<ModalityStateChangedEventArgs> handler = null;
handler = (sender, e) => {
if (e.NewState != ModalityState.Connected) return;
avModality.ModalityStateChanged -= handler;
tcs.TrySetResult(true);
};
avModality.ModalityStateChanged += handler;
return tcs.Task;
}
public async Task<VideoChannel> GetVideoChannel()
{
var conversation = GetConversation();
if (conversation == null) throw new System.InvalidOperationException("Cannot start video on non-extant conversation");
var avModality = ((AVModality)conversation.Modalities[ModalityTypes.AudioVideo]);
if (avModality.State != ModalityState.Connected) {
await WaitToConnect();
}
return avModality.VideoChannel;
}
public async Task<object> Invoke(string ignored)
{
var videoChannel = await GetVideoChannel();
await Task.Factory.FromAsync(videoChannel.BeginStart, videoChannel.EndStart, null);
return GetAllConversations().Count;
}
}
| mit | C# |
f5af9522249665201663eb0d2ac81a1c894458a1 | Fix ButtonMadness application closes when Close button is clicked. | PlayScriptRedux/monomac,dlech/monomac | samples/ButtonMadness/AppDelegate.cs | samples/ButtonMadness/AppDelegate.cs | using System;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.ObjCRuntime;
namespace SamplesButtonMadness
{
public partial class AppDelegate : NSApplicationDelegate
{
TestWindowController mainWindowController;
public AppDelegate ()
{
}
public override void FinishedLaunching (NSObject notification)
{
mainWindowController = new TestWindowController ();
mainWindowController.Window.MakeKeyAndOrderFront (this);
}
public override bool ApplicationShouldTerminateAfterLastWindowClosed (NSApplication sender)
{
return true;
}
}
}
| using System;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.ObjCRuntime;
namespace SamplesButtonMadness
{
public partial class AppDelegate : NSApplicationDelegate
{
TestWindowController mainWindowController;
public AppDelegate ()
{
}
public override void FinishedLaunching (NSObject notification)
{
mainWindowController = new TestWindowController ();
mainWindowController.Window.MakeKeyAndOrderFront (this);
}
}
}
| apache-2.0 | C# |
8aabed59b3ba1dba667303c9161fa823e2f399df | clear cache when refreshing stats | Nsm7Nash/stack-exchange-data-explorer,Nsm7Nash/stack-exchange-data-explorer,Nsm7Nash/stack-exchange-data-explorer,Nsm7Nash/stack-exchange-data-explorer | App/StackExchange.DataExplorer/Controllers/AdminController.cs | App/StackExchange.DataExplorer/Controllers/AdminController.cs | using System.Web.Mvc;
using StackExchange.DataExplorer.Helpers;
using StackExchange.DataExplorer.Models;
namespace StackExchange.DataExplorer.Controllers
{
public class AdminController : StackOverflowController
{
[Route("admin")]
public ActionResult Index()
{
if (!Allowed())
{
return TextPlainNotFound();
}
return View();
}
[Route("admin/refresh_stats", HttpVerbs.Post)]
public ActionResult RefreshStats()
{
if (!Allowed())
{
return TextPlainNotFound();
}
foreach (Site site in Current.DB.Sites)
{
site.UpdateStats();
}
Current.DB.ExecuteCommand("DELETE FROM CachedResults");
return Content("sucess");
}
public bool Allowed()
{
return CurrentUser.IsAdmin;
}
}
} | using System.Web.Mvc;
using StackExchange.DataExplorer.Helpers;
using StackExchange.DataExplorer.Models;
namespace StackExchange.DataExplorer.Controllers
{
public class AdminController : StackOverflowController
{
[Route("admin")]
public ActionResult Index()
{
if (!Allowed())
{
return TextPlainNotFound();
}
return View();
}
[Route("admin/refresh_stats", HttpVerbs.Post)]
public ActionResult RefreshStats()
{
if (!Allowed())
{
return TextPlainNotFound();
}
foreach (Site site in Current.DB.Sites)
{
site.UpdateStats();
}
return Content("sucess");
}
public bool Allowed()
{
return CurrentUser.IsAdmin;
}
}
} | mit | C# |
27baf686c54c779a54d1b17a0c7a103fe7e70fd7 | Remove unapplicable todo comment from LinuxGameHost. | paparony03/osu-framework,RedNesto/osu-framework,peppy/osu-framework,default0/osu-framework,naoey/osu-framework,ZLima12/osu-framework,NeoAdonis/osu-framework,paparony03/osu-framework,default0/osu-framework,RedNesto/osu-framework,Tom94/osu-framework,NeoAdonis/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,naoey/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework | osu.Framework.Desktop/OS/Linux/LinuxGameHost.cs | osu.Framework.Desktop/OS/Linux/LinuxGameHost.cs | // Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Collections.Generic;
using osu.Framework.Desktop.Input.Handlers.Keyboard;
using osu.Framework.Desktop.Input.Handlers.Mouse;
using osu.Framework.Input.Handlers;
using OpenTK.Graphics;
namespace osu.Framework.Desktop.OS.Linux
{
public class LinuxGameHost : DesktopGameHost
{
public override bool IsActive => true; // TODO LINUX
internal LinuxGameHost(GraphicsContextFlags flags)
{
Window = new LinuxGameWindow(flags);
}
public override IEnumerable<InputHandler> GetInputHandlers()
{
return new InputHandler[] {
new OpenTKMouseHandler(), //handles cursor position
new FormMouseHandler(), //handles button states
new OpenTKKeyboardHandler(),
};
}
}
}
| // Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Collections.Generic;
using osu.Framework.Desktop.Input.Handlers.Keyboard;
using osu.Framework.Desktop.Input.Handlers.Mouse;
using osu.Framework.Input.Handlers;
using OpenTK.Graphics;
namespace osu.Framework.Desktop.OS.Linux
{
public class LinuxGameHost : DesktopGameHost
{
public override bool IsActive => true; // TODO LINUX
internal LinuxGameHost(GraphicsContextFlags flags)
{
Window = new LinuxGameWindow(flags);
}
public override IEnumerable<InputHandler> GetInputHandlers()
{
//todo: figure why opentk input handlers aren't working.
return new InputHandler[] {
new OpenTKMouseHandler(), //handles cursor position
new FormMouseHandler(), //handles button states
new OpenTKKeyboardHandler(),
};
}
}
}
| mit | C# |
2b4e6fe4f93bac89f22e2603a7c9e4a49e2bf5b8 | Allow Title to be set for searching GetSurveyList | davek17/SurveyMonkeyApi-v3,bcemmett/SurveyMonkeyApi-v3 | SurveyMonkey/RequestSettings/GetSurveyListSettings.cs | SurveyMonkey/RequestSettings/GetSurveyListSettings.cs | using System;
namespace SurveyMonkey.RequestSettings
{
public class GetSurveyListSettings : IPagingSettings
{
public enum SortByOption
{
Title,
DateModified,
NumResponses
}
public enum SortOrderOption
{
ASC,
DESC
}
public int? Page { get; set; }
public int? PerPage { get; set; }
public SortByOption? SortBy { get; set; }
public SortOrderOption? SortOrder { get; set; }
public DateTime? StartModifiedAt { get; set; }
public DateTime? EndModifiedAt { get; set; }
public string Title { get; set; }
public string Include { get { return "response_count,date_created,date_modified,language,question_count,analyze_url,preview"; } }
}
} | using System;
namespace SurveyMonkey.RequestSettings
{
public class GetSurveyListSettings : IPagingSettings
{
public enum SortByOption
{
Title,
DateModified,
NumResponses
}
public enum SortOrderOption
{
ASC,
DESC
}
public int? Page { get; set; }
public int? PerPage { get; set; }
public SortByOption? SortBy { get; set; }
public SortOrderOption? SortOrder { get; set; }
public DateTime? StartModifiedAt { get; set; }
public DateTime? EndModifiedAt { get; set; }
public string Include { get { return "response_count,date_created,date_modified,language,question_count,analyze_url,preview"; } }
}
} | mit | C# |
93a17064010d033cf52917652a7da2b6aca03e4b | Update MicrosoftBannerAdUnitBundle.cs | tiksn/TIKSN-Framework | TIKSN.Core/Advertising/MicrosoftBannerAdUnitBundle.cs | TIKSN.Core/Advertising/MicrosoftBannerAdUnitBundle.cs | namespace TIKSN.Advertising
{
public class MicrosoftBannerAdUnitBundle : MicrosoftAdUnitBundle
{
public static readonly AdUnit MicrosoftTestModeBannerAdUnit = new AdUnit(AdProviders.Microsoft,
"3f83fe91-d6be-434d-a0ae-7351c5a997f1",
"10865270", true);
public MicrosoftBannerAdUnitBundle(string applicationId, string adUnitId)
: base(MicrosoftTestModeBannerAdUnit, applicationId, adUnitId)
{
}
}
} | namespace TIKSN.Advertising
{
public class MicrosoftBannerAdUnitBundle : MicrosoftAdUnitBundle
{
public static readonly AdUnit MicrosoftTestModeBannerAdUnit = new AdUnit(AdProviders.Microsoft,
"3f83fe91-d6be-434d-a0ae-7351c5a997f1",
"10865270", true);
public MicrosoftBannerAdUnitBundle(string tabletApplicationId, string tabletAdUnitId, string mobileApplicationId, string mobileAdUnitId)
: base(MicrosoftTestModeBannerAdUnit, tabletApplicationId, tabletAdUnitId, mobileApplicationId, mobileAdUnitId)
{
}
}
} | mit | C# |
9ccf0af2705757130a70475c5f92057fe71046fb | Make the Loading html page look better. | bklimt/BabbyJotz,bklimt/BabbyJotz,bklimt/BabbyJotz,bklimt/BabbyJotz | BabbyJotz/Pages/WebViewPage.xaml.cs | BabbyJotz/Pages/WebViewPage.xaml.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace BabbyJotz {
public partial class WebViewPage : ContentPage {
public WebViewPage(string title, Func<Task<string>> htmlFunc) {
InitializeComponent();
Title = title;
((HtmlWebViewSource)webview.Source).Html = @"
<html>
<head>
<style>
body {
padding: 0px;
margin: 8px;
font-family: Helvetica;
background-color: #333333;
color: #ffffff;
}
</style>
</head>
<body>
Loading...
</body>
</html>";
doFunc(htmlFunc);
}
private async void doFunc(Func<Task<string>> htmlFunc) {
((HtmlWebViewSource)webview.Source).Html = await htmlFunc();
}
}
} | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace BabbyJotz {
public partial class WebViewPage : ContentPage {
public WebViewPage(string title, Func<Task<string>> htmlFunc) {
InitializeComponent();
Title = title;
((HtmlWebViewSource)webview.Source).Html = "<html><body>Loading...</body></html>";
doFunc(htmlFunc);
}
private async void doFunc(Func<Task<string>> htmlFunc) {
((HtmlWebViewSource)webview.Source).Html = await htmlFunc();
}
}
} | mit | C# |
367da8d9e610d15695674bff579f7aab07230b11 | Use lighter delete icon | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University/Components/UniversityIcons.cs | R7.University/Components/UniversityIcons.cs | //
// UniversityIcons.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2017 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 DotNetNuke.Entities.Icons;
namespace R7.University.Components
{
public static class UniversityIcons
{
public static readonly string Edit = IconController.IconURL ("Edit", IconController.DefaultIconSize, "Gray");
public static readonly string Add = IconController.IconURL ("Add");
public static readonly string Delete = IconController.IconURL ("ActionDelete");
public static readonly string Details = IconController.IconURL ("View");
public static readonly string Rollback = "~/DesktopModules/MVC/R7.University/R7.University/images/Rollback_16x16_Gray.png";
}
}
| //
// UniversityIcons.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2017 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 DotNetNuke.Entities.Icons;
namespace R7.University.Components
{
public static class UniversityIcons
{
public static readonly string Edit = IconController.IconURL ("Edit", IconController.DefaultIconSize, "Gray");
public static readonly string Add = IconController.IconURL ("Add");
public static readonly string Delete = IconController.IconURL ("Delete", IconController.DefaultIconSize, "PermissionGrid");
public static readonly string Details = IconController.IconURL ("View");
public static readonly string Rollback = "~/DesktopModules/MVC/R7.University/R7.University/images/Rollback_16x16_Gray.png";
}
}
| agpl-3.0 | C# |
2523d8c0f0f32e041b3e8ac4221a4bdff3d6991c | Include interface to make IoC easier | MatthewSteeples/XeroAPI.Net | source/XeroApi/Model/ModelBase.cs | source/XeroApi/Model/ModelBase.cs | using System.Collections.Generic;
using System.Xml.Serialization;
namespace XeroApi.Model
{
public abstract class EndpointModelBase : ModelBase
{
}
public abstract class ModelBase : IModelBase
{
[XmlAttribute("status")]
public ValidationStatus ValidationStatus
{
get;
set;
}
public List<ValidationError> ValidationErrors
{
get;
set;
}
public List<Warning> Warnings
{
get;
set;
}
}
public interface IModelBase
{
}
public enum ValidationStatus
{
OK,
WARNING,
ERROR
}
public struct Warning
{
public string Message;
}
public struct ValidationError
{
public string Message;
}
}
| using System.Collections.Generic;
using System.Xml.Serialization;
namespace XeroApi.Model
{
public abstract class EndpointModelBase : ModelBase
{
}
public abstract class ModelBase
{
[XmlAttribute("status")]
public ValidationStatus ValidationStatus
{
get;
set;
}
public List<ValidationError> ValidationErrors
{
get;
set;
}
public List<Warning> Warnings
{
get;
set;
}
}
public enum ValidationStatus
{
OK,
WARNING,
ERROR
}
public struct Warning
{
public string Message;
}
public struct ValidationError
{
public string Message;
}
}
| mit | C# |
ec42302cdf4f365fedfcfef26eefe2fcf6b04ea1 | Update RedisConfiguration.cs commenting | imperugo/StackExchange.Redis.Extensions,imperugo/StackExchange.Redis.Extensions | src/StackExchange.Redis.Extensions.Core/Configuration/RedisConfiguration.cs | src/StackExchange.Redis.Extensions.Core/Configuration/RedisConfiguration.cs | using System.Net.Security;
namespace StackExchange.Redis.Extensions.Core.Configuration
{
public class RedisConfiguration
{
private static ConnectionMultiplexer connection;
private static ConfigurationOptions options;
/// <summary>
/// The key separation prefix used for all cache entries
/// </summary>
public string KeyPrefix { get; set; }
/// <summary>
/// The password or access key
/// </summary>
public string Password { get; set; }
/// <summary>
/// Specify if the connection can use Admin commands like flush database
/// </summary>
/// <value>
/// <c>true</c> if can use admin commands; otherwise, <c>false</c>.
/// </value>
public bool AllowAdmin { get; set; } = false;
/// <summary>
/// Specify if the connection is a secure connection or not.
/// </summary>
/// <value>
/// <c>true</c> if is secure; otherwise, <c>false</c>.
/// </value>
public bool Ssl { get; set; } = false;
/// <summary>
/// The connection timeout
/// </summary>
public int ConnectTimeout { get; set; } = 5000;
/// <summary>
/// If true, Connect will not create a connection while no servers are available
/// </summary>
public bool AbortOnConnectFail { get; set; }
/// <summary>
/// Database Id
/// </summary>
/// <value>
/// The database id, the default value is 0
/// </value>
public int Database { get; set; } = 0;
/// <summary>
/// The host of Redis Servers
/// </summary>
/// <value>
/// The ips or names
/// </value>
public RedisHost[] Hosts { get; set; }
/// <summary>
/// The strategy to use when executing server wide commands
/// </summary>
public ServerEnumerationStrategy ServerEnumerationStrategy { get; set; }
/// <summary>
/// A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party; note
/// that this cannot be specified in the configuration-string.
/// </summary>
public event RemoteCertificateValidationCallback CertificateValidation;
public ConfigurationOptions ConfigurationOptions
{
get
{
if (options == null)
{
options = new ConfigurationOptions
{
Ssl = Ssl,
AllowAdmin = AllowAdmin,
Password = Password,
ConnectTimeout = ConnectTimeout,
AbortOnConnectFail = AbortOnConnectFail
};
foreach (var redisHost in Hosts)
options.EndPoints.Add(redisHost.Host, redisHost.Port);
options.CertificateValidation += CertificateValidation;
}
return options;
}
}
public ConnectionMultiplexer Connection
{
get
{
if (connection == null)
connection = ConnectionMultiplexer.Connect(options);
return connection;
}
}
}
}
| using System.Net.Security;
namespace StackExchange.Redis.Extensions.Core.Configuration
{
public class RedisConfiguration
{
private static ConnectionMultiplexer connection;
private static ConfigurationOptions options;
/// <summary>
/// The key separation prefix used for all cache entries
/// </summary>
public string KeyPrefix { get; set; }
/// <summary>
/// The password or access key
/// </summary>
public string Password { get; set; }
/// <summary>
/// Specify if the connection can use Admin commands like flush database
/// </summary>
/// <value>
/// <c>true</c> if can use admin commands; otherwise, <c>false</c>.
/// </value>
public bool AllowAdmin { get; set; } = false;
/// <summary>
/// Specify if the connection is a secure connection or not.
/// </summary>
/// <value>
/// <c>true</c> if is secure; otherwise, <c>false</c>.
/// </value>
public bool Ssl { get; set; } = false;
/// <summary>
/// The connection timeout
/// </summary>
public int ConnectTimeout { get; set; } = 5000;
/// <summary>
/// If true, Connect will not create a connection while no servers are available
/// </summary>
public bool AbortOnConnectFail { get; set; }
/// <summary>
/// Database Id
/// </summary>
/// <value>
/// The database id, the default value is 0
/// </value>
public int Database { get; set; } = 0;
/// <summary>
/// The host of Redis Server
/// </summary>
/// <value>
/// The ip or name
/// </value>
public RedisHost[] Hosts { get; set; }
/// <summary>
/// The strategy to use when executing server wide commands
/// </summary>
public ServerEnumerationStrategy ServerEnumerationStrategy { get; set; }
/// <summary>
/// A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party; note
/// that this cannot be specified in the configuration-string.
/// </summary>
public event RemoteCertificateValidationCallback CertificateValidation;
public ConfigurationOptions ConfigurationOptions
{
get
{
if (options == null)
{
options = new ConfigurationOptions
{
Ssl = Ssl,
AllowAdmin = AllowAdmin,
Password = Password,
ConnectTimeout = ConnectTimeout,
AbortOnConnectFail = AbortOnConnectFail
};
foreach (var redisHost in Hosts)
options.EndPoints.Add(redisHost.Host, redisHost.Port);
options.CertificateValidation += CertificateValidation;
}
return options;
}
}
public ConnectionMultiplexer Connection
{
get
{
if (connection == null)
connection = ConnectionMultiplexer.Connect(options);
return connection;
}
}
}
} | mit | C# |
02376b830daddada831bd32864db7f89db0c0fec | Fix master server address retrieve | gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer | LMP.MasterServer/Helper.cs | LMP.MasterServer/Helper.cs | using System.IO;
using System.Net;
using System.Text.RegularExpressions;
namespace LMP.MasterServer
{
public class Helper
{
public static string GetOwnIpAddress()
{
var currentIpAddress = TryGetIpAddress("http://ip.42.pl/raw");
if (string.IsNullOrEmpty(currentIpAddress))
currentIpAddress = TryGetIpAddress("https://api.ipify.org/");
if (string.IsNullOrEmpty(currentIpAddress))
currentIpAddress = TryGetIpAddress("http://httpbin.org/ip");
if (string.IsNullOrEmpty(currentIpAddress))
currentIpAddress = TryGetIpAddress("http://checkip.dyndns.org");
return currentIpAddress;
}
private static string TryGetIpAddress(string url)
{
try
{
using (var client = new WebClient())
using (var stream = client.OpenRead(url))
{
if (stream == null) return null;
using (var reader = new StreamReader(stream))
{
var ipRegEx = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
var result = ipRegEx.Matches(reader.ReadToEnd());
if (IPAddress.TryParse(result[0].Value, out var ip))
return ip.ToString();
}
}
}
catch
{
// ignored
}
return null;
}
}
}
| using System.IO;
using System.Net;
using System.Text.RegularExpressions;
namespace LMP.MasterServer
{
public class Helper
{
public static string GetOwnIpAddress()
{
var currentIpAddress = TryGetIpAddress("http://ip.42.pl/raw");
if (string.IsNullOrEmpty(currentIpAddress))
currentIpAddress = TryGetIpAddress("https://api.ipify.org/");
if (string.IsNullOrEmpty(currentIpAddress))
currentIpAddress = TryGetIpAddress("http://httpbin.org/ip");
if (string.IsNullOrEmpty(currentIpAddress))
currentIpAddress = TryGetIpAddress("http://checkip.dyndns.org");
return currentIpAddress;
}
private static string TryGetIpAddress(string url)
{
using (var client = new WebClient())
using (var stream = client.OpenRead(url))
{
if (stream == null) return null;
using (var reader = new StreamReader(stream))
{
var ipRegEx = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
var result = ipRegEx.Matches(reader.ReadToEnd());
if (IPAddress.TryParse(result[0].Value, out var ip))
return ip.ToString();
}
}
return null;
}
}
}
| mit | C# |
735eb39faf89027032a9ac324dec085695ba4e5e | Update AssemblyInfo.cs | Barings/Barings.Controls.WPF | Barings.Controls.WPF/Properties/AssemblyInfo.cs | Barings.Controls.WPF/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Barings WPF Controls")]
[assembly: AssemblyDescription("A collection of generic WPF controls (no licensed third party software present).")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Barings")]
[assembly: AssemblyProduct("Barings.Controls.WPF")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]n
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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:cd bar
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Barings WPF Controls")]
[assembly: AssemblyDescription("A collection of generic WPF controls (no licensed third party software present).")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Barings")]
[assembly: AssemblyProduct("Barings.Controls.WPF")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]n
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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:cd bar
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
| mit | C# |
9e9cc83fd90dc52d78eee2c983c2da482358ef02 | Update MyDataRepository.cs | CarmelSoftware/Data-Repository-with-Data-Caching-in-ASP.NET-MVC-4,kelong/Data-Repository-with-Data-Caching-in-ASP.NET-MVC-4 | Models/MyDataRepository.cs | Models/MyDataRepository.cs | using system;
public class MyDataRepository
{
// TODO: check what happens when different users use Cache simultaneously
public ObjectCache Cache
{
get { return MemoryCache.Default; }
}
public bool IsInMemory(string Key)
{
return Cache.Contains(Key);
}
public void Add(string Key, object Value, int Expiration)
{
Cache.Add(Key, Value, new CacheItemPolicy().AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(Expiration));
}
public IQueryable<T> FetchData<T>(string Key) where T : class
{
return Cache[Key] as IQueryable<T>;
}
public void Remove(string Key)
{
Cache.Remove(Key);
}
}
}
| using system;
public class MyDataRepository
{
}
| mit | C# |
31ad82d325aeed7137929ac01ed3b5231a6e2abf | Update AssemblyInfo app version | CalebChalmers/KAGTools | KAGTools/Properties/AssemblyInfo.cs | KAGTools/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// 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("KAG Tools")]
[assembly: AssemblyDescription("A set of useful modding tools for the game King Arthur's Gold.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("KAG Tools")]
[assembly: AssemblyCopyright("Copyright © Caleb Chalmers 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyMetadata("SquirrelAwareVersion", "1")]
// 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0")]
[assembly: AssemblyFileVersion("0.9.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// 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("KAG Tools")]
[assembly: AssemblyDescription("A set of useful modding tools for the game King Arthur's Gold.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("KAG Tools")]
[assembly: AssemblyCopyright("Copyright © Caleb Chalmers 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyMetadata("SquirrelAwareVersion", "1")]
// 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.5.0")]
[assembly: AssemblyFileVersion("0.5.0")]
| mit | C# |
33bb86cdfda35fb1ee8ff8dd5b63166e8b9e0948 | fix test breaking due to template change | Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen | Dashen.Tests/Acceptance/ViewCompilationTests.cs | Dashen.Tests/Acceptance/ViewCompilationTests.cs | using System;
using System.IO;
using System.Text;
using Dashen.Endpoints.Index;
using Dashen.Endpoints.Stats;
using Dashen.Infrastructure.Spark;
using Shouldly;
using Xunit;
namespace Dashen.Tests.Acceptance
{
public class ViewCompilationTests
{
private readonly SparkEngine _spark;
public ViewCompilationTests()
{
var config = new DashenConfiguration();
config.AddControlView<FakeControlViewModel>(CreateView());
var app = new ApplicationModel(config);
var configuredEngine = new SparkBuilder(config).Build();
var descriptorBuilder = new DescriptorBuilder(configuredEngine);
_spark = new SparkEngine(configuredEngine, descriptorBuilder, app);
}
[Fact]
public void A_control_view_with_no_template_renders()
{
var model = new TextControlViewModel { Content = "Test Text" };
var content = Render(model);
content.ShouldNotContain("<html>");
}
[Fact]
public void A_view_with_template_renders()
{
var model = new IndexViewModel();
var content = Render(model);
content.ShouldNotBeEmpty();
}
[Fact]
public void A_custom_view_can_be_added_and_compiled()
{
var model = new FakeControlViewModel();
var content = Render(model);
content.ShouldContain("<p>Testing omg!</p>");
}
private byte[] CreateView()
{
var view =
@"<viewdata model='Dashen.Tests.Acceptance.FakeControlViewModel' />" + Environment.NewLine +
@"<p>!{Model.Content}</p>";
return Encoding.UTF8.GetBytes(view);
}
private string Render<T>(T model)
{
var view = _spark.CreateView(model);
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
view.RenderView(sw);
sw.Flush();
}
return sb.ToString();
}
}
public class FakeControlViewModel : ControlViewModel
{
public string Content { get; set; }
public FakeControlViewModel()
{
Content = "Testing omg!";
}
}
} | using System;
using System.IO;
using System.Text;
using Dashen.Endpoints.Index;
using Dashen.Endpoints.Stats;
using Dashen.Infrastructure.Spark;
using Shouldly;
using Xunit;
namespace Dashen.Tests.Acceptance
{
public class ViewCompilationTests
{
private readonly SparkEngine _spark;
public ViewCompilationTests()
{
var config = new DashenConfiguration();
config.AddControlView<FakeControlViewModel>(CreateView());
var app = new ApplicationModel(config);
var configuredEngine = new SparkBuilder(config).Build();
var descriptorBuilder = new DescriptorBuilder(configuredEngine);
_spark = new SparkEngine(configuredEngine, descriptorBuilder, app);
}
[Fact]
public void A_control_view_with_no_template_renders()
{
var model = new TextControlViewModel { Content = "Test Text" };
var content = Render(model);
content.ShouldContain("<div class=\"text-center\">Test Text</div>");
}
[Fact]
public void A_view_with_template_renders()
{
var model = new IndexViewModel();
var content = Render(model);
content.ShouldNotBeEmpty();
}
[Fact]
public void A_custom_view_can_be_added_and_compiled()
{
var model = new FakeControlViewModel();
var content = Render(model);
content.ShouldContain("<p>Testing omg!</p>");
}
private byte[] CreateView()
{
var view =
@"<viewdata model='Dashen.Tests.Acceptance.FakeControlViewModel' />" + Environment.NewLine +
@"<p>!{Model.Content}</p>";
return Encoding.UTF8.GetBytes(view);
}
private string Render<T>(T model)
{
var view = _spark.CreateView(model);
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
view.RenderView(sw);
sw.Flush();
}
return sb.ToString();
}
}
public class FakeControlViewModel : ControlViewModel
{
public string Content { get; set; }
public FakeControlViewModel()
{
Content = "Testing omg!";
}
}
} | lgpl-2.1 | C# |
1080c89f239993aa2a9e3afe424eae83cda25bd5 | Fix TestNormalisingPreprocessor using wrong ADFloat32Array name | GreekDictionary/Sigma | Sigma.Tests/Data/Preprocessors/TestNormalisingPreprocessor.cs | Sigma.Tests/Data/Preprocessors/TestNormalisingPreprocessor.cs | /*
MIT License
Copyright (c) 2016-2017 Florian Cäsar, Michael Plainer
For full license see LICENSE in the root directory of this project.
*/
using NUnit.Framework;
using Sigma.Core.Data.Preprocessors;
using Sigma.Core.Handlers;
using Sigma.Core.MathAbstract;
using System;
using System.Collections.Generic;
using System.Linq;
using Sigma.Core.Handlers.Backends.SigmaDiff.NativeCpu;
using Sigma.Core.MathAbstract.Backends.SigmaDiff.NativeCpu;
namespace Sigma.Tests.Data.Preprocessors
{
public class TestNormalisingPreprocessor
{
private static Dictionary<string, INDArray> GetNamedArrayTestData()
{
return new Dictionary<string, INDArray>() { ["test"] = new ADFloat32NDArray(-1L, new float[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 1, 1, 9)};
}
[TestCase]
public void TestNormalisingPreprocessorCreate()
{
Assert.Throws<ArgumentException>(() => new NormalisingPreprocessor(2, 1, "test"));
Assert.Throws<ArgumentException>(() => new NormalisingPreprocessor(1, 2, 2, 1));
NormalisingPreprocessor normaliser = new NormalisingPreprocessor(1, 3, 0, 1, "test");
Assert.AreEqual(1, normaliser.MinInputValue);
Assert.AreEqual(3, normaliser.MaxInputValue);
Assert.AreEqual(0, normaliser.MinOutputValue);
Assert.AreEqual(1, normaliser.MaxOutputValue);
Assert.AreEqual(new[] { "test" }, normaliser.ProcessedSectionNames);
}
[TestCase]
public void TestNormalisingPreprocessorExtractDirect()
{
NormalisingPreprocessor normaliser = new NormalisingPreprocessor(1, 9, 0, 1, "test");
IComputationHandler handler = new CpuFloat32Handler();
Dictionary<string, INDArray> extracted = normaliser.ExtractDirectFrom(GetNamedArrayTestData(), 1, handler);
Assert.AreEqual(new[] { 0.0f, 0.125f, 0.25f, 0.375f, 0.5f, 0.625f, 0.75f, 0.875f, 1.0f }, extracted["test"].GetDataAs<float>().GetValuesArrayAs<float>(0, 9).ToArray());
}
}
}
| /*
MIT License
Copyright (c) 2016-2017 Florian Cäsar, Michael Plainer
For full license see LICENSE in the root directory of this project.
*/
using NUnit.Framework;
using Sigma.Core.Data.Preprocessors;
using Sigma.Core.Handlers;
using Sigma.Core.MathAbstract;
using System;
using System.Collections.Generic;
using System.Linq;
using Sigma.Core.Handlers.Backends.SigmaDiff.NativeCpu;
using Sigma.Core.MathAbstract.Backends.SigmaDiff.NativeCpu;
namespace Sigma.Tests.Data.Preprocessors
{
public class TestNormalisingPreprocessor
{
private static Dictionary<string, INDArray> GetNamedArrayTestData()
{
return new Dictionary<string, INDArray>() { ["test"] = new ADNDFloat32Array(-1L, new float[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 1, 1, 9)};
}
[TestCase]
public void TestNormalisingPreprocessorCreate()
{
Assert.Throws<ArgumentException>(() => new NormalisingPreprocessor(2, 1, "test"));
Assert.Throws<ArgumentException>(() => new NormalisingPreprocessor(1, 2, 2, 1));
NormalisingPreprocessor normaliser = new NormalisingPreprocessor(1, 3, 0, 1, "test");
Assert.AreEqual(1, normaliser.MinInputValue);
Assert.AreEqual(3, normaliser.MaxInputValue);
Assert.AreEqual(0, normaliser.MinOutputValue);
Assert.AreEqual(1, normaliser.MaxOutputValue);
Assert.AreEqual(new[] { "test" }, normaliser.ProcessedSectionNames);
}
[TestCase]
public void TestNormalisingPreprocessorExtractDirect()
{
NormalisingPreprocessor normaliser = new NormalisingPreprocessor(1, 9, 0, 1, "test");
IComputationHandler handler = new CpuFloat32Handler();
Dictionary<string, INDArray> extracted = normaliser.ExtractDirectFrom(GetNamedArrayTestData(), 1, handler);
Assert.AreEqual(new[] { 0.0f, 0.125f, 0.25f, 0.375f, 0.5f, 0.625f, 0.75f, 0.875f, 1.0f }, extracted["test"].GetDataAs<float>().GetValuesArrayAs<float>(0, 9).ToArray());
}
}
}
| mit | C# |
eb6fe1e4d33a506bb40ef60ea0f9d433740a79be | Fix unit test that was failing after moving from yepnope to LazyLoad.js | gregoriusxu/Umbraco-CMS,rasmuseeg/Umbraco-CMS,timothyleerussell/Umbraco-CMS,Khamull/Umbraco-CMS,Spijkerboer/Umbraco-CMS,Pyuuma/Umbraco-CMS,romanlytvyn/Umbraco-CMS,Phosworks/Umbraco-CMS,VDBBjorn/Umbraco-CMS,ordepdev/Umbraco-CMS,tcmorris/Umbraco-CMS,timothyleerussell/Umbraco-CMS,lingxyd/Umbraco-CMS,countrywide/Umbraco-CMS,rasmusfjord/Umbraco-CMS,markoliver288/Umbraco-CMS,sargin48/Umbraco-CMS,engern/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,qizhiyu/Umbraco-CMS,ehornbostel/Umbraco-CMS,qizhiyu/Umbraco-CMS,iahdevelop/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,gkonings/Umbraco-CMS,gavinfaux/Umbraco-CMS,lingxyd/Umbraco-CMS,nvisage-gf/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,m0wo/Umbraco-CMS,aadfPT/Umbraco-CMS,mittonp/Umbraco-CMS,bjarnef/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,sargin48/Umbraco-CMS,tompipe/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,kgiszewski/Umbraco-CMS,christopherbauer/Umbraco-CMS,hfloyd/Umbraco-CMS,rustyswayne/Umbraco-CMS,Khamull/Umbraco-CMS,kgiszewski/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,TimoPerplex/Umbraco-CMS,ehornbostel/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,timothyleerussell/Umbraco-CMS,KevinJump/Umbraco-CMS,DaveGreasley/Umbraco-CMS,aaronpowell/Umbraco-CMS,DaveGreasley/Umbraco-CMS,base33/Umbraco-CMS,AzarinSergey/Umbraco-CMS,DaveGreasley/Umbraco-CMS,mstodd/Umbraco-CMS,mittonp/Umbraco-CMS,abryukhov/Umbraco-CMS,AzarinSergey/Umbraco-CMS,christopherbauer/Umbraco-CMS,rajendra1809/Umbraco-CMS,timothyleerussell/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,mattbrailsford/Umbraco-CMS,engern/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,aaronpowell/Umbraco-CMS,gregoriusxu/Umbraco-CMS,madsoulswe/Umbraco-CMS,gregoriusxu/Umbraco-CMS,mstodd/Umbraco-CMS,m0wo/Umbraco-CMS,mstodd/Umbraco-CMS,rasmusfjord/Umbraco-CMS,markoliver288/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,m0wo/Umbraco-CMS,markoliver288/Umbraco-CMS,gavinfaux/Umbraco-CMS,ordepdev/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,abjerner/Umbraco-CMS,rasmusfjord/Umbraco-CMS,Khamull/Umbraco-CMS,robertjf/Umbraco-CMS,mittonp/Umbraco-CMS,hfloyd/Umbraco-CMS,mittonp/Umbraco-CMS,Spijkerboer/Umbraco-CMS,leekelleher/Umbraco-CMS,Tronhus/Umbraco-CMS,bjarnef/Umbraco-CMS,kasperhhk/Umbraco-CMS,rajendra1809/Umbraco-CMS,yannisgu/Umbraco-CMS,VDBBjorn/Umbraco-CMS,mstodd/Umbraco-CMS,mittonp/Umbraco-CMS,DaveGreasley/Umbraco-CMS,marcemarc/Umbraco-CMS,rasmuseeg/Umbraco-CMS,yannisgu/Umbraco-CMS,arknu/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,aadfPT/Umbraco-CMS,engern/Umbraco-CMS,hfloyd/Umbraco-CMS,markoliver288/Umbraco-CMS,lingxyd/Umbraco-CMS,NikRimington/Umbraco-CMS,rustyswayne/Umbraco-CMS,abryukhov/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,KevinJump/Umbraco-CMS,lingxyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,kasperhhk/Umbraco-CMS,rajendra1809/Umbraco-CMS,VDBBjorn/Umbraco-CMS,gkonings/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,rustyswayne/Umbraco-CMS,gkonings/Umbraco-CMS,nvisage-gf/Umbraco-CMS,Pyuuma/Umbraco-CMS,corsjune/Umbraco-CMS,yannisgu/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,gavinfaux/Umbraco-CMS,VDBBjorn/Umbraco-CMS,rajendra1809/Umbraco-CMS,tompipe/Umbraco-CMS,tcmorris/Umbraco-CMS,Pyuuma/Umbraco-CMS,gkonings/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,romanlytvyn/Umbraco-CMS,KevinJump/Umbraco-CMS,WebCentrum/Umbraco-CMS,tcmorris/Umbraco-CMS,Pyuuma/Umbraco-CMS,dawoe/Umbraco-CMS,aadfPT/Umbraco-CMS,sargin48/Umbraco-CMS,Spijkerboer/Umbraco-CMS,Phosworks/Umbraco-CMS,ordepdev/Umbraco-CMS,qizhiyu/Umbraco-CMS,nvisage-gf/Umbraco-CMS,markoliver288/Umbraco-CMS,ordepdev/Umbraco-CMS,leekelleher/Umbraco-CMS,countrywide/Umbraco-CMS,Tronhus/Umbraco-CMS,neilgaietto/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,lars-erik/Umbraco-CMS,lars-erik/Umbraco-CMS,romanlytvyn/Umbraco-CMS,TimoPerplex/Umbraco-CMS,mstodd/Umbraco-CMS,marcemarc/Umbraco-CMS,AzarinSergey/Umbraco-CMS,neilgaietto/Umbraco-CMS,TimoPerplex/Umbraco-CMS,base33/Umbraco-CMS,timothyleerussell/Umbraco-CMS,qizhiyu/Umbraco-CMS,abryukhov/Umbraco-CMS,kasperhhk/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,iahdevelop/Umbraco-CMS,ehornbostel/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,rasmusfjord/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,madsoulswe/Umbraco-CMS,neilgaietto/Umbraco-CMS,sargin48/Umbraco-CMS,rustyswayne/Umbraco-CMS,engern/Umbraco-CMS,ordepdev/Umbraco-CMS,yannisgu/Umbraco-CMS,marcemarc/Umbraco-CMS,gkonings/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,mattbrailsford/Umbraco-CMS,countrywide/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,AzarinSergey/Umbraco-CMS,corsjune/Umbraco-CMS,sargin48/Umbraco-CMS,ehornbostel/Umbraco-CMS,mattbrailsford/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,jchurchley/Umbraco-CMS,umbraco/Umbraco-CMS,qizhiyu/Umbraco-CMS,christopherbauer/Umbraco-CMS,Phosworks/Umbraco-CMS,countrywide/Umbraco-CMS,iahdevelop/Umbraco-CMS,neilgaietto/Umbraco-CMS,m0wo/Umbraco-CMS,lingxyd/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,Khamull/Umbraco-CMS,marcemarc/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,Spijkerboer/Umbraco-CMS,leekelleher/Umbraco-CMS,kgiszewski/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,dawoe/Umbraco-CMS,DaveGreasley/Umbraco-CMS,nvisage-gf/Umbraco-CMS,romanlytvyn/Umbraco-CMS,m0wo/Umbraco-CMS,TimoPerplex/Umbraco-CMS,lars-erik/Umbraco-CMS,countrywide/Umbraco-CMS,gavinfaux/Umbraco-CMS,gavinfaux/Umbraco-CMS,rasmuseeg/Umbraco-CMS,markoliver288/Umbraco-CMS,gregoriusxu/Umbraco-CMS,tompipe/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,lars-erik/Umbraco-CMS,Phosworks/Umbraco-CMS,iahdevelop/Umbraco-CMS,WebCentrum/Umbraco-CMS,romanlytvyn/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,WebCentrum/Umbraco-CMS,Tronhus/Umbraco-CMS,NikRimington/Umbraco-CMS,yannisgu/Umbraco-CMS,corsjune/Umbraco-CMS,TimoPerplex/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,kasperhhk/Umbraco-CMS,gregoriusxu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,jchurchley/Umbraco-CMS,corsjune/Umbraco-CMS,Pyuuma/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,neilgaietto/Umbraco-CMS,leekelleher/Umbraco-CMS,ehornbostel/Umbraco-CMS,kasperhhk/Umbraco-CMS,christopherbauer/Umbraco-CMS,VDBBjorn/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,corsjune/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,tcmorris/Umbraco-CMS,rasmusfjord/Umbraco-CMS,NikRimington/Umbraco-CMS,Phosworks/Umbraco-CMS,base33/Umbraco-CMS,rajendra1809/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,abjerner/Umbraco-CMS,nvisage-gf/Umbraco-CMS,AzarinSergey/Umbraco-CMS,Tronhus/Umbraco-CMS,christopherbauer/Umbraco-CMS,iahdevelop/Umbraco-CMS,jchurchley/Umbraco-CMS,KevinJump/Umbraco-CMS,rustyswayne/Umbraco-CMS,aaronpowell/Umbraco-CMS,Spijkerboer/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,engern/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,lars-erik/Umbraco-CMS,Khamull/Umbraco-CMS,Tronhus/Umbraco-CMS | src/Umbraco.Tests/AngularIntegration/JsInitializationTests.cs | src/Umbraco.Tests/AngularIntegration/JsInitializationTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Manifest;
using Umbraco.Web.UI.JavaScript;
namespace Umbraco.Tests.AngularIntegration
{
[TestFixture]
public class JsInitializationTests
{
[Test]
public void Get_Default_Init()
{
var init = JsInitialization.GetDefaultInitialization();
Assert.IsTrue(init.Any());
}
[Test]
public void Parse_Main()
{
var result = JsInitialization.ParseMain(new[] {"[World]", "Hello" });
Assert.AreEqual(@"LazyLoad.js([World], function () {
//we need to set the legacy UmbClientMgr path
UmbClientMgr.setUmbracoPath('Hello');
jQuery(document).ready(function () {
angular.bootstrap(document, ['umbraco']);
});
});", result);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Manifest;
using Umbraco.Web.UI.JavaScript;
namespace Umbraco.Tests.AngularIntegration
{
[TestFixture]
public class JsInitializationTests
{
[Test]
public void Get_Default_Init()
{
var init = JsInitialization.GetDefaultInitialization();
Assert.IsTrue(init.Any());
}
[Test]
public void Parse_Main()
{
var result = JsInitialization.ParseMain(new[] {"[World]", "Hello" });
Assert.AreEqual(@"
yepnope({
load: [
'lib/jquery/jquery-2.0.3.min.js',
'lib/angular/1.1.5/angular.min.js',
'lib/underscore/underscore.js',
],
complete: function () {
yepnope({
load: [World],
complete: function () {
//we need to set the legacy UmbClientMgr path
UmbClientMgr.setUmbracoPath('Hello');
jQuery(document).ready(function () {
angular.bootstrap(document, ['umbraco']);
});
}
});
}
});", result);
}
}
}
| mit | C# |
c9e02ae4f3f92528477f3554259b7c2c56d30ce5 | Make portability tests run on every target | aaubry/YamlDotNet,aaubry/YamlDotNet,aaubry/YamlDotNet | YamlDotNet.Test/Helpers/PortabilityTests.cs | YamlDotNet.Test/Helpers/PortabilityTests.cs | // This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// 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.Globalization;
using Xunit;
namespace YamlDotNet.Test.Helpers
{
public class PortabilityTests
{
[Fact]
public void GetPublicStaticMethodReturnsCorrectMethodInfo()
{
var expected = DateTimeOffset.UtcNow;
var type = typeof(DateTimeOffset);
var method = type.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider));
var actual = (DateTimeOffset)method.Invoke(null, new object[] { expected.ToString("o"), CultureInfo.InvariantCulture });
Assert.Equal(expected, actual);
}
}
} | // This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// 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.Reflection;
using Xunit;
namespace YamlDotNet.Test.Helpers
{
public class PortabilytyTests
{
#if PORTABLE
[Fact]
public void GetPublicStaticMethodReturnsCorrectMethodInfo()
{
var type = typeof(DateTimeOffset);
var expected = type.GetMethod("Parse", new [] { typeof(string), typeof(IFormatProvider) });
var method = type.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider));
Assert.Equal(expected, method);
}
#endif
}
} | mit | C# |
9a68de156d54241dbccc60bd954dc78250a22675 | remove parameter values fom reaction enum | Sarmad93/octokit.net,M-Zuber/octokit.net,octokit/octokit.net,eriawan/octokit.net,TattsGroup/octokit.net,thedillonb/octokit.net,editor-tools/octokit.net,SmithAndr/octokit.net,TattsGroup/octokit.net,shiftkey/octokit.net,ivandrofly/octokit.net,gdziadkiewicz/octokit.net,M-Zuber/octokit.net,shiftkey-tester/octokit.net,khellang/octokit.net,octokit/octokit.net,alfhenrik/octokit.net,devkhan/octokit.net,SmithAndr/octokit.net,alfhenrik/octokit.net,rlugojr/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,adamralph/octokit.net,thedillonb/octokit.net,ivandrofly/octokit.net,rlugojr/octokit.net,khellang/octokit.net,shiftkey-tester/octokit.net,dampir/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,editor-tools/octokit.net,shana/octokit.net,shiftkey/octokit.net,devkhan/octokit.net,gdziadkiewicz/octokit.net,Sarmad93/octokit.net,shana/octokit.net,eriawan/octokit.net,dampir/octokit.net | Octokit/Models/Response/Reaction.cs | Octokit/Models/Response/Reaction.cs | using Octokit.Internal;
using System;
using System.Diagnostics;
using System.Globalization;
namespace Octokit
{
public enum ReactionType
{
[Parameter(Value = "+1")]
Plus1,
[Parameter(Value = "-1")]
Minus1,
Laugh,
Confused,
Heart,
Hooray
}
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class Reaction
{
public Reaction() { }
public Reaction(int id, int userId, ReactionType content)
{
Id = id;
UserId = userId;
Content = content;
}
/// <summary>
/// The Id for this reaction.
/// </summary>
public int Id { get; protected set; }
/// <summary>
/// The UserId.
/// </summary>
public int UserId { get; protected set; }
/// <summary>
/// The reaction type for this commit comment.
/// </summary>
[Parameter(Key = "content")]
public ReactionType Content { get; protected set; }
internal string DebuggerDisplay
{
get
{
return string.Format(CultureInfo.InvariantCulture, "Id: {0}, Reaction: {1}", Id, Content);
}
}
}
}
| using Octokit.Internal;
using System;
using System.Diagnostics;
using System.Globalization;
namespace Octokit
{
public enum ReactionType
{
[Parameter(Value = "+1")]
Plus1,
[Parameter(Value = "-1")]
Minus1,
[Parameter(Value = "laugh")]
Laugh,
[Parameter(Value = "confused")]
Confused,
[Parameter(Value = "heart")]
Heart,
[Parameter(Value = "hooray")]
Hooray
}
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class Reaction
{
public Reaction() { }
public Reaction(int id, int userId, ReactionType content)
{
Id = id;
UserId = userId;
Content = content;
}
/// <summary>
/// The Id for this reaction.
/// </summary>
public int Id { get; protected set; }
/// <summary>
/// The UserId.
/// </summary>
public int UserId { get; protected set; }
/// <summary>
/// The reaction type for this commit comment.
/// </summary>
[Parameter(Key = "content")]
public ReactionType Content { get; protected set; }
internal string DebuggerDisplay
{
get
{
return string.Format(CultureInfo.InvariantCulture, "Id: {0}, Reaction: {1}", Id, Content);
}
}
}
}
| mit | C# |
4040eaaef0861d24d5060055948a97dfb79dc5f2 | Add VersionUrl constant. | AeonLucid/POGOLib,m5219/POGOLib | src/POGOLib.Official/Constants.cs | src/POGOLib.Official/Constants.cs | namespace POGOLib.Official
{
public static class Constants
{
// API stuff
public const string ApiUrl = "https://pgorelease.nianticlabs.com/plfe/rpc";
public const string VersionUrl = "https://pgorelease.nianticlabs.com/plfe/version";
// Login stuff
public const string LoginUrl = "https://sso.pokemon.com/sso/login?service=https%3A%2F%2Fsso.pokemon.com%2Fsso%2Foauth2.0%2FcallbackAuthorize";
public const string LoginUserAgent = "Niantic App";
public const string LoginOauthUrl = "https://sso.pokemon.com/sso/oauth2.0/accessToken";
public const string GoogleAuthService = "audience:server:client_id:848232511240-7so421jotr2609rmqakceuu1luuq0ptb.apps.googleusercontent.com";
public const string GoogleAuthApp = "com.nianticlabs.pokemongo";
public const string GoogleAuthClientSig = "321187995bc7cdc2b5fc91b11a96e2baa8602c62";
// Hash stuff
// Currently updated for version IOS(1.15.0) and Android(0.45.0)
public const long Unknown25 = -1553869577012279119;
}
} | namespace POGOLib.Official
{
public static class Constants
{
// API stuff
public const string ApiUrl = "https://pgorelease.nianticlabs.com/plfe/rpc";
// Login stuff
public const string LoginUrl = "https://sso.pokemon.com/sso/login?service=https%3A%2F%2Fsso.pokemon.com%2Fsso%2Foauth2.0%2FcallbackAuthorize";
public const string LoginUserAgent = "Niantic App";
public const string LoginOauthUrl = "https://sso.pokemon.com/sso/oauth2.0/accessToken";
public const string GoogleAuthService = "audience:server:client_id:848232511240-7so421jotr2609rmqakceuu1luuq0ptb.apps.googleusercontent.com";
public const string GoogleAuthApp = "com.nianticlabs.pokemongo";
public const string GoogleAuthClientSig = "321187995bc7cdc2b5fc91b11a96e2baa8602c62";
// Hash stuff
// Currently updated for version IOS(1.15.0) and Android(0.45.0)
public const long Unknown25 = -1553869577012279119;
}
} | mit | C# |
d011b28eb445fb3639de7a8044e2d442596df20e | Add missing variable | IG-Group/ig-webapi-dotnet-sample | IGWebApiClient/Model/dto/endpoint/positions/close/v1/ClosePositionRequest.cs | IGWebApiClient/Model/dto/endpoint/positions/close/v1/ClosePositionRequest.cs | using System.Collections.Generic;
using dto.endpoint.auth.session;
namespace dto.endpoint.positions.close.v1
{
public class ClosePositionRequest{
///<Summary>
///Deal identifier
///</Summary>
public string dealId { get; set; }
///<Summary>
///Instrument epic identifier
///</Summary>
public string epic { get; set; }
///<Summary>
///Instrument expiry
///</Summary>
public string expiry { get; set; }
///<Summary>
///Deal direction
///</Summary>
public string direction { get; set; }
///<Summary>
///Deal size
///</Summary>
public decimal? size { get; set; }
///<Summary>
///Closing deal level
///</Summary>
public decimal? level { get; set; }
///<Summary>
///Order type
///</Summary>
public string orderType { get; set; }
///<Summary>
///Time in force
///</Summary>
public string timeInForce { get; set; }
///<Summary>
///Lightstreamer price quote identifier
///</Summary>
public string quoteId { get; set; }
}
}
| using System.Collections.Generic;
using dto.endpoint.auth.session;
namespace dto.endpoint.positions.close.v1
{
public class ClosePositionRequest{
///<Summary>
///Deal identifier
///</Summary>
public string dealId { get; set; }
///<Summary>
///Instrument epic identifier
///</Summary>
public string epic { get; set; }
///<Summary>
///Instrument expiry
///</Summary>
public string expiry { get; set; }
///<Summary>
///Deal direction
///</Summary>
public string direction { get; set; }
///<Summary>
///Deal size
///</Summary>
public decimal? size { get; set; }
///<Summary>
///Closing deal level
///</Summary>
public decimal? level { get; set; }
///<Summary>
///True if a market order is required
///</Summary>
public string orderType { get; set; }
///<Summary>
///Lightstreamer price quote identifier
///</Summary>
public string quoteId { get; set; }
}
}
| bsd-3-clause | C# |
c2d9789671fb9095935f28c3ab012d67df0536a9 | Implement Repeat function | kornelijepetak/incident-cs | IncidentCS/Incident.Utils.cs | IncidentCS/Incident.Utils.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace KornelijePetak.IncidentCS
{
public static partial class Incident
{
/// <summary>
/// Chooses an element from the list
/// </summary>
/// <typeparam name="T">Collection item type</typeparam>
/// <param name="collection">[Extended] A collection from which to choose</param>
/// <returns>A random element from the collection</returns>
public static T ChooseAtRandom<T>(this IEnumerable<T> collection)
{
int index;
IList<T> collectionAsList = collection as IList<T>;
if (collectionAsList != null)
{
index = Rand.Next(collectionAsList.Count);
T element = collectionAsList[index];
return element;
}
T[] collectionAsArray = collection as T[];
if (collectionAsArray != null)
{
index = Rand.Next(collectionAsArray.Length);
T element = collectionAsArray[index];
return element;
}
index = Rand.Next(collection.Count());
return collection.Skip(index).First();
}
public static T PickAtRandom<T>(this List<T> collection)
{
int index = Rand.Next(collection.Count);
T element = collection[index];
collection.RemoveAt(index);
return element;
}
internal static string TextFromResource(this string resource)
{
Assembly assembly = typeof(Incident).Assembly;
string resourcePath = "IncidentCS." + resource;
using (StreamReader reader = new StreamReader(assembly.GetManifestResourceStream(resourcePath)))
{
return reader.ReadToEnd();
}
}
internal static IEnumerable<string> LinesFromResource(this string resource)
{
Assembly assembly = typeof(Incident).Assembly;
string incidentNamespace = typeof(Incident).Namespace;
string resourcePath = string.Format("{0}.Resources.{1}", incidentNamespace, resource);
using (StreamReader reader =
new StreamReader(assembly.GetManifestResourceStream(resourcePath)))
{
return reader.ReadToEnd().Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
}
}
public static string Capitalize(this string text)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.Length; i++)
{
if (i == 0)
{
result.Append(text[i].ToString().ToUpper());
continue;
}
if (text[i - 1] == ' ')
result.Append(text[i].ToString().ToUpper());
else
result.Append(text[i]);
}
return result.ToString();
}
public static IEnumerable<T> Repeat<T>(this IEnumerable<T> collection, int count)
{
for (int i = 0; i < count; i++)
{
foreach (T item in collection)
{
yield return item;
}
}
}
public static string Repeat(Func<string> itemGenerator, int count)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < count; i++)
result.Append(itemGenerator());
return result.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace KornelijePetak.IncidentCS
{
public static partial class Incident
{
/// <summary>
/// Chooses an element from the list
/// </summary>
/// <typeparam name="T">Collection item type</typeparam>
/// <param name="collection">[Extended] A collection from which to choose</param>
/// <returns>A random element from the collection</returns>
public static T ChooseAtRandom<T>(this IEnumerable<T> collection)
{
int index;
IList<T> collectionAsList = collection as IList<T>;
if (collectionAsList != null)
{
index = Rand.Next(collectionAsList.Count);
T element = collectionAsList[index];
return element;
}
T[] collectionAsArray = collection as T[];
if (collectionAsArray != null)
{
index = Rand.Next(collectionAsArray.Length);
T element = collectionAsArray[index];
return element;
}
index = Rand.Next(collection.Count());
return collection.Skip(index).First();
}
public static T PickAtRandom<T>(this List<T> collection)
{
int index = Rand.Next(collection.Count);
T element = collection[index];
collection.RemoveAt(index);
return element;
}
internal static string TextFromResource(this string resource)
{
Assembly assembly = typeof(Incident).Assembly;
string resourcePath = "IncidentCS." + resource;
using (StreamReader reader = new StreamReader(assembly.GetManifestResourceStream(resourcePath)))
{
return reader.ReadToEnd();
}
}
internal static IEnumerable<string> LinesFromResource(this string resource)
{
Assembly assembly = typeof(Incident).Assembly;
string incidentNamespace = typeof(Incident).Namespace;
string resourcePath = string.Format("{0}.Resources.{1}", incidentNamespace, resource);
using (StreamReader reader =
new StreamReader(assembly.GetManifestResourceStream(resourcePath)))
{
return reader.ReadToEnd().Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
}
}
public static string Capitalize(this string text)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.Length; i++)
{
if (i == 0)
{
result.Append(text[i].ToString().ToUpper());
continue;
}
if (text[i - 1] == ' ')
result.Append(text[i].ToString().ToUpper());
else
result.Append(text[i]);
}
return result.ToString();
}
}
}
| mit | C# |
523c79b44b5b5313d94c8ef0aedbff6811c20d94 | update actor paths to work on mono | MarcelWouters/akkadotnet-code-samples,irperez/akkadotnet-code-samples,Aaronontheweb/akkadotnet-code-samples,MarcelWouters/akkadotnet-code-samples,Excommunicated/akkadotnet-code-samples,MarcelWouters/akkadotnet-code-samples,paulroho/akkadotnet-code-samples,paulroho/akkadotnet-code-samples,skotzko/akkadotnet-code-samples,jeremybphillips/akkadotnet-code-samples,Excommunicated/akkadotnet-code-samples,andrii-baranov/akkadotnet-code-samples,jeremybphillips/akkadotnet-code-samples,petabridge/akkadotnet-code-samples,petabridge/akkadotnet-code-samples,Aaronontheweb/akkadotnet-code-samples,petabridge/akkadotnet-code-samples,jeremybphillips/akkadotnet-code-samples,skotzko/akkadotnet-code-samples,skotzko/akkadotnet-code-samples,irperez/akkadotnet-code-samples,petabridge/akkadotnet-code-samples,Excommunicated/akkadotnet-code-samples,paulroho/akkadotnet-code-samples,irperez/akkadotnet-code-samples,Aaronontheweb/akkadotnet-code-samples,andrii-baranov/akkadotnet-code-samples,Aaronontheweb/akkadotnet-code-samples,andrii-baranov/akkadotnet-code-samples | PipeTo/src/PipeTo.App/ActorNames.cs | PipeTo/src/PipeTo.App/ActorNames.cs | using System;
namespace PipeTo.App
{
/// <summary>
/// Helper class that provides basic name and address information for Actors.
///
/// That way if we need to change the name of an actor, we only need to do it in one place.
/// </summary>
public static class ActorNames
{
/// <summary>
/// Responsible for serializing writes to the <see cref="Console"/>
/// </summary>
public static readonly ActorData ConsoleWriterActor = new ActorData("consoleWriter", "akka://MyFirstActorSystem/user"); // /user/consoleWriter
/// <summary>
/// Responsible for serializing reads from the <see cref="Console"/>
/// </summary>
public static readonly ActorData ConsoleReaderActor = new ActorData("consoleReaderActor", "akka://MyFirstActorSystem/user"); // /user/consoleReader
/// <summary>
/// Responsible for validating data from <see cref="ConsoleReaderActor"/> and kicking off the feed parsing process
/// </summary>
public static readonly ActorData FeedValidatorActor = new ActorData("feedValidator", "akka://MyFirstActorSystem/user"); // /user/feedValidator
}
/// <summary>
/// Meta-data class for working with high-level Actor names and paths
/// </summary>
public class ActorData
{
public ActorData(string name, string parent)
{
Path = parent + "/" + name;
Name = name;
}
public ActorData(string name)
{
Path = "akka://MyFirstActorSystem/" + name;
Name = name;
}
public string Name { get; private set; }
public string Path { get; private set; }
}
}
| using System;
namespace PipeTo.App
{
/// <summary>
/// Helper class that provides basic name and address information for Actors.
///
/// That way if we need to change the name of an actor, we only need to do it in one place.
/// </summary>
public static class ActorNames
{
/// <summary>
/// Responsible for serializing writes to the <see cref="Console"/>
/// </summary>
public static readonly ActorData ConsoleWriterActor = new ActorData("consoleWriter", "/user"); // /user/consoleWriter
/// <summary>
/// Responsible for serializing reads from the <see cref="Console"/>
/// </summary>
public static readonly ActorData ConsoleReaderActor = new ActorData("consoleReaderActor", "/user"); // /user/consoleReader
/// <summary>
/// Responsible for validating data from <see cref="ConsoleReaderActor"/> and kicking off the feed parsing process
/// </summary>
public static readonly ActorData FeedValidatorActor = new ActorData("feedValidator", "/user"); // /user/feedValidator
}
/// <summary>
/// Meta-data class for working with high-level Actor names and paths
/// </summary>
public class ActorData
{
public ActorData(string name, string parent)
{
Path = parent + "/" + name;
Name = name;
}
public ActorData(string name)
{
Path = "/" + name;
Name = name;
}
public string Name { get; private set; }
public string Path { get; private set; }
}
}
| apache-2.0 | C# |
cb952ab75ff37421faa1d8895a438fdd994548af | Update comment | SixLabors/Fonts | src/SixLabors.Fonts/FontCollectionExtensions.cs | src/SixLabors.Fonts/FontCollectionExtensions.cs | // Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System;
namespace SixLabors.Fonts
{
/// <summary>
/// Extension methods for <see cref="IFontCollection"/>.
/// </summary>
public static class FontCollectionExtensions
{
/// <summary>
/// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>.
/// </summary>
/// <param name="collection">The font collection.</param>
/// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns>
public static FontCollection AddSystemFonts(this FontCollection collection)
{
// This cast is safe because our underlying SystemFontCollection implements
// both interfaces separately.
foreach (FontMetrics metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection)
{
((IFontMetricsCollection)collection).AddMetrics(metric);
}
return collection;
}
/// <summary>
/// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>.
/// </summary>
/// <param name="collection">The font collection.</param>
/// <param name="match">The <see cref="System.Predicate"/> delegate that defines the conditions of <see cref="FontMetrics"/> to add into the font collection.</param>
/// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns>
public static FontCollection AddSystemFonts(this FontCollection collection, Predicate<FontMetrics> match)
{
foreach (FontMetrics metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection)
{
if (match(metric))
{
((IFontMetricsCollection)collection).AddMetrics(metric);
}
}
return collection;
}
}
}
| // Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System;
namespace SixLabors.Fonts
{
/// <summary>
/// Extension methods for <see cref="IFontCollection"/>.
/// </summary>
public static class FontCollectionExtensions
{
/// <summary>
/// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>.
/// </summary>
/// <param name="collection">The font collection.</param>
/// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns>
public static FontCollection AddSystemFonts(this FontCollection collection)
{
// This cast is safe because our underlying SystemFontCollection implements
// both interfaces separately.
foreach (FontMetrics metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection)
{
((IFontMetricsCollection)collection).AddMetrics(metric);
}
return collection;
}
/// <summary>
/// Adds the fonts from the <see cref="SystemFonts"/> collection to this <see cref="FontCollection"/>.
/// </summary>
/// <param name="collection">The font collection.</param>
/// <param name="match">The System.Predicate delegate that defines the conditions of <see cref="FontMetrics"/> to add into the font collection.</param>
/// <returns>The <see cref="FontCollection"/> containing the system fonts.</returns>
public static FontCollection AddSystemFonts(this FontCollection collection, Predicate<FontMetrics> match)
{
foreach (FontMetrics metric in (IReadOnlyFontMetricsCollection)SystemFonts.Collection)
{
if (match(metric))
{
((IFontMetricsCollection)collection).AddMetrics(metric);
}
}
return collection;
}
}
}
| apache-2.0 | C# |
c23fac3431f184ce2835a59aba09c6ef7b201445 | Fix - Tolti controlli sui ruoli dell'utente nella ricerca del personale | vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf | src/backend/SO115App.Models/Servizi/CQRS/Queries/GestioneUtente/ListaPersonaleVVF/PersonaleVVFAuthorizationQueryHandlerDecorator.cs | src/backend/SO115App.Models/Servizi/CQRS/Queries/GestioneUtente/ListaPersonaleVVF/PersonaleVVFAuthorizationQueryHandlerDecorator.cs | using CQRS.Authorization;
using CQRS.Queries.Authorizers;
using SO115App.API.Models.Classi.Autenticazione;
using SO115App.Models.Classi.Utility;
using SO115App.Models.Servizi.Infrastruttura.Autenticazione;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.VerificaUtente;
using System;
using System.Collections.Generic;
using System.Security.Principal;
using System.Text;
namespace SO115App.Models.Servizi.CQRS.Queries.GestioneUtente.ListaPersonaleVVF
{
public class PersonaleVVFAuthorizationQueryHandlerDecorator : IQueryAuthorizer<PersonaleVVFQuery, PersonaleVVFResult>
{
private readonly IPrincipal _currentUser;
private readonly IFindUserByUsername _findUserByUsername;
private readonly IGetAutorizzazioni _getAutorizzazioni;
public PersonaleVVFAuthorizationQueryHandlerDecorator(IPrincipal currentUser, IFindUserByUsername findUserByUsername, IGetAutorizzazioni getAutorizzazioni)
{
_currentUser = currentUser;
_findUserByUsername = findUserByUsername;
_getAutorizzazioni = getAutorizzazioni;
}
public IEnumerable<AuthorizationResult> Authorize(PersonaleVVFQuery query)
{
string username = _currentUser.Identity.Name;
Utente user = _findUserByUsername.FindUserByUs(username);
if (_currentUser.Identity.IsAuthenticated)
{
if (user == null)
yield return new AuthorizationResult(Costanti.UtenteNonAutorizzato);
}
else
yield return new AuthorizationResult(Costanti.UtenteNonAutorizzato);
}
}
}
| using CQRS.Authorization;
using CQRS.Queries.Authorizers;
using SO115App.API.Models.Classi.Autenticazione;
using SO115App.Models.Classi.Utility;
using SO115App.Models.Servizi.Infrastruttura.Autenticazione;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.VerificaUtente;
using System;
using System.Collections.Generic;
using System.Security.Principal;
using System.Text;
namespace SO115App.Models.Servizi.CQRS.Queries.GestioneUtente.ListaPersonaleVVF
{
public class PersonaleVVFAuthorizationQueryHandlerDecorator : IQueryAuthorizer<PersonaleVVFQuery, PersonaleVVFResult>
{
private readonly IPrincipal _currentUser;
private readonly IFindUserByUsername _findUserByUsername;
private readonly IGetAutorizzazioni _getAutorizzazioni;
public PersonaleVVFAuthorizationQueryHandlerDecorator(IPrincipal currentUser, IFindUserByUsername findUserByUsername, IGetAutorizzazioni getAutorizzazioni)
{
_currentUser = currentUser;
_findUserByUsername = findUserByUsername;
_getAutorizzazioni = getAutorizzazioni;
}
public IEnumerable<AuthorizationResult> Authorize(PersonaleVVFQuery query)
{
string username = _currentUser.Identity.Name;
Utente user = _findUserByUsername.FindUserByUs(username);
if (_currentUser.Identity.IsAuthenticated)
{
if (user == null)
yield return new AuthorizationResult(Costanti.UtenteNonAutorizzato);
else
{
foreach (var ruolo in user.Ruoli)
{
if (!_getAutorizzazioni.GetAutorizzazioniUtente(user.Ruoli, query.CodiceSede, Costanti.Amministratore))
yield return new AuthorizationResult(Costanti.UtenteNonAutorizzato);
}
}
}
else
yield return new AuthorizationResult(Costanti.UtenteNonAutorizzato);
}
}
}
| agpl-3.0 | C# |
b085821092bbac6bb58785c8d5dc7fb68dc7910c | indent LowercaseDocumentFilter | arsouza/Aritter,arsouza/Aritter,aritters/Ritter | samples/Ritter.Samples.Web/SwaggerFilters/LowercaseDocumentFilter.cs | samples/Ritter.Samples.Web/SwaggerFilters/LowercaseDocumentFilter.cs | using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;
using System.Linq;
namespace Ritter.Samples.Web.SwaggerFilters
{
public class LowercaseDocumentFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
// paths
var paths = swaggerDoc.Paths;
// generate the new keys
var newPaths = new Dictionary<string, PathItem>();
var removeKeys = new List<string>();
foreach (var path in paths)
{
var newKey = LowercaseEverythingButParameters(path.Key);
if (newKey != path.Key)
{
removeKeys.Add(path.Key);
newPaths.Add(newKey, path.Value);
}
}
// add the new keys
foreach (var path in newPaths)
swaggerDoc.Paths.Add(path.Key, path.Value);
// remove the old keys
foreach (var key in removeKeys)
swaggerDoc.Paths.Remove(key);
}
private string LowercaseEverythingButParameters(string key)
=> string.Join('/', key.Split('/').Select(x => x.Contains("{") ? x : x.ToLower()));
}
}
| using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;
using System.Linq;
namespace Ritter.Samples.Web.SwaggerFilters
{
public class LowercaseDocumentFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
// paths
var paths = swaggerDoc.Paths;
// generate the new keys
var newPaths = new Dictionary<string, PathItem>();
var removeKeys = new List<string>();
foreach (var path in paths)
{
var newKey = LowercaseEverythingButParameters(path.Key);
if (newKey != path.Key)
{
removeKeys.Add(path.Key);
newPaths.Add(newKey, path.Value);
}
}
// add the new keys
foreach (var path in newPaths)
{
swaggerDoc.Paths.Add(path.Key, path.Value);
}
// remove the old keys
foreach (var key in removeKeys)
{
swaggerDoc.Paths.Remove(key);
}
}
private string LowercaseEverythingButParameters(string key)=> string.Join('/', key.Split('/').Select(x => x.Contains("{") ? x : x.ToLower()));
}
}
| mit | C# |
6f1489fd9f49dad8af19cc20a162fea9b1f0ab6a | Remove unused namespaces | extremecodetv/SocksSharp | src/SocksSharp/Proxy/IProxyClient.cs | src/SocksSharp/Proxy/IProxyClient.cs | using System.Net.Sockets;
namespace SocksSharp.Proxy
{
public interface IProxyClient<out T> where T : IProxy
{
ProxySettings Settings { get; set; }
NetworkStream GetDestinationStream(string destinationHost, int destinationPort);
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocksSharp.Proxy
{
public interface IProxyClient<out T> where T : IProxy
{
ProxySettings Settings { get; set; }
NetworkStream GetDestinationStream(string destinationHost, int destinationPort);
}
}
| mit | C# |
ed45834d56405c4862c2ce0566863e3dd5b61419 | use the Core binaries path search logic | NServiceBusSqlPersistence/NServiceBus.SqlPersistence | src/SqlPersistence/ScriptLocation.cs | src/SqlPersistence/ScriptLocation.cs | using System;
using System.IO;
using NServiceBus;
using NServiceBus.Settings;
static class ScriptLocation
{
const string ScriptFolder = "NServiceBus.Persistence.Sql";
public static string FindScriptDirectory(ReadOnlySettings settings)
{
var currentDirectory = GetScriptsRootPath(settings);
return Path.Combine(currentDirectory, ScriptFolder, settings.GetSqlDialect().Name);
}
static string GetScriptsRootPath(ReadOnlySettings settings)
{
if (settings.TryGet("SqlPersistence.ScriptDirectory", out string scriptDirectory))
{
return scriptDirectory;
}
//NOTE: This is the same logic that Core uses for finding assembly scanning path.
// RelativeSearchPath is set for ASP .NET and points to the binaries folder i.e. /bin
return AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
}
public static void ValidateScriptExists(string createScript)
{
if (!File.Exists(createScript))
{
throw new Exception($"Expected '{createScript}' to exist. It is possible it was not deployed with the endpoint.");
}
}
}
| using System;
using System.IO;
using System.Reflection;
using NServiceBus;
using NServiceBus.Settings;
static class ScriptLocation
{
const string ScriptFolder = "NServiceBus.Persistence.Sql";
public static string FindScriptDirectory(ReadOnlySettings settings)
{
var currentDirectory = GetCurrentDirectory(settings);
return Path.Combine(currentDirectory, ScriptFolder, settings.GetSqlDialect().Name);
}
static string GetCurrentDirectory(ReadOnlySettings settings)
{
if (settings.TryGet("SqlPersistence.ScriptDirectory", out string scriptDirectory))
{
return scriptDirectory;
}
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly == null)
{
var baseDir = AppDomain.CurrentDomain.BaseDirectory;
var scriptDir = Path.Combine(baseDir, ScriptFolder);
//if the app domain base dir contains the scripts folder, return it. Otherwise add "bin" to the base dir so that web apps work correctly
if (Directory.Exists(scriptDir))
{
return baseDir;
}
return Path.Combine(baseDir, "bin");
}
var codeBase = entryAssembly.CodeBase;
return Directory.GetParent(new Uri(codeBase).LocalPath).FullName;
}
public static void ValidateScriptExists(string createScript)
{
if (!File.Exists(createScript))
{
throw new Exception($"Expected '{createScript}' to exist. It is possible it was not deployed with the endpoint.");
}
}
}
| mit | C# |
df564e63c5f62d519ac534a790ab8cb880739574 | Remove blank line | tmat/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,mavasani/roslyn,bartdesmet/roslyn,tannergooding/roslyn,physhi/roslyn,weltkante/roslyn,dotnet/roslyn,heejaechang/roslyn,tmat/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,tmat/roslyn,AmadeusW/roslyn,wvdd007/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,AlekseyTs/roslyn,eriawan/roslyn,mavasani/roslyn,KevinRansom/roslyn,physhi/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,eriawan/roslyn,sharwell/roslyn,panopticoncentral/roslyn,ErikSchierboom/roslyn,eriawan/roslyn,KevinRansom/roslyn,tannergooding/roslyn,tannergooding/roslyn,dotnet/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,diryboy/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,wvdd007/roslyn,AmadeusW/roslyn,weltkante/roslyn,AlekseyTs/roslyn,KirillOsenkov/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,mavasani/roslyn | src/Features/Core/Portable/Structure/BlockStructureOptionProvider.cs | src/Features/Core/Portable/Structure/BlockStructureOptionProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Structure
{
internal sealed class BlockStructureOptionProvider
{
private readonly OptionSet _options;
public BlockStructureOptionProvider(OptionSet options, bool isMetadataAsSource)
{
_options = options;
IsMetadataAsSource = isMetadataAsSource;
}
public bool IsMetadataAsSource { get; }
public T GetOption<T>(PerLanguageOption2<T> option, string language)
=> _options.GetOption(option, language);
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Structure
{
internal sealed class BlockStructureOptionProvider
{
private readonly OptionSet _options;
public BlockStructureOptionProvider(OptionSet options, bool isMetadataAsSource)
{
_options = options;
IsMetadataAsSource = isMetadataAsSource;
}
public bool IsMetadataAsSource { get; }
public T GetOption<T>(PerLanguageOption2<T> option, string language)
=> _options.GetOption(option, language);
}
}
| mit | C# |
8e54ea42e6cc4514397724d472699df9968f94dd | Fix rare crash when deleting airlock while the deny animation is playing | space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Client/GameObjects/Components/Wires/WiresVisualizer.cs | Content.Client/GameObjects/Components/Wires/WiresVisualizer.cs | using Robust.Client.GameObjects;
using Robust.Client.Interfaces.GameObjects.Components;
using static Content.Shared.GameObjects.Components.SharedWiresComponent;
namespace Content.Client.GameObjects.Components.Wires
{
public class WiresVisualizer : AppearanceVisualizer
{
public override void OnChangeData(AppearanceComponent component)
{
base.OnChangeData(component);
if (component.Owner.Deleted)
return;
var sprite = component.Owner.GetComponent<ISpriteComponent>();
if (component.TryGetData<bool>(WiresVisuals.MaintenancePanelState, out var state))
{
sprite.LayerSetVisible(WiresVisualLayers.MaintenancePanel, state);
}
}
public enum WiresVisualLayers
{
MaintenancePanel,
}
}
}
| using Robust.Client.GameObjects;
using Robust.Client.Interfaces.GameObjects.Components;
using static Content.Shared.GameObjects.Components.SharedWiresComponent;
namespace Content.Client.GameObjects.Components.Wires
{
public class WiresVisualizer : AppearanceVisualizer
{
public override void OnChangeData(AppearanceComponent component)
{
base.OnChangeData(component);
var sprite = component.Owner.GetComponent<ISpriteComponent>();
if (component.TryGetData<bool>(WiresVisuals.MaintenancePanelState, out var state))
{
sprite.LayerSetVisible(WiresVisualLayers.MaintenancePanel, state);
}
}
public enum WiresVisualLayers
{
MaintenancePanel,
}
}
}
| mit | C# |
d700448ddf8a852527a96effe574915d75fb0956 | Change Steam switch timeout and check time | danielchalmers/SteamAccountSwitcher | SteamAccountSwitcher/SteamClient.cs | SteamAccountSwitcher/SteamClient.cs | #region
using System.Diagnostics;
using System.IO;
using System.Threading;
using SteamAccountSwitcher.Properties;
#endregion
namespace SteamAccountSwitcher
{
internal class SteamClient
{
public static void LogIn(Account account)
{
Process.Start(Settings.Default.SteamPath,
$"{Resources.SteamLoginArgument} \"{account.Username}\" \"{account.Password}\"");
}
public static void LogOut()
{
Process.Start(Settings.Default.SteamPath, Resources.SteamShutdownArgument);
}
public static bool LogOutAuto()
{
var timeout = 0;
const int maxtimeout = 10000;
const int waitstep = 100;
if (IsSteamOpen())
{
LogOut();
while (IsSteamOpen())
{
if (timeout >= maxtimeout)
{
Popup.Show("Logout operation has timed out. Please force close steam and try again.");
return false;
}
Thread.Sleep(waitstep);
timeout += waitstep;
}
}
return true;
}
public static string ResolvePath()
{
if (File.Exists(Resources.SteamPath32))
return Resources.SteamPath32;
if (File.Exists(Resources.SteamPath64))
return Resources.SteamPath64;
Popup.Show("Default Steam path could not be located.\r\n\r\nPlease enter Steam executable location.");
var dia = new SteamPath();
dia.ShowDialog();
return dia.Path;
}
public static bool IsSteamOpen()
{
return (Process.GetProcessesByName(Resources.Steam).Length > 0);
}
}
} | #region
using System.Diagnostics;
using System.IO;
using System.Threading;
using SteamAccountSwitcher.Properties;
#endregion
namespace SteamAccountSwitcher
{
internal class SteamClient
{
public static void LogIn(Account account)
{
Process.Start(Settings.Default.SteamPath,
$"{Resources.SteamLoginArgument} \"{account.Username}\" \"{account.Password}\"");
}
public static void LogOut()
{
Process.Start(Settings.Default.SteamPath, Resources.SteamShutdownArgument);
}
public static bool LogOutAuto()
{
var timeout = 0;
const int maxtimeout = 5000;
const int waitstep = 500;
if (IsSteamOpen())
{
LogOut();
while (IsSteamOpen())
{
if (timeout >= maxtimeout)
{
Popup.Show("Logout operation has timed out. Please force close steam and try again.");
return false;
}
Thread.Sleep(waitstep);
timeout += waitstep;
}
}
return true;
}
public static string ResolvePath()
{
if (File.Exists(Resources.SteamPath32))
return Resources.SteamPath32;
if (File.Exists(Resources.SteamPath64))
return Resources.SteamPath64;
Popup.Show("Default Steam path could not be located.\r\n\r\nPlease enter Steam executable location.");
var dia = new SteamPath();
dia.ShowDialog();
return dia.Path;
}
public static bool IsSteamOpen()
{
return (Process.GetProcessesByName(Resources.Steam).Length > 0);
}
}
} | mit | C# |
87d5c0c57080f27596e65d9a0131b6c6a95d1fb5 | Use correct colors. | eatskolnikov/mobile,masterrr/mobile,eatskolnikov/mobile,eatskolnikov/mobile,peeedge/mobile,ZhangLeiCharles/mobile,ZhangLeiCharles/mobile,peeedge/mobile,masterrr/mobile | Ross/Theme/Style.NavTimer.cs | Ross/Theme/Style.NavTimer.cs | using System;
using MonoTouch.UIKit;
using Toggl.Ross.Views;
namespace Toggl.Ross.Theme
{
public static partial class Style
{
public static class NavTimer
{
public static void DurationButton (UIButton v)
{
v.Font = UIFont.FromName ("HelveticaNeue-Thin", 32f);
v.LineBreakMode = UILineBreakMode.Clip;
v.SetTitleColor (Color.Black, UIControlState.Normal);
v.SetTitleColor (Color.Gray, UIControlState.Highlighted);
}
public static void StartButton (UIButton v)
{
v.Font = UIFont.FromName ("HelveticaNeue", 16f);
v.SetBackgroundImage (Image.CircleStart, UIControlState.Normal);
v.SetBackgroundImage (Image.CircleStartPressed, UIControlState.Highlighted);
v.SetTitleColor (Color.White, UIControlState.Normal);
v.SetTitleColor (Color.White, UIControlState.Highlighted);
v.SetTitle ("NavTimerStart".Tr (), UIControlState.Normal);
// TODO: Remove this scale workaround
v.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeScale (0.7f, 0.7f);
}
public static void StopButton (UIButton v)
{
v.Font = UIFont.FromName ("HelveticaNeue-Light", 16f);
v.SetBackgroundImage (Image.CircleStop, UIControlState.Normal);
v.SetBackgroundImage (Image.CircleStopPressed, UIControlState.Highlighted);
v.SetTitleColor (Color.Red, UIControlState.Normal);
v.SetTitleColor (Color.White, UIControlState.Highlighted);
v.SetTitle ("NavTimerStop".Tr (), UIControlState.Normal);
// TODO: Remove this scale workaround
v.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeScale (0.7f, 0.7f);
}
}
}
}
| using System;
using MonoTouch.UIKit;
using Toggl.Ross.Views;
namespace Toggl.Ross.Theme
{
public static partial class Style
{
public static class NavTimer
{
public static void DurationButton (UIButton v)
{
v.Font = UIFont.FromName ("HelveticaNeue-Thin", 32f);
v.LineBreakMode = UILineBreakMode.Clip;
v.SetTitleColor (UIColor.Black, UIControlState.Normal);
v.SetTitleColor (UIColor.Gray, UIControlState.Highlighted);
}
public static void StartButton (UIButton v)
{
v.Font = UIFont.FromName ("HelveticaNeue", 16f);
v.SetBackgroundImage (Image.CircleStart, UIControlState.Normal);
v.SetBackgroundImage (Image.CircleStartPressed, UIControlState.Highlighted);
v.SetTitleColor (Color.White, UIControlState.Normal);
v.SetTitleColor (Color.White, UIControlState.Highlighted);
v.SetTitle ("NavTimerStart".Tr (), UIControlState.Normal);
// TODO: Remove this scale workaround
v.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeScale (0.7f, 0.7f);
}
public static void StopButton (UIButton v)
{
v.Font = UIFont.FromName ("HelveticaNeue-Light", 16f);
v.SetBackgroundImage (Image.CircleStop, UIControlState.Normal);
v.SetBackgroundImage (Image.CircleStopPressed, UIControlState.Highlighted);
v.SetTitleColor (Color.Red, UIControlState.Normal);
v.SetTitleColor (Color.White, UIControlState.Highlighted);
v.SetTitle ("NavTimerStop".Tr (), UIControlState.Normal);
// TODO: Remove this scale workaround
v.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeScale (0.7f, 0.7f);
}
}
}
}
| bsd-3-clause | C# |
69234454ebdc3b5e505f746c6a5c312315006445 | Fix name | DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer | Client/Harmony/FlightDriver_ReturnToEditor.cs | Client/Harmony/FlightDriver_ReturnToEditor.cs | using Harmony;
using LunaClient.Events;
// ReSharper disable All
namespace LunaClient.Harmony
{
/// <summary>
/// This harmony patch is intended to trigger an event when returning to editor
/// </summary>
[HarmonyPatch(typeof(FlightDriver))]
[HarmonyPatch("ReturnToEditor")]
public class FlightDriver_ReturnToEditor
{
[HarmonyPrefix]
private static void PrefixReturnToEditor(EditorFacility facility)
{
RevertEvent.onReturnToEditor.Fire(facility);
}
}
}
| using Harmony;
using LunaClient.Events;
// ReSharper disable All
namespace LunaClient.Harmony
{
/// <summary>
/// This harmony patch is intended to trigger an event when returning to editor
/// </summary>
[HarmonyPatch(typeof(FlightDriver))]
[HarmonyPatch("ReturnToEditor")]
public class FlightDriver_ReturnToEditor
{
[HarmonyPrefix]
private static void PostfixReturnToEditor(EditorFacility facility)
{
RevertEvent.onReturnToEditor.Fire(facility);
}
}
}
| mit | C# |
5e3454e5c55add39fa31bb706471d86d46e364a7 | Update 0.11 beta | HoneyFox/KerbTown | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("KerbTown")]
[assembly: AssemblyDescription("Allows placing of static objects in the KSP game universe")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hubs' Electrical")]
[assembly: AssemblyProduct("KerbTown")]
[assembly: AssemblyCopyright("Copyright © Ryan Irecki 2013")]
[assembly: AssemblyTrademark("All trademarks are copyright to their respective owners.")]
[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("8c93fbed-be20-48c8-a7ab-a9e5ad1452c2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.11.*")]
[assembly: AssemblyFileVersion("0.11.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("KerbTown")]
[assembly: AssemblyDescription("Allows placing of static objects in the KSP game universe")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hubs' Electrical")]
[assembly: AssemblyProduct("KerbTown")]
[assembly: AssemblyCopyright("Copyright © Ryan Irecki 2013")]
[assembly: AssemblyTrademark("All trademarks are copyright to their respective owners.")]
[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("8c93fbed-be20-48c8-a7ab-a9e5ad1452c2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.06.*")]
[assembly: AssemblyFileVersion("0.06.0.0")]
| mit | C# |
2203882dca2efe3bea4cece3324f7e829fe7bc84 | Move assembly description to assembly title | protyposis/AudioAlign | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("AudioAlign Audio Synchronization and Analysis Library")]
[assembly: AssemblyCopyright("Copyright © 2010-2015 Mario Guggenberger")]
// 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("AudioAlign")]
[assembly: AssemblyDescription("AudioAlign Audio Synchronization and Analysis Library")]
[assembly: AssemblyCopyright("Copyright © 2010-2015 Mario Guggenberger")]
// 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
| agpl-3.0 | C# |
9d1e3287c26eb9503dddf7b518b40adaa2b5f183 | Fix copypasta mistake | Ernegien/ViridiX | ViridiX.Mason/Extensions/TcpClientExtensions.cs | ViridiX.Mason/Extensions/TcpClientExtensions.cs | using System;
using System.Net.Sockets;
using ViridiX.Mason.Utilities;
namespace ViridiX.Mason.Extensions
{
public static class TcpClientExtensions
{
/// <summary>
/// Temporarily extends the receive timeout value.
/// Wrap with a using statement to control scope automatically, or dispose manually.
/// </summary>
/// <param name="client">The TcpClient.</param>
/// <param name="extension">The number of milliseconds to extend the timeout for.</param>
/// <returns>An object that will restore the original timeout value once disposed.</returns>
public static IDisposable ExtendReceiveTimeout(this TcpClient client, int extension)
{
return new TemporaryPropertyAssignment<int>(client, nameof(client.ReceiveTimeout), client.ReceiveTimeout + extension);
}
/// <summary>
/// Temporarily extends the send timeout value.
/// Wrap with a using statement to control scope automatically, or dispose manually.
/// </summary>
/// <param name="client">The TcpClient.</param>
/// <param name="extension">The number of milliseconds to extend the timeout for.</param>
/// <returns>An object that will restore the original timeout value once disposed.</returns>
public static IDisposable ExtendSendTimeout(this TcpClient client, int extension)
{
return new TemporaryPropertyAssignment<int>(client, nameof(client.SendTimeout), client.SendTimeout + extension);
}
}
}
| using System;
using System.Net.Sockets;
using ViridiX.Mason.Utilities;
namespace ViridiX.Mason.Extensions
{
public static class TcpClientExtensions
{
/// <summary>
/// Temporarily extends the receive timeout value.
/// Wrap with a using statement to control scope automatically, or dispose manually.
/// </summary>
/// <param name="client">The TcpClient.</param>
/// <param name="extension">The number of milliseconds to extend the timeout for.</param>
/// <returns>An object that will restore the original timeout value once disposed.</returns>
public static IDisposable ExtendReceiveTimeout(this TcpClient client, int extension)
{
return new TemporaryPropertyAssignment<int>(client, nameof(client.ReceiveTimeout), client.ReceiveTimeout + extension);
}
/// <summary>
/// Temporarily extends the receive timeout value.
/// Wrap with a using statement to control scope automatically, or dispose manually.
/// </summary>
/// <param name="client">The TcpClient.</param>
/// <param name="extension">The number of milliseconds to extend the timeout for.</param>
/// <returns>An object that will restore the original timeout value once disposed.</returns>
public static IDisposable ExtendSendTimeout(this TcpClient client, int extension)
{
return new TemporaryPropertyAssignment<int>(client, nameof(client.SendTimeout), client.SendTimeout + extension);
}
}
}
| mit | C# |
06f1f255f769367b4ef0288ee927b8fcc4637a02 | Bump version to 0.9.10 | rpaquay/mtsuite | src/core-filesystem/VersionNumber.cs | src/core-filesystem/VersionNumber.cs | // Copyright 2015 Renaud Paquay All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace mtsuite.CoreFileSystem {
public static class VersionNumber {
public const string Product = "0.9.10";
public const string File = Product + ".0";
}
}
| // Copyright 2015 Renaud Paquay All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace mtsuite.CoreFileSystem {
public static class VersionNumber {
public const string Product = "0.9.9";
public const string File = Product + ".0";
}
}
| apache-2.0 | C# |
3d594b88b987c04e0e1650868e33b57619b5862d | use null conditional operator to retrieve length | OlegKleyman/Omego.Selenium | core/Omego.Selenium/Extensions/WebDriverExtensions.cs | core/Omego.Selenium/Extensions/WebDriverExtensions.cs | namespace Omego.Selenium.Extensions
{
using System;
using System.Diagnostics;
using System.Drawing.Imaging;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.Extensions;
public static class WebDriverExtensions
{
public static void SaveScreenshotAs(this IWebDriver driver, int timeLimit, ImageTarget target)
{
if (driver == null) throw new ArgumentNullException(nameof(driver));
var stopWatch = new Stopwatch();
stopWatch.Start();
Screenshot screenshot;
do
{
screenshot = driver.TakeScreenshot();
}
while (stopWatch.ElapsedMilliseconds < timeLimit && screenshot?.AsByteArray?.Length == 0);
stopWatch.Stop();
if (screenshot?.AsByteArray?.Length == 0)
{
throw new TimeoutException(
$"Unable to get screenshot after trying for {stopWatch.ElapsedMilliseconds}ms.");
}
}
}
}
| namespace Omego.Selenium.Extensions
{
using System;
using System.Diagnostics;
using System.Drawing.Imaging;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.Extensions;
public static class WebDriverExtensions
{
public static void SaveScreenshotAs(this IWebDriver driver, int timeLimit, ImageTarget target)
{
if (driver == null) throw new ArgumentNullException(nameof(driver));
var stopWatch = new Stopwatch();
stopWatch.Start();
Screenshot screenshot;
do
{
screenshot = driver.TakeScreenshot();
}
while (stopWatch.ElapsedMilliseconds < timeLimit && screenshot.AsByteArray.Length == 0);
stopWatch.Stop();
if (screenshot.AsByteArray.Length == 0)
{
throw new TimeoutException(
$"Unable to get screenshot after trying for {stopWatch.ElapsedMilliseconds}ms.");
}
}
}
}
| unlicense | C# |
52a135c3b1bb3497e3c99c144d37a5f47c3f5e3e | Load from embedded resources on GTK too. | jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,susloparovdenis/Avalonia,MrDaedra/Avalonia,akrisiun/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,tshcherban/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,punker76/Perspex,jazzay/Perspex,grokys/Perspex,SuperJMN/Avalonia,kekekeks/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,susloparovdenis/Avalonia,kekekeks/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,bbqchickenrobot/Perspex,grokys/Perspex,wieslawsoltes/Perspex,Perspex/Perspex,danwalmsley/Perspex,DavidKarlas/Perspex,susloparovdenis/Perspex,jkoritzinsky/Avalonia,OronDF343/Avalonia,wieslawsoltes/Perspex,MrDaedra/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,susloparovdenis/Perspex,OronDF343/Avalonia,Perspex/Perspex | src/Gtk/Perspex.Gtk/AssetLoader.cs | src/Gtk/Perspex.Gtk/AssetLoader.cs | // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using Perspex.Platform;
namespace Perspex.Gtk
{
/// <summary>
/// Loads assets compiled into the application binary.
/// </summary>
public class AssetLoader : IAssetLoader
{
/// <summary>
/// Opens the resource with the requested URI.
/// </summary>
/// <param name="uri">The URI.</param>
/// <returns>A stream containing the resource contents.</returns>
/// <exception cref="FileNotFoundException">
/// The resource was not found.
/// </exception>
public Stream Open(Uri uri)
{
var assembly = Assembly.GetEntryAssembly();
return assembly.GetManifestResourceStream(uri.ToString());
}
}
}
| // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using Perspex.Platform;
namespace Perspex.Gtk
{
/// <summary>
/// Loads assets compiled into the application binary.
/// </summary>
public class AssetLoader : IAssetLoader
{
/// <summary>
/// Opens the resource with the requested URI.
/// </summary>
/// <param name="uri">The URI.</param>
/// <returns>A stream containing the resource contents.</returns>
/// <exception cref="FileNotFoundException">
/// The resource was not found.
/// </exception>
public Stream Open(Uri uri)
{
var assembly = Assembly.GetEntryAssembly();
var resourceName = assembly.GetName().Name + ".g";
var manager = new ResourceManager(resourceName, assembly);
using (var resourceSet = manager.GetResourceSet(CultureInfo.CurrentCulture, true, true))
{
var stream = (Stream)resourceSet.GetObject(uri.ToString(), true);
if (stream == null)
{
throw new FileNotFoundException($"The requested asset could not be found: {uri}");
}
return stream;
}
}
}
}
| mit | C# |
69090c600f76f21e1596d5eeb6c9e6470749dc47 | Make AutoCompleteRequest.WordToComplete null safe | mispencer/OmniSharpServer,corngood/omnisharp-server,x335/omnisharp-server,OmniSharp/omnisharp-server,x335/omnisharp-server,syl20bnr/omnisharp-server,corngood/omnisharp-server,syl20bnr/omnisharp-server,svermeulen/omnisharp-server | OmniSharp/AutoComplete/AutoCompleteRequest.cs | OmniSharp/AutoComplete/AutoCompleteRequest.cs | using OmniSharp.Common;
namespace OmniSharp.AutoComplete
{
public class AutoCompleteRequest : Request
{
private string _wordToComplete;
public string WordToComplete {
get {
return _wordToComplete ?? "";
}
set {
_wordToComplete = value;
}
}
}
}
| using OmniSharp.Common;
namespace OmniSharp.AutoComplete
{
public class AutoCompleteRequest : Request
{
public string WordToComplete { get; set; }
}
}
| mit | C# |
dfb8f0848a02a940eafbc8fc81a03d5245757683 | Check disposed | FICTURE7/unicorn-net,FICTURE7/unicorn-net | src/Unicorn.Net/x86/x86Emulator.cs | src/Unicorn.Net/x86/x86Emulator.cs | namespace Unicorn.x86
{
/// <summary>
/// Represents an x86 architecture <see cref="Emulator"/>.
/// </summary>
public class x86Emulator : Emulator
{
/// <summary>
/// Initializes a new instance of the <see cref="x86Emulator"/> class with the specified
/// <see cref="x86Mode"/> to use.
/// </summary>
/// <param name="mode">Mode to use.</param>
public x86Emulator(x86Mode mode) : base(Bindings.Arch.x86, (Bindings.Mode)mode)
{
_registers = new x86Registers(this);
}
private readonly x86Registers _registers;
/// <summary>
/// Gets the <see cref="x86Registers"/> of the <see cref="x86Emulator"/> instance.
/// </summary>
public x86Registers Registers
{
get
{
CheckDisposed();
return _registers;
}
}
/// <summary>
/// Gets the <see cref="x86Mode"/> of the <see cref="x86Emulator"/>.
/// </summary>
public x86Mode Mode
{
get
{
CheckDisposed();
return (x86Mode)_mode;
}
}
}
}
| namespace Unicorn.x86
{
/// <summary>
/// Represents an x86 architecture <see cref="Emulator"/>.
/// </summary>
public class x86Emulator : Emulator
{
/// <summary>
/// Initializes a new instance of the <see cref="x86Emulator"/> class with the specified
/// <see cref="x86Mode"/> to use.
/// </summary>
/// <param name="mode">Mode to use.</param>
public x86Emulator(x86Mode mode) : base(Bindings.Arch.x86, (Bindings.Mode)mode)
{
_registers = new x86Registers(this);
}
private readonly x86Registers _registers;
/// <summary>
/// Gets the <see cref="x86Registers"/> of the <see cref="x86Emulator"/> instance.
/// </summary>
public x86Registers Registers
{
get
{
CheckDisposed();
return _registers;
}
}
/// <summary>
/// Gets the <see cref="x86Mode"/> of the <see cref="x86Emulator"/>.
/// </summary>
public x86Mode Mode => (x86Mode)_mode;
}
}
| mit | C# |
e23cbdb5377a16b6b33e8977c8b9b2adc1ee67c5 | Add test | sakapon/Samples-2017 | ProxySample/TransparentHttpConsole/Program.cs | ProxySample/TransparentHttpConsole/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace TransparentHttpConsole
{
class Program
{
static void Main(string[] args)
{
var zipCloud = HttpProxy.CreateProxy<IZipCloudService>();
Console.WriteLine(zipCloud.Get("6020881"));
var cgis = HttpProxy.CreateProxy<ICgisService>();
Console.WriteLine(cgis.Get("6048301"));
Console.WriteLine(cgis.Get("501", 1));
}
}
[BaseUri("http://zipcloud.ibsnet.co.jp/api/search")]
public interface IZipCloudService
{
string Get(string zipcode);
}
[BaseUri("http://zip.cgis.biz/xml/zip.php")]
public interface ICgisService
{
string Get(string zn);
string Get(string zn, int ver);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TransparentHttpConsole
{
class Program
{
static void Main(string[] args)
{
}
}
}
| mit | C# |
b536c54b91858a202cab6916731abf27cd344be2 | Stop button presses on strike | CaitSith2/ktanemod-twitchplays,ashbash1987/ktanemod-twitchplays | Assets/Scripts/ComponentSolvers/Modded/CryptographyComponentSolver.cs | Assets/Scripts/ComponentSolvers/Modded/CryptographyComponentSolver.cs | using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using UnityEngine;
public class CryptographyComponentSolver : ComponentSolver
{
public CryptographyComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller) :
base(bombCommander, bombComponent, ircConnection, canceller)
{
_buttons = (MonoBehaviour[])_keysField.GetValue(bombComponent.GetComponent(_componentType));
}
protected override IEnumerator RespondToCommandInternal(string inputCommand)
{
var BeforeStrikes = StrikeCount;
var split = inputCommand.Trim().ToLowerInvariant().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (split.Length < 2 || split[0] != "press")
yield break;
string keytext = _buttons.Aggregate(string.Empty, (current, button) => current + ((KMSelectable) button).GetComponentInChildren<TextMesh>().text.ToLowerInvariant());
foreach (var x in split.Skip(1))
{
foreach (var y in x)
if (!keytext.Contains(y))
yield break;
}
yield return "Cryptography Solve Attempt";
foreach (var x in split.Skip(1))
{
foreach (var y in x)
{
DoInteractionStart(_buttons[keytext.IndexOf(y)]);
yield return new WaitForSeconds(0.1f);
DoInteractionEnd(_buttons[keytext.IndexOf(y)]);
if (StrikeCount != BeforeStrikes)
yield break;
}
}
}
static CryptographyComponentSolver()
{
_componentType = ReflectionHelper.FindType("CryptMod");
_keysField = _componentType.GetField("Keys", BindingFlags.Public | BindingFlags.Instance);
}
private static Type _componentType = null;
private static FieldInfo _keysField = null;
private MonoBehaviour[] _buttons = null;
}
| using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using UnityEngine;
public class CryptographyComponentSolver : ComponentSolver
{
public CryptographyComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller) :
base(bombCommander, bombComponent, ircConnection, canceller)
{
_buttons = (MonoBehaviour[])_keysField.GetValue(bombComponent.GetComponent(_componentType));
}
protected override IEnumerator RespondToCommandInternal(string inputCommand)
{
var split = inputCommand.Trim().ToLowerInvariant().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (split.Length < 2 || split[0] != "press")
yield break;
string keytext = _buttons.Aggregate(string.Empty, (current, button) => current + ((KMSelectable) button).GetComponentInChildren<TextMesh>().text.ToLowerInvariant());
foreach (var x in split.Skip(1))
{
foreach (var y in x)
if (!keytext.Contains(y))
yield break;
}
yield return "Cryptography Solve Attempt";
foreach (var x in split.Skip(1))
{
foreach (var y in x)
{
DoInteractionStart(_buttons[keytext.IndexOf(y)]);
yield return new WaitForSeconds(0.1f);
DoInteractionEnd(_buttons[keytext.IndexOf(y)]);
}
}
}
static CryptographyComponentSolver()
{
_componentType = ReflectionHelper.FindType("CryptMod");
_keysField = _componentType.GetField("Keys", BindingFlags.Public | BindingFlags.Instance);
}
private static Type _componentType = null;
private static FieldInfo _keysField = null;
private MonoBehaviour[] _buttons = null;
}
| mit | C# |
ff14a0c80c8a0451e8769e45d9bd6cccf693dc1e | Add null check | yellowfeather/DbfReader | src/DbfDataReader/DbfValueMemo.cs | src/DbfDataReader/DbfValueMemo.cs | using System.IO;
namespace DbfDataReader
{
public class DbfValueMemo : DbfValueString
{
private readonly DbfMemo _memo;
public DbfValueMemo(int length, DbfMemo memo)
: base(length)
{
_memo = memo;
}
public override void Read(BinaryReader binaryReader)
{
if (Length == 4)
{
var startBlock = binaryReader.ReadUInt32();
Value = _memo.Get(startBlock);
}
else
{
var value = new string(binaryReader.ReadChars(Length));
if (string.IsNullOrWhiteSpace(value))
{
Value = string.Empty;
}
else
{
var startBlock = long.Parse(value);
Value = _memo?.Get(startBlock);
}
}
}
}
} | using System.IO;
namespace DbfDataReader
{
public class DbfValueMemo : DbfValueString
{
private readonly DbfMemo _memo;
public DbfValueMemo(int length, DbfMemo memo)
: base(length)
{
_memo = memo;
}
public override void Read(BinaryReader binaryReader)
{
if (Length == 4)
{
var startBlock = binaryReader.ReadUInt32();
Value = _memo.Get(startBlock);
}
else
{
var value = new string(binaryReader.ReadChars(Length));
if (string.IsNullOrWhiteSpace(value))
{
Value = string.Empty;
}
else
{
var startBlock = long.Parse(value);
Value = _memo.Get(startBlock);
}
}
}
}
} | mit | C# |
5bcccad3fc9c243e30c77d64795353ffcdca8273 | Solve build related issue | Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist | Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs | Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs | using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;
namespace Promact.Trappist.Core.Controllers
{
[Route("api")]
public class QuestionsController : Controller
{
private readonly IQuestionRepository _questionsRepository;
public QuestionsController(IQuestionRepository questionsRepository)
{
_questionsRepository = questionsRepository;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
/// <returns></returns>
[Route("single-multiple-question")]
[HttpPost]
public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion, singleMultipleAnswerQuestionOption);
return Ok();
}
}
}
| using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;
namespace Promact.Trappist.Core.Controllers
{
[Route("api")]
public class QuestionsController : Controller
{
private readonly IQuestionRepository _questionsRepository;
public QuestionsController(IQuestionRepository questionsRepository)
{
_questionsRepository = questionsRepository;
}
[Route("single-multiple-question")]
[HttpPost]
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion, singleMultipleAnswerQuestionOption);
return Ok();
}
}
}
| mit | C# |
01f9292750e75aa2f27bfab689c447c4f7b4907c | test fix | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/test/src/CSharp/Daemon/Stages/Burst/BurstStageTest.cs | resharper/resharper-unity/test/src/CSharp/Daemon/Stages/Burst/BurstStageTest.cs | using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.BurstCodeAnalysis.Highlightings;
using JetBrains.ReSharper.Psi;
using NUnit.Framework;
namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Daemon.Stages.Burst
{
[TestUnity]
public class BurstStageTest : UnityGlobalHighlightingsStageTestBase
{
protected override string RelativeTestDataRoot => @"CSharp\Daemon\Stages\BurstCodeAnalysis\";
[Test] public void SmartMarkingTests() { DoNamedTest(); }
[Test] public void PrimitivesTests() { DoNamedTest(); }
[Test] public void ReferenceExpressionTests() { DoNamedTest(); }
[Test] public void MethodInvocationTests() { DoNamedTest(); }
[Test] public void FunctionParametersReturnTests() { DoNamedTest(); }
[Ignore("Try/finally, using and foreach are allowed fom burst 1.4")][Test] public void ExceptionsTests() { DoNamedTest(); }
[Test] public void EqualsTests() { DoNamedTest(); }
[Test] public void DirectivesTests() { DoNamedTest(); }
[Test] public void BurstDiscardTests() { DoNamedTest(); }
[Test] public void DebugStringTests() { DoNamedTest(); }
[Test] public void TypeofTests() { DoNamedTest(); }
[Test] public void SharedStaticCreateTests() { DoNamedTest(); }
[Test] public void NullableTests() { DoNamedTest(); }
[Test] public void ConditionalAttributesTests() { DoNamedTest(); }
[Test] public void CommentRootsTests() { DoNamedTest(); }
[Test] public void BugRider53010() { DoNamedTest(); }
protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile file, IContextBoundSettingsStore settingsStore)
{
return highlighting is IBurstHighlighting;
}
}
} | using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.BurstCodeAnalysis.Highlightings;
using JetBrains.ReSharper.Psi;
using NUnit.Framework;
namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Daemon.Stages.Burst
{
[TestUnity]
public class BurstStageTest : UnityGlobalHighlightingsStageTestBase
{
protected override string RelativeTestDataRoot => @"CSharp\Daemon\Stages\BurstCodeAnalysis\";
[Test] public void SmartMarkingTests() { DoNamedTest(); }
[Test] public void PrimitivesTests() { DoNamedTest(); }
[Test] public void ReferenceExpressionTests() { DoNamedTest(); }
[Test] public void MethodInvocationTests() { DoNamedTest(); }
[Test] public void FunctionParametersReturnTests() { DoNamedTest(); }
[Test] public void ExceptionsTests() { DoNamedTest(); }
[Test] public void EqualsTests() { DoNamedTest(); }
[Test] public void DirectivesTests() { DoNamedTest(); }
[Test] public void BurstDiscardTests() { DoNamedTest(); }
[Test] public void DebugStringTests() { DoNamedTest(); }
[Test] public void TypeofTests() { DoNamedTest(); }
[Test] public void SharedStaticCreateTests() { DoNamedTest(); }
[Test] public void NullableTests() { DoNamedTest(); }
[Test] public void ConditionalAttributesTests() { DoNamedTest(); }
[Test] public void CommentRootsTests() { DoNamedTest(); }
[Test] public void BugRider53010() { DoNamedTest(); }
protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile file, IContextBoundSettingsStore settingsStore)
{
return highlighting is IBurstHighlighting;
}
}
} | apache-2.0 | C# |
eb1288f79724019c631b3d8911b161f1195d2bbe | Implement AppHarborClient#GetUser | appharbor/appharbor-cli | src/AppHarbor/AppHarborClient.cs | src/AppHarbor/AppHarborClient.cs | using System;
using AppHarbor.Model;
namespace AppHarbor
{
public class AppHarborClient : IAppHarborClient
{
private readonly AuthInfo _authInfo;
public AppHarborClient(string AccessToken)
{
_authInfo = new AuthInfo { AccessToken = AccessToken };
}
public CreateResult<string> CreateApplication(string name, string regionIdentifier = null)
{
var appHarborApi = GetAppHarborApi();
return appHarborApi.CreateApplication(name, regionIdentifier);
}
private AppHarborApi GetAppHarborApi()
{
try
{
return new AppHarborApi(_authInfo);
}
catch (ArgumentNullException)
{
throw new CommandException("You're not logged in. Log in with \"appharbor login\"");
}
}
public User GetUser()
{
var appHarborApi = GetAppHarborApi();
return appHarborApi.GetUser();
}
}
}
| using System;
using AppHarbor.Model;
namespace AppHarbor
{
public class AppHarborClient : IAppHarborClient
{
private readonly AuthInfo _authInfo;
public AppHarborClient(string AccessToken)
{
_authInfo = new AuthInfo { AccessToken = AccessToken };
}
public CreateResult<string> CreateApplication(string name, string regionIdentifier = null)
{
var appHarborApi = GetAppHarborApi();
return appHarborApi.CreateApplication(name, regionIdentifier);
}
private AppHarborApi GetAppHarborApi()
{
try
{
return new AppHarborApi(_authInfo);
}
catch (ArgumentNullException)
{
throw new CommandException("You're not logged in. Log in with \"appharbor login\"");
}
}
public User GetUser()
{
throw new NotImplementedException();
}
}
}
| mit | C# |
b2cd9835c157faa07c21ae116caf72168f573003 | Make sure that the ViewResultFoundStatusMessage implements correct interface | peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype | src/Glimpse.Agent.Web/Providers/Mvc/Messages/ViewResultFoundStatusMessage.cs | src/Glimpse.Agent.Web/Providers/Mvc/Messages/ViewResultFoundStatusMessage.cs | using System.Collections.Generic;
namespace Glimpse.Agent.AspNet.Mvc.Messages
{
public class ViewResultFoundStatusMessage : IActionViewMessage
{
public string ActionId { get; set; }
public string ActionName { get; set; }
public string ControllerName { get; set; }
public string ViewName { get; set; }
public bool DidFind { get; set; }
public IEnumerable<string> SearchedLocations { get; set; }
public ViewResult ViewData { get; set; }
}
} | using System.Collections.Generic;
namespace Glimpse.Agent.AspNet.Mvc.Messages
{
public class ViewResultFoundStatusMessage
{
public string ActionId { get; set; }
public string ActionName { get; set; }
public string ControllerName { get; set; }
public string ViewName { get; set; }
public bool DidFind { get; set; }
public IEnumerable<string> SearchedLocations { get; set; }
public ViewResult ViewData { get; set; }
}
} | mit | C# |
22d73c508ce64bb8353d21b70ca9ef5360007a85 | Add --map command to launcher to help with debugging | feliwir/openSage,feliwir/openSage | src/OpenSage.Launcher/Program.cs | src/OpenSage.Launcher/Program.cs | using System.CommandLine;
using System.Linq;
using OpenSage.Data;
using OpenSage.Mods.BuiltIn;
using OpenSage.Network;
namespace OpenSage.Launcher
{
public static class Program
{
public static void Main(string[] args)
{
var noShellMap = false;
var definition = GameDefinition.FromGame(SageGame.CncGenerals);
string mapName = null;
ArgumentSyntax.Parse(args, syntax =>
{
syntax.DefineOption("noshellmap", ref noShellMap, false, "Disables loading the shell map, speeding up startup time.");
string gameName = null;
var availableGames = string.Join(", ", GameDefinition.All.Select(def => def.Game.ToString()));
syntax.DefineOption("game", ref gameName, false, $"Chooses which game to start. Valid options: {availableGames}");
// If a game has been specified, make sure it's valid.
if (gameName != null && !GameDefinition.TryGetByName(gameName, out definition))
{
syntax.ReportError($"Unknown game: {gameName}");
}
syntax.DefineOption("map", ref mapName, false,
"Immediately starts a new skirmish with default settings in the specified map. The map file must be specified with the full path.");
});
Platform.CurrentPlatform = new Sdl2Platform();
Platform.CurrentPlatform.Start();
// TODO: Support other locators.
var locator = new RegistryInstallationLocator();
var game = GameFactory.CreateGame(
definition,
locator,
// TODO: Read game version from assembly metadata or .git folder
// TODO: Set window icon.
() => Platform.CurrentPlatform.CreateWindow("OpenSAGE (master)", 100, 100, 1024, 768));
game.Configuration.LoadShellMap = !noShellMap;
if (mapName == null)
{
game.ShowMainMenu();
}
else
{
game.StartGame(mapName, new EchoConnection(), new[] {"America", "GLA"}, 0);
}
while (game.IsRunning)
{
game.Tick();
}
Platform.CurrentPlatform.Stop();
}
}
}
| using OpenSage.Data;
using OpenSage.Mods.BuiltIn;
using System.CommandLine;
using System.Linq;
namespace OpenSage.Launcher
{
public static class Program
{
public static void Main(string[] args)
{
var noShellMap = false;
var definition = GameDefinition.FromGame(SageGame.CncGenerals);
ArgumentSyntax.Parse(args, syntax =>
{
syntax.DefineOption("noshellmap", ref noShellMap, false, "Disables loading the shell map, speeding up startup time.");
string gameName = null;
var availableGames = string.Join(", ", GameDefinition.All.Select(def => def.Game.ToString()));
syntax.DefineOption("game", ref gameName, false, $"Chooses which game to start. Valid options: {availableGames}");
// If a game has been specified, make sure it's valid.
if (gameName != null && !GameDefinition.TryGetByName(gameName, out definition))
{
syntax.ReportError($"Unknown game: {gameName}");
}
});
Platform.CurrentPlatform = new Sdl2Platform();
Platform.CurrentPlatform.Start();
// TODO: Support other locators.
var locator = new RegistryInstallationLocator();
var game = GameFactory.CreateGame(
definition,
locator,
// TODO: Read game version from assembly metadata or .git folder
// TODO: Set window icon.
() => Platform.CurrentPlatform.CreateWindow("OpenSAGE (master)", 100, 100, 1024, 768));
game.Configuration.LoadShellMap = !noShellMap;
game.ShowMainMenu();
while (game.IsRunning)
{
game.Tick();
}
Platform.CurrentPlatform.Stop();
}
}
}
| mit | C# |
6c56df8e13b9ff4555106b463b021e4ae7be5951 | add more info there | tugberkugurlu/BonVoyage,tugberkugurlu/BonVoyage | src/BonVoyage/BonVoyageContext.cs | src/BonVoyage/BonVoyageContext.cs | using BonVoyage.Infrastructure;
using System;
using System.Net.Http;
namespace BonVoyage
{
public class BonVoyageContext : IDisposable
{
private readonly HttpMessageHandler _handler;
public BonVoyageContext() : this(CreateHandler())
{
}
public BonVoyageContext(HttpMessageHandler handler)
{
_handler = handler ?? throw new ArgumentNullException(nameof(handler));
}
public FoursquareContext CreateFoursquareContext(string accessToken)
{
if (accessToken == null)
{
throw new ArgumentNullException(nameof(accessToken));
}
return new FoursquareContext(_handler, accessToken);
}
public void Dispose()
{
_handler?.Dispose();
}
/// <remarks>
/// <seealso href="https://developer.foursquare.com/overview/versioning" /> for versioning.
/// </remarks>>
private static HttpMessageHandler CreateHandler()
{
return HttpClientFactory.CreatePipeline(new HttpClientHandler(), new DelegatingHandler[]
{
new OAuthTokenSwitchHandler(),
new QueryAppenderHandler("v", "20151111")
});
}
}
}
| using BonVoyage.Infrastructure;
using System;
using System.Net.Http;
namespace BonVoyage
{
public class BonVoyageContext : IDisposable
{
private readonly HttpMessageHandler _handler;
public BonVoyageContext() : this(CreateHandler())
{
}
public BonVoyageContext(HttpMessageHandler handler)
{
_handler = handler ?? throw new ArgumentNullException(nameof(handler));
}
public FoursquareContext CreateFoursquareContext(string accessToken)
{
if (accessToken == null)
{
throw new ArgumentNullException(nameof(accessToken));
}
return new FoursquareContext(_handler, accessToken);
}
public void Dispose()
{
_handler?.Dispose();
}
private static HttpMessageHandler CreateHandler()
{
return HttpClientFactory.CreatePipeline(new HttpClientHandler(), new DelegatingHandler[]
{
new OAuthTokenSwitchHandler(),
new QueryAppenderHandler("v", "20151111")
});
}
}
}
| mit | C# |
c1a4486cd0bd33b381c1435d1782daf015d0640f | Update UriExtensions.cs | IAmAnubhavSaini/RedditSharp,nyanpasudo/RedditSharp,pimanac/RedditSharp,RobThree/RedditSharp,SirCmpwn/RedditSharp,tomnolan95/RedditSharp,Jinivus/RedditSharp,CrustyJew/RedditSharp,justcool393/RedditSharp-1,ekaralar/RedditSharpWindowsStore,chuggafan/RedditSharp-1,epvanhouten/RedditSharp,angelotodaro/RedditSharp,theonlylawislove/RedditSharp | RedditSharp/UriExtensions.cs | RedditSharp/UriExtensions.cs | using System;
using System.Web;
namespace RedditSharp
{
public static class UriExtensions
{
/// <summary>
/// Adds the specified parameter to the Query String.
/// </summary>
/// <param name="url"></param>
/// <param name="paramName">Name of the parameter to add.</param>
/// <param name="paramValue">Value for the parameter to add.</param>
/// <returns>Url with added parameter.</returns>
public static Uri AddParameter(this Uri url, string paramName, object paramValue)
{
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query[paramName] = paramValue.ToString();
uriBuilder.Query = query.ToString();
return new Uri(uriBuilder.ToString());
}
}
}
| using System;
using System.Web;
namespace RedditSharp
{
public static class UriExtensions
{
/// <summary>
/// Adds the specified parameter to the Query String.
/// </summary>
/// <param name="url"></param>
/// <param name="paramName">Name of the parameter to add.</param>
/// <param name="paramValue">Value for the parameter to add.</param>
/// <returns>Url with added parameter.</returns>
public static Uri AddParameter(this Uri url, string paramName, object paramValue)
{
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query[paramName] = paramValue.ToString();
uriBuilder.Query = query.ToString();
return new Uri(uriBuilder.ToString());
}
}
}
| mit | C# |
cf954766b6cadec65cdcfc42211dfa58129430d2 | Remove sticky note 'Patron's Trophy' | croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/website-application | source/CroquetAustralia.Website/Layouts/Shared/Sidebar.cshtml | source/CroquetAustralia.Website/Layouts/Shared/Sidebar.cshtml | <div class="sticky-notes">
<div class="sticky-note">
<i class="pin"></i>
<div class="content green">
<h1>
Recent Updates
</h1>
<ul>
<li>Link to Association Croquet World Rankings added to <a href="/disciplines/association-croquet/resources">resources</a>.</li>
<li>Link to Golf Croquet World Rankings added to <a href="/disciplines/golf-croquet/resources">resources</a>.</li>
</ul>
</div>
</div>
</div>
| <div class="sticky-notes">
<div class="sticky-note">
<i class="pin"></i>
<div class="content yellow">
<h1>
Patron's Trophy
</h1>
<p>
Entries for Parton's Trophy close Thursday, 2nd June 2016. <a href="/tournaments">Learn more</a> or <a href="/tournaments/2016/ac/patrons-trophy">enter now!</a>
</p>
</div>
</div>
<div class="sticky-note">
<i class="pin"></i>
<div class="content green">
<h1>
Recent Updates
</h1>
<ul>
<li>Link to Association Croquet World Rankings added to <a href="/disciplines/association-croquet/resources">resources</a>.</li>
<li>Link to Golf Croquet World Rankings added to <a href="/disciplines/golf-croquet/resources">resources</a>.</li>
</ul>
</div>
</div>
</div>
| mit | C# |
4cbd0935c8cdcaba9d534395d1346a8e82a42cd9 | Build the builder in order to create the receiver | RockFramework/RockLib.Configuration | RockLib.Configuration.MessagingProvider/RockLibMessagingProviderExtensions.cs | RockLib.Configuration.MessagingProvider/RockLibMessagingProviderExtensions.cs | using Microsoft.Extensions.Configuration;
using RockLib.Messaging;
namespace RockLib.Configuration.MessagingProvider
{
public static class RockLibMessagingProviderExtensions
{
public static IConfigurationBuilder AddRockLibMessagingProvider(this IConfigurationBuilder builder, string scenarioName) =>
builder.AddRockLibMessagingProvider(builder.Build().GetSection("RockLib.Messaging").CreateReceiver(scenarioName));
public static IConfigurationBuilder AddRockLibMessagingProvider(this IConfigurationBuilder builder, IReceiver receiver) =>
builder.Add(new MessagingConfigurationSource(receiver));
}
}
| using Microsoft.Extensions.Configuration;
using RockLib.Messaging;
namespace RockLib.Configuration.MessagingProvider
{
public static class RockLibMessagingProviderExtensions
{
public static IConfigurationBuilder AddRockLibMessagingProvider(this IConfigurationBuilder builder, string scenarioName) =>
builder.AddRockLibMessagingProvider(MessagingScenarioFactory.CreateReceiver(scenarioName));
public static IConfigurationBuilder AddRockLibMessagingProvider(this IConfigurationBuilder builder, IReceiver receiver) =>
builder.Add(new MessagingConfigurationSource(receiver));
}
}
| mit | C# |
079e8a44ed3fc2a1f3691e12c9ed4acfa805eafe | Adjust font size of data list page | erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner | Zk/Views/Crop/Index.cshtml | Zk/Views/Crop/Index.cshtml | @model IEnumerable<Zk.Models.Crop>
@{
ViewBag.Title = "Gewassen";
}
<h2>Dit zijn de gewassen in de database:</h2>
<table style="font-size: 12px;">
<tr>
<th>Id</th><th>Naam</th><th>Ras</th><th>Categorie</th><th>Opp. per 1</th>
<th>Opp. per zak</th><th>Prijs per zakje</th><th>Zaaimaanden</th><th>Oogstmaanden</th>
</tr>
<tbody>
@foreach (var crop in Model) {
<tr>
<td>@crop.Id</td><td>@crop.Name</td><td>@crop.Race</td><td>@crop.Category</td><td>@crop.AreaPerCrop</td>
<td>@crop.AreaPerBag</td><td>@crop.PricePerBag</td>
<td>@crop.SowingMonths</td><td>@crop.HarvestingMonths</td>
</tr>
}
</tbody>
</table>
@Html.ActionLink("Terug naar thuis", "Index", "Home", null, null) | @model IEnumerable<Zk.Models.Crop>
@{
ViewBag.Title = "Gewassen";
}
<h2>Dit zijn de gewassen in de database:</h2>
<table class="table table-striped">
<tr>
<th>Id</th><th>Naam</th><th>Ras</th><th>Categorie</th><th>Opp. per 1</th>
<th>Opp. per zak</th><th>Prijs per zakje</th><th>Zaaimaanden</th><th>Oogstmaanden</th>
</tr>
<tbody>
@foreach (var crop in Model) {
<tr>
<td>@crop.Id</td><td>@crop.Name</td><td>@crop.Race</td><td>@crop.Category</td><td>@crop.AreaPerCrop</td>
<td>@crop.AreaPerBag</td><td>@crop.PricePerBag</td>
<td>@crop.SowingMonths</td><td>@crop.HarvestingMonths</td>
</tr>
}
</tbody>
</table>
<a href="/Home/Index">Terug naar thuis.</a> | mit | C# |
53ebd93048457bead0b9cbddc6dd3030fe81ce4f | Test Update | ramyothman/DotNetAnalyticsAPI | SimpleAnalytics/AnalyticsTest/Default.aspx.cs | SimpleAnalytics/AnalyticsTest/Default.aspx.cs | using Google.Apis.Auth.OAuth2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AnalyticsTest
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Analytics.AnalyticsManager manager = new Analytics.AnalyticsManager(Server.MapPath("~/bin/privatekey.p12"), "600980447623-ide8u9tp3ud9ven0v640r64hqn0cb7pr@developer.gserviceaccount.com");
//that's the number after the p in google analytics url
//ps. you need to give your email account taken from the service access from the web control panel in google analytics
manager.LoadAnalyticsProfiles();
//Place Profile Web ID
manager.SetDefaultAnalyticProfile("80425770");
List<Analytics.Data.DataItem> metrics = new List<Analytics.Data.DataItem>();
metrics.Add(Analytics.Data.Session.Metrics.visits);
metrics.Add(Analytics.Data.Session.Metrics.timeOnSite);
metrics.Add(Analytics.Data.Adsense.Metrics.adsenseRevenue);
List<Analytics.Data.DataItem> dimensions = new List<Analytics.Data.DataItem>();
dimensions.Add(Analytics.Data.GeoNetwork.Dimensions.country);
List<Analytics.Data.DataItem> filters = new List<Analytics.Data.DataItem>();
Analytics.Data.DataItem country = new Analytics.Data.DataItem(Analytics.Data.GeoNetwork.Dimensions.country.Name);
country.Equals("Saudi Arabia");
filters.Add(country);
System.Data.DataTable table = manager.GetGaDataTable(DateTime.Today.AddDays(-3), DateTime.Today, metrics, dimensions, filters, metrics, true);
GridViewControl.DataSource = table;
GridViewControl.DataBind();
}
}
} | using Google.Apis.Auth.OAuth2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AnalyticsTest
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Analytics.AnalyticsManager manager = new Analytics.AnalyticsManager(Server.MapPath("~/bin/privatekey.p12"), "600980447623-ide8u9tp3ud9ven0v640r64hqn0cb7pr@developer.gserviceaccount.com");
//that's the number after the p in google analytics url
//ps. you need to give your email account taken from the service access from the web control panel in google analytics
manager.LoadAnalyticsProfiles();
manager.SetDefaultAnalyticProfile("80425770");
List<Analytics.Data.DataItem> metrics = new List<Analytics.Data.DataItem>();
metrics.Add(Analytics.Data.Session.Metrics.visits);
metrics.Add(Analytics.Data.Session.Metrics.timeOnSite);
metrics.Add(Analytics.Data.Adsense.Metrics.adsenseRevenue);
List<Analytics.Data.DataItem> dimensions = new List<Analytics.Data.DataItem>();
dimensions.Add(Analytics.Data.GeoNetwork.Dimensions.country);
List<Analytics.Data.DataItem> filters = new List<Analytics.Data.DataItem>();
Analytics.Data.DataItem country = new Analytics.Data.DataItem(Analytics.Data.GeoNetwork.Dimensions.country.Name);
country.Equals("Saudi Arabia");
filters.Add(country);
System.Data.DataTable table = manager.GetGaDataTable(DateTime.Today.AddDays(-3), DateTime.Today, metrics, dimensions, filters, metrics, true);
GridViewControl.DataSource = table;
GridViewControl.DataBind();
}
}
} | mit | C# |
5209e24a933d8963fe2b58c9275b14da46f667dc | Make IVostokHostingEnvironment props readonly | vostok/core | Vostok.Hosting.Core/IVostokHostingEnvironment.cs | Vostok.Hosting.Core/IVostokHostingEnvironment.cs | using System.Threading;
using Microsoft.Extensions.Configuration;
using Vostok.Airlock;
using Vostok.Logging;
using Vostok.Metrics;
namespace Vostok.Hosting
{
public interface IVostokHostingEnvironment
{
string Project { get; }
string Environment { get; }
string Service { get; }
IConfiguration Configuration { get; }
IAirlockClient AirlockClient { get; }
IMetricScope MetricScope { get; }
ILog HostLog { get; }
CancellationToken ShutdownCancellationToken { get; }
void RequestShutdown();
}
} | using System.Threading;
using Microsoft.Extensions.Configuration;
using Vostok.Airlock;
using Vostok.Logging;
using Vostok.Metrics;
namespace Vostok.Hosting
{
public interface IVostokHostingEnvironment
{
string Project { get; set; }
string Environment { get; set; }
string Service { get; set; }
IAirlockClient AirlockClient { get; set; }
IMetricScope MetricScope { get; set; }
ILog HostLog { get; set; }
CancellationToken ShutdownCancellationToken { get; }
IConfiguration Configuration { get; set; }
void RequestShutdown();
}
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.