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 |
---|---|---|---|---|---|---|---|---|
ff52a5ddc6bc5cbb4d5dfdf52fed460b6e660826 | Add callbacks for join/leave events to notify other room occupants | smoogipooo/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu | osu.Game/Online/RealtimeMultiplayer/ISpectatorClient.cs | osu.Game/Online/RealtimeMultiplayer/ISpectatorClient.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining a spectator client instance.
/// </summary>
public interface IMultiplayerClient
{
/// <summary>
/// Signals that the room has changed state.
/// </summary>
/// <param name="state">The state of the room.</param>
Task RoomStateChanged(MultiplayerRoomState state);
/// <summary>
/// Signals that a user has joined the room.
/// </summary>
/// <param name="user">The user.</param>
Task UserJoined(MultiplayerRoomUser user);
/// <summary>
/// Signals that a user has left the room.
/// </summary>
/// <param name="user">The user.</param>
Task UserLeft(MultiplayerRoomUser user);
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining a spectator client instance.
/// </summary>
public interface IMultiplayerClient
{
/// <summary>
/// Signals that the room has changed state.
/// </summary>
/// <param name="state">The state of the room.</param>
Task RoomStateChanged(MultiplayerRoomState state);
}
}
| mit | C# |
5e5901ef0f64f20b58a3fd935e39546dc3eb1794 | revert last few | collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists | api/FilterLists.Api/Startup.cs | api/FilterLists.Api/Startup.cs | using FilterLists.Api.DependencyInjection.Extensions;
using FilterLists.Data.DependencyInjection.Extensions;
using FilterLists.Services.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FilterLists.Api
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.RegisterFilterListsRepositories(Configuration);
services.RegisterFilterListsServices();
services.RegisterFilterListsApi();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
}
} | using FilterLists.Api.DependencyInjection.Extensions;
using FilterLists.Data.DependencyInjection.Extensions;
using FilterLists.Services.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FilterLists.Api
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.RegisterFilterListsRepositories(Configuration);
services.RegisterFilterListsServices();
services.RegisterFilterListsApi();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
}
}
} | mit | C# |
0dc257d1d72852d0d83f1fa0bc795c6ad60ae7b9 | Change raw file request rewriter to use AppRelativeCurrentExecutionFilePath instead of PathInfo to determine the file path. When not running in IIS PathInfo seems to be empty at the point when the rewriter is called. | damiensawyer/cassette,andrewdavey/cassette,BluewireTechnologies/cassette,honestegg/cassette,andrewdavey/cassette,BluewireTechnologies/cassette,andrewdavey/cassette,honestegg/cassette,honestegg/cassette,damiensawyer/cassette,damiensawyer/cassette | src/Cassette.Aspnet/RawFileRequestRewriter.cs | src/Cassette.Aspnet/RawFileRequestRewriter.cs | using System;
using System.Text.RegularExpressions;
using System.Web;
namespace Cassette.Aspnet
{
public class RawFileRequestRewriter
{
readonly HttpContextBase context;
readonly IFileAccessAuthorization fileAccessAuthorization;
readonly HttpRequestBase request;
public RawFileRequestRewriter(HttpContextBase context, IFileAccessAuthorization fileAccessAuthorization)
{
this.context = context;
this.fileAccessAuthorization = fileAccessAuthorization;
request = context.Request;
}
public void Rewrite()
{
if (!IsCassetteRequest()) return;
string path;
if (!TryGetFilePath(out path)) return;
EnsureFileCanBeAccessed(path);
SetFarFutureExpiresHeader();
context.RewritePath(path);
}
bool IsCassetteRequest()
{
return request.AppRelativeCurrentExecutionFilePath.StartsWith("~/cassette.axd/file", StringComparison.OrdinalIgnoreCase);
}
bool TryGetFilePath(out string path)
{
var match = Regex.Match(request.AppRelativeCurrentExecutionFilePath, "/file/[^/]+/(.*)", RegexOptions.IgnoreCase);
if (match.Success)
{
path = "~/" + match.Groups[1].Value;
return true;
}
path = null;
return false;
}
void EnsureFileCanBeAccessed(string path)
{
if (!fileAccessAuthorization.CanAccess(path))
{
throw new HttpException(404, "File not found");
}
}
void SetFarFutureExpiresHeader()
{
context.Response.Cache.SetExpires(DateTime.UtcNow.AddYears(1));
}
}
} | using System;
using System.Text.RegularExpressions;
using System.Web;
namespace Cassette.Aspnet
{
public class RawFileRequestRewriter
{
readonly HttpContextBase context;
readonly IFileAccessAuthorization fileAccessAuthorization;
readonly HttpRequestBase request;
public RawFileRequestRewriter(HttpContextBase context, IFileAccessAuthorization fileAccessAuthorization)
{
this.context = context;
this.fileAccessAuthorization = fileAccessAuthorization;
request = context.Request;
}
public void Rewrite()
{
if (!IsCassetteRequest()) return;
string path;
if (!TryGetFilePath(out path)) return;
EnsureFileCanBeAccessed(path);
SetFarFutureExpiresHeader();
context.RewritePath(path);
}
bool IsCassetteRequest()
{
return request.AppRelativeCurrentExecutionFilePath == "~/cassette.axd";
}
bool TryGetFilePath(out string path)
{
var match = Regex.Match(request.PathInfo, "/file/[^/]+/(.*)", RegexOptions.IgnoreCase);
if (match.Success)
{
path = "~/" + match.Groups[1].Value;
return true;
}
path = null;
return false;
}
void EnsureFileCanBeAccessed(string path)
{
if (!fileAccessAuthorization.CanAccess(path))
{
throw new HttpException(404, "File not found");
}
}
void SetFarFutureExpiresHeader()
{
context.Response.Cache.SetExpires(DateTime.UtcNow.AddYears(1));
}
}
} | mit | C# |
93bb3a5f4221a9a9505ffffc79821ad375a14e0a | fix configuration ctor change | Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen | Dashen.Tests/DashenConfigurationTests.cs | Dashen.Tests/DashenConfigurationTests.cs | using System.IO;
using System.Linq;
using System.Text;
using Dashen.Endpoints.Static;
using Dashen.Endpoints.Static.ContentProviders;
using Dashen.Infrastructure;
using Dashen.Initialisation;
using Shouldly;
using Xunit;
namespace Dashen.Tests
{
public class DashenConfigurationTests
{
[Fact]
public void EnableConsoleLog_adds_a_logger_to_the_handlers_if_one_is_not_present()
{
var config = new DashenConfiguration();
config.EnableConsoleLog();
config.MessageHandlers.Single().ShouldBeOfType<ConsoleLoggingHandler>();
}
[Fact]
public void EnableConsoleLog_doesnt_add_a_logger_if_handlers_contains_a_console_logger_already()
{
var config = new DashenConfiguration();
config.MessageHandlers.Add(new ConsoleLoggingHandler());
config.EnableConsoleLog();
config.MessageHandlers.Count.ShouldBe(1);
config.MessageHandlers.Single().ShouldBeOfType<ConsoleLoggingHandler>();
}
[Fact]
public void DisableConsoleLog_removes_the_logger_if_it_exists()
{
var config = new DashenConfiguration();
config.MessageHandlers.Add(new ConsoleLoggingHandler());
config.DisableConsoleLog();
config.MessageHandlers.ShouldBeEmpty();
}
[Fact]
public void DisableConsoleLog_does_nothing_if_there_is_no_logger_already()
{
var config = new DashenConfiguration();
config.DisableConsoleLog();
config.MessageHandlers.ShouldBeEmpty();
}
[Fact]
public void AddResource_allows_the_content_stream_to_be_shut()
{
var config = new DashenConfiguration();
using (var ms = new MemoryStream())
using( var writer = new StreamWriter(ms))
{
writer.Write("Test value");
writer.Flush();
ms.Position = 0;
config.AddResource("test", ms, "text/plain");
}
var adhoc = new AdhocContentProvider();
var init = new StaticContentInitialisation(config, new ReplacementSource(), adhoc);
init.ApplyTo(null);
using (var reader = new StreamReader(adhoc.GetContent("test").Stream))
{
reader.ReadToEnd().ShouldBe("Test value");
}
}
}
}
| using System.IO;
using System.Linq;
using System.Text;
using Dashen.Endpoints.Static;
using Dashen.Endpoints.Static.ContentProviders;
using Dashen.Infrastructure;
using Dashen.Initialisation;
using Shouldly;
using Xunit;
namespace Dashen.Tests
{
public class DashenConfigurationTests
{
[Fact]
public void EnableConsoleLog_adds_a_logger_to_the_handlers_if_one_is_not_present()
{
var config = new DashenConfiguration();
config.EnableConsoleLog();
config.MessageHandlers.Single().ShouldBeOfType<ConsoleLoggingHandler>();
}
[Fact]
public void EnableConsoleLog_doesnt_add_a_logger_if_handlers_contains_a_console_logger_already()
{
var config = new DashenConfiguration();
config.MessageHandlers.Add(new ConsoleLoggingHandler());
config.EnableConsoleLog();
config.MessageHandlers.Count.ShouldBe(1);
config.MessageHandlers.Single().ShouldBeOfType<ConsoleLoggingHandler>();
}
[Fact]
public void DisableConsoleLog_removes_the_logger_if_it_exists()
{
var config = new DashenConfiguration();
config.MessageHandlers.Add(new ConsoleLoggingHandler());
config.DisableConsoleLog();
config.MessageHandlers.ShouldBeEmpty();
}
[Fact]
public void DisableConsoleLog_does_nothing_if_there_is_no_logger_already()
{
var config = new DashenConfiguration();
config.DisableConsoleLog();
config.MessageHandlers.ShouldBeEmpty();
}
[Fact]
public void AddResource_allows_the_content_stream_to_be_shut()
{
var config = new DashenConfiguration();
using (var ms = new MemoryStream())
using( var writer = new StreamWriter(ms))
{
writer.Write("Test value");
writer.Flush();
ms.Position = 0;
config.AddResource("test", ms, "text/plain");
}
var adhoc = new AdhocContentProvider();
var init = new StaticContentInitialisation(new ReplacementSource(), adhoc);
init.ApplyTo(config, null);
using (var reader = new StreamReader(adhoc.GetContent("test").Stream))
{
reader.ReadToEnd().ShouldBe("Test value");
}
}
}
}
| lgpl-2.1 | C# |
2d7e461d7eb581c8e05164791096e78880d25b78 | Remove unneed ToString (on string) | takenet/lime-csharp | src/Lime.Protocol/Network/EnvelopeTooLargeException.cs | src/Lime.Protocol/Network/EnvelopeTooLargeException.cs | using System;
namespace Lime.Protocol.Network
{
public class EnvelopeTooLargeException : Exception
{
public EnvelopeTooLargeException()
: base()
{
}
public EnvelopeTooLargeException(string message)
: base(message)
{
}
public EnvelopeTooLargeException(string message, Envelope envelope)
: base(message)
{
AddEnvelopePropertiesToData(envelope);
}
public EnvelopeTooLargeException(string message, Exception innerException)
: base(message, innerException)
{
}
public EnvelopeTooLargeException(string message, Envelope envelope, Exception innerException)
: base(message, innerException)
{
AddEnvelopePropertiesToData(envelope);
}
private void AddEnvelopePropertiesToData(Envelope envelope)
{
Data["EnvelopeType"] = envelope.GetType().Name;
Data[nameof(envelope.Id)] = envelope.Id;
Data[nameof(envelope.To)] = envelope.To?.ToString();
Data[nameof(envelope.From)] = envelope.From?.ToString();
Data[nameof(envelope.Pp)] = envelope.Pp?.ToString();
Data[nameof(envelope.Metadata)] = envelope.Metadata;
}
}
}
| using System;
namespace Lime.Protocol.Network
{
public class EnvelopeTooLargeException : Exception
{
public EnvelopeTooLargeException()
: base()
{
}
public EnvelopeTooLargeException(string message)
: base(message)
{
}
public EnvelopeTooLargeException(string message, Envelope envelope)
: base(message)
{
AddEnvelopePropertiesToData(envelope);
}
public EnvelopeTooLargeException(string message, Exception innerException)
: base(message, innerException)
{
}
public EnvelopeTooLargeException(string message, Envelope envelope, Exception innerException)
: base(message, innerException)
{
AddEnvelopePropertiesToData(envelope);
}
private void AddEnvelopePropertiesToData(Envelope envelope)
{
Data["EnvelopeType"] = envelope.GetType().Name;
Data[nameof(envelope.Id)] = envelope.Id?.ToString();
Data[nameof(envelope.To)] = envelope.To?.ToString();
Data[nameof(envelope.From)] = envelope.From?.ToString();
Data[nameof(envelope.Pp)] = envelope.Pp?.ToString();
Data[nameof(envelope.Metadata)] = envelope.Metadata;
}
}
}
| apache-2.0 | C# |
7acf464e0a2107c1d5054488a6219bc85ec5e009 | Kill unneeded special case. | arlobelshee/Fools.net,Minions/Fools.net | src/Core/Gibberish.Tests/ZzTestHelpers/RecognitionAssertions.cs | src/Core/Gibberish.Tests/ZzTestHelpers/RecognitionAssertions.cs | using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using FluentAssertions.Primitives;
using Gibberish.AST;
using JetBrains.Annotations;
namespace Gibberish.Tests.ZzTestHelpers
{
internal class RecognitionAssertions<TConstruct> : ObjectAssertions
{
public RecognitionAssertions(bool success, [NotNull] IEnumerable<TConstruct> result) : base(result)
{
Success = success;
Result = result.ToArray();
}
public bool Success { get; }
[NotNull]
public TConstruct[] Result { get; }
internal void BeRecognizedAs(params AstBuilder<TConstruct>[] expected)
{
_Verify(
expected.SelectMany(b => b.Build())
.ToList());
}
private void _Verify(List<TConstruct> statements)
{
Success.Should()
.BeTrue("parse should have fully matched the input. This is probably an error in the test");
Result.ShouldBeEquivalentTo(
statements,
options => options.IncludingFields()
.IncludingProperties()
.IncludingNestedObjects()
.RespectingRuntimeTypes()
.ComparingByValue<PossiblySpecified<bool>>()
.ComparingByValue<PossiblySpecified<int>>());
}
}
}
| using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using FluentAssertions.Primitives;
using Gibberish.AST;
using JetBrains.Annotations;
namespace Gibberish.Tests.ZzTestHelpers
{
internal class RecognitionAssertions<TConstruct> : ObjectAssertions
{
public RecognitionAssertions(bool success, [NotNull] IEnumerable<TConstruct> result) : base(result)
{
Success = success;
Result = result.ToArray();
}
public bool Success { get; }
[NotNull]
public TConstruct[] Result { get; }
public void BeRecognizedAs(AstBuilder<TConstruct> expected)
{
_Verify(expected.Build());
}
internal void BeRecognizedAs(params AstBuilder<TConstruct>[] expected)
{
_Verify(
expected.SelectMany(b => b.Build())
.ToList());
}
private void _Verify(List<TConstruct> statements)
{
Success.Should()
.BeTrue("parse should have fully matched the input. This is probably an error in the test");
Result.ShouldBeEquivalentTo(
statements,
options => options.IncludingFields()
.IncludingProperties()
.IncludingNestedObjects()
.RespectingRuntimeTypes()
.ComparingByValue<PossiblySpecified<bool>>()
.ComparingByValue<PossiblySpecified<int>>());
}
}
}
| bsd-3-clause | C# |
b10af6eb4770b2bcefa9b7edfc1099bb11c413ac | stop animation on loss | NitorInc/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare | Assets/Microgames/KnifeDodge/Scripts/KnifeDodgeKnife.cs | Assets/Microgames/KnifeDodge/Scripts/KnifeDodgeKnife.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnifeDodgeKnife : MonoBehaviour {
Vector3 facingDirection;
int state;
bool tilted;
public float knifeSpeed = 40.0f;
public float knifeRotationSpeed = 1.0f;
public enum KnifeState
{
FLYING_IN,
STOP_AND_ROTATE,
MOVING_TO_GROUND,
}
// Use this for initialization
void Start () {
state = (int)KnifeState.STOP_AND_ROTATE;
}
// Update is called once per frame
void Update () {
switch (state)
{
case (int)KnifeState.FLYING_IN:
GetComponent<Rigidbody2D>().velocity = transform.up * -1.0f * knifeSpeed;
break;
case (int)KnifeState.STOP_AND_ROTATE:
GetComponent<Rigidbody2D>().velocity = Vector3.zero;
GetComponent<Rigidbody2D>().angularVelocity = 0.0f;
if (tilted)
{
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(Vector3.forward, transform.position - facingDirection), knifeRotationSpeed * Time.deltaTime);
}
break;
case (int)KnifeState.MOVING_TO_GROUND:
//GetComponent<Rigidbody2D>().AddForce(-1.0f * transform.up * knifeSpeed);
GetComponent<Rigidbody2D>().velocity = transform.up * -1.0f * knifeSpeed;
break;
}
}
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "KnifeDodgeGround") {
GetComponent<Rigidbody2D> ().simulated = false;
CameraShake.instance.setScreenShake(.15f);
CameraShake.instance.shakeCoolRate = .5f;
}
}
public void SetFacing(Vector3 vec) {
facingDirection = vec;
}
public void SetTilted(bool isTilted)
{
tilted = isTilted;
}
public void SetState(int stateNumber)
{
state = stateNumber;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnifeDodgeKnife : MonoBehaviour {
Vector3 facingDirection;
int state;
bool tilted;
public float knifeSpeed = 40.0f;
public float knifeRotationSpeed = 1.0f;
public enum KnifeState
{
FLYING_IN,
STOP_AND_ROTATE,
MOVING_TO_GROUND,
}
// Use this for initialization
void Start () {
state = (int)KnifeState.STOP_AND_ROTATE;
}
// Update is called once per frame
void Update () {
switch (state)
{
case (int)KnifeState.FLYING_IN:
// GetComponent<Rigidbody2D>().AddForce(-0.5f * transform.up * knifeSpeed);
GetComponent<Rigidbody2D>().velocity = transform.up * -1.0f * knifeSpeed;
break;
case (int)KnifeState.STOP_AND_ROTATE:
GetComponent<Rigidbody2D>().velocity = Vector3.zero;
GetComponent<Rigidbody2D>().angularVelocity = 0.0f;
if (tilted)
{
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(Vector3.forward, transform.position - facingDirection), knifeRotationSpeed * Time.deltaTime);
}
break;
case (int)KnifeState.MOVING_TO_GROUND:
//GetComponent<Rigidbody2D>().AddForce(-1.0f * transform.up * knifeSpeed);
GetComponent<Rigidbody2D>().velocity = transform.up * -1.0f * knifeSpeed;
break;
}
}
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "KnifeDodgeGround") {
GetComponent<Rigidbody2D> ().simulated = false;
CameraShake.instance.setScreenShake(.15f);
CameraShake.instance.shakeCoolRate = .5f;
}
}
public void SetFacing(Vector3 vec) {
facingDirection = vec;
}
public void SetTilted(bool isTilted)
{
tilted = isTilted;
}
public void SetState(int stateNumber)
{
state = stateNumber;
}
}
| mit | C# |
194dc7c543b368f8f5725c0b728bb626b0d74b16 | change level 2 boss split | Dalet/140-speedrun-timer,Dalet/140-speedrun-timer,Dalet/140-speedrun-timer | 140-speedrun-timer/GameObservers/Level2BossObserver.cs | 140-speedrun-timer/GameObservers/Level2BossObserver.cs | using System.Reflection;
using UnityEngine;
namespace SpeedrunTimerMod.GameObservers
{
[GameObserver]
class Level2BossObserver : MonoBehaviour
{
TunnelBossEndSequence _tunnelSequence;
bool _checkScrollEnded;
void Awake()
{
if (!Application.loadedLevelName.StartsWith("Level2_"))
{
Destroy(this);
return;
}
var bossObj = GameObject.Find("BossPart3");
if (bossObj == null)
{
Debug.Log($"{nameof(Level2BossObserver)}: Couldn't find BossPart3 object");
Destroy(this);
return;
}
_tunnelSequence = bossObj.GetComponent<TunnelBossEndSequence>();
}
void OnEnable()
{
if (_tunnelSequence != null)
_tunnelSequence.endScrollingBeat.onBeat += EndScrollingBeat_onBeat;
}
void OnDisable()
{
if (_tunnelSequence != null)
_tunnelSequence.endScrollingBeat.onBeat -= EndScrollingBeat_onBeat;
}
void EndScrollingBeat_onBeat()
{
_checkScrollEnded = true;
}
void LateUpdate()
{
if (!_checkScrollEnded)
return;
_checkScrollEnded = false;
if (_tunnelSequence.wallToMakeTriggerWhenDoorsStartClosing1.isTrigger)
OnLevel2BossEnd();
}
void OnLevel2BossEnd()
{
Debug.Log("OnLevel2BossEnd: " + DebugBeatListener.DebugStr);
SpeedrunTimer.Instance?.CompleteLevel(2);
this.enabled = false;
}
}
}
| using UnityEngine;
namespace SpeedrunTimerMod.GameObservers
{
[GameObserver]
class Level2BossObserver : MonoBehaviour
{
MyCharacterController _player;
TunnelBossEndSequence _tunnelSequence;
void Awake()
{
if (!Application.loadedLevelName.StartsWith("Level2_"))
{
Destroy(this);
return;
}
var bossObj = GameObject.Find("BossPart3");
if (bossObj == null)
{
Debug.Log($"{nameof(Level2BossObserver)}: Couldn't find BossPart3 object");
Destroy(this);
return;
}
_tunnelSequence = bossObj.GetComponent<TunnelBossEndSequence>();
}
void Start()
{
_player = Globals.player.GetComponent<MyCharacterController>();
}
void OnEnable()
{
_tunnelSequence.evilBlock.attack += EvilBlock_attack;
}
void OnDisable()
{
if (_tunnelSequence != null)
_tunnelSequence.evilBlock.attack -= EvilBlock_attack;
if (_player != null)
_player.Killed -= Player_Killed;
}
void EvilBlock_attack(int attackIndex)
{
if (attackIndex != 10)
return;
_player.Killed += Player_Killed;
OnLevel2BossEnd();
}
void Player_Killed()
{
_player.Killed -= Player_Killed;
SpeedrunTimer.Instance?.Unsplit();
}
void OnLevel2BossEnd()
{
Debug.Log("OnLevel2BossEnd: " + DebugBeatListener.DebugStr);
SpeedrunTimer.Instance?.CompleteLevel(2);
}
}
}
| unlicense | C# |
688982337f5f195705c453e8e5621c1b7578aaaf | Fix meetup display date | DotNetRu/App,DotNetRu/App | DotNetRu.DataStore.Audit/Extensions/MeetupExtensions.cs | DotNetRu.DataStore.Audit/Extensions/MeetupExtensions.cs | namespace DotNetRu.DataStore.Audit.Extensions
{
using System.Linq;
using DotNetRu.DataStore.Audit.Models;
using DotNetRu.DataStore.Audit.RealmModels;
public static class MeetupExtensions
{
public static MeetupModel ToModel(this Meetup meetup)
{
return new MeetupModel
{
CommunityID = meetup.CommunityId,
Description = meetup.Name,
IsAllDay = true,
Title = meetup.Name,
StartTime = meetup.Date.LocalDateTime,
EndTime = meetup.Date.LocalDateTime,
Venue = meetup.Venue.ToModel(),
Talks = meetup.Talks.Select(x => x.ToModel()),
Friends = meetup.Friends.Select(x => x.ToModel())
};
}
}
}
| namespace DotNetRu.DataStore.Audit.Extensions
{
using System.Linq;
using DotNetRu.DataStore.Audit.Models;
using DotNetRu.DataStore.Audit.RealmModels;
public static class MeetupExtensions
{
public static MeetupModel ToModel(this Meetup meetup)
{
return new MeetupModel
{
CommunityID = meetup.CommunityId,
Description = meetup.Name,
IsAllDay = true,
Title = meetup.Name,
StartTime = meetup.Date.DateTime,
EndTime = meetup.Date.DateTime,
Venue = meetup.Venue.ToModel(),
Talks = meetup.Talks.Select(x => x.ToModel()),
Friends = meetup.Friends.Select(x => x.ToModel())
};
}
}
}
| mit | C# |
c8a0054baccf0a579f93fb34f61b7ac6763398f1 | revert config | NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework | Spa2/NakedObjects.Spa.Selenium.Test/tests/TestConfig.cs | Spa2/NakedObjects.Spa.Selenium.Test/tests/TestConfig.cs |
namespace NakedObjects.Selenium
{
public static class TestConfig
{
//public const string BaseUrl = "http://localhost:49998/";
public const string BaseUrl = "http://nakedobjectstest2.azurewebsites.net/";
}
}
|
namespace NakedObjects.Selenium
{
public static class TestConfig
{
public const string BaseUrl = "http://localhost:49998/";
//public const string BaseUrl = "http://nakedobjectstest2.azurewebsites.net/";
}
}
| apache-2.0 | C# |
710354895a812f7142a2a43c4c29cba9296ecbc7 | Fix change that broke updating the setting. | devworx-au/Devworx.CodePrettify,devworx-au/Devworx.CodePrettify | Views/EditorTemplates/Parts/CodePrettifySettings.cshtml | Views/EditorTemplates/Parts/CodePrettifySettings.cshtml | @model Devworx.CodePrettify.ViewModels.CodePrettifySettingsViewModel
<fieldset>
<legend>@T("Code Prettify")</legend>
<div>
@Html.CheckBox("UseAutoLoader", Model.PrettifySettingsPart.UseAutoLoader)
<label for="CodePrettifySettings_UseAutoLoader" class="forcheckbox">@T("Use default async auto load script.")</label>
<span class="hint">@T("If checked, will be loaded using the 'run_prettify.js' script from github asynchronously, and only themes available in the <a target=\"_blank\" href=\"https://cdn.rawgit.com/google/code-prettify/master/styles/index.html\">theme gallery</a> are supported. You will also have to manually add the class=\"prettyprint\" to all <pre> and/or <code> tags that need to be prettyprint'd")</span>
</div>
<div>
<label for="CodePrettifySettings_Theme">@T("Theme")</label>
@Html.DropDownList("Theme", new[] {new SelectListItem {Text = T("").Text, Value = ""}}.Union(new SelectList(Model.Themes, "", "", Model.PrettifySettingsPart.Theme)))
@Html.ValidationMessage("Theme", "*")
</div>
</fieldset> | @model Devworx.CodePrettify.ViewModels.CodePrettifySettingsViewModel
<fieldset>
<legend>@T("Code Prettify")</legend>
<div>
@Html.EditorFor(m => m.PrettifySettingsPart.UseAutoLoader)
<label for="@Html.FieldIdFor(m => m.PrettifySettingsPart.UseAutoLoader)" class="forcheckbox">@T("Use default async auto load script.")</label>
@Html.ValidationMessageFor(m => m.PrettifySettingsPart.UseAutoLoader)
<span class="hint">@T("If checked, will be loaded using the 'run_prettify.js' script from github asynchronously, and only themes available in the <a target=\"_blank\" href=\"https://cdn.rawgit.com/google/code-prettify/master/styles/index.html\">theme gallery</a> are supported. You will also have to manually add the class=\"prettyprint\" to all <pre> and/or <code> tags that need to be prettyprint'd")</span>
</div>
<div>
<label for="Theme">@T("Theme")</label>
@Html.DropDownList("Theme", new[] {new SelectListItem {Text = T("").Text, Value = ""}}.Union(new SelectList(Model.Themes, "", "", Model.PrettifySettingsPart.Theme)))
@Html.ValidationMessage("Theme", "*")
</div>
</fieldset> | mit | C# |
264eb00e9fab1384106ad018aff66e3ab3fed8a1 | use the new method of registering middleware | kerryjiang/SuperSocket,kerryjiang/SuperSocket,memleaks/SuperSocket | src/SuperSocket.Command/CommandMiddlewareExtensions.cs | src/SuperSocket.Command/CommandMiddlewareExtensions.cs | using System;
namespace SuperSocket.Command
{
public static class CommandMiddlewareExtensions
{
public static void UseCommand<TKey, TPackageInfo>(this IServer server)
where TPackageInfo : IKeyedPackageInfo<TKey>
{
server.UseMiddleware<CommandMiddleware<TKey, TPackageInfo>>();
}
}
}
| using System;
namespace SuperSocket.Command
{
public static class CommandMiddlewareExtensions
{
public static void UseCommand<TKey, TPackageInfo>(this IServer server)
where TPackageInfo : IKeyedPackageInfo<TKey>
{
server.Use<CommandMiddleware<TKey, TPackageInfo>>();
}
}
}
| apache-2.0 | C# |
dcdc291f8377ee3684928504cf447bc625c65cef | Remove skill association from ApplicationUser (not ready for that yet) | dangle1/allReady,GProulx/allReady,jonatwabash/allReady,gitChuckD/allReady,kmlewis/allReady,JowenMei/allReady,mikesigs/allReady,timstarbuck/allReady,enderdickerson/allReady,jonatwabash/allReady,stevejgordon/allReady,aliiftikhar/allReady,c0g1t8/allReady,MisterJames/allReady,MisterJames/allReady,BillWagner/allReady,mheggeseth/allReady,jonatwabash/allReady,pranap/allReady,jonhilt/allReady,binaryjanitor/allReady,colhountech/allReady,shawnwildermuth/allReady,SteveStrong/allReady,shanecharles/allReady,aliiftikhar/allReady,bcbeatty/allReady,forestcheng/allReady,mipre100/allReady,anobleperson/allReady,joelhulen/allReady,auroraocciduusadmin/allReady,jonatwabash/allReady,BarryBurke/allReady,mgmccarthy/allReady,aliiftikhar/allReady,HTBox/allReady,GProulx/allReady,mikesigs/allReady,shanecharles/allReady,ksk100/allReady,BarryBurke/allReady,HTBox/allReady,shawnwildermuth/allReady,mipre100/allReady,HamidMosalla/allReady,joelhulen/allReady,VishalMadhvani/allReady,arst/allReady,mipre100/allReady,auroraocciduusadmin/allReady,shanecharles/allReady,jonhilt/allReady,gftrader/allReady,binaryjanitor/allReady,joelhulen/allReady,anobleperson/allReady,stevejgordon/allReady,gftrader/allReady,gitChuckD/allReady,JowenMei/allReady,ksk100/allReady,stevejgordon/allReady,binaryjanitor/allReady,enderdickerson/allReady,GProulx/allReady,forestcheng/allReady,chinwobble/allReady,bcbeatty/allReady,SteveStrong/allReady,gftrader/allReady,pranap/allReady,MisterJames/allReady,mheggeseth/allReady,colhountech/allReady,pranap/allReady,shawnwildermuth/allReady,pranap/allReady,BillWagner/allReady,enderdickerson/allReady,SteveStrong/allReady,arst/allReady,MisterJames/allReady,dpaquette/allReady,c0g1t8/allReady,mgmccarthy/allReady,mgmccarthy/allReady,gitChuckD/allReady,arst/allReady,timstarbuck/allReady,VishalMadhvani/allReady,timstarbuck/allReady,auroraocciduusadmin/allReady,chinwobble/allReady,dpaquette/allReady,colhountech/allReady,ksk100/allReady,kmlewis/allReady,shawnwildermuth/allReady,SteveStrong/allReady,shanecharles/allReady,VishalMadhvani/allReady,gftrader/allReady,mikesigs/allReady,kmlewis/allReady,JowenMei/allReady,dangle1/allReady,dangle1/allReady,ksk100/allReady,HTBox/allReady,auroraocciduusadmin/allReady,HamidMosalla/allReady,HTBox/allReady,timstarbuck/allReady,mheggeseth/allReady,mgmccarthy/allReady,kmlewis/allReady,forestcheng/allReady,binaryjanitor/allReady,HamidMosalla/allReady,jonhilt/allReady,aliiftikhar/allReady,joelhulen/allReady,chinwobble/allReady,HamidMosalla/allReady,stevejgordon/allReady,GProulx/allReady,VishalMadhvani/allReady,bcbeatty/allReady,anobleperson/allReady,arst/allReady,BillWagner/allReady,dangle1/allReady,anobleperson/allReady,dpaquette/allReady,chinwobble/allReady,mipre100/allReady,enderdickerson/allReady,bcbeatty/allReady,c0g1t8/allReady,BillWagner/allReady,jonhilt/allReady,mikesigs/allReady,colhountech/allReady,gitChuckD/allReady,dpaquette/allReady,BarryBurke/allReady,forestcheng/allReady,JowenMei/allReady,c0g1t8/allReady,BarryBurke/allReady,mheggeseth/allReady | AllReadyApp/Web-App/AllReady/Models/ApplicationUser.cs | AllReadyApp/Web-App/AllReady/Models/ApplicationUser.cs | using Microsoft.AspNet.Identity.EntityFramework;
namespace AllReady.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
}
}
| using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
namespace AllReady.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
public List<Skill> AssociatedSkills { get; set; }
}
}
| mit | C# |
8b4354cfe90068112e2806e57bdf63da10ff09e8 | Manage account page wip | peterblazejewicz/aspnet-5-bootstrap-4,peterblazejewicz/aspnet-5-bootstrap-4 | mvc-individual-authentication/Views/Manage/Index.cshtml | mvc-individual-authentication/Views/Manage/Index.cshtml | @model IndexViewModel
@{
ViewData["Title"] = "Profile";
ViewData.AddActivePage(ManageNavPages.Index);
}
<h4>@ViewData["Title"]</h4>
@Html.Partial("_StatusMessage", Model.StatusMessage)
<div class="row">
<div class="col-md-6">
<form id="manageAccountForm" method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Username"></label>
<input asp-for="Username" class="form-control" disabled />
</div>
<div class="form-group">
<label asp-for="Email"></label>
@if (Model.IsEmailConfirmed)
{
<div class="input-group">
<input asp-for="Email" class="form-control" />
<span class="input-group-addon" aria-hidden="true"><span class="glyphicon glyphicon-ok text-success"></span></span>
</div>
}
else
{
<input asp-for="Email" class="form-control" />
<button asp-action="SendVerificationEmail" class="btn btn-link">Send verification email</button>
}
<span asp-validation-for="Email" class="form-text text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PhoneNumber"></label>
<input asp-for="PhoneNumber" class="form-control" />
<span asp-validation-for="PhoneNumber" class="form-text text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
@section Scripts {
@await Html.PartialAsync("_ValidationScriptsPartial")
}
| @model IndexViewModel
@{
ViewData["Title"] = "Profile";
ViewData.AddActivePage(ManageNavPages.Index);
}
<h4>@ViewData["Title"]</h4>
@Html.Partial("_StatusMessage", Model.StatusMessage)
<div class="row">
<div class="col-md-6">
<form method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Username"></label>
<input asp-for="Username" class="form-control" disabled />
</div>
<div class="form-group">
<label asp-for="Email"></label>
@if (Model.IsEmailConfirmed)
{
<div class="input-group">
<input asp-for="Email" class="form-control" />
<span class="input-group-addon" aria-hidden="true"><span class="glyphicon glyphicon-ok text-success"></span></span>
</div>
}
else
{
<input asp-for="Email" class="form-control" />
<button asp-action="SendVerificationEmail" class="btn btn-link">Send verification email</button>
}
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PhoneNumber"></label>
<input asp-for="PhoneNumber" class="form-control" />
<span asp-validation-for="PhoneNumber" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
@section Scripts {
@await Html.PartialAsync("_ValidationScriptsPartial")
}
| mit | C# |
bd631e7421efa92cbbb09b69b7ef74ab97b7c0a8 | Add documentation for genres module. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Modules/TraktGenresModule.cs | Source/Lib/TraktApiSharp/Modules/TraktGenresModule.cs | namespace TraktApiSharp.Modules
{
using Enums;
using Objects.Basic;
using Requests.WithoutOAuth.Genres;
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>
/// Provides access to data retrieving methods specific to genres.
/// <para>
/// This module contains all methods of the <a href ="http://docs.trakt.apiary.io/#reference/genres">"Trakt API Doc - Genres"</a> section.
/// </para>
/// </summary>
public class TraktGenresModule : TraktBaseModule
{
internal TraktGenresModule(TraktClient client) : base(client) { }
/// <summary>
/// Gets a list of all movie genres.
/// <para>OAuth authorization NOT required.</para>
/// <para>
/// See <a href="http://docs.trakt.apiary.io/#reference/genres/list/get-genres">"Trakt API Doc - Genres: List"</a> for more information.
/// </para>
/// </summary>
/// <returns>A list of <see cref="TraktGenre" /> instances.</returns>
/// <exception cref="Exceptions.TraktException">Thrown, if the request fails.</exception>
public async Task<IEnumerable<TraktGenre>> GetMovieGenresAsync()
{
var movieGenres = await QueryAsync(new TraktGenresMoviesRequest(Client));
foreach (var genre in movieGenres)
genre.Type = TraktGenreType.Movies;
return movieGenres;
}
/// <summary>
/// Gets a list of all show genres.
/// <para>OAuth authorization NOT required.</para>
/// <para>
/// See <a href="http://docs.trakt.apiary.io/#reference/genres/list/get-genres">"Trakt API Doc - Genres: List"</a> for more information.
/// </para>
/// </summary>
/// <returns>A list of <see cref="TraktGenre" /> instances.</returns>
/// <exception cref="Exceptions.TraktException">Thrown, if the request fails.</exception>
public async Task<IEnumerable<TraktGenre>> GetShowGenresAsync()
{
var showGenres = await QueryAsync(new TraktGenresShowsRequest(Client));
foreach (var genre in showGenres)
genre.Type = TraktGenreType.Shows;
return showGenres;
}
}
}
| namespace TraktApiSharp.Modules
{
using Enums;
using Objects.Basic;
using Requests.WithoutOAuth.Genres;
using System.Collections.Generic;
using System.Threading.Tasks;
public class TraktGenresModule : TraktBaseModule
{
internal TraktGenresModule(TraktClient client) : base(client) { }
public async Task<IEnumerable<TraktGenre>> GetMovieGenresAsync()
{
var movieGenres = await QueryAsync(new TraktGenresMoviesRequest(Client));
foreach (var genre in movieGenres)
genre.Type = TraktGenreType.Movies;
return movieGenres;
}
public async Task<IEnumerable<TraktGenre>> GetShowGenresAsync()
{
var showGenres = await QueryAsync(new TraktGenresShowsRequest(Client));
foreach (var genre in showGenres)
genre.Type = TraktGenreType.Shows;
return showGenres;
}
}
}
| mit | C# |
ee35a3493bb8e45cd7c9bb78aa5e72d9dfd5cb23 | Add a new field to JobType + refactor its respective Controller | patsy02/KompetansetorgetServer,patsy02/KompetansetorgetServer,patsy02/KompetansetorgetServer | KompetansetorgetServer/Models/JobType.cs | KompetansetorgetServer/Models/JobType.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace KompetansetorgetServer.Models
{
/// <summary>
/// This Class maps a table that represents jobs types like fulltime, part time, apprenticeship etc..
/// </summary>
[Table("JobType")]
public class JobType
{
[Key]
public string id { get; set; }
public string name { get; set; }
public string type { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace KompetansetorgetServer.Models
{
/// <summary>
/// This Class maps a table that represents jobs types like fulltime, part time, apprenticeship etc..
/// </summary>
[Table("JobType")]
public class JobType
{
[Key]
public string id { get; set; }
public string name { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
} | artistic-2.0 | C# |
c9aad50d190c938ccc7fad1e79a7a0869dfb7af1 | Fix AddFiresContentChangedEvent - make base type abstract | unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,mmoening/MatterControl,jlewin/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl | Library/Providers/MatterControl/PlatingHistoryContainer.cs | Library/Providers/MatterControl/PlatingHistoryContainer.cs | /*
Copyright (c) 2018, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MatterHackers.Agg.Image;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.DataStorage;
namespace MatterHackers.MatterControl.Library
{
public class PlatingHistoryContainer : HistoryContainerBase
{
public PlatingHistoryContainer():
base (ApplicationDataStorage.Instance.PlatingDirectory)
{
this.Name = "Plating History".Localize();
}
}
public abstract class HistoryContainerBase : FileSystemContainer, ILibraryWritableContainer
{
public HistoryContainerBase(string fullPath)
: base(fullPath)
{
this.ChildContainers = new List<ILibraryContainerLink>();
this.Items = new List<ILibraryItem>();
this.IsProtected = true;
}
public int PageSize { get; set; } = 25;
public event EventHandler<ItemChangedEventArgs> ItemContentChanged;
public bool AllowAction(ContainerActions containerActions)
{
switch(containerActions)
{
case ContainerActions.AddItems:
case ContainerActions.AddContainers:
case ContainerActions.RemoveItems:
case ContainerActions.RenameItems:
return false;
default:
System.Diagnostics.Debugger.Break();
return false;
}
}
// PrintItems projected onto FileSystemFileItem
public override void Load()
{
// Select the 25 most recent files and project onto FileSystemItems
if (Directory.Exists(this.FullPath))
{
var recentFiles = new DirectoryInfo(this.FullPath).GetFiles("*.mcx").OrderByDescending(f => f.LastWriteTime);
Items = recentFiles.Take(this.PageSize).Select(f => new SceneReplacementFileItem(f.FullName)).ToList<ILibraryItem>();
}
}
public void SetThumbnail(ILibraryItem item, int width, int height, ImageBuffer imageBuffer)
{
}
}
}
| /*
Copyright (c) 2018, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MatterHackers.Agg.Image;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.DataStorage;
namespace MatterHackers.MatterControl.Library
{
public class PlatingHistoryContainer : HistoryContainerBase
{
public PlatingHistoryContainer():
base (ApplicationDataStorage.Instance.PlatingDirectory)
{
this.Name = "Plating History".Localize();
}
}
public class HistoryContainerBase : FileSystemContainer, ILibraryWritableContainer
{
public HistoryContainerBase(string fullPath)
: base(fullPath)
{
this.ChildContainers = new List<ILibraryContainerLink>();
this.Items = new List<ILibraryItem>();
this.IsProtected = true;
}
public int PageSize { get; set; } = 25;
public event EventHandler<ItemChangedEventArgs> ItemContentChanged;
public bool AllowAction(ContainerActions containerActions)
{
switch(containerActions)
{
case ContainerActions.AddItems:
case ContainerActions.AddContainers:
case ContainerActions.RemoveItems:
case ContainerActions.RenameItems:
return false;
default:
System.Diagnostics.Debugger.Break();
return false;
}
}
// PrintItems projected onto FileSystemFileItem
public override void Load()
{
// Select the 25 most recent files and project onto FileSystemItems
if (Directory.Exists(this.FullPath))
{
var recentFiles = new DirectoryInfo(this.FullPath).GetFiles("*.mcx").OrderByDescending(f => f.LastWriteTime);
Items = recentFiles.Take(this.PageSize).Select(f => new SceneReplacementFileItem(f.FullName)).ToList<ILibraryItem>();
}
}
public void SetThumbnail(ILibraryItem item, int width, int height, ImageBuffer imageBuffer)
{
}
}
}
| bsd-2-clause | C# |
e41d396293a26f174da3e9e9eba0b0a02ad18a9c | Update assembly version | TesserisPro/ASP.NET-SImple-Security-Provider | Tesseris.Web.SimpleSecurity/Properties/AssemblyInfo.cs | Tesseris.Web.SimpleSecurity/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("Tesseris.Web.SimpleSecurity")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Tesseris Pro LLC")]
[assembly: AssemblyProduct("Tesseris.Web.SimpleSecurity")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4628f015-a311-4090-acd6-836bc01696af")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.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("Tesseris.Web.SimpleSecurity")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Tesseris.Web.SimpleSecurity")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4628f015-a311-4090-acd6-836bc01696af")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
44ed0e9ab4b274f89222b17ba0697a4bcfa1209a | Add test for JsonService.GetValue() | arthurrump/Zermelo.API | Zermelo/Zermelo.API.Tests/Services/JsonServiceTests.cs | Zermelo/Zermelo.API.Tests/Services/JsonServiceTests.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Zermelo.API.Services;
namespace Zermelo.API.Tests.Services
{
public class JsonServiceTests
{
[Fact]
public void ShouldDeserializeDataInResponeData()
{
var sut = new JsonService();
ObservableCollection<TestClass> expected = new ObservableCollection<TestClass>
{
new TestClass(5),
new TestClass(3)
};
string testData = "{ \"response\": { \"data\": [ { \"Number\": 5 }, { \"Number\": 3 } ] } }";
ObservableCollection<TestClass> result = sut.DeserializeCollection<TestClass>(testData);
Assert.Equal(expected.Count, result.Count);
for (int i = 0; i < expected.Count; i++)
Assert.Equal(expected[i].Number, result[i].Number);
}
[Fact]
public void ShouldReturnValue()
{
var sut = new JsonService();
string expected = "value";
string testData = "{ \"key\": \"value\" }";
string result = sut.GetValue<string>(testData, "key");
Assert.Equal(expected, result);
}
}
internal class TestClass
{
public TestClass(int number)
{
this.Number = number;
}
public int Number { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Zermelo.API.Services;
namespace Zermelo.API.Tests.Services
{
public class JsonServiceTests
{
[Fact]
public void ShouldDeserializeDataInResponeData()
{
var sut = new JsonService();
ObservableCollection<TestClass> expected = new ObservableCollection<TestClass>
{
new TestClass(5),
new TestClass(3)
};
string testData = "{ \"response\": { \"data\": [ { \"Number\": 5 }, { \"Number\": 3 } ] } }";
ObservableCollection<TestClass> result = sut.DeserializeCollection<TestClass>(testData);
Assert.Equal(expected.Count, result.Count);
for (int i = 0; i < expected.Count; i++)
Assert.Equal(expected[i].Number, result[i].Number);
}
}
internal class TestClass
{
public TestClass(int number)
{
this.Number = number;
}
public int Number { get; set; }
}
}
| mit | C# |
4115fb747f5a825efb571f690d9e5919a3664a97 | Add pfx private key instructions | tresf/qz-print,cbondo/qz-print,tresf/qz-print,gillg/qz-print,gillg/qz-print,qzind/qz-print,gillg/qz-print,dsanders11/qz-print,lzpfmh/qz-print,lzpfmh/qz-print,tresf/qz-print,qzind/qz-print,cbondo/qz-print,tresf/qz-print,dsanders11/qz-print,qzind/qz-print,cbondo/qz-print,tresf/qz-print,tresf/qz-print,gillg/qz-print,dsanders11/qz-print,dsanders11/qz-print,klabarge/qz-print,qzind/qz-print,cbondo/qz-print,gillg/qz-print,gillg/qz-print,qzind/qz-print,cbondo/qz-print,lzpfmh/qz-print,tresf/qz-print,gillg/qz-print,lzpfmh/qz-print,gillg/qz-print,qzind/qz-print,klabarge/qz-print,dsanders11/qz-print,qzind/qz-print,qzind/qz-print,tresf/qz-print,cbondo/qz-print,dsanders11/qz-print,klabarge/qz-print,klabarge/qz-print,dsanders11/qz-print,cbondo/qz-print,klabarge/qz-print,qzind/qz-print,klabarge/qz-print,klabarge/qz-print,lzpfmh/qz-print,lzpfmh/qz-print,lzpfmh/qz-print,tresf/qz-print,klabarge/qz-print,klabarge/qz-print,dsanders11/qz-print,cbondo/qz-print,lzpfmh/qz-print | assets/signing/sign-message.cs | assets/signing/sign-message.cs | /**
* Echoes the signed message and exits
*/
public void SignMessage(String message)
{
// #########################################################
// # WARNING WARNING WARNING #
// #########################################################
// # #
// # This file is intended for demonstration purposes #
// # only. #
// # #
// # It is the SOLE responsibility of YOU, the programmer #
// # to prevent against unauthorized access to any signing #
// # functions. #
// # #
// # Organizations that do not protect against un- #
// # authorized signing will be black-listed to prevent #
// # software piracy. #
// # #
// # -QZ Industries, LLC #
// # #
// #########################################################
// Sample key. Replace with one used for CSR generation
// How to associate a private key with the X509Certificate2 class in .net
// openssl pkcs12 -export -in private-key.pem -inkey digital-certificate.txt -out private-key.pfx
var KEY = "private-key.pfx";
var PASS = "S3cur3P@ssw0rd";
var cert = new X509Certificate2( KEY, PASS );
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PrivateKey;
byte[] data = new ASCIIEncoding().GetBytes(message);
byte[] hash = new SHA1Managed().ComputeHash(data);
Response.ContentType = "text/plain";
Response.Write(csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")));
Environment.Exit(0)
}
| /**
* Echoes the signed message and exits
*/
public void SignMessage(String message)
{
// #########################################################
// # WARNING WARNING WARNING #
// #########################################################
// # #
// # This file is intended for demonstration purposes #
// # only. #
// # #
// # It is the SOLE responsibility of YOU, the programmer #
// # to prevent against unauthorized access to any signing #
// # functions. #
// # #
// # Organizations that do not protect against un- #
// # authorized signing will be black-listed to prevent #
// # software piracy. #
// # #
// # -QZ Industries, LLC #
// # #
// #########################################################
// Sample key. Replace with one used for CSR generation
var KEY = "private-key.pem";
var PASS = "S3cur3P@ssw0rd";
var pem = System.IO.File.ReadAllText( KEY );
var cert = new X509Certificate2( GetBytesFromPEM( pem, "RSA PRIVATE", PASS );
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PrivateKey;
byte[] data = new ASCIIEncoding().GetBytes(message);
byte[] hash = new SHA1Managed().ComputeHash(data);
Response.ContentType = "text/plain";
Response.Write(csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")));
Environment.Exit(0)
}
/**
* Get PEM certificate data using C#
*/
private byte[] GetBytesFromPEM( string pemString, string section )
{
var header = String.Format("-----BEGIN {0}-----", section);
var footer = String.Format("-----END {0}-----", section);
var start = pemString.IndexOf(header, StringComparison.Ordinal) + header.Length;
var end = pemString.IndexOf(footer, start, StringComparison.Ordinal) - start;
return start < 0 || end < 0 ? null :
Convert.FromBase64String( pemString.Substring( start, end ) );
}
| lgpl-2.1 | C# |
b6f157e3ab4e9a4716f24c515f370f8a56d4f1c6 | check to avoid tricky redirects | appharbor/AppHarbor.Web.Security | AuthenticationExample.Web/Controllers/SessionController.cs | AuthenticationExample.Web/Controllers/SessionController.cs | using System;
using System.Linq;
using System.Web.Mvc;
using AppHarbor.Web.Security;
using AuthenticationExample.Web.Model;
using AuthenticationExample.Web.PersistenceSupport;
using AuthenticationExample.Web.ViewModels;
namespace AuthenticationExample.Web.Controllers
{
public class SessionController : Controller
{
private readonly IAuthenticator _authenticator;
private readonly IRepository _repository;
public SessionController(IAuthenticator authenticator, IRepository repository)
{
_authenticator = authenticator;
_repository = repository;
}
[HttpGet]
public ActionResult New(string returnUrl)
{
return View(new SessionViewModel { ReturnUrl = returnUrl });
}
[HttpPost]
public ActionResult Create(SessionViewModel sessionViewModel)
{
User user = null;
if (ModelState.IsValid)
{
user = _repository.GetAll<User>().SingleOrDefault(x => x.Username == sessionViewModel.Username);
if (user == null)
{
ModelState.AddModelError("Username", "User not found");
}
}
if (ModelState.IsValid)
{
if (!BCrypt.Net.BCrypt.Verify(sessionViewModel.Password, user.Password))
{
ModelState.AddModelError("Password", "Wrong password");
}
}
if (ModelState.IsValid)
{
_authenticator.SetCookie(user.Username);
var returnUrl = sessionViewModel.ReturnUrl;
if (!string.IsNullOrEmpty(returnUrl))
{
var returnUri = new Uri(returnUrl);
if (!returnUri.IsAbsoluteUri || returnUri.Host == Request.Url.Host)
{
return Redirect(sessionViewModel.ReturnUrl);
}
}
return RedirectToAction("Index", "Home");
}
return View("New", sessionViewModel);
}
[HttpPost]
public ActionResult Destroy()
{
_authenticator.SignOut();
Session.Abandon();
return RedirectToAction("Index", "Home");
}
}
}
| using System.Linq;
using System.Web.Mvc;
using AppHarbor.Web.Security;
using AuthenticationExample.Web.Model;
using AuthenticationExample.Web.PersistenceSupport;
using AuthenticationExample.Web.ViewModels;
namespace AuthenticationExample.Web.Controllers
{
public class SessionController : Controller
{
private readonly IAuthenticator _authenticator;
private readonly IRepository _repository;
public SessionController(IAuthenticator authenticator, IRepository repository)
{
_authenticator = authenticator;
_repository = repository;
}
[HttpGet]
public ActionResult New(string returnUrl)
{
return View(new SessionViewModel { ReturnUrl = returnUrl });
}
[HttpPost]
public ActionResult Create(SessionViewModel sessionViewModel)
{
User user = null;
if (ModelState.IsValid)
{
user = _repository.GetAll<User>().SingleOrDefault(x => x.Username == sessionViewModel.Username);
if (user == null)
{
ModelState.AddModelError("Username", "User not found");
}
}
if (ModelState.IsValid)
{
if (!BCrypt.Net.BCrypt.Verify(sessionViewModel.Password, user.Password))
{
ModelState.AddModelError("Password", "Wrong password");
}
}
if (ModelState.IsValid)
{
_authenticator.SetCookie(user.Username);
if (!string.IsNullOrEmpty(sessionViewModel.ReturnUrl))
{
return Redirect(sessionViewModel.ReturnUrl);
}
return RedirectToAction("Index", "Home");
}
return View("New", sessionViewModel);
}
[HttpPost]
public ActionResult Destroy()
{
_authenticator.SignOut();
Session.Abandon();
return RedirectToAction("Index", "Home");
}
}
}
| mit | C# |
8b2ac545f3da4425b7126cb6f85c5c52b7b5092e | Update example using Unsubscribe. | hschaeidt/unity-mediator | Assets/Letscode/Signal/Example/Scripts/PillSpawner.cs | Assets/Letscode/Signal/Example/Scripts/PillSpawner.cs | using UnityEngine;
using System.Collections.Generic;
using Letscode.Signal;
public class PillSpawner : MonoBehaviour {
string eventSpawn = "Spawn";
string eventAttach = "Attach";
bool attached = false;
void Start ()
{
Mediator.Subscribe (eventAttach, Attach);
}
void Attach(object sender, Dictionary<string, object> args)
{
if (!attached) {
attached = true;
Mediator.Subscribe (eventSpawn, SpawnPill);
Mediator.Unsubscribe (eventAttach, Attach);
}
}
void SpawnPill (object sender, Dictionary<string, object> args)
{
Instantiate ((GameObject)args["objectToSpawn"], transform.position, Quaternion.identity);
}
void OnDestroy()
{
Mediator.Unsubscribe (eventSpawn, SpawnPill);
Mediator.Unsubscribe (eventAttach, Attach);
}
}
| using UnityEngine;
using System.Collections.Generic;
using Letscode.Signal;
public class PillSpawner : MonoBehaviour {
string eventSpawn = "Spawn";
bool attached = false;
void Start ()
{
Mediator.Subscribe ("Attach", Attach);
}
void Attach(object sender, Dictionary<string, object> args)
{
if (!attached) {
attached = true;
Mediator.Subscribe (eventSpawn, SpawnPill);
}
}
void SpawnPill (object sender, Dictionary<string, object> args)
{
Instantiate ((GameObject)args["objectToSpawn"], transform.position, Quaternion.identity);
}
}
| mit | C# |
e48a7ba905bc0454f793a645b4c8f27883c8cf1d | Update AssemblyInfo.cs | Esri/workflowmanager-samples,Esri/workflowmanager-samples,Esri/workflowmanager-samples | ClearAOIContextMenu/CSharp/Properties/AssemblyInfo.cs | ClearAOIContextMenu/CSharp/Properties/AssemblyInfo.cs | /*Copyright 2015 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
using System.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("ClearAOI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ESRI")]
[assembly: AssemblyProduct("ClearAOI")]
[assembly: AssemblyCopyright("Copyright © ESRI 2011")]
[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("c4fec254-3b56-4492-84ce-9ddae38536f4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ClearAOI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ESRI")]
[assembly: AssemblyProduct("ClearAOI")]
[assembly: AssemblyCopyright("Copyright © ESRI 2011")]
[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("c4fec254-3b56-4492-84ce-9ddae38536f4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
f62229ab84df077566cee49d9d566649e9fb4827 | Update iOSAccelerometerProbe.cs | predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus | Sensus.iOS.Shared/Probes/Movement/iOSAccelerometerProbe.cs | Sensus.iOS.Shared/Probes/Movement/iOSAccelerometerProbe.cs | // Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Sensus.Probes.Movement;
using CoreMotion;
using Foundation;
using Plugin.Permissions.Abstractions;
using System.Threading.Tasks;
namespace Sensus.iOS.Probes.Movement
{
public class iOSAccelerometerProbe : AccelerometerProbe
{
private CMMotionManager _motionManager;
protected override async Task InitializeAsync()
{
await base.InitializeAsync();
if (await SensusServiceHelper.Get().ObtainPermissionAsync(Permission.Sensors) == PermissionStatus.Granted)
{
_motionManager = new CMMotionManager();
}
else
{
// throw standard exception instead of NotSupportedException, since the user might decide to enable sensors in the future
// and we'd like the probe to be restarted at that time.
string error = "This device does not contain an accelerometer, or the user has denied access to it. Cannot start accelerometer probe.";
await SensusServiceHelper.Get().FlashNotificationAsync(error);
throw new Exception(error);
}
}
protected override async Task StartListeningAsync()
{
await base.StartListeningAsync();
_motionManager?.StartAccelerometerUpdates(new NSOperationQueue(), async (data, error) =>
{
if (data != null && error == null)
{
await StoreDatumAsync(new AccelerometerDatum(DateTimeOffset.UtcNow, data.Acceleration.X, data.Acceleration.Y, data.Acceleration.Z));
}
});
}
protected override async Task StopListeningAsync()
{
await base.StopListeningAsync();
_motionManager?.StopAccelerometerUpdates();
}
}
} | // Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Sensus.Probes.Movement;
using CoreMotion;
using Foundation;
using Plugin.Permissions.Abstractions;
using System.Threading.Tasks;
namespace Sensus.iOS.Probes.Movement
{
public class iOSAccelerometerProbe : AccelerometerProbe
{
private CMMotionManager _motionManager;
protected override async Task InitializeAsync()
{
await base.InitializeAsync();
if (await SensusServiceHelper.Get().ObtainPermissionAsync(Permission.Sensors) == PermissionStatus.Granted)
{
_motionManager = new CMMotionManager();
}
else
{
// throw standard exception instead of NotSupportedException, since the user might decide to enable sensors in the future
// and we'd like the probe to be restarted at that time.
string error = "This device does not contain an accelerometer, or the user has denied access to it. Cannot start accelerometer probe.";
await SensusServiceHelper.Get().FlashNotificationAsync(error);
throw new Exception(error);
}
}
protected override async Task StartListeningAsync()
{
await base.StartListeningAsync();
_motionManager?.StartAccelerometerUpdates(new NSOperationQueue(), async (data, error) =>
{
if (data != null && error == null)
{
await StoreDatumAsync(new LinearAccelerationDatum(DateTimeOffset.UtcNow, data.Acceleration.X, data.Acceleration.Y, data.Acceleration.Z));
}
});
}
protected override async Task StopListeningAsync()
{
await base.StopListeningAsync();
_motionManager?.StopAccelerometerUpdates();
}
}
} | apache-2.0 | C# |
cb9dad286f43e6af34d9df3f1455dbadf57b3cda | Add desktop check and documentation to CapturePhotoConfirmation. | sharpdx/SharpDX,waltdestler/SharpDX,dazerdude/SharpDX,waltdestler/SharpDX,sharpdx/SharpDX,andrewst/SharpDX,andrewst/SharpDX,dazerdude/SharpDX,sharpdx/SharpDX,mrvux/SharpDX,mrvux/SharpDX,andrewst/SharpDX,dazerdude/SharpDX,mrvux/SharpDX,waltdestler/SharpDX,waltdestler/SharpDX,dazerdude/SharpDX | Source/SharpDX.MediaFoundation/CapturePhotoConfirmation.cs | Source/SharpDX.MediaFoundation/CapturePhotoConfirmation.cs | #if DESKTOP_APP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharpDX.MediaFoundation
{
public partial class CapturePhotoConfirmation
{
/// <summary>
/// No documentation.
/// </summary>
/// <param name="notificationCallbackRef">No documentation.</param>
/// <returns>No documentation.</returns>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='IMFCapturePhotoConfirmation::SetPhotoConfirmationCallback']/*"/>
/// <unmanaged>HRESULT IMFCapturePhotoConfirmation::SetPhotoConfirmationCallback([In] IMFAsyncCallback* pNotificationCallback)</unmanaged>
/// <unmanaged-short>IMFCapturePhotoConfirmation::SetPhotoConfirmationCallback</unmanaged-short>
public IAsyncCallback PhotoConfirmationCallback
{
set
{
SetPhotoConfirmationCallback_(AsyncCallbackShadow.ToIntPtr(value));
}
}
}
}
#endif | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharpDX.MediaFoundation
{
public partial class CapturePhotoConfirmation
{
public IAsyncCallback PhotoConfirmationCallback
{
set
{
SetPhotoConfirmationCallback_(AsyncCallbackShadow.ToIntPtr(value));
}
}
}
}
| mit | C# |
661e2936d9258e220e8ec93fe7934450a2f2db7a | Add documentation comment | yfakariya/NLiblet,yfakariya/NLiblet | src/CoreUtilities/Collections/ArraySegmentExtensions.cs | src/CoreUtilities/Collections/ArraySegmentExtensions.cs | #region -- License Terms --
//
// NLiblet
//
// Copyright (C) 2011 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
namespace NLiblet.Collections
{
/// <summary>
/// Extension methods to use <see cref="ArraySegment{T}"/> more easily.
/// </summary>
public static class ArraySegmentExtensions
{
/// <summary>
/// Get <see cref="IEnumerable{T}"/> to enumerent items in the segment.
/// </summary>
/// <typeparam name="T">Type of item.</typeparam>
/// <param name="source"><see cref="ArraySegment{T}"/></param>
/// <returns>
/// <see cref="IEnumerable{T}"/> to enumerent items in the segment.
/// If the segment of <paramref name="source"/> is empty or is not available then empty.
/// </returns>
[Pure]
public static IEnumerable<T> AsEnumerable<T>( this ArraySegment<T> source )
{
Contract.Ensures( Contract.Result<IEnumerable<T>>() != null );
if ( source.Array == null
|| source.Offset < 0
|| source.Array.Length <= source.Offset
|| source.Count <= 0
|| ( source.Array.Length - source.Offset ) < source.Count
)
{
return Empty.Array<T>();
}
else
{
return source.Array.Skip( source.Offset ).Take( source.Count );
}
}
/// <summary>
/// Get item of <see cref="ArraySegment{T}"/> at specified <paramref name="relativeIndex"/>.
/// </summary>
/// <typeparam name="T">Type of item of <see cref="ArraySegment{T}"/>.</typeparam>
/// <param name="source"><see cref="ArraySegment{T}"/>.</param>
/// <param name="relativeIndex">
/// Relative index of the item from <see cref="ArraySegment{T}.Offset"/>.
/// </param>
/// <returns>
/// Item at <paramref name="relativeIndex"/>,
/// thus item at <see cref="ArraySegment{T}.Offset"/> + <paramref name="relativeIndex"/>.
/// </returns>
public static T GetItemAt<T>( this ArraySegment<T> source, int relativeIndex )
{
Contract.Requires<ArgumentException>( source.Array != null );
Contract.Requires<ArgumentOutOfRangeException>( 0 <= relativeIndex );
Contract.Requires<ArgumentOutOfRangeException>( relativeIndex < source.Count );
return source.Array[ source.Offset + relativeIndex ];
}
/// <summary>
/// Set item of <see cref="ArraySegment{T}"/> at specified <paramref name="relativeIndex"/>.
/// </summary>
/// <typeparam name="T">Type of item of <see cref="ArraySegment{T}"/>.</typeparam>
/// <param name="source"><see cref="ArraySegment{T}"/>.</param>
/// <param name="relativeIndex">
/// Relative index of the item from <see cref="ArraySegment{T}.Offset"/>.
/// </param>
/// <param name="value">
/// Value to be set at <paramref name="relativeIndex"/>,
/// thus item at <see cref="ArraySegment{T}.Offset"/> + <paramref name="relativeIndex"/>.
/// </param>
public static void SetItemAt<T>( this ArraySegment<T> source, int relativeIndex, T value )
{
Contract.Requires<ArgumentException>( source.Array != null );
Contract.Requires<ArgumentOutOfRangeException>( 0 <= relativeIndex );
Contract.Requires<ArgumentOutOfRangeException>( relativeIndex < source.Count );
source.Array[ source.Offset + relativeIndex ] = value;
}
}
}
| #region -- License Terms --
//
// NLiblet
//
// Copyright (C) 2011 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
namespace NLiblet.Collections
{
/// <summary>
/// Extension methods to use <see cref="ArraySegment{T}"/> more easily.
/// </summary>
public static class ArraySegmentExtensions
{
/// <summary>
/// Get <see cref="IEnumerable{T}"/> to enumerent items in the segment.
/// </summary>
/// <typeparam name="T">Type of item.</typeparam>
/// <param name="source"><see cref="ArraySegment{T}"/></param>
/// <returns>
/// <see cref="IEnumerable{T}"/> to enumerent items in the segment.
/// If the segment of <paramref name="source"/> is empty or is not available then empty.
/// </returns>
[Pure]
public static IEnumerable<T> AsEnumerable<T>( this ArraySegment<T> source )
{
Contract.Ensures( Contract.Result<IEnumerable<T>>() != null );
if ( source.Array == null
|| source.Offset < 0
|| source.Array.Length <= source.Offset
|| source.Count <= 0
|| ( source.Array.Length - source.Offset ) < source.Count
)
{
return Empty.Array<T>();
}
else
{
return source.Array.Skip( source.Offset ).Take( source.Count );
}
}
}
}
| apache-2.0 | C# |
422aa9eb3d081a4b92b10889904920f5fe4a5753 | remove unused override method ToString. | icsharp/Hangfire.RecurringJobExtensions | src/Hangfire.RecurringJobExtensions/RecurringJobInfo.cs | src/Hangfire.RecurringJobExtensions/RecurringJobInfo.cs | using System;
using System.Collections.Generic;
using System.Reflection;
namespace Hangfire.RecurringJobExtensions
{
/// <summary>
/// It is used to build <see cref="RecurringJob"/>
/// with <see cref="IRecurringJobBuilder.Build(Func{System.Collections.Generic.IEnumerable{RecurringJobInfo}})"/>.
/// </summary>
public class RecurringJobInfo
{
/// <summary>
/// The identifier of the RecurringJob
/// </summary>
public string RecurringJobId { get; set; }
/// <summary>
/// Cron expressions
/// </summary>
public string Cron { get; set; }
/// <summary>
/// TimeZoneInfo
/// </summary>
public TimeZoneInfo TimeZone { get; set; }
/// <summary>
/// Queue name
/// </summary>
public string Queue { get; set; }
/// <summary>
/// Method to execute while <see cref="RecurringJob"/> running.
/// </summary>
public MethodInfo Method { get; set; }
/// <summary>
/// The <see cref="RecurringJob"/> data persisted in storage.
/// </summary>
public IDictionary<string, object> JobData { get; set; }
/// <summary>
/// Whether the <see cref="RecurringJob"/> can be added/updated,
/// default value is true, if false it will be deleted automatically.
/// </summary>
public bool Enable { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
namespace Hangfire.RecurringJobExtensions
{
/// <summary>
/// It is used to build <see cref="RecurringJob"/>
/// with <see cref="IRecurringJobBuilder.Build(Func{System.Collections.Generic.IEnumerable{RecurringJobInfo}})"/>.
/// </summary>
public class RecurringJobInfo
{
/// <summary>
/// The identifier of the RecurringJob
/// </summary>
public string RecurringJobId { get; set; }
/// <summary>
/// Cron expressions
/// </summary>
public string Cron { get; set; }
/// <summary>
/// TimeZoneInfo
/// </summary>
public TimeZoneInfo TimeZone { get; set; }
/// <summary>
/// Queue name
/// </summary>
public string Queue { get; set; }
/// <summary>
/// Method to execute while <see cref="RecurringJob"/> running.
/// </summary>
public MethodInfo Method { get; set; }
/// <summary>
/// The <see cref="RecurringJob"/> data persisted in storage.
/// </summary>
public IDictionary<string, object> JobData { get; set; }
/// <summary>
/// Whether the <see cref="RecurringJob"/> can be added/updated,
/// default value is true, if false it will be deleted automatically.
/// </summary>
public bool Enable { get; set; }
/// <summary>
/// Returns a string that represents {<see cref="Method"/>.DeclaringType.Name}.{<see cref="Method"/>.Name}
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return Method.GetRecurringJobId();
}
}
}
| mit | C# |
424492d20bcf3a84b7c933974cff32db2c0a5dc7 | Update version to 1.71 | tjeerdhans/proxyunsetter | ProxyUnsetter/Properties/AssemblyInfo.cs | ProxyUnsetter/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("ProxyUnsetter")]
[assembly: AssemblyDescription("Tray application that will unset your proxy.\n\nLogo and icons adapted from http://icons8.com/")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("THT")]
[assembly: AssemblyProduct("ProxyUnsetter")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e39399e7-bede-4531-b906-5c3b9e0d7b15")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.71.*")]
| 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("ProxyUnsetter")]
[assembly: AssemblyDescription("Tray application that will unset your proxy.\n\nLogo and icons adapted from http://icons8.com/")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("THT")]
[assembly: AssemblyProduct("ProxyUnsetter")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e39399e7-bede-4531-b906-5c3b9e0d7b15")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.70.*")]
| mit | C# |
4f9e1e4945d002ea20a35855bd2bcdd160aa50eb | Check for new components every one second to handle late loaders | NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu | osu.Game/Skinning/Editor/SkinBlueprintContainer.cs | osu.Game/Skinning/Editor/SkinBlueprintContainer.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets.Edit;
using osu.Game.Screens.Edit.Compose.Components;
using osu.Game.Screens.Play.HUD;
namespace osu.Game.Skinning.Editor
{
public class SkinBlueprintContainer : BlueprintContainer<ISkinnableComponent>
{
private readonly Drawable target;
public SkinBlueprintContainer(Drawable target)
{
this.target = target;
}
protected override void LoadComplete()
{
base.LoadComplete();
checkForComponents();
}
private void checkForComponents()
{
foreach (var c in target.ChildrenOfType<ISkinnableComponent>().ToArray()) AddBlueprintFor(c);
Scheduler.AddDelayed(checkForComponents, 1000);
}
protected override SelectionHandler<ISkinnableComponent> CreateSelectionHandler() => new SkinSelectionHandler();
protected override SelectionBlueprint<ISkinnableComponent> CreateBlueprintFor(ISkinnableComponent component)
=> new SkinBlueprint(component);
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets.Edit;
using osu.Game.Screens.Edit.Compose.Components;
using osu.Game.Screens.Play.HUD;
namespace osu.Game.Skinning.Editor
{
public class SkinBlueprintContainer : BlueprintContainer<ISkinnableComponent>
{
private readonly Drawable target;
public SkinBlueprintContainer(Drawable target)
{
this.target = target;
}
protected override void LoadComplete()
{
base.LoadComplete();
ISkinnableComponent[] components = target.ChildrenOfType<ISkinnableComponent>().ToArray();
foreach (var c in components) AddBlueprintFor(c);
}
protected override SelectionHandler<ISkinnableComponent> CreateSelectionHandler() => new SkinSelectionHandler();
protected override SelectionBlueprint<ISkinnableComponent> CreateBlueprintFor(ISkinnableComponent component)
=> new SkinBlueprint(component);
}
}
| mit | C# |
98e773ab8ad11b077e7d04be93e0dd219d123262 | Remove comment, expanding the hittable area is possible | jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,grokys/Perspex,Perspex/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia | src/Avalonia.Visuals/Rendering/ICustomSimpleHitTest.cs | src/Avalonia.Visuals/Rendering/ICustomSimpleHitTest.cs | using System.Collections.Generic;
using System.Linq;
using Avalonia.VisualTree;
namespace Avalonia.Rendering
{
/// <summary>
/// An interface to allow non-templated controls to customize their hit-testing
/// when using a renderer with a simple hit-testing algorithm without a scene graph,
/// such as <see cref="ImmediateRenderer" />
/// </summary>
public interface ICustomSimpleHitTest
{
bool HitTest(Point point);
}
/// <summary>
/// Allows customization of hit-testing for all renderers.
/// </summary>
public interface ICustomHitTest : ICustomSimpleHitTest
{
}
public static class CustomSimpleHitTestExtensions
{
public static bool HitTestCustom(this IVisual visual, Point point)
=> (visual as ICustomSimpleHitTest)?.HitTest(point) ?? visual.TransformedBounds?.Contains(point) == true;
public static bool HitTestCustom(this IEnumerable<IVisual> children, Point point)
=> children.Any(ctrl => ctrl.HitTestCustom(point));
}
}
| using System.Collections.Generic;
using System.Linq;
using Avalonia.VisualTree;
namespace Avalonia.Rendering
{
/// <summary>
/// An interface to allow non-templated controls to customize their hit-testing
/// when using a renderer with a simple hit-testing algorithm without a scene graph,
/// such as <see cref="ImmediateRenderer" />
/// </summary>
public interface ICustomSimpleHitTest
{
bool HitTest(Point point);
}
/// <summary>
/// Allows customization of hit-testing for all renderers.
/// </summary>
/// <remarks>
/// Note that this interface can only used to make a portion of a control non-hittable, it
/// cannot expand the hittable area of a control.
/// </remarks>
public interface ICustomHitTest : ICustomSimpleHitTest
{
}
public static class CustomSimpleHitTestExtensions
{
public static bool HitTestCustom(this IVisual visual, Point point)
=> (visual as ICustomSimpleHitTest)?.HitTest(point) ?? visual.TransformedBounds?.Contains(point) == true;
public static bool HitTestCustom(this IEnumerable<IVisual> children, Point point)
=> children.Any(ctrl => ctrl.HitTestCustom(point));
}
}
| mit | C# |
05be369bb335f158b697ad58033bf015d8160f22 | Remove unused code | altmann/CherrySeed | src/CherrySeed.Test/Infrastructure/CherrySeedDriver.cs | src/CherrySeed.Test/Infrastructure/CherrySeedDriver.cs | using System;
using System.Collections.Generic;
using CherrySeed.Configuration;
using CherrySeed.EntityDataProvider;
using CherrySeed.Repositories;
using CherrySeed.Test.Mocks;
namespace CherrySeed.Test.Infrastructure
{
public class CherrySeedDriver
{
private ICherrySeeder _cherrySeeder;
public void InitAndSeed(IDataProvider dataProvider, IRepository repository,
Action<ISeederConfigurationBuilder> entitySettings)
{
var config = new CherrySeedConfiguration(cfg =>
{
cfg.WithDataProvider(dataProvider);
cfg.WithRepository(repository);
entitySettings(cfg);
});
_cherrySeeder = config.CreateSeeder();
_cherrySeeder.Seed();
}
public void Clear()
{
_cherrySeeder.Clear();
}
}
} | using System;
using System.Collections.Generic;
using CherrySeed.Configuration;
using CherrySeed.EntityDataProvider;
using CherrySeed.Repositories;
using CherrySeed.Test.Mocks;
namespace CherrySeed.Test.Infrastructure
{
public class CherrySeedDriver
{
private ICherrySeeder _cherrySeeder;
public void InitAndSeed(List<EntityData> data, IRepository repository,
Action<ISeederConfigurationBuilder> entitySettings)
{
var config = new CherrySeedConfiguration(cfg =>
{
cfg.WithDataProvider(new DictionaryDataProvider(data));
cfg.WithRepository(repository);
entitySettings(cfg);
});
var cherrySeeder = config.CreateSeeder();
cherrySeeder.Seed();
}
public void InitAndSeed(IDataProvider dataProvider, IRepository repository,
Action<ISeederConfigurationBuilder> entitySettings)
{
var config = new CherrySeedConfiguration(cfg =>
{
cfg.WithDataProvider(dataProvider);
cfg.WithRepository(repository);
entitySettings(cfg);
});
_cherrySeeder = config.CreateSeeder();
_cherrySeeder.Seed();
}
public void Clear()
{
_cherrySeeder.Clear();
}
}
} | mit | C# |
0920c5e5aeac3a1b2c40c51fabe501bd88536d4b | Fix Typo | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Tabs/WalletManager/ReceiveTabViewModel.cs | WalletWasabi.Gui/Tabs/WalletManager/ReceiveTabViewModel.cs | using ReactiveUI;
using System.Collections.ObjectModel;
using System.Linq;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.KeyManagement;
namespace WalletWasabi.Gui.Tabs.WalletManager
{
internal class ReceiveTabViewModel : WasabiDocumentTabViewModel
{
private string _walletName;
private ObservableCollection<AddressViewModel> _addresses;
private string _label;
public ReceiveTabViewModel(string walletName)
{
_walletName = walletName;
_addresses = new ObservableCollection<AddressViewModel>();
InitializeAddresses();
GenerateCommand = ReactiveCommand.Create(() =>
{
var newKey = Global.WalletService.KeyManager.GenerateNewKey(Label, KeyState.Clean, false);
Addresses.Add(new AddressViewModel(newKey));
Label = null;
}, this.WhenAnyValue(x => x.Label, label => !string.IsNullOrWhiteSpace(label)));
}
private void InitializeAddresses()
{
_addresses?.Clear();
var keys = Global.WalletService.KeyManager.GetKeys(KeyState.Clean, false);
foreach (var key in keys)
{
_addresses.Add(new AddressViewModel(key));
}
}
public override string Title
{
get => "Receive: " + _walletName;
set
{
}
}
public ObservableCollection<AddressViewModel> Addresses
{
get { return _addresses; }
set { this.RaiseAndSetIfChanged(ref _addresses, value); }
}
public string Label
{
get { return _label; }
set { this.RaiseAndSetIfChanged(ref _label, value); }
}
public ReactiveCommand GenerateCommand { get; }
}
}
| using ReactiveUI;
using System.Collections.ObjectModel;
using System.Linq;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.KeyManagement;
namespace WalletWasabi.Gui.Tabs.WalletManager
{
internal class ReceiveTabViewModel : WasabiDocumentTabViewModel
{
private string _walletName;
private ObservableCollection<AddressViewModel> _addresses;
private string _label;
public ReceiveTabViewModel(string walletName)
{
_walletName = walletName;
_addresses = new ObservableCollection<AddressViewModel>();
InitialiseAddresses();
GenerateCommand = ReactiveCommand.Create(() =>
{
var newKey = Global.WalletService.KeyManager.GenerateNewKey(Label, KeyState.Clean, false);
Addresses.Add(new AddressViewModel(newKey));
Label = null;
}, this.WhenAnyValue(x => x.Label, label => !string.IsNullOrWhiteSpace(label)));
}
private void InitialiseAddresses()
{
_addresses?.Clear();
var keys = Global.WalletService.KeyManager.GetKeys(KeyState.Clean, false);
foreach (var key in keys)
{
_addresses.Add(new AddressViewModel(key));
}
}
public override string Title
{
get => "Receive: " + _walletName;
set
{
}
}
public ObservableCollection<AddressViewModel> Addresses
{
get { return _addresses; }
set { this.RaiseAndSetIfChanged(ref _addresses, value); }
}
public string Label
{
get { return _label; }
set { this.RaiseAndSetIfChanged(ref _label, value); }
}
public ReactiveCommand GenerateCommand { get; }
}
}
| mit | C# |
a9df190c5a03c3897d1aafe1b5c244b7b871791b | Increment build -> v0.1.2 | awseward/Bugsnag.NET,awseward/Bugsnag.NET | Bugsnag.NET/Properties/AssemblyInfo.cs | Bugsnag.NET/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("Bugsnag.NET")]
[assembly: AssemblyProduct("Bugsnag.NET")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: InternalsVisibleTo("Bugsnag.NET.Tests")]
// 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("72121f80-f8ac-4be5-b914-4f65faffc1cc")]
// 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.2.0")]
[assembly: AssemblyFileVersion("0.1.2.0")]
[assembly: AssemblyInformationalVersion("0.1.2")]
| 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("Bugsnag.NET")]
[assembly: AssemblyProduct("Bugsnag.NET")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: InternalsVisibleTo("Bugsnag.NET.Tests")]
// 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("72121f80-f8ac-4be5-b914-4f65faffc1cc")]
// 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.1.0")]
[assembly: AssemblyFileVersion("0.1.1.0")]
[assembly: AssemblyInformationalVersion("0.1.1")]
| mit | C# |
78cb708a02f79fc0c0746e8b259ff91780a79889 | Bump framework version to 1.3.4 | hotelde/regtesting | RegTesting.Tests.Framework/Properties/AssemblyInfo.cs | RegTesting.Tests.Framework/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("RegTesting.Tests.Framework")]
[assembly: AssemblyDescription("A test framework for tests with selenium.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HOTELDE AG")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2012-2015 HOTELDE AG, Apache License, Version 2.0")]
[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("a7e6a771-5f9d-425a-a401-3a5f4c71b270")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyFileVersion("1.3.4.0")]
[assembly: AssemblyInformationalVersion("1.3.4.0")]
// Change AssemblyVersion for breaking api changes
// http://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin
[assembly: AssemblyVersion("1.3.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("RegTesting.Tests.Framework")]
[assembly: AssemblyDescription("A test framework for tests with selenium.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HOTELDE AG")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2012-2015 HOTELDE AG, Apache License, Version 2.0")]
[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("a7e6a771-5f9d-425a-a401-3a5f4c71b270")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyFileVersion("1.3.3.0")]
[assembly: AssemblyInformationalVersion("1.3.3.0")]
// Change AssemblyVersion for breaking api changes
// http://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin
[assembly: AssemblyVersion("1.3.0.0")] | apache-2.0 | C# |
af3fdc12ed3e51a83a80cb3b0eae87dfb9c9079d | remove floaty death and reimu keeps momentum when hit by knife | Barleytree/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare | Assets/Microgames/KnifeDodge/Scripts/KnifeDodgeReimu.cs | Assets/Microgames/KnifeDodge/Scripts/KnifeDodgeReimu.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnifeDodgeReimu : MonoBehaviour {
public float speed = 1; // speed in meters per second
public float animSpeed = 1f;
public float animSpeedStopped = 0.25f;
public float killLaunchSpeed = 20.0f;
public GameObject leftBound;
public GameObject rightBound;
bool bIsKilled;
Vector3 previousMoveDir;
// Use this for initialization
void Start () {
bIsKilled = false;
}
void Update(){
Vector3 moveDir = Vector3.zero;
if (!bIsKilled) {
moveDir.x = Input.GetAxisRaw ("Horizontal"); // get result of AD keys in X
moveDir.z = 0;
previousMoveDir = moveDir;
} else
{
transform.position += previousMoveDir * speed * Time.deltaTime;
return;
}
if (moveDir == Vector3.zero) {
GetComponent<Animator> ().speed = animSpeedStopped;
GetComponent<Animator> ().Play ("Standing");
} else {
GetComponent<Animator> ().speed = animSpeed;
GetComponent<Animator> ().Play ("Moving");
}
// move this object at frame rate independent speed:
float boundryColliderSize = leftBound.GetComponent<BoxCollider2D>().size.x;
if (moveDir.x > 0
&& transform.position.x < rightBound.GetComponent<Transform> ().position.x) {
transform.position += moveDir * speed * Time.deltaTime;
}
if ((transform.position.x > leftBound.GetComponent<Transform> ().position.x)
&& moveDir.x < 0) {
transform.position += moveDir * speed * Time.deltaTime;
}
}
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "KnifeDodgeHazard") {
Kill ();
}
}
public void Kill() {
bIsKilled = true;
GetComponent<BoxCollider2D> ().size = new Vector2 (0, 0);
transform.GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, killLaunchSpeed);
transform.GetComponent<Rigidbody2D> ().angularVelocity = 80.0f;
MicrogameController.instance.setVictory (false, true);
// To implement later
CameraShake.instance.setScreenShake (.15f);
CameraShake.instance.shakeCoolRate = .5f;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnifeDodgeReimu : MonoBehaviour {
public float speed = 1; // speed in meters per second
public float animSpeed = 1f;
public float animSpeedStopped = 0.25f;
public float killLaunchSpeed = 15.0f;
public GameObject leftBound;
public GameObject rightBound;
bool bIsKilled;
// Use this for initialization
void Start () {
bIsKilled = false;
}
void Update(){
Vector3 moveDir = Vector3.zero;
if (!bIsKilled) {
moveDir.x = Input.GetAxisRaw ("Horizontal"); // get result of AD keys in X
moveDir.z = 0;
}
if (moveDir == Vector3.zero) {
GetComponent<Animator> ().speed = animSpeedStopped;
GetComponent<Animator> ().Play ("Standing");
} else {
GetComponent<Animator> ().speed = animSpeed;
GetComponent<Animator> ().Play ("Moving");
}
// move this object at frame rate independent speed:
float boundryColliderSize = leftBound.GetComponent<BoxCollider2D>().size.x;
if (moveDir.x > 0
&& transform.position.x < rightBound.GetComponent<Transform> ().position.x) {
transform.position += moveDir * speed * Time.deltaTime;
}
if ((transform.position.x > leftBound.GetComponent<Transform> ().position.x)
&& moveDir.x < 0) {
transform.position += moveDir * speed * Time.deltaTime;
}
}
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "KnifeDodgeHazard") {
Kill ();
MicrogameController.instance.setVictory (false, true);
}
}
public void Kill() {
bIsKilled = true;
GetComponent<BoxCollider2D> ().size = new Vector2 (0, 0);
transform.GetComponent<Rigidbody2D> ().velocity = new Vector2 (0, killLaunchSpeed);
transform.GetComponent<Rigidbody2D> ().angularVelocity = 80.0f;
MicrogameController.instance.setVictory (false, true);
// To implement later
CameraShake.instance.setScreenShake (.15f);
CameraShake.instance.shakeCoolRate = .5f;
}
}
| mit | C# |
1e35f688de23e59f3385c0f54b87a5ead6d5907f | remove unneeded code | StefanoFiumara/Harry-Potter-Unity | Assets/Editor/HarryPotterExtensions/CardProcessing.cs | Assets/Editor/HarryPotterExtensions/CardProcessing.cs | using System.Linq;
using HarryPotterUnity.Cards.PlayRequirements;
using HarryPotterUnity.DeckGeneration.Requirements;
using JetBrains.Annotations;
using UnityEditor;
using UnityEngine;
namespace HarryPotterExtensions
{
public static class CardProcessing
{
/// <summary>
/// Template for applying changes to all card objects in the library
/// </summary>
[UsedImplicitly]
//[MenuItem("Harry Potter TCG/Find Requirement")]
public static void DoWork()
{
var assetFolderPaths = AssetDatabase.GetAllAssetPaths().Where(path => path.EndsWith(".prefab") && path.Contains("/Cards/"));
foreach (string path in assetFolderPaths)
{
var obj = (GameObject)AssetDatabase.LoadAssetAtPath(path, typeof(GameObject));
//if (obj.GetComponent<DeckDoesNotContainCardWithNameRequirement>() != null)
//{
// Debug.Log(obj.name);
//}
}
}
}
}
| using System.Linq;
using HarryPotterUnity.Cards.PlayRequirements;
using HarryPotterUnity.DeckGeneration.Requirements;
using JetBrains.Annotations;
using UnityEditor;
using UnityEngine;
namespace HarryPotterExtensions
{
public static class CardProcessing
{
/// <summary>
/// Template for applying changes to all card objects in the library
/// </summary>
[UsedImplicitly]
//[MenuItem("Harry Potter TCG/Find Requirement")]
public static void DoWork()
{
var assetFolderPaths = AssetDatabase.GetAllAssetPaths().Where(path => path.EndsWith(".prefab") && path.Contains("/Cards/"));
foreach (string path in assetFolderPaths)
{
var obj = (GameObject)AssetDatabase.LoadAssetAtPath(path, typeof(GameObject));
if (obj.GetComponent<DeckDoesNotContainCardWithNameRequirement>() != null)
{
Debug.Log(obj.name);
}
}
}
}
}
| mit | C# |
34b96a482dc27039caba48a5a41d8b60d903985b | Update AzureStorageAlias.cs | RadioSystems/Cake.AzureStorage | Cake.AzureStorage/AzureStorageAlias.cs | Cake.AzureStorage/AzureStorageAlias.cs | using System;
using Cake.Core;
using Cake.Core.Annotations;
using Cake.Core.IO;
namespace Cake.AzureStorage {
[CakeAliasCategory("AzureStorage")]
public static class AzureStorageAlias {
[CakeMethodAlias]
public static void UploadFileToBlob(this ICakeContext context, AzureStorageSettings settings, FilePath fileToUpload) {
if (context == null) {
throw new ArgumentNullException(nameof(context));
}
AzureStorage.UploadFileToBlob(settings, fileToUpload);
}
}
}
| using System;
using Cake.Core;
using Cake.Core.Annotations;
using Cake.Core.IO;
namespace Cake.AzureStorage {
[CakeAliasCategory("AzureStorage")]
public static class AzureStorageAlias {
[CakeMethodAlias]
[CakeNamespaceImport("Microsoft.WindowsAzure")]
public static void UploadFileToBlob(this ICakeContext context, AzureStorageSettings settings, FilePath fileToUpload) {
if (context == null) {
throw new ArgumentNullException(nameof(context));
}
AzureStorage.UploadFileToBlob(settings, fileToUpload);
}
}
}
| apache-2.0 | C# |
78baf6d5d303139b341d85d95907d04f963f44fb | Implement proper history in HearthWindow | theAprel/OptionsDisplay | OptionsDisplay/HearthWindow.cs | OptionsDisplay/HearthWindow.cs | using Hearthstone_Deck_Tracker;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace OptionsDisplay
{
class HearthWindow : InfoWindow
{
private HearthstoneTextBlock info;
private HearthstoneTextBlock history;
public HearthWindow()
{
info = new HearthstoneTextBlock();
history = new HearthstoneTextBlock();
foreach (HearthstoneTextBlock htb in new HearthstoneTextBlock[] { info, history }) {
htb.Text = "";
htb.FontSize = 12;
}
var canvas = Hearthstone_Deck_Tracker.API.Core.OverlayCanvas;
var fromTop = canvas.Height / 2;
var fromLeft = canvas.Width / 2;
Canvas.SetTop(history, fromTop);
Canvas.SetLeft(history, fromLeft);
Canvas.SetTop(info, fromTop + 20);
Canvas.SetLeft(info, fromLeft);
canvas.Children.Add(info);
canvas.Children.Add(history);
}
public void AppendWindowText(string text)
{
info.Text = info.Text + text;
}
public void ClearAll()
{
info.Text = "";
history.Text = "";
}
public void MoveToHistory()
{
history.Text = info.Text;
info.Text = "";
}
public void SetWindowText(string text)
{
info.Text = text;
}
}
}
| using Hearthstone_Deck_Tracker;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace OptionsDisplay
{
class HearthWindow : InfoWindow
{
private HearthstoneTextBlock info;
public HearthWindow()
{
info = new HearthstoneTextBlock();
info.Text = "";
info.FontSize = 12;
var canvas = Hearthstone_Deck_Tracker.API.Core.OverlayCanvas;
var fromTop = canvas.Height / 2;
var fromLeft = canvas.Width / 2;
Canvas.SetTop(info, fromTop);
Canvas.SetLeft(info, fromLeft);
canvas.Children.Add(info);
}
public void AppendWindowText(string text)
{
info.Text = info.Text + text;
}
public void ClearAll()
{
info.Text = "";
}
public void MoveToHistory()
{
info.Text = "";
}
public void SetWindowText(string text)
{
info.Text = text;
}
}
}
| agpl-3.0 | C# |
72126e33cf397195ee6678827b2c75169b4dca99 | Update Program.cs | vishipayyallore/CSharp-DotNet-Core-Samples | LearningDesignPatterns/Source/Alogithms/LogicPrograms/Program.cs | LearningDesignPatterns/Source/Alogithms/LogicPrograms/Program.cs | using LogicPrograms.Interfaces;
using LogicPrograms.Logics;
using static System.Console;
namespace LogicPrograms
{
class Program
{
static void Main(string[] args)
{
IMonthNames monthNames = new MonthNames();
monthNames.DisplayMonthNames();
//------------------------------------------------------------------------------------------
var arrayItems = new int[] { 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0 };
var left = 0;
var right = arrayItems.Length - 1;
for(var index=0; index<arrayItems.Length; index++)
{
if(arrayItems[left] > arrayItems[right])
{
var temp = arrayItems[left];
arrayItems[left] = arrayItems[right];
arrayItems[right] = temp;
left++;
right--;
}
}
ISortBinaryArray sortBinaryArray = new SortBinaryArray();
sortBinaryArray.SortArray(arrayItems);
//------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------
IMath math = new Math();
Write("\n\nEnter a number for finding Factorial: ");
if (int.TryParse(ReadLine(), out int number))
{
var factorial = math.GetFactorial(number);
WriteLine($"Factorial: {factorial}");
}
//------------------------------------------------------------------------------------------
WriteLine("\n\nPress any key ...");
ReadKey();
}
}
}
| using LogicPrograms.Interfaces;
using LogicPrograms.Logics;
using static System.Console;
namespace LogicPrograms
{
class Program
{
static void Main(string[] args)
{
//------------------------------------------------------------------------------------------
var arrayItems = new int[] { 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0 };
var left = 0;
var right = arrayItems.Length - 1;
for(var index=0; index<arrayItems.Length; index++)
{
if(arrayItems[left] > arrayItems[right])
{
var temp = arrayItems[left];
arrayItems[left] = arrayItems[right];
arrayItems[right] = temp;
left++;
right--;
}
}
ISortBinaryArray sortBinaryArray = new SortBinaryArray();
sortBinaryArray.SortArray(arrayItems);
//------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------
IMath math = new Math();
Write("\n\nEnter a number for finding Factorial: ");
if (int.TryParse(ReadLine(), out int number))
{
var factorial = math.GetFactorial(number);
WriteLine($"Factorial: {factorial}");
}
//------------------------------------------------------------------------------------------
WriteLine("\n\nPress any key ...");
ReadKey();
}
}
}
| apache-2.0 | C# |
c578030a55792ee902735afe73b76331064b8a7a | Remove some methods to try get element, as if an element is not found, Direct2D only returns a zero pointer with a S_Ok hresult | sharpdx/SharpDX,sharpdx/SharpDX,sharpdx/SharpDX | Source/SharpDX.Direct2D1/SvgDocument.cs | Source/SharpDX.Direct2D1/SvgDocument.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharpDX.Direct2D1
{
public partial class SvgDocument
{
/// <summary>
/// Finds an svg element by id
/// </summary>
/// <param name="id">Id to lookup for</param>
/// <returns>SvgElement if found, null otherwise</returns>
public SvgElement FindElementById(string id)
{
SharpDX.Result __result__;
SvgElement svgElement;
__result__ = TryFindElementById_(id, out svgElement);
__result__.CheckError();
return svgElement;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharpDX.Direct2D1
{
public partial class SvgDocument
{
/// <summary>
/// Finds an svg element by id
/// </summary>
/// <param name="id">Id to lookup for</param>
/// <returns>SvgElement</returns>
public SvgElement FindElementById(string id)
{
SharpDX.Result __result__;
SvgElement svgElement;
__result__ = TryFindElementById_(id, out svgElement);
__result__.CheckError();
return svgElement;
}
/// <summary>
/// Try to find an element by id
/// </summary>
/// <param name="id">id to search for</param>
/// <param name="svgElement">When this method completes, contains the relevant element (if applicable)</param>
/// <returns>true if element has been found, false otherwise</returns>
public bool TryFindElementById(string id, out SvgElement svgElement)
{
SharpDX.Result __result__;
__result__ = TryFindElementById_(id, out svgElement);
return __result__.Code >= 0;
}
}
}
| mit | C# |
9c643e83df2fe9bca7b8cd6526f4003881fdedb7 | Fix #1 | farity/farity | CSharp.Functional/Enumerable.cs | CSharp.Functional/Enumerable.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace CSharp.Functional
{
public static partial class F
{
public static IEnumerable<int> Range(int start, int end)
=> start > end ? Enumerable.Empty<int>() : Enumerable.Range(start, end - start + 1);
public static IList<T> ToList<T>(IEnumerable<T> source) => source.ToList();
public static IEnumerable<T> Reverse<T>(IEnumerable<T> source) => source.Reverse();
public static IEnumerable<T> Drop<T>(int count, IEnumerable<T> source) => source.Skip(count);
public static IEnumerable<T> Take<T>(int count, IEnumerable<T> source) => source.Take(count);
public static IEnumerable<T> Sort<T>(IEnumerable<T> source) => source.OrderBy(x => x);
public static IEnumerable<T> Unique<T>(IEnumerable<T> source) => source.Distinct();
public static IEnumerable<T> SkipUntil<T>(int index, IEnumerable<T> source)
{
if (!(source is IReadOnlyList<T>))
{
var i = 0;
foreach (var item in source)
if (index >= i++) yield return item;
}
var list = (IReadOnlyList<T>) source;
for (var i = index; i < list.Count; i++)
yield return list[i];
}
public static IEnumerable<T> Filter<T>(Func<T, bool> predicate, IEnumerable<T> source)
=> source.Where(predicate);
public static IEnumerable<T> DefaultTo<T>(T value, IEnumerable<T> source) => source.DefaultIfEmpty(value);
public static T First<T>(IEnumerable<T> source) => source.First();
public static T Last<T>(IEnumerable<T> source) => source.Last();
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace CSharp.Functional
{
public static partial class F
{
public static IEnumerable<int> Range(int start, int end) => Enumerable.Range(start, end - start + 1);
public static IList<T> ToList<T>(IEnumerable<T> source) => source.ToList();
public static IEnumerable<T> Reverse<T>(IEnumerable<T> source) => source.Reverse();
public static IEnumerable<T> Drop<T>(int count, IEnumerable<T> source) => source.Skip(count);
public static IEnumerable<T> Take<T>(int count, IEnumerable<T> source) => source.Take(count);
public static IEnumerable<T> Sort<T>(IEnumerable<T> source) => source.OrderBy(x => x);
public static IEnumerable<T> Unique<T>(IEnumerable<T> source) => source.Distinct();
public static IEnumerable<T> SkipUntil<T>(int index, IEnumerable<T> source)
{
if (!(source is IReadOnlyList<T>))
{
var i = 0;
foreach (var item in source)
if (index >= i++) yield return item;
}
var list = (IReadOnlyList<T>) source;
for (var i = index; i < list.Count; i++)
yield return list[i];
}
public static IEnumerable<T> Filter<T>(Func<T, bool> predicate, IEnumerable<T> source)
=> source.Where(predicate);
public static IEnumerable<T> DefaultTo<T>(T value, IEnumerable<T> source) => source.DefaultIfEmpty(value);
public static T First<T>(IEnumerable<T> source) => source.First();
public static T Last<T>(IEnumerable<T> source) => source.Last();
}
} | mit | C# |
3911f771183d6b2efc9f8c308ba905e001fb5cd7 | Add LICENSE | shiena/DominoesWithBricks | Assets/Scripts/BrickGenerator.cs | Assets/Scripts/BrickGenerator.cs | /*
* Copyright 2017 Mitsuhiro Koga
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BrickGenerator : MonoBehaviour
{
public GameObject brick;
public Vector3 StartPosition;
public int Count = 29;
// Use this for initialization
void Start()
{
for (int index = 0; index < Count; index++)
{
Instantiate(brick, StartPosition + Vector3.left * index, Quaternion.identity);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BrickGenerator : MonoBehaviour
{
public GameObject brick;
public Vector3 StartPosition;
public int Count = 29;
// Use this for initialization
void Start()
{
for (int index = 0; index < Count; index++)
{
Instantiate(brick, StartPosition + Vector3.left * index, Quaternion.identity);
}
}
}
| apache-2.0 | C# |
e8ec943fba2eb2d25e9d9a16418dfffe4daa7672 | fix missing factory setter | dgarage/NBXplorer,dgarage/NBXplorer | NBXplorer.Client/NBXplorerNetwork.cs | NBXplorer.Client/NBXplorerNetwork.cs | using NBitcoin;
using NBXplorer.DerivationStrategy;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace NBXplorer
{
public class NBXplorerNetwork
{
public NBXplorerNetwork(INetworkSet networkSet, NetworkType networkType,
DerivationStrategyFactory derivationStrategyFactory = null)
{
NBitcoinNetwork = networkSet.GetNetwork(networkType);
CryptoCode = networkSet.CryptoCode;
DefaultSettings = NBXplorerDefaultSettings.GetDefaultSettings(networkType);
DerivationStrategyFactory = derivationStrategyFactory;
}
public Network NBitcoinNetwork
{
get;
private set;
}
public int MinRPCVersion
{
get;
internal set;
}
public string CryptoCode
{
get;
private set;
}
public NBXplorerDefaultSettings DefaultSettings
{
get;
private set;
}
public DerivationStrategy.DerivationStrategyFactory DerivationStrategyFactory
{
get;
internal set;
}
public virtual BitcoinAddress CreateAddress(DerivationStrategyBase derivationStrategy, KeyPath keyPath, Script scriptPubKey)
{
return scriptPubKey.GetDestinationAddress(NBitcoinNetwork);
}
public bool SupportCookieAuthentication
{
get;
internal set;
} = true;
private Serializer _Serializer;
public Serializer Serializer
{
get
{
_Serializer = _Serializer ?? new Serializer(this);
return _Serializer;
}
}
public JsonSerializerSettings JsonSerializerSettings
{
get
{
return Serializer.Settings;
}
}
public TimeSpan ChainLoadingTimeout
{
get;
set;
} = TimeSpan.FromMinutes(15);
public TimeSpan ChainCacheLoadingTimeout
{
get;
set;
} = TimeSpan.FromSeconds(30);
/// <summary>
/// Minimum blocks to keep if pruning is activated
/// </summary>
public int MinBlocksToKeep
{
get; set;
} = 288;
public KeyPath CoinType { get; internal set; }
public override string ToString()
{
return CryptoCode.ToString();
}
public virtual ExplorerClient CreateExplorerClient(Uri uri)
{
return new ExplorerClient(this, uri);
}
}
}
| using NBitcoin;
using NBXplorer.DerivationStrategy;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace NBXplorer
{
public class NBXplorerNetwork
{
public NBXplorerNetwork(INetworkSet networkSet, NetworkType networkType,
DerivationStrategyFactory derivationStrategyFactory = null)
{
NBitcoinNetwork = networkSet.GetNetwork(networkType);
CryptoCode = networkSet.CryptoCode;
DefaultSettings = NBXplorerDefaultSettings.GetDefaultSettings(networkType);
}
public Network NBitcoinNetwork
{
get;
private set;
}
public int MinRPCVersion
{
get;
internal set;
}
public string CryptoCode
{
get;
private set;
}
public NBXplorerDefaultSettings DefaultSettings
{
get;
private set;
}
public DerivationStrategy.DerivationStrategyFactory DerivationStrategyFactory
{
get;
internal set;
}
public virtual BitcoinAddress CreateAddress(DerivationStrategyBase derivationStrategy, KeyPath keyPath, Script scriptPubKey)
{
return scriptPubKey.GetDestinationAddress(NBitcoinNetwork);
}
public bool SupportCookieAuthentication
{
get;
internal set;
} = true;
private Serializer _Serializer;
public Serializer Serializer
{
get
{
_Serializer = _Serializer ?? new Serializer(this);
return _Serializer;
}
}
public JsonSerializerSettings JsonSerializerSettings
{
get
{
return Serializer.Settings;
}
}
public TimeSpan ChainLoadingTimeout
{
get;
set;
} = TimeSpan.FromMinutes(15);
public TimeSpan ChainCacheLoadingTimeout
{
get;
set;
} = TimeSpan.FromSeconds(30);
/// <summary>
/// Minimum blocks to keep if pruning is activated
/// </summary>
public int MinBlocksToKeep
{
get; set;
} = 288;
public KeyPath CoinType { get; internal set; }
public override string ToString()
{
return CryptoCode.ToString();
}
public virtual ExplorerClient CreateExplorerClient(Uri uri)
{
return new ExplorerClient(this, uri);
}
}
}
| mit | C# |
d4910e009bc26ae5e8b69b36d391e054f981985f | Bump version number | AnshulYADAV007/Lean,Jay-Jay-D/LeanSTP,AnshulYADAV007/Lean,redmeros/Lean,QuantConnect/Lean,jameschch/Lean,kaffeebrauer/Lean,tomhunter-gh/Lean,StefanoRaggi/Lean,kaffeebrauer/Lean,Jay-Jay-D/LeanSTP,AnshulYADAV007/Lean,QuantConnect/Lean,jameschch/Lean,kaffeebrauer/Lean,young-zhang/Lean,tomhunter-gh/Lean,andrewhart098/Lean,redmeros/Lean,QuantConnect/Lean,Jay-Jay-D/LeanSTP,AlexCatarino/Lean,andrewhart098/Lean,Jay-Jay-D/LeanSTP,StefanoRaggi/Lean,jameschch/Lean,AnshulYADAV007/Lean,AlexCatarino/Lean,AlexCatarino/Lean,young-zhang/Lean,tomhunter-gh/Lean,Mendelone/forex_trading,StefanoRaggi/Lean,andrewhart098/Lean,Mendelone/forex_trading,Mendelone/forex_trading,kaffeebrauer/Lean,kaffeebrauer/Lean,andrewhart098/Lean,Mendelone/forex_trading,AlexCatarino/Lean,AnshulYADAV007/Lean,jameschch/Lean,jameschch/Lean,Jay-Jay-D/LeanSTP,QuantConnect/Lean,JKarathiya/Lean,young-zhang/Lean,redmeros/Lean,JKarathiya/Lean,redmeros/Lean,JKarathiya/Lean,StefanoRaggi/Lean,JKarathiya/Lean,StefanoRaggi/Lean,tomhunter-gh/Lean,young-zhang/Lean | Common/Properties/SharedAssemblyInfo.cs | Common/Properties/SharedAssemblyInfo.cs | using System.Reflection;
// common assembly attributes
[assembly: AssemblyDescription("Lean Algorithmic Trading Engine - QuantConnect.com")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyCompany("QuantConnect")]
[assembly: AssemblyTrademark("QuantConnect")]
[assembly: AssemblyVersion("2.3.0.1")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif | using System.Reflection;
// common assembly attributes
[assembly: AssemblyDescription("Lean Algorithmic Trading Engine - QuantConnect.com")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyCompany("QuantConnect")]
[assembly: AssemblyTrademark("QuantConnect")]
[assembly: AssemblyVersion("2.2.0.2")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif | apache-2.0 | C# |
bcf6cfbfae9230fd77ccbd49cb71786c04ced58e | add comments. | stangelandcl/Actors | Actors.Example/Program.cs | Actors.Example/Program.cs | using System;
namespace Actors.Example
{
class MainClass
{
public static void Main (string[] args)
{
// a node is like an erlang node. it is like a VM. like its own world
var node = new Node();
// listen on port
var server = node.Listen("127.0.0.1", 18222);
// add actor, an actor is like an object. it can send & receive messages
node.Add(new EchoActor("echo"));
// create a node
var n2 = new Node();
// connect to an endpoint which is in this case a separate node.
// so now we can route messages from actors in this node to the
// other node
using(var conn = n2.Connect("127.0.0.1", 18222)){
// send async but receive sync. send to localhost/echo which happens to
// be in the other node
var result = n2.SendReceive<string>("localhost/echo", "echo", "hi");
// print response
Console.WriteLine(result);
// DynamicProxy wraps a remote actor.
var echo = n2.GetProxy("localhost/echo");
// this is the same as SendReceive<string>("localhost/echo", "echo", "hey dude");
var r2 = echo.echo("hey dude");
// print response
Console.WriteLine(r2);
} // close the connection and remove from n2. Now there is no route to the first node and the echo actor
// TODO: set default ports so given a computer name we can try to connect to a few ports if someone
// tries to send a message to one of those actors then we could avoid this explicit connection and
// let the node/VM handle it.
//TODO: change router to directly put messages in mailbox using function without going through tcp sockets
// if the other actor is in the same node. This would make it feasible to use actors for some things inside a single
// process/node/program
}
}
}
| using System;
namespace Actors.Example
{
class MainClass
{
public static void Main (string[] args)
{
var node = new Node();
var server = node.Listen("127.0.0.1", 18222);
node.Add(new EchoActor("echo"));
var n2 = new Node();
var conn = n2.Connect("127.0.0.1", 18222);
var result = n2.SendReceive<string>("localhost/echo", "echo", "hi");
Console.WriteLine(result);
var echo = n2.GetProxy("localhost/echo");
var r2 = echo.echo("hey dude");
Console.WriteLine(r2);
}
}
}
| mit | C# |
04ea8089e72101b1d3a5b7d86b2a62a7a10f5572 | Introduce song duration vriable; Remove old comments; Remove file extension from filename; | HakuTeam/SoundWizard | Playground/IO/Command/OpenCommand.cs | Playground/IO/Command/OpenCommand.cs | namespace Playground.IO.Command
{
using System;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Win32;
using Microsoft.WindowsAPICodePack.Shell;
using Playground.Core;
using Playground.Interfaces;
public class OpenCommand : Command, IExecutable
{
public OpenCommand(MediaElement mediaElement, ListBox PlayList)
: base(mediaElement, PlayList)
{
}
public void Execute()
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = true;
dlg.DefaultExt = ".mp3";
dlg.Filter = "All Supported Audio | *.mp3; *.wma | MP3s | *.mp3 | WMAs | *.wma";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string[] filename = dlg.FileNames;
foreach (var songPath in filename)
{
ShellFile songFile = ShellFile.FromFilePath(songPath);
int extensionDotIndex = songFile.Name.LastIndexOf('.');
string songName = songFile.Name.Substring(0, extensionDotIndex);
// System.Media.Duration is in 100nS (hundreds of nanoseconds) => 1sec = 10 000 000 100nS
int songDuraitonSeconds = (int)(songFile.Properties.System.Media.Duration.Value / 10000000);
TimeSpan songDuration = TimeSpan.FromSeconds(songDuraitonSeconds);
Song song = new Song(songName, songDuration, songPath);
PlayList.Items.Add(song);
}
}
}
}
} | namespace Playground.IO.Command
{
using System;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Win32;
using Microsoft.WindowsAPICodePack.Shell;
using Playground.Core;
using Playground.Interfaces;
public class OpenCommand : Command, IExecutable
{
public OpenCommand(MediaElement mediaElement, ListBox PlayList)
: base(mediaElement, PlayList)
{
}
public void Execute()
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = true;
dlg.DefaultExt = ".mp3";
dlg.Filter = "All Supported Audio | *.mp3; *.wma | MP3s | *.mp3 | WMAs | *.wma";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string[] filename = dlg.FileNames;
foreach (var songPath in filename)
{
ShellFile songFile = ShellFile.FromFilePath(songPath);
int nameStartIndex = songPath.LastIndexOf('\\') + 1;
int extensionDotIndex = songPath.LastIndexOf('.');
int nameLength = extensionDotIndex - nameStartIndex;
string songName = songFile.Name;
//Mp3FileReader getSongDuration = new Mp3FileReader(item);
//TimeSpan time = getSongDuration.TotalTime;
//string duration = string.Format("{0:00}:{1:00}:{2:00}", (int)time.TotalHours, time.Minutes, time.Seconds);
TimeSpan songDuration = new TimeSpan(0, 0, 0, (int)(songFile.Properties.System.Media.Duration.Value / 10000000));
Song song = new Song(songName, songDuration, songPath);
PlayList.Items.Add(song);
}
}
}
}
} | mit | C# |
f3d501a397eb523ad98abf2b1a22ffe7fe1cab49 | add sample for multiline text entry | sevoku/xwt,iainx/xwt,directhex/xwt,cra0zy/xwt,antmicro/xwt,mminns/xwt,hamekoz/xwt,mminns/xwt,steffenWi/xwt,akrisiun/xwt,mono/xwt,hwthomas/xwt,residuum/xwt,lytico/xwt,TheBrainTech/xwt | TestApps/Samples/Samples/TextEntries.cs | TestApps/Samples/Samples/TextEntries.cs | //
// TextEntries.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// 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 Xwt;
namespace Samples
{
public class TextEntries: VBox
{
public TextEntries ()
{
TextEntry te1 = new TextEntry ();
PackStart (te1);
Label la = new Label ();
PackStart (la);
te1.Changed += delegate {
la.Text = "Text: " + te1.Text;
};
PackStart (new Label ("Entry with small font"));
TextEntry te2 = new TextEntry ();
te2.Font = te2.Font.WithScaledSize (0.5);
PackStart (te2);
PackStart (new Label ("Entry with placeholder text"));
TextEntry te3 = new TextEntry ();
te3.PlaceholderText = "Placeholder text";
PackStart (te3);
PackStart (new Label ("Entry with no frame"));
TextEntry te4 = new TextEntry();
te4.ShowFrame = false;
PackStart (te4);
TextEntry te5 = new TextEntry ();
te5.Text = "I should be centered!";
te5.TextAlignment = Alignment.Center;
PackStart (te5);
TextEntry te6 = new TextEntry ();
te6.Text = "I should have" + Environment.NewLine + "multiple lines!";
te6.MultiLine = true;
PackStart (te6);
}
}
}
| //
// TextEntries.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2011 Xamarin Inc
//
// 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 Xwt;
namespace Samples
{
public class TextEntries: VBox
{
public TextEntries ()
{
TextEntry te1 = new TextEntry ();
PackStart (te1);
Label la = new Label ();
PackStart (la);
te1.Changed += delegate {
la.Text = "Text: " + te1.Text;
};
PackStart (new Label ("Entry with small font"));
TextEntry te2 = new TextEntry ();
te2.Font = te2.Font.WithScaledSize (0.5);
PackStart (te2);
PackStart (new Label ("Entry with placeholder text"));
TextEntry te3 = new TextEntry ();
te3.PlaceholderText = "Placeholder text";
PackStart (te3);
PackStart (new Label ("Entry with no frame"));
TextEntry te4 = new TextEntry();
te4.ShowFrame = false;
PackStart (te4);
TextEntry te5 = new TextEntry ();
te5.Text = "I should be centered!";
te5.TextAlignment = Alignment.Center;
PackStart (te5);
}
}
}
| mit | C# |
830d65e4abb798ef809509db8ce55e0358f8a7f4 | Put test result back | rippo/CQSMediatorPattern | Cqs.Mediator.Pattern.Mvc/App_Start/RouteConfig.cs | Cqs.Mediator.Pattern.Mvc/App_Start/RouteConfig.cs | using System.Web.Mvc;
using System.Web.Routing;
namespace Cqs.Mediator.Pattern.Mvc
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"HomePage",
"",
new { controller = "Home", action = "Index", id = "" }
);
//Home contoller action methods
routes.MapRoute(
"Contact",
"contact",
new { controller = "Home", action = "Contact" }
);
routes.MapRoute(
"test",
"test",
new { controller = "Home", action = "Test" }
);
//controller routes, need to define them...
routes.MapRoute(
"Login",
"Login/{action}/{id}",
new { controller = "Login", action = "Index", id = "" }
);
//... if you have other controller, specify the name here
routes.MapRoute(
"Sitemap",
"sitemap.xml",
new { controller = "Home", action = "SiteMapXml" }
);
routes.MapRoute(
"Content",
"{*id}",
new { controller = "Home", action = "Cms", id = "" }
);
}
}
}
| using System.Web.Mvc;
using System.Web.Routing;
namespace Cqs.Mediator.Pattern.Mvc
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"HomePage",
"",
new { controller = "Home", action = "Index", id = "" }
);
//Home contoller action methods
routes.MapRoute(
"Contact",
"contact",
new { controller = "Home", action = "Contact" }
);
//controller routes, need to define them...
routes.MapRoute(
"Login",
"Login/{action}/{id}",
new { controller = "Login", action = "Index", id = "" }
);
//... if you have other controller, specify the name here
routes.MapRoute(
"Sitemap",
"sitemap.xml",
new { controller = "Home", action = "SiteMapXml" }
);
routes.MapRoute(
"Content",
"{*id}",
new { controller = "Home", action = "Cms", id = "" }
);
}
}
}
| mit | C# |
1941c2a54d120aaaf111ed98f878aa58ebec8d16 | clean up dead code | icraftsoftware/BizTalk.Factory,icraftsoftware/BizTalk.Factory,icraftsoftware/BizTalk.Factory | src/BizTalk.Unit/Unit/Resources/ResourceManager.cs | src/BizTalk.Unit/Unit/Resources/ResourceManager.cs | #region Copyright & License
// Copyright © 2012 - 2019 François Chabot
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Xml.Xsl;
namespace Be.Stateless.BizTalk.Unit.Resources
{
public static class ResourceManager
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static Stream Load(string name)
{
return GetResourceManagerImpl().Load(name);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static T Load<T>(string name, Func<Stream, T> deserializer)
{
return GetResourceManagerImpl().Load(name, deserializer);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string LoadString(string name)
{
return GetResourceManagerImpl().LoadString(name);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static XslCompiledTransform LoadTransform(string name)
{
return GetResourceManagerImpl().LoadTransform(name);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string LoadXmlString(string name)
{
return GetResourceManagerImpl().LoadXmlString(name);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static IResourceManager GetResourceManagerImpl()
{
var resourceManagerCallerFrame = new StackFrame(2);
return new ResourceManagerImpl(resourceManagerCallerFrame.GetMethod().DeclaringType);
}
}
}
| #region Copyright & License
// Copyright © 2012 - 2019 François Chabot
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Xml.Xsl;
namespace Be.Stateless.BizTalk.Unit.Resources
{
public static class ResourceManager
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static Stream Load(string name)
{
return GetResourceManagerImpl().Load(name);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static T Load<T>(string name, Func<Stream, T> deserializer)
{
return GetResourceManagerImpl().Load(name, deserializer);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string LoadString(string name)
{
return GetResourceManagerImpl().LoadString(name);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static XslCompiledTransform LoadTransform(string name)
{
return GetResourceManagerImpl().LoadTransform(name);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string LoadXmlString(string name)
{
return GetResourceManagerImpl().LoadXmlString(name);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static T Load<T>(Assembly assembly, string name, Func<Stream, T> deserializer)
{
return GetResourceManagerImpl().Load<T>(name, deserializer);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static IResourceManager GetResourceManagerImpl()
{
var resourceManagerCallerFrame = new StackFrame(2);
return new ResourceManagerImpl(resourceManagerCallerFrame.GetMethod().DeclaringType);
}
}
}
| apache-2.0 | C# |
a0ad8fa3f524fbdd09cfdef3417666a427ae530b | sort the renderLayers, just in case | prime31/Nez,eumario/Nez,prime31/Nez,prime31/Nez,ericmbernier/Nez,Blucky87/Nez | Nez-PCL/Graphics/Renderers/RenderLayerRenderer.cs | Nez-PCL/Graphics/Renderers/RenderLayerRenderer.cs | using System;
using Microsoft.Xna.Framework.Graphics;
namespace Nez
{
/// <summary>
/// Renderer that only renders a single renderLayer. Useful to keep UI rendering separate from the rest of the game when used in conjunction
/// with a RenderLayerRenderer
/// </summary>
public class RenderLayerRenderer : Renderer
{
public int[] renderLayers;
public RenderLayerRenderer( int renderOrder, params int[] renderLayers ) : base( renderOrder, null )
{
Array.Sort( renderLayers );
this.renderLayers = renderLayers;
}
public override void render( Scene scene )
{
var cam = camera ?? scene.camera;
beginRender( cam );
for( var i = 0; i < renderLayers.Length; i++ )
{
var renderables = scene.renderableComponents.componentsWithRenderLayer( renderLayers[i] );
for( var j = 0; j < renderables.Count; j++ )
{
var renderable = renderables[j];
if( renderable.enabled )
renderAfterStateCheck( renderable, cam );
}
}
if( shouldDebugRender && Core.debugRenderEnabled )
debugRender( scene, cam );
endRender();
}
}
}
| using System;
using Microsoft.Xna.Framework.Graphics;
namespace Nez
{
/// <summary>
/// Renderer that only renders a single renderLayer. Useful to keep UI rendering separate from the rest of the game when used in conjunction
/// with a RenderLayerRenderer
/// </summary>
public class RenderLayerRenderer : Renderer
{
public int[] renderLayers;
public RenderLayerRenderer( int renderOrder, params int[] renderLayers ) : base( renderOrder, null )
{
this.renderLayers = renderLayers;
}
public override void render( Scene scene )
{
var cam = camera ?? scene.camera;
beginRender( cam );
for( var i = 0; i < renderLayers.Length; i++ )
{
var renderables = scene.renderableComponents.componentsWithRenderLayer( renderLayers[i] );
for( var j = 0; j < renderables.Count; j++ )
{
var renderable = renderables[j];
if( renderable.enabled )
renderAfterStateCheck( renderable, cam );
}
}
if( shouldDebugRender && Core.debugRenderEnabled )
debugRender( scene, cam );
endRender();
}
}
}
| mit | C# |
c52792c5785aea5a2321e44613095d919b2c37c8 | test bobe | charlesfarmer/sylvain,charlesfarmer/sylvain,charlesfarmer/sylvain | ProjetSylvain/ControlCoordonées/ControleLogin.cs | ProjetSylvain/ControlCoordonées/ControleLogin.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ControlCoordonées
{
public partial class ControleLogin : UserControl
{
#region constructor
public ControleLogin()
{
InitializeComponent();
}
#endregion
#region properties
public string TxtIdentifiant
{
get;
set;
}
public string TxtPassword
{
get;
set;
}
#endregion
#region events
public event EventHandler<EventConnexion> ClickBtnConnexion;
#endregion
#region event handlers
private void btnConnexion_Click(object sender, EventArgs e)
{
string identifiant = this.TxtIdentifiant;
string password = this.TxtPassword;
if (ClickBtnConnexion != null)
{
ClickBtnConnexion(this, new EventConnexion(identifiant, password));
}
}
#endregion
}
public class EventConnexion : EventArgs
{//bobe
public string Identifiant { get; private set; }
public string Password { get; private set; }
public EventConnexion(string identifiant, string password)
{
this.Identifiant = identifiant;
this.Password = password;
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ControlCoordonées
{
public partial class ControleLogin : UserControl
{
#region constructor
public ControleLogin()
{
InitializeComponent();
}
#endregion
#region properties
public string TxtIdentifiant
{
get;
set;
}
public string TxtPassword
{
get;
set;
}
#endregion
#region events
public event EventHandler<EventConnexion> ClickBtnConnexion;
#endregion
#region event handlers
private void btnConnexion_Click(object sender, EventArgs e)
{
string identifiant = this.TxtIdentifiant;
string password = this.TxtPassword;
if (ClickBtnConnexion != null)
{
ClickBtnConnexion(this, new EventConnexion(identifiant, password));
}
}
#endregion
}
public class EventConnexion : EventArgs
{
public string Identifiant { get; private set; }
public string Password { get; private set; }
public EventConnexion(string identifiant, string password)
{
this.Identifiant = identifiant;
this.Password = password;
}
}
}
| unlicense | C# |
43c4e4c5ba7de98a813d30e2bdb87f4081c20723 | Update demo | sunkaixuan/SqlSugar | Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Config.cs | Src/Asp.NetCore2/SqlSeverTest/PgSqlTest/Config.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
/// <summary>
/// Setting up the database name does not require you to create the database
/// 设置好数据库名不需要你去手动建库
/// </summary>
public class Config
{
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString = "PORT=5432;DATABASE=SqlSugar4xTest;HOST=localhost;PASSWORD=jhl52771;USER ID=postgres";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString2 = "PORT=5432;DATABASE=SqlSugar4xTest2;HOST=localhost;PASSWORD=jhl52771;USER ID=postgres";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString3 = "PORT=5432;DATABASE=SqlSugar4xTest3;HOST=localhost;PASSWORD=jhl52771;USER ID=postgres";
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
/// <summary>
/// Setting up the database name does not require you to create the database
/// 设置好数据库名不需要你去手动建库
/// </summary>
public class Config
{
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString = "PORT=5432;DATABASE=SqlSugar4xTest;HOST=localhost;PASSWORD=haosql;USER ID=postgres";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString2 = "PORT=5432;DATABASE=SqlSugar4xTest2;HOST=localhost;PASSWORD=haosql;USER ID=postgres";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString3 = "PORT=5432;DATABASE=SqlSugar4xTest3;HOST=localhost;PASSWORD=haosql;USER ID=postgres";
}
}
| apache-2.0 | C# |
ea31af7a56045c81f01207f2e9bc493a17d25aa4 | Add ChessGame parameter to IsValidDestination | ProgramFOX/Chess.NET | ChessDotNet/ChessPiece.cs | ChessDotNet/ChessPiece.cs | namespace ChessDotNet
{
public abstract class ChessPiece
{
public abstract Player Owner
{
get;
set;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
return true;
if (obj == null || GetType() != obj.GetType())
return false;
ChessPiece piece1 = this;
ChessPiece piece2 = (ChessPiece)obj;
return piece1.Owner == piece2.Owner;
}
public override int GetHashCode()
{
return new { Piece = GetFenCharacter(), Owner }.GetHashCode();
}
public static bool operator ==(ChessPiece piece1, ChessPiece piece2)
{
if (ReferenceEquals(piece1, piece2))
return true;
if ((object)piece1 == null || (object)piece2 == null)
return false;
return piece1.Equals(piece2);
}
public static bool operator !=(ChessPiece piece1, ChessPiece piece2)
{
if (ReferenceEquals(piece1, piece2))
return false;
if ((object)piece1 == null || (object)piece2 == null)
return true;
return !piece1.Equals(piece2);
}
public abstract string GetFenCharacter();
public abstract bool IsValidDestination(Position from, Position to, ChessGame game);
}
}
| namespace ChessDotNet
{
public abstract class ChessPiece
{
public abstract Player Owner
{
get;
set;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
return true;
if (obj == null || GetType() != obj.GetType())
return false;
ChessPiece piece1 = this;
ChessPiece piece2 = (ChessPiece)obj;
return piece1.Owner == piece2.Owner;
}
public override int GetHashCode()
{
return new { Piece = GetFenCharacter(), Owner }.GetHashCode();
}
public static bool operator ==(ChessPiece piece1, ChessPiece piece2)
{
if (ReferenceEquals(piece1, piece2))
return true;
if ((object)piece1 == null || (object)piece2 == null)
return false;
return piece1.Equals(piece2);
}
public static bool operator !=(ChessPiece piece1, ChessPiece piece2)
{
if (ReferenceEquals(piece1, piece2))
return false;
if ((object)piece1 == null || (object)piece2 == null)
return true;
return !piece1.Equals(piece2);
}
public abstract string GetFenCharacter();
public abstract bool IsValidDestination(Position from, Position to);
}
}
| mit | C# |
7367dc92ffc9b2a593c2952cef972603f850e091 | fix in nuget restore "syntax" | vvvvpm/vpm,vvvvpm/vpm,vvvvpm/vpm | vpdb/velcrome/Message/github.mdreffix.csx | vpdb/velcrome/Message/github.mdreffix.csx | GitClone("https://github.com/microdee/vvvv-Message.git", Pack.TempDir);
BuildSolution(
2013,
Pack.TempDir + "\\src\\vvvv-Message.sln", "Release|" + VVVV.Architecture,
restorenugets = true
);
CopyDir(
Pack.TempDir + "\\build\\" + VVVV.Architecture + "\\Release",
VVVV.Dir + "\\packs\\vvvv-Message"
);
CopyDir(
Pack.TempDir + "\\build\\AnyCPU\\Release",
VVVV.Dir + "\\packs\\vvvv-Message"
);
| GitClone("https://github.com/microdee/vvvv-Message.git", Pack.TempDir);
BuildSolution(2013, Pack.TempDir + "\\src\\vvvv-Message.sln", "Release|" + VVVV.Architecture, true);
CopyDir(
Pack.TempDir + "\\build\\" + VVVV.Architecture + "\\Release",
VVVV.Dir + "\\packs\\vvvv-Message"
);
CopyDir(
Pack.TempDir + "\\build\\AnyCPU\\Release",
VVVV.Dir + "\\packs\\vvvv-Message"
);
| mit | C# |
3498401eb321b1ab3e887f38892098c7b01c12c6 | bump version | samiy-xx/keysndr,samiy-xx/keysndr,samiy-xx/keysndr | KeySndr.Base/Properties/AssemblyInfo.cs | KeySndr.Base/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("KeySndr.Base")]
[assembly: AssemblyDescription("Base library for KeySndr server")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("blockz3d.com")]
[assembly: AssemblyProduct("KeySndr.Base")]
[assembly: AssemblyCopyright("Copyright © Sami Ylönen 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9413db07-5510-46a4-82b0-38485af52792")]
// 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.*")]
| 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("KeySndr.Base")]
[assembly: AssemblyDescription("Base library for KeySndr server")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("blockz3d.com")]
[assembly: AssemblyProduct("KeySndr.Base")]
[assembly: AssemblyCopyright("Copyright © Sami Ylönen 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9413db07-5510-46a4-82b0-38485af52792")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.8.9.*")]
| mit | C# |
11f63603850c911d37f8ad200cd9cae4325a59cf | Check for header before removing it | RonaldValkenburg/AutoHeader | Source/Options/RemoveHeaderOption.cs | Source/Options/RemoveHeaderOption.cs | using System;
using System.IO;
using System.Linq;
namespace AutoHeader.Options
{
public class RemoveHeaderOption : Option
{
public override void Execute()
{
Console.WriteLine("Execute \'RemoveHeaderOption\': {0}", Arg);
if (!Directory.Exists(Arg))
{
throw new ExecutionException(string.Format("Directory does not exist: {0}", Arg));
}
RemoveHeaderFromFilesInDirectory(Arg);
}
private void RemoveHeaderFromFilesInDirectory(string directory)
{
foreach (var filePath in Directory.GetFiles(directory).Where(f => f.EndsWith(".cs")))
{
RemoveHeaderFromFile(filePath);
}
foreach (var subDir in Directory.GetDirectories(directory))
{
RemoveHeaderFromFilesInDirectory(subDir);
}
}
private void RemoveHeaderFromFile(string filePath)
{
string header;
using (var streamReader = new StreamReader("HeaderTemplate.txt"))
{
header = streamReader.ReadToEnd();
}
string fileContent;
using (var streamReader = new StreamReader(filePath))
{
fileContent = streamReader.ReadToEnd();
}
if (fileContent.Length >= header.Length)
{
var fileHeader = fileContent.Substring(0, header.Length);
if (fileHeader == header)
{
fileContent = fileContent.Substring(header.Length);
using (var stream = new StreamWriter(filePath, false))
{
stream.Write(fileContent);
}
}
}
}
}
} | using System;
using System.IO;
using System.Linq;
namespace AutoHeader.Options
{
public class RemoveHeaderOption : Option
{
public override void Execute()
{
Console.WriteLine("Execute \'RemoveHeaderOption\': {0}", Arg);
if (!Directory.Exists(Arg))
{
throw new ExecutionException(string.Format("Directory does not exist: {0}", Arg));
}
RemoveHeaderFromFilesInDirectory(Arg);
}
private void RemoveHeaderFromFilesInDirectory(string directory)
{
foreach (var filePath in Directory.GetFiles(directory).Where(f => f.EndsWith(".cs")))
{
RemoveHeaderFromFile(filePath);
}
foreach (var subDir in Directory.GetDirectories(directory))
{
RemoveHeaderFromFilesInDirectory(subDir);
}
}
private void RemoveHeaderFromFile(string filePath)
{
var tempFilePath = GetTempFileName(filePath);
File.Move(filePath, tempFilePath);
string header;
using (var streamReader = new StreamReader("HeaderTemplate.txt"))
{
header = streamReader.ReadToEnd();
}
string fileContent;
using (var streamReader = new StreamReader(tempFilePath))
{
fileContent = streamReader.ReadToEnd();
}
fileContent = fileContent.Substring(header.Length);
using (var stream = new StreamWriter(filePath, false))
{
stream.Write(fileContent);
}
File.Delete(tempFilePath);
}
private static string GetTempFileName(string filePath)
{
var fileName = Path.GetFileName(filePath);
var path = Path.GetDirectoryName(filePath) ?? string.Empty;
var tempFilePath = Path.Combine(path, string.Format("~{0}", fileName));
return tempFilePath;
}
}
} | mit | C# |
0e97c8fc27ec69d4d9ddd46ceff29ca21540bfa7 | Change color to be more visible | k-t/SharpHaven | MonoHaven.Client/UI/Widgets/Progress.cs | MonoHaven.Client/UI/Widgets/Progress.cs | using System.Drawing;
using MonoHaven.Graphics;
using MonoHaven.Graphics.Text;
namespace MonoHaven.UI.Widgets
{
public class Progress : Widget
{
private readonly TextLine textLine;
private int value;
public Progress(Widget parent) : base(parent)
{
textLine = new TextLine(Fonts.LabelText);
textLine.TextColor = Color.Yellow;
textLine.TextAlign = TextAlign.Center;
textLine.SetWidth(75);
Resize(textLine.Width, 20);
}
public int Value
{
get { return value; }
set
{
this.value = value;
textLine.Clear();
textLine.Append(string.Format("{0}%", value));
}
}
protected override void OnDraw(DrawingContext dc)
{
dc.Draw(textLine, 0, 0);
}
protected override void OnDispose()
{
if (textLine != null)
textLine.Dispose();
}
}
}
| using System.Drawing;
using MonoHaven.Graphics;
using MonoHaven.Graphics.Text;
namespace MonoHaven.UI.Widgets
{
public class Progress : Widget
{
private readonly TextLine textLine;
private int value;
public Progress(Widget parent) : base(parent)
{
textLine = new TextLine(Fonts.LabelText);
textLine.TextColor = Color.DeepPink;
textLine.TextAlign = TextAlign.Center;
textLine.SetWidth(75);
Resize(textLine.Width, 20);
}
public int Value
{
get { return value; }
set
{
this.value = value;
textLine.Clear();
textLine.Append(string.Format("{0}%", value));
}
}
protected override void OnDraw(DrawingContext dc)
{
dc.Draw(textLine, 0, 0);
}
protected override void OnDispose()
{
if (textLine != null)
textLine.Dispose();
}
}
}
| mit | C# |
3b530fb1fc5a048fae76a561203e196bc2db68d1 | Clean Scratchpad | KirillShlenskiy/Kirkin,KirillShlenskiy/Kirkin,KirillShlenskiy/Kirkin | src/Kirkin.Tests/Scratchpad.cs | src/Kirkin.Tests/Scratchpad.cs | using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Kirkin.Logging;
using Xunit;
using Xunit.Abstractions;
namespace Kirkin.Tests
{
public class Scratchpad
{
private readonly Logger Output;
public Scratchpad(ITestOutputHelper output)
{
Output = Logger
.Create(output.WriteLine)
.WithFormatters(EntryFormatter.TimestampNonEmptyEntries());
}
}
} | using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Kirkin.Logging;
using Kirkin.Reflection;
using Xunit;
using Xunit.Abstractions;
namespace Kirkin.Tests
{
public class Scratchpad
{
private readonly Logger Output;
public Scratchpad(ITestOutputHelper output)
{
Output = Logger
.Create(output.WriteLine)
.WithFormatters(EntryFormatter.TimestampNonEmptyEntries());
}
[Fact]
public void GetRightFactoryWithActivator()
{
PropertyInfo property = typeof(string).GetProperty("Length");
for (int i = 0; i < 200000; i++)
{
IPropertyAccessorFactory factory = (IPropertyAccessorFactory)Activator.CreateInstance(
typeof(PropertyAccessorFactory<,>).MakeGenericType(property.DeclaringType, property.PropertyType)
);
IPropertyAccessor accessor = factory.Create(property);
}
}
//[Fact]
//public void GetRightFactoryWithConstructorInfo()
//{
// PropertyInfo property = typeof(string).GetProperty("Length");
// for (int i = 0; i < 200000; i++)
// {
// IPropertyAccessor accessor = (IPropertyAccessor)typeof(PropertyAccessor<,>)
// .MakeGenericType(property.DeclaringType, property.PropertyType)
// .GetConstructor(new[] { typeof(PropertyInfo) })
// .Invoke(new[] { property });
// Assert.NotNull(accessor);
// }
//}
interface IPropertyAccessorFactory
{
IPropertyAccessor Create(PropertyInfo property);
}
sealed class PropertyAccessorFactory<TTarget, TProperty>
: IPropertyAccessorFactory
{
public IPropertyAccessor Create(PropertyInfo property)
{
return new PropertyAccessor<TTarget, TProperty>(property);
}
}
}
} | mit | C# |
62db6a53c29100b98b1575efab5a3ac121472016 | Add AssemblyHash.CreatePublicKeyToken() method | 0xd4d/dnlib,Arthur2e5/dnlib,ZixiangBoy/dnlib,modulexcite/dnlib,kiootic/dnlib,yck1509/dnlib,jorik041/dnlib,picrap/dnlib,ilkerhalil/dnlib | dot10/dotNET/Types/AssemblyHash.cs | dot10/dotNET/Types/AssemblyHash.cs | using System.Security.Cryptography;
namespace dot10.dotNET.Types {
/// <summary>
/// Hashes some data according to a <see cref="AssemblyHashAlgorithm"/>
/// </summary>
static class AssemblyHash {
/// <summary>
/// Hash data
/// </summary>
/// <remarks>If <paramref name="hashAlgo"/> is an unsupported hash algorithm, then
/// <see cref="AssemblyHashAlgorithm.SHA1"/> will be used as the hash algorithm.</remarks>
/// <param name="data">The data</param>
/// <param name="hashAlgo">The algorithm to use</param>
/// <returns>Hashed data or null if <paramref name="data"/> was <c>null</c></returns>
public static byte[] Hash(byte[] data, AssemblyHashAlgorithm hashAlgo) {
if (data == null)
return null;
switch (hashAlgo) {
case AssemblyHashAlgorithm.MD5:
using (var hash = MD5.Create())
return hash.ComputeHash(data);
case AssemblyHashAlgorithm.None:
case AssemblyHashAlgorithm.MD2:
case AssemblyHashAlgorithm.MD4:
case AssemblyHashAlgorithm.SHA1:
case AssemblyHashAlgorithm.MAC:
case AssemblyHashAlgorithm.SSL3_SHAMD5:
case AssemblyHashAlgorithm.HMAC:
case AssemblyHashAlgorithm.TLS1PRF:
case AssemblyHashAlgorithm.HASH_REPLACE_OWF:
default:
using (var hash = SHA1.Create())
return hash.ComputeHash(data);
case AssemblyHashAlgorithm.SHA_256:
using (var hash = SHA256.Create())
return hash.ComputeHash(data);
case AssemblyHashAlgorithm.SHA_384:
using (var hash = SHA384.Create())
return hash.ComputeHash(data);
case AssemblyHashAlgorithm.SHA_512:
using (var hash = SHA512.Create())
return hash.ComputeHash(data);
}
}
/// <summary>
/// Creates a public key token from the hash of some <paramref name="publicKeyData"/>
/// </summary>
/// <remarks>A public key is hashed, and the last 8 bytes of the hash, in reverse
/// order, is used as the public key token</remarks>
/// <param name="publicKeyData">The data</param>
/// <param name="hashAlgo">The algorithm to use</param>
/// <returns>A new <see cref="PublicKeyToken"/> instance</returns>
public static PublicKeyToken CreatePublicKeyToken(byte[] publicKeyData, AssemblyHashAlgorithm hashAlgo) {
if (publicKeyData == null)
return new PublicKeyToken();
var hash = Hash(publicKeyData, hashAlgo);
byte[] pkt = new byte[8];
for (int i = 0; i < pkt.Length && i < hash.Length; i++)
pkt[i] = hash[hash.Length - i - 1];
return new PublicKeyToken(pkt);
}
}
}
| using System.Security.Cryptography;
namespace dot10.dotNET.Types {
/// <summary>
/// Hashes some data according to a <see cref="AssemblyHashAlgorithm"/>
/// </summary>
static class AssemblyHash {
/// <summary>
/// Hash data
/// </summary>
/// <remarks>If <paramref name="hashAlgo"/> is an unsupported hash algorithm, then
/// <see cref="AssemblyHashAlgorithm.SHA1"/> will be used as the hash algorithm.</remarks>
/// <param name="data">The data</param>
/// <param name="hashAlgo">The algorithm to use</param>
/// <returns>Hashed data or null if <paramref name="data"/> was <c>null</c></returns>
public static byte[] Hash(byte[] data, AssemblyHashAlgorithm hashAlgo) {
if (data == null)
return null;
switch (hashAlgo) {
case AssemblyHashAlgorithm.MD5:
using (var hash = MD5.Create())
return hash.ComputeHash(data);
case AssemblyHashAlgorithm.None:
case AssemblyHashAlgorithm.MD2:
case AssemblyHashAlgorithm.MD4:
case AssemblyHashAlgorithm.SHA1:
case AssemblyHashAlgorithm.MAC:
case AssemblyHashAlgorithm.SSL3_SHAMD5:
case AssemblyHashAlgorithm.HMAC:
case AssemblyHashAlgorithm.TLS1PRF:
case AssemblyHashAlgorithm.HASH_REPLACE_OWF:
default:
using (var hash = SHA1.Create())
return hash.ComputeHash(data);
case AssemblyHashAlgorithm.SHA_256:
using (var hash = SHA256.Create())
return hash.ComputeHash(data);
case AssemblyHashAlgorithm.SHA_384:
using (var hash = SHA384.Create())
return hash.ComputeHash(data);
case AssemblyHashAlgorithm.SHA_512:
using (var hash = SHA512.Create())
return hash.ComputeHash(data);
}
}
}
}
| mit | C# |
7857ae6b8d0a6db86312e618b16d8e409a1fcd79 | Use Pascal case | mstrother/BmpListener | BmpListener/Serialization/BmpSerializer.cs | BmpListener/Serialization/BmpSerializer.cs | using BmpListener.Bmp;
using BmpListener.Serialization.JsonConverters;
using BmpListener.Serialization.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace BmpListener.Serialization
{
public static class BmpSerializer
{
static BmpSerializer()
{
JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
//settings.ContractResolver = new ConverterContractResolver();
settings.Converters.Add(new PathAttributeJsonConverter());
settings.Converters.Add(new IPAddressJsonConverter());
settings.Converters.Add(new IPAddrPrefixJsonConverter());
settings.Converters.Add(new BmpPeerHeaderJsonConverter());
settings.Converters.Add(new BgpUpdateConverter());
settings.Converters.Add(new BgpOpenMessageJsonConverter());
settings.Converters.Add(new PeerUpNotificationJsonConverter());
settings.Converters.Add(new StringEnumConverter(true));
return settings;
};
}
public static string ToJson(BmpMessage message)
{
var jsonMsg = JsonMessage.Create(message);
var json = JsonConvert.SerializeObject(jsonMsg);
return json;
}
}
}
| using BmpListener.Bmp;
using BmpListener.Serialization.JsonConverters;
using BmpListener.Serialization.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace BmpListener.Serialization
{
public static class BmpSerializer
{
static BmpSerializer()
{
JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
//settings.ContractResolver = new ConverterContractResolver();
settings.Converters.Add(new PathAttributeJsonConverter());
settings.Converters.Add(new IPAddressJsonConverter());
settings.Converters.Add(new IPAddrPrefixJsonConverter());
settings.Converters.Add(new BmpPeerHeaderJsonConverter());
settings.Converters.Add(new BgpUpdateConverter());
settings.Converters.Add(new BgpOpenMessageJsonConverter());
settings.Converters.Add(new PeerUpNotificationJsonConverter());
settings.Converters.Add(new StringEnumConverter(true));
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
return settings;
};
}
public static string ToJson(BmpMessage message)
{
var jsonMsg = JsonMessage.Create(message);
var json = JsonConvert.SerializeObject(jsonMsg);
return json;
}
}
}
| mit | C# |
717c5bc74c6afed98e8e8044dcf194f878a86998 | Update code | sakapon/Samples-2014,sakapon/Samples-2014,sakapon/Samples-2014 | RxSample/MouseRx2Wpf/MainWindow.xaml.cs | RxSample/MouseRx2Wpf/MainWindow.xaml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MouseRx2Wpf
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public static readonly DependencyProperty DeltaProperty =
DependencyProperty.Register(nameof(Delta), typeof(Vector?), typeof(MainWindow), new PropertyMetadata(null, (d, e) => ((MainWindow)d).DeltaChanged()));
public Vector? Delta
{
get { return (Vector?)GetValue(DeltaProperty); }
set { SetValue(DeltaProperty, value); }
}
public static readonly DependencyProperty OrientationProperty =
DependencyProperty.Register(nameof(Orientation), typeof(string), typeof(MainWindow), new PropertyMetadata(null));
public string Orientation
{
get { return (string)GetValue(OrientationProperty); }
private set { SetValue(OrientationProperty, value); }
}
public MainWindow()
{
InitializeComponent();
var events = new EventsExtension<Window>(this);
events.MouseDrag.Subscribe(d => d.Subscribe(v => Delta = v, () => Delta = null));
}
void DeltaChanged()
{
Orientation = Delta.IfNotNull(ToOrientation);
}
const double π = Math.PI;
static readonly string[] orientationSymbols = new[] { "→", "↘", "↓", "↙", "←", "↖", "↑", "↗" };
static readonly double zoneAngleRange = 2 * π / orientationSymbols.Length;
static string ToOrientation(Vector v)
{
var angle = 2 * π + Math.Atan2(v.Y, v.X);
var zone = (int)Math.Round(angle / zoneAngleRange) % orientationSymbols.Length;
return orientationSymbols[zone];
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MouseRx2Wpf
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public static readonly DependencyProperty DeltaProperty =
DependencyProperty.Register(nameof(Delta), typeof(Vector?), typeof(MainWindow), new PropertyMetadata(null, (d, e) => ((MainWindow)d).DeltaChanged()));
public Vector? Delta
{
get { return (Vector?)GetValue(DeltaProperty); }
set { SetValue(DeltaProperty, value); }
}
public static readonly DependencyProperty OrientationProperty =
DependencyProperty.Register(nameof(Orientation), typeof(string), typeof(MainWindow), new PropertyMetadata(null));
public string Orientation
{
get { return (string)GetValue(OrientationProperty); }
private set { SetValue(OrientationProperty, value); }
}
public MainWindow()
{
InitializeComponent();
var events = new EventsExtension<Window>(this);
events.MouseDrag.Subscribe(d => d.Subscribe(v => Delta = v, () => Delta = null));
}
void DeltaChanged()
{
Orientation = Delta == null ? null : ToOrientation(Delta.Value);
}
const double π = Math.PI;
static readonly string[] orientationSymbols = new[] { "→", "↘", "↓", "↙", "←", "↖", "↑", "↗" };
static readonly double zoneAngleRange = 2 * π / orientationSymbols.Length;
static string ToOrientation(Vector v)
{
var angle = 2 * π + Math.Atan2(v.Y, v.X);
var zone = (int)Math.Round(angle / zoneAngleRange) % orientationSymbols.Length;
return orientationSymbols[zone];
}
}
}
| mit | C# |
cd297a4e52b76418819808aab6691d1e34c44365 | Make sure Expiration field is also indexed in the db | CIR2000/Amica.vNext.SimpleCache | SimpleCache.Core/CacheElement.cs | SimpleCache.Core/CacheElement.cs | using System;
using SQLite;
namespace Amica.vNext.SimpleCache
{
class CacheElement
{
[PrimaryKey]
public string Key { get; set; }
[Indexed]
public string TypeName { get; set; }
public byte[] Value { get; set; }
[Indexed]
public DateTime? Expiration { get; set; }
public DateTimeOffset CreatedAt { get; set; }
}
}
| using System;
using SQLite;
namespace Amica.vNext.SimpleCache
{
class CacheElement
{
[PrimaryKey]
public string Key { get; set; }
[Indexed]
public string TypeName { get; set; }
public byte[] Value { get; set; }
public DateTime? Expiration { get; set; }
public DateTimeOffset CreatedAt { get; set; }
}
}
| bsd-3-clause | C# |
1998c91825164a28d18cd8f471683eda53cd4bc3 | Implement ManagerCollection.GetManager<T>() | tainicom/Aether | Source/Engine/Data/ManagerCollection.cs | Source/Engine/Data/ManagerCollection.cs | #region License
// Copyright 2015 Kastellanos Nikolaos
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System.Collections.ObjectModel;
using tainicom.Aether.Elementary.Managers;
namespace tainicom.Aether.Engine.Data
{
public partial class ManagerCollection : Collection<IAetherManager>
{
private AetherEngine _engine;
public ManagerCollection(AetherEngine engine)
{
this._engine = engine;
}
public IAetherManager this[string name]
{
get
{
for (int i = 0; i < this.Count; i++)
{
if (this[i].Name == name)
return this[i];
}
return null;
}
}
public TManager GetManager<TManager>() where TManager : class, IAetherManager
{
var itemType = typeof(TManager);
for (int i = 0; i < this.Count; i++)
{
if (this[i].GetType() == itemType)
return (TManager)this[i];
}
return null;
}
protected override void InsertItem(int index, IAetherManager item)
{
// check if manager allready in use.
var itemType = item.GetType();
foreach (var manager in this)
{
if (manager.GetType().Equals(itemType))
throw new AetherException(string.Format("Manager of type {0} allready in use.", itemType.Name));
}
base.InsertItem(index, item);
}
}
}
| #region License
// Copyright 2015 Kastellanos Nikolaos
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System.Collections.ObjectModel;
using tainicom.Aether.Elementary.Managers;
namespace tainicom.Aether.Engine.Data
{
public partial class ManagerCollection : Collection<IAetherManager>
{
private AetherEngine _engine;
public ManagerCollection(AetherEngine engine)
{
this._engine = engine;
}
public IAetherManager this[string name]
{
get
{
for (int i = 0; i < this.Count; i++)
{
if (this[i].Name == name)
return this[i];
}
return null;
}
}
protected override void InsertItem(int index, IAetherManager item)
{
// check if manager allready in use.
var itemType = item.GetType();
foreach (var manager in this)
{
if (manager.GetType().Equals(itemType))
throw new AetherException(string.Format("Manager of type {0} allready in use.", itemType.Name));
}
base.InsertItem(index, item);
}
}
}
| apache-2.0 | C# |
0d829a9ea2d1b07232a35345509de3755baf74e7 | Remove redundant method | k-t/SharpHaven | MonoHaven.Client/UI/Remote/ServerWidget.cs | MonoHaven.Client/UI/Remote/ServerWidget.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using MonoHaven.Game;
using MonoHaven.UI.Widgets;
using MonoHaven.Utils;
using NLog;
using OpenTK;
namespace MonoHaven.UI.Remote
{
public abstract class ServerWidget : TreeNode<ServerWidget>, IDisposable
{
private readonly static Logger Log = LogManager.GetCurrentClassLogger();
private readonly ushort id;
private readonly GameSession session;
private readonly Dictionary<string, Action<object[]>> handlers;
protected ServerWidget(ushort id, GameSession session)
{
this.id = id;
this.session = session;
this.handlers = new Dictionary<string, Action<object[]>>();
// TODO: handle common widget commands (focus, tab, etc).
SetHandler("curs", SetCursor);
}
protected ServerWidget(ushort id, ServerWidget parent)
: this(id, parent.Session)
{
parent.AddChild(this);
}
public ushort Id
{
get { return id; }
}
public GameSession Session
{
get { return session; }
}
public abstract Widget Widget
{
get;
}
public void Init(Point position, object[] args)
{
OnInit(position, args);
}
public void Dispose()
{
OnDestroy();
if (Widget != null)
{
Widget.Remove();
Widget.Dispose();
}
}
public void HandleMessage(string message, object[] args)
{
Action<object[]> handler;
if (handlers.TryGetValue(message, out handler))
handler(args);
else
Log.Warn("Unhandled message {0}({1}) for {2}",
message, string.Join(",", args), GetType());
}
protected virtual void OnInit(Point position, object[] args)
{
}
protected virtual void OnDestroy()
{
}
protected void SetHandler(string messageName, Action<object[]> handler)
{
handlers[messageName] = handler;
}
protected void SendMessage(string message, params object[] args)
{
session.SendMessage(id, message, args ?? new object[0]);
}
private void SetCursor(object[] args)
{
if (Widget == null)
return;
Widget.Cursor = args.Length > 0
? App.Resources.Get<MouseCursor>((string)args[0])
: null;
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using MonoHaven.Game;
using MonoHaven.UI.Widgets;
using MonoHaven.Utils;
using NLog;
using OpenTK;
namespace MonoHaven.UI.Remote
{
public abstract class ServerWidget : TreeNode<ServerWidget>, IDisposable
{
private readonly static Logger Log = LogManager.GetCurrentClassLogger();
private readonly ushort id;
private readonly GameSession session;
private readonly Dictionary<string, Action<object[]>> handlers;
protected ServerWidget(ushort id, GameSession session)
{
this.id = id;
this.session = session;
this.handlers = new Dictionary<string, Action<object[]>>();
// TODO: handle common widget commands (focus, tab, etc).
SetHandler("curs", SetCursor);
}
protected ServerWidget(ushort id, ServerWidget parent)
: this(id, parent.Session)
{
parent.AddChild(this);
}
public ushort Id
{
get { return id; }
}
public GameSession Session
{
get { return session; }
}
public abstract Widget Widget
{
get;
}
public void Init(Point position, object[] args)
{
OnInit(position, args);
}
public void Dispose()
{
OnDestroy();
if (Widget != null)
{
Widget.Remove();
Widget.Dispose();
}
}
public void HandleMessage(string message, object[] args)
{
Action<object[]> handler;
if (handlers.TryGetValue(message, out handler))
handler(args);
else
Log.Warn("Unhandled message {0}({1}) for {2}",
message, string.Join(",", args), GetType());
}
protected virtual void OnInit(Point position, object[] args)
{
}
protected virtual void OnDestroy()
{
}
protected void SetHandler(string messageName, Action<object[]> handler)
{
handlers[messageName] = handler;
}
protected void SendMessage(string message)
{
SendMessage(message, new object[0]);
}
protected void SendMessage(string message, params object[] args)
{
session.SendMessage(id, message, args);
}
private void SetCursor(object[] args)
{
if (Widget == null)
return;
Widget.Cursor = args.Length > 0
? App.Resources.Get<MouseCursor>((string)args[0])
: null;
}
}
}
| mit | C# |
2edf8eb7e3a16575ba932e1dee274222297936d5 | fix default url in flot app | Liwoj/Metrics.NET,DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET,etishor/Metrics.NET,huoxudong125/Metrics.NET,MetaG8/Metrics.NET,Liwoj/Metrics.NET,ntent-ad/Metrics.NET,cvent/Metrics.NET,mnadel/Metrics.NET,DeonHeyns/Metrics.NET,Recognos/Metrics.NET,Recognos/Metrics.NET,etishor/Metrics.NET,cvent/Metrics.NET,mnadel/Metrics.NET,alhardy/Metrics.NET,alhardy/Metrics.NET,huoxudong125/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET | Src/Metrics/Visualization/FlotWebApp.cs | Src/Metrics/Visualization/FlotWebApp.cs | using System;
using System.IO;
using System.IO.Compression;
using System.Reflection;
namespace Metrics.Visualization
{
public static class FlotWebApp
{
private static string ReadFromEmbededResource()
{
using (var stream = Assembly.GetAssembly(typeof(FlotWebApp)).GetManifestResourceStream("Metrics.Visualization.index.full.html.gz"))
using (var gzip = new GZipStream(stream, CompressionMode.Decompress))
using (var reader = new StreamReader(gzip))
{
return reader.ReadToEnd();
}
}
private static Lazy<string> htmlContent = new Lazy<string>(() => ReadFromEmbededResource());
public static string GetFlotApp(Uri metricsJsonEndpoint)
{
return htmlContent.Value.Replace("http://localhost:1234/json", metricsJsonEndpoint.ToString());
}
}
}
| using System;
using System.IO;
using System.IO.Compression;
using System.Reflection;
namespace Metrics.Visualization
{
public static class FlotWebApp
{
private static string ReadFromEmbededResource()
{
using (var stream = Assembly.GetAssembly(typeof(FlotWebApp)).GetManifestResourceStream("Metrics.Visualization.index.full.html.gz"))
using (var gzip = new GZipStream(stream, CompressionMode.Decompress))
using (var reader = new StreamReader(gzip))
{
return reader.ReadToEnd();
}
}
private static Lazy<string> htmlContent = new Lazy<string>(() => ReadFromEmbededResource());
public static string GetFlotApp(Uri metricsJsonEndpoint)
{
return htmlContent.Value.Replace("http://localhost:1234/metrics/json", metricsJsonEndpoint.ToString());
}
}
}
| apache-2.0 | C# |
ce86d7953fc016210b162513efae1f8677a9ad15 | bump version | poma/HotsStats | StatsDisplay/Properties/AssemblyInfo.cs | StatsDisplay/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("HotsStats")]
[assembly: AssemblyDescription("An app that shows player stats in Heroes of the Storm")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HotsStats")]
[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)]
//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.4.1")]
[assembly: AssemblyFileVersion("0.4.1")]
| 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("HotsStats")]
[assembly: AssemblyDescription("An app that shows player stats in Heroes of the Storm")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HotsStats")]
[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)]
//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.4.0")]
[assembly: AssemblyFileVersion("0.4.0")]
| mit | C# |
dda229161fff10d1c3c78d9c0f0848a6e2e86c56 | Update ISerializer.cs | tiksn/TIKSN-Framework | TIKSN.Core/Serialization/ISerializer.cs | TIKSN.Core/Serialization/ISerializer.cs | namespace TIKSN.Serialization
{
/// <summary>
/// Serializer interface
/// </summary>
/// <typeparam name="TSerial">Type to serialize to, usually string or byte array</typeparam>
public interface ISerializer<TSerial> where TSerial : class
{
/// <summary>
/// Serialize to <typeparamref name="TSerial"/> type
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
TSerial Serialize<T>(T obj);
}
} | namespace TIKSN.Serialization
{
/// <summary>
/// Serializer interface
/// </summary>
/// <typeparam name="TSerial">Type to serialize to, usually string or byte array</typeparam>
public interface ISerializer<TSerial> where TSerial : class
{
/// <summary>
/// Serialize to <typeparamref name="TSerial"/> type
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
TSerial Serialize(object obj);
}
} | mit | C# |
85e66bb65bf257045a135157e7b57f5bd1d5c1ea | Fix FakeStandardValuesProvider instatiation in tests | sergeyshushlyapin/Sitecore.FakeDb | test/Sitecore.FakeDb.Tests/Data/FakeStandardValuesProviderTest.cs | test/Sitecore.FakeDb.Tests/Data/FakeStandardValuesProviderTest.cs | namespace Sitecore.FakeDb.Tests.Data
{
using System;
using FluentAssertions;
using NSubstitute;
using global::AutoFixture.Xunit2;
using Sitecore.Abstractions;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.FakeDb.Data;
using Sitecore.FakeDb.Data.Engines;
using Sitecore.FakeDb.Data.Items;
using Xunit;
public class FakeStandardValuesProviderTest
{
[Theory, DefaultSubstituteAutoData]
public void ShouldReturnEmptyStringIfNoTemplateFound(
FakeStandardValuesProvider sut,
[Greedy] Field field,
DataStorage dataStorage)
{
using (new DataStorageSwitcher(dataStorage))
{
sut.GetStandardValue(field).Should().BeEmpty();
}
}
[Theory, DefaultSubstituteAutoData]
public void ShouldThrowIfNoDataStorageSet(
BaseItemManager itemManager,
BaseTemplateManager templateManager,
BaseFactory factory)
{
// arrange
var sut = Substitute.ForPartsOf<FakeStandardValuesProvider>(itemManager, templateManager, factory);
sut.DataStorage(Arg.Any<Database>()).Returns((DataStorage)null);
var field = new Field(ID.NewID, ItemHelper.CreateInstance());
// act
Action action = () => sut.GetStandardValue(field);
// assert
action.ShouldThrow<InvalidOperationException>()
.WithMessage("DataStorage cannot be null.");
}
}
}
| namespace Sitecore.FakeDb.Tests.Data
{
using System;
using FluentAssertions;
using NSubstitute;
using global::AutoFixture.Xunit2;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.FakeDb.Data;
using Sitecore.FakeDb.Data.Engines;
using Sitecore.FakeDb.Data.Items;
using Xunit;
public class FakeStandardValuesProviderTest
{
[Theory, DefaultAutoData]
public void ShouldReturnEmptyStringIfNoTemplateFound(
FakeStandardValuesProvider sut,
[Greedy] Field field,
DataStorage dataStorage)
{
using (new DataStorageSwitcher(dataStorage))
{
sut.GetStandardValue(field).Should().BeEmpty();
}
}
[Fact]
public void ShouldThrowIfNoDataStorageSet()
{
// arrange
var sut = Substitute.ForPartsOf<FakeStandardValuesProvider>();
sut.DataStorage(Arg.Any<Database>()).Returns((DataStorage)null);
var field = new Field(ID.NewID, ItemHelper.CreateInstance());
// act
Action action = () => sut.GetStandardValue(field);
// assert
action.ShouldThrow<InvalidOperationException>()
.WithMessage("DataStorage cannot be null.");
}
}
} | mit | C# |
a97ffa9a84576d5ef61310d0dec91ef89846e8b4 | Update WalletWasabi/Models/CoinsView.cs | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Models/CoinsView.cs | WalletWasabi/Models/CoinsView.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NBitcoin;
using WalletWasabi.Helpers;
using WalletWasabi.Models;
namespace WalletWasabi.Models
{
public class CoinsView : IEnumerable<SmartCoin>
{
private IEnumerable<SmartCoin> _coins;
public CoinsView(IEnumerable<SmartCoin> coins)
{
_coins = Guard.NotNull(nameof(coins), coins);
}
public CoinsView UnSpent()
{
return new CoinsView(_coins.Where(x => x.Unspent && !x.SpentAccordingToBackend));
}
public CoinsView Available()
{
return new CoinsView(_coins.Where(x => !x.Unavailable));
}
public CoinsView CoinJoinInProcess()
{
return new CoinsView(_coins.Where(x => x.CoinJoinInProgress));
}
public CoinsView Confirmed()
{
return new CoinsView(_coins.Where(x => x.Confirmed));
}
public CoinsView Unconfirmed()
{
return new CoinsView(_coins.Where(x => !x.Confirmed));
}
public CoinsView AtBlockHeight(Height height)
{
return new CoinsView(_coins.Where(x => x.Height == height));
}
public CoinsView SpentBy(uint256 txid)
{
return new CoinsView(_coins.Where(x => x.SpenderTransactionId == txid));
}
public CoinsView ChildrenOf(SmartCoin coin)
{
return new CoinsView(_coins.Where(x => x.TransactionId == coin.SpenderTransactionId));
}
public CoinsView DescendantOf(SmartCoin coin)
{
IEnumerable<SmartCoin> Generator(SmartCoin scoin)
{
foreach (var child in ChildrenOf(scoin))
{
foreach (var childDescendant in ChildrenOf(child))
{
yield return childDescendant;
}
yield return child;
}
}
return new CoinsView(Generator(coin));
}
public CoinsView FilterBy(Func<SmartCoin, bool> expression)
{
return new CoinsView(_coins.Where(expression));
}
public CoinsView OutPoints(IEnumerable<TxoRef> outPoints)
{
return new CoinsView(_coins.Where(x => outPoints.Any(y => y == x.GetOutPoint())));
}
public Money TotalAmount()
{
return _coins.Sum(x => x.Amount);
}
public SmartCoin[] ToArray()
{
return _coins.ToArray();
}
public IEnumerator<SmartCoin> GetEnumerator()
{
return _coins.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _coins.GetEnumerator();
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NBitcoin;
using WalletWasabi.Helpers;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.Models
{
public class CoinsView : IEnumerable<SmartCoin>
{
private IEnumerable<SmartCoin> _coins;
public CoinsView(IEnumerable<SmartCoin> coins)
{
_coins = Guard.NotNull(nameof(coins), coins);
}
public CoinsView UnSpent()
{
return new CoinsView(_coins.Where(x => x.Unspent && !x.SpentAccordingToBackend));
}
public CoinsView Available()
{
return new CoinsView(_coins.Where(x => !x.Unavailable));
}
public CoinsView CoinJoinInProcess()
{
return new CoinsView(_coins.Where(x => x.CoinJoinInProgress));
}
public CoinsView Confirmed()
{
return new CoinsView(_coins.Where(x => x.Confirmed));
}
public CoinsView Unconfirmed()
{
return new CoinsView(_coins.Where(x => !x.Confirmed));
}
public CoinsView AtBlockHeight(Height height)
{
return new CoinsView(_coins.Where(x => x.Height == height));
}
public CoinsView SpentBy(uint256 txid)
{
return new CoinsView(_coins.Where(x => x.SpenderTransactionId == txid));
}
public CoinsView ChildrenOf(SmartCoin coin)
{
return new CoinsView(_coins.Where(x => x.TransactionId == coin.SpenderTransactionId));
}
public CoinsView DescendantOf(SmartCoin coin)
{
IEnumerable<SmartCoin> Generator(SmartCoin scoin)
{
foreach (var child in ChildrenOf(scoin))
{
foreach (var childDescendant in ChildrenOf(child))
{
yield return childDescendant;
}
yield return child;
}
}
return new CoinsView(Generator(coin));
}
public CoinsView FilterBy(Func<SmartCoin, bool> expression)
{
return new CoinsView(_coins.Where(expression));
}
public CoinsView OutPoints(IEnumerable<TxoRef> outPoints)
{
return new CoinsView(_coins.Where(x => outPoints.Any(y => y == x.GetOutPoint())));
}
public Money TotalAmount()
{
return _coins.Sum(x => x.Amount);
}
public SmartCoin[] ToArray()
{
return _coins.ToArray();
}
public IEnumerator<SmartCoin> GetEnumerator()
{
return _coins.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _coins.GetEnumerator();
}
}
}
| mit | C# |
0873d0078525b24417553276a1eab22f4a27f390 | change versin | chsword/ResizingServer | source/ResizingClient/Properties/AssemblyInfo.cs | source/ResizingClient/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ResizingClient")]
[assembly: AssemblyDescription("Client for ResizingServer https://github.com/chsword/ResizingServer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("https://github.com/chsword/ResizingServer")]
[assembly: AssemblyProduct("ResizingClient")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("0a9d7a29-99b7-46a5-8370-56c0e2e454a3")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ResizingClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ResizingClient")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("0a9d7a29-99b7-46a5-8370-56c0e2e454a3")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
8ebd720a9a04ef7b592d2be167e2580e5de38f0a | Fix bug when click exit program but HttpListener didn't stop | witoong623/TirkxDownloader,witoong623/TirkxDownloader | Models/MessageReciever.cs | Models/MessageReciever.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using Caliburn.Micro;
using Newtonsoft.Json;
using TirkxDownloader.ViewModels;
using TirkxDownloader.Framework;
namespace TirkxDownloader.Models
{
public class MessageReciever
{
private readonly HttpListener Listener;
private readonly DownloadEngine Engine;
private readonly IEventAggregator EventAggregator;
private readonly IWindowManager WindowManager;
private Thread BackgroundThread;
public MessageReciever(IWindowManager windowManager, IEventAggregator eventAggregator, DownloadEngine engine)
{
WindowManager = windowManager;
EventAggregator = eventAggregator;
Engine = engine;
BackgroundThread = new Thread(StartReciever);
Listener = new HttpListener();
Listener.Prefixes.Add("http://localhost:6230/");
}
private void StartReciever()
{
while (true)
{
var fileInfo = GetFileInfo();
if (fileInfo != null)
{
Execute.OnUIThread(() => WindowManager.ShowDialog(
new NewDownloadViewModel(WindowManager, EventAggregator, fileInfo, Engine)));
}
}
}
private TirkxFileInfo GetFileInfo()
{
try
{
Listener.Start();
var requestContext = Listener.GetContext();
var streamReader = new StreamReader(requestContext.Request.InputStream, requestContext.Request.ContentEncoding);
string jsonString = streamReader.ReadToEnd();
Listener.Stop();
return JsonConvert.DeserializeObject<TirkxFileInfo>(jsonString);
}
catch (ThreadAbortException)
{
return null;
}
catch (HttpListenerException)
{
return null;
}
}
public void Start()
{
BackgroundThread.Start();
}
public void Stop()
{
Listener.Close();
BackgroundThread.Abort();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using Caliburn.Micro;
using Newtonsoft.Json;
using TirkxDownloader.ViewModels;
using TirkxDownloader.Framework;
namespace TirkxDownloader.Models
{
public class MessageReciever
{
private readonly DownloadEngine Engine;
private readonly IEventAggregator EventAggregator;
private readonly IWindowManager WindowManager;
private Thread BackgroundThread;
public MessageReciever(IWindowManager windowManager, IEventAggregator eventAggregator, DownloadEngine engine)
{
WindowManager = windowManager;
EventAggregator = eventAggregator;
Engine = engine;
BackgroundThread = new Thread(StartReciever);
}
private void StartReciever()
{
while (true)
{
var fileInfo = GetFileInfo();
Execute.OnUIThread(() => WindowManager.ShowDialog(
new NewDownloadViewModel(WindowManager, EventAggregator, fileInfo, Engine)));
}
}
private TirkxFileInfo GetFileInfo()
{
using (var listener = new HttpListener())
{
listener.Prefixes.Add("http://localhost:6230/");
listener.Start();
var requestContext = listener.GetContext();
var streamReader = new StreamReader(requestContext.Request.InputStream, requestContext.Request.ContentEncoding);
string jsonString = streamReader.ReadToEnd();
return JsonConvert.DeserializeObject<TirkxFileInfo>(jsonString);
}
}
public void Start()
{
BackgroundThread.Start();
}
public void Stop()
{
BackgroundThread.Abort();
}
}
}
| mit | C# |
454aeef75b33493bf63a67bd2949cb7dbee26bb5 | Allow FeaturesInstaller to install additional sources | Miruken-DotNet/Miruken | Source/Miruken.Castle/FeaturesInstaller.cs | Source/Miruken.Castle/FeaturesInstaller.cs | namespace Miruken.Castle
{
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using global::Castle.MicroKernel.Registration;
using global::Castle.MicroKernel.SubSystems.Configuration;
using global::Castle.Windsor;
public class FeaturesInstaller : IWindsorInstaller
{
private readonly List<FeatureInstaller> _features;
private readonly List<FromDescriptor> _from;
private IWindsorContainer _container;
public FeaturesInstaller(params FeatureInstaller[] features)
{
_features = new List<FeatureInstaller>();
_from = new List<FromDescriptor>();
Add(features);
}
public FeaturesInstaller Add(params FeatureInstaller[] features)
{
_features.AddRange(features);
return this;
}
public FeaturesInstaller Use(params FromDescriptor[] from)
{
if (_container == null)
_from.AddRange(from);
else
foreach (var f in from)
InstallFeatures(f);
return this;
}
void IWindsorInstaller.Install(
IWindsorContainer container, IConfigurationStore store)
{
if (Interlocked.CompareExchange(
ref _container, container, null) != null)
return;
if (_features.Count == 0) return;
var implied = new List<FromDescriptor>();
foreach (var feature in _features)
{
((IWindsorInstaller)feature).Install(container, store);
implied.AddRange(feature.GetFeatures());
}
foreach (var from in _from.Concat(implied))
InstallFeatures(from);
}
private void InstallFeatures(FromDescriptor from)
{
foreach (var feature in _features)
feature.InstallFeatures(from);
_container.Register(from);
}
}
}
| namespace Miruken.Castle
{
using System.Collections.Generic;
using System.Linq;
using global::Castle.MicroKernel.Registration;
using global::Castle.MicroKernel.SubSystems.Configuration;
using global::Castle.Windsor;
public class FeaturesInstaller : IWindsorInstaller
{
private readonly List<FeatureInstaller> _features;
private readonly List<FromDescriptor> _from;
public FeaturesInstaller(params FeatureInstaller[] features)
{
_features = new List<FeatureInstaller>();
_from = new List<FromDescriptor>();
Add(features);
}
public FeaturesInstaller Add(params FeatureInstaller[] features)
{
_features.AddRange(features);
return this;
}
public FeaturesInstaller Use(params FromDescriptor[] from)
{
_from.AddRange(from);
return this;
}
void IWindsorInstaller.Install(
IWindsorContainer container, IConfigurationStore store)
{
if (_features.Count == 0) return;
var implied = new List<FromDescriptor>();
foreach (var feature in _features)
{
((IWindsorInstaller)feature).Install(container, store);
implied.AddRange(feature.GetFeatures());
}
foreach (var from in _from.Concat(implied))
{
foreach (var feature in _features)
feature.InstallFeatures(from);
container.Register(from);
}
}
}
}
| mit | C# |
9bd7941d31771c8b6772535c72e8d9f40e9fa733 | set C# serializer ID to not conflict with Java IDs | asimarslan/hazelcast-csharp-client,asimarslan/hazelcast-csharp-client | Hazelcast.Net/Hazelcast.IO.Serialization/SerializationConstants.cs | Hazelcast.Net/Hazelcast.IO.Serialization/SerializationConstants.cs | // Copyright (c) 2008-2015, Hazelcast, 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.
namespace Hazelcast.IO.Serialization
{
internal sealed class SerializationConstants
{
public const int ConstantTypeNull = 0;
public const int ConstantTypePortable = -1;
public const int ConstantTypeDataSerializable = -2;
public const int ConstantTypeByte = -3;
public const int ConstantTypeBoolean = -4;
public const int ConstantTypeChar = -5;
public const int ConstantTypeShort = -6;
public const int ConstantTypeInteger = -7;
public const int ConstantTypeLong = -8;
public const int ConstantTypeFloat = -9;
public const int ConstantTypeDouble = -10;
public const int ConstantTypeString = -11;
public const int ConstantTypeByteArray = -12;
public const int ConstantTypeBooleanArray = -13;
public const int ConstantTypeCharArray = -14;
public const int ConstantTypeShortArray = -15;
public const int ConstantTypeIntegerArray = -16;
public const int ConstantTypeLongArray = -17;
public const int ConstantTypeFloatArray = -18;
public const int ConstantTypeDoubleArray = -19;
public const int ConstantTypeStringArray = -20;
public const int DefaultTypeJavaClass = -21;
public const int DefaultTypeDate = -22;
public const int DefaultTypeBigInteger = -23;
public const int DefaultTypeBigDecimal = -24;
public const int DefaultTypeJavaEnum = -25;
public const int DefaultTypeArrayList = -26;
public const int DefaultTypeLinkedList = -27;
public const int ConstantSerializersLength = 28;
public const int DefaultTypeSerializable = -110; //C# serializable
}
internal static class FactoryIds
{
public const int PredicateFactoryId = -32;
}
} | // Copyright (c) 2008-2015, Hazelcast, 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.
namespace Hazelcast.IO.Serialization
{
internal sealed class SerializationConstants
{
public const int ConstantTypeNull = 0;
public const int ConstantTypePortable = -1;
public const int ConstantTypeDataSerializable = -2;
public const int ConstantTypeByte = -3;
public const int ConstantTypeBoolean = -4;
public const int ConstantTypeChar = -5;
public const int ConstantTypeShort = -6;
public const int ConstantTypeInteger = -7;
public const int ConstantTypeLong = -8;
public const int ConstantTypeFloat = -9;
public const int ConstantTypeDouble = -10;
public const int ConstantTypeString = -11;
public const int ConstantTypeByteArray = -12;
public const int ConstantTypeBooleanArray = -13;
public const int ConstantTypeCharArray = -14;
public const int ConstantTypeShortArray = -15;
public const int ConstantTypeIntegerArray = -16;
public const int ConstantTypeLongArray = -17;
public const int ConstantTypeFloatArray = -18;
public const int ConstantTypeDoubleArray = -19;
public const int ConstantTypeStringArray = -20;
public const int DefaultTypeJavaClass = -21;
public const int DefaultTypeDate = -22;
public const int DefaultTypeBigInteger = -23;
public const int DefaultTypeBigDecimal = -24;
public const int DefaultTypeJavaEnum = -25;
public const int DefaultTypeArrayList = -26;
public const int DefaultTypeLinkedList = -27;
public const int ConstantSerializersLength = 28;
public const int DefaultTypeSerializable = -101; //C# serializable
}
internal static class FactoryIds
{
public const int PredicateFactoryId = -32;
}
} | apache-2.0 | C# |
1d4fc441b908e428378d35d70932c3a9646afbc6 | Revert "Ignore FormatException, that can be caused by an error in the MongoDb.Driver" | sergeyzwezdin/Hangfire.Mongo,persi12/Hangfire.Mongo,sergun/Hangfire.Mongo,sergun/Hangfire.Mongo,sergeyzwezdin/Hangfire.Mongo,sergeyzwezdin/Hangfire.Mongo,persi12/Hangfire.Mongo | src/Hangfire.Mongo/MongoUtils/MongoExtensions.cs | src/Hangfire.Mongo/MongoUtils/MongoExtensions.cs | using Hangfire.Mongo.Database;
using MongoDB.Driver;
using System;
using Hangfire.Mongo.Helpers;
using MongoDB.Bson;
namespace Hangfire.Mongo.MongoUtils
{
/// <summary>
/// Helper utilities to work with Mongo database
/// </summary>
public static class MongoExtensions
{
/// <summary>
/// Retreives server time in UTC zone
/// </summary>
/// <param name="database">Mongo database</param>
/// <returns>Server time</returns>
public static DateTime GetServerTimeUtc(this IMongoDatabase database)
{
try
{
dynamic serverStatus = AsyncHelper.RunSync(() => database.RunCommandAsync<dynamic>(new BsonDocument("isMaster", 1)));
return ((DateTime)serverStatus.localTime).ToUniversalTime();
}
catch (MongoException)
{
return DateTime.UtcNow;
}
}
/// <summary>
/// Retreives server time in UTC zone
/// </summary>
/// <param name="dbContext">Hangfire database context</param>
/// <returns>Server time</returns>
public static DateTime GetServerTimeUtc(this HangfireDbContext dbContext)
{
return GetServerTimeUtc(dbContext.Database);
}
}
} | using Hangfire.Mongo.Database;
using MongoDB.Driver;
using System;
using Hangfire.Mongo.Helpers;
using MongoDB.Bson;
namespace Hangfire.Mongo.MongoUtils
{
/// <summary>
/// Helper utilities to work with Mongo database
/// </summary>
public static class MongoExtensions
{
/// <summary>
/// Retreives server time in UTC zone
/// </summary>
/// <param name="database">Mongo database</param>
/// <returns>Server time</returns>
public static DateTime GetServerTimeUtc(this IMongoDatabase database)
{
try
{
dynamic serverStatus = AsyncHelper.RunSync(() => database.RunCommandAsync<dynamic>(new BsonDocument("isMaster", 1)));
return ((DateTime)serverStatus.localTime).ToUniversalTime();
}
catch (MongoException)
{
return DateTime.UtcNow;
}
catch (FormatException)
{
return DateTime.UtcNow;
}
}
/// <summary>
/// Retreives server time in UTC zone
/// </summary>
/// <param name="dbContext">Hangfire database context</param>
/// <returns>Server time</returns>
public static DateTime GetServerTimeUtc(this HangfireDbContext dbContext)
{
return GetServerTimeUtc(dbContext.Database);
}
}
} | mit | C# |
ba4912861f822db8d08ae531f4a5ab88b11de458 | Add App Package location sample code | mallibone/Xtc101 | Xtc101.UITest/AppInitializer.cs | Xtc101.UITest/AppInitializer.cs | using Xamarin.UITest;
namespace Xtc101.UITest
{
public class AppInitializer
{
public static IApp StartApp(Platform platform)
{
if (platform == Platform.Android)
{
return ConfigureApp
.Android
// Run Release Android project on Simulator and then uncomment line bellow (you can run the tests under the debug config)
//.ApkFile("../../../Xtc101/bin/Release/com.companyname.xtc101.apk")
.PreferIdeSettings()
.StartApp();
}
return ConfigureApp
.iOS
.PreferIdeSettings()
.StartApp();
}
}
} | using Xamarin.UITest;
namespace Xtc101.UITest
{
public class AppInitializer
{
public static IApp StartApp(Platform platform)
{
if (platform == Platform.Android)
{
return ConfigureApp
.Android
.PreferIdeSettings()
.StartApp();
}
return ConfigureApp
.iOS
.PreferIdeSettings()
.StartApp();
}
}
} | mit | C# |
f1eceae3cdd16a9a961ff9268cd3efb52151167c | Fix problem loading image for GraphicsWindow.DrawImage (#98) | OmarTawfik/SuperBasic,OmarTawfik/SuperBasic,OmarTawfik/SuperBasic | Source/SmallBasic.Editor/Libraries/Graphics/ImageGraphicsObject.cs | Source/SmallBasic.Editor/Libraries/Graphics/ImageGraphicsObject.cs | // <copyright file="ImageGraphicsObject.cs" company="2018 Omar Tawfik">
// Copyright (c) 2018 Omar Tawfik. All rights reserved. Licensed under the MIT License. See LICENSE file in the project root for license information.
// </copyright>
namespace SmallBasic.Editor.Libraries.Graphics
{
using System.Collections.Generic;
using System.Globalization;
using SmallBasic.Editor.Components;
using SmallBasic.Editor.Libraries.Utilities;
internal sealed class ImageGraphicsObject : BaseGraphicsObject
{
public ImageGraphicsObject(decimal x, decimal y, decimal scaleX, decimal scaleY, string name, GraphicsWindowStyles styles)
: base(styles)
{
this.X = x;
this.Y = y;
this.ScaleX = scaleX;
this.ScaleY = scaleY;
this.Name = name;
}
public decimal X { get; set; }
public decimal Y { get; set; }
public decimal ScaleX { get; set; }
public decimal ScaleY { get; set; }
public string Name { get; set; }
public override void ComposeTree(TreeComposer composer)
{
composer.Element(
name: "image",
attributes: new Dictionary<string, string>
{
{ "href", this.Name },
{ "x", this.X.ToString(CultureInfo.CurrentCulture) },
{ "y", this.Y.ToString(CultureInfo.CurrentCulture) },
{ "transform", $"scale({this.ScaleX}, {this.ScaleY})" }
});
}
}
}
| // <copyright file="ImageGraphicsObject.cs" company="2018 Omar Tawfik">
// Copyright (c) 2018 Omar Tawfik. All rights reserved. Licensed under the MIT License. See LICENSE file in the project root for license information.
// </copyright>
namespace SmallBasic.Editor.Libraries.Graphics
{
using System.Collections.Generic;
using System.Globalization;
using SmallBasic.Editor.Components;
using SmallBasic.Editor.Libraries.Utilities;
internal sealed class ImageGraphicsObject : BaseGraphicsObject
{
public ImageGraphicsObject(decimal x, decimal y, decimal scaleX, decimal scaleY, string name, GraphicsWindowStyles styles)
: base(styles)
{
this.X = x;
this.Y = y;
this.ScaleX = scaleX;
this.ScaleY = scaleY;
this.Name = name;
}
public decimal X { get; set; }
public decimal Y { get; set; }
public decimal ScaleX { get; set; }
public decimal ScaleY { get; set; }
public string Name { get; set; }
public override void ComposeTree(TreeComposer composer)
{
composer.Element(
name: "use",
attributes: new Dictionary<string, string>
{
{ "href", $"#{this.Name}" },
{ "x", this.X.ToString(CultureInfo.CurrentCulture) },
{ "y", this.Y.ToString(CultureInfo.CurrentCulture) },
{ "transform", $"scale({this.ScaleX}, {this.ScaleY})" }
});
}
}
}
| mit | C# |
ae416afc0a25a4077f42cf6a92a099e29be43c7e | remove the superfluous registration | eShopWorld/devopsflex-telemetry | src/Eshopworld.Telemetry/Configuration/ServiceFabricTelemetryModule.cs | src/Eshopworld.Telemetry/Configuration/ServiceFabricTelemetryModule.cs | using System.Fabric;
using Autofac;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.ServiceFabric;
using Microsoft.ApplicationInsights.ServiceFabric.Module;
namespace Eshopworld.Telemetry.Configuration
{
/// <summary>
/// Registers Service Fabric components of telemetry pipeline.
/// </summary>
public class ServiceFabricTelemetryModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(x =>
{
var serviceContext = x.ResolveOptional<ServiceContext>();
return FabricTelemetryInitializerExtension.CreateFabricTelemetryInitializer(serviceContext);
}).As<ITelemetryInitializer>();
builder.Register(c => new ServiceRemotingRequestTrackingTelemetryModule { SetComponentCorrelationHttpHeaders = true }).As<ITelemetryModule>();
}
}
}
| using System.Fabric;
using Autofac;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.ServiceFabric;
using Microsoft.ApplicationInsights.ServiceFabric.Module;
namespace Eshopworld.Telemetry.Configuration
{
/// <summary>
/// Registers Service Fabric components of telemetry pipeline.
/// </summary>
public class ServiceFabricTelemetryModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(x =>
{
var serviceContext = x.ResolveOptional<ServiceContext>();
return FabricTelemetryInitializerExtension.CreateFabricTelemetryInitializer(serviceContext);
}).As<ITelemetryInitializer>();
builder.Register(c => new ServiceRemotingRequestTrackingTelemetryModule { SetComponentCorrelationHttpHeaders = true }).As<ITelemetryModule>();
builder.RegisterType<ServiceRemotingDependencyTrackingTelemetryModule>().As<ITelemetryModule>();
}
}
}
| mit | C# |
e446dcadfc6c1d1f6eee8ac81752977ea25c08fe | update UseAspectCore extensions | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | src/WeihanLi.Common.Aspect.AspectCore/FluentAspectBuilderExtensions.cs | src/WeihanLi.Common.Aspect.AspectCore/FluentAspectBuilderExtensions.cs | using Microsoft.Extensions.DependencyInjection;
using System;
using WeihanLi.Common.DependencyInjection;
namespace WeihanLi.Common.Aspect.AspectCore
{
public static class FluentAspectBuilderExtensions
{
public static IFluentAspectsBuilder UseAspectCoreProxy(this IFluentAspectsBuilder builder)
{
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Services.AddTransient<IProxyFactory, AspectCoreProxyFactory>();
builder.Services.AddTransient<IProxyTypeFactory, AspectCoreProxyTypeFactory>();
FluentAspects.AspectOptions.ProxyFactory = AspectCoreProxyFactory.Instance;
return builder;
}
public static IFluentAspectsServiceContainerBuilder UseAspectCoreProxy(this IFluentAspectsServiceContainerBuilder builder)
{
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Services.AddTransient<IProxyFactory, AspectCoreProxyFactory>();
builder.Services.AddTransient<IProxyTypeFactory, AspectCoreProxyTypeFactory>();
FluentAspects.AspectOptions.ProxyFactory = AspectCoreProxyFactory.Instance;
return builder;
}
}
}
| using Microsoft.Extensions.DependencyInjection;
using System;
using WeihanLi.Common.DependencyInjection;
namespace WeihanLi.Common.Aspect.AspectCore
{
public static class FluentAspectBuilderExtensions
{
public static IFluentAspectsBuilder UseAspectCoreProxy(this IFluentAspectsBuilder builder)
{
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Services.AddTransient<IProxyFactory, AspectCoreProxyFactory>();
FluentAspects.AspectOptions.ProxyFactory = AspectCoreProxyFactory.Instance;
return builder;
}
public static IFluentAspectsServiceContainerBuilder UseAspectCoreProxy(this IFluentAspectsServiceContainerBuilder builder)
{
if (builder is null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.Services.AddTransient<IProxyFactory, AspectCoreProxyFactory>();
FluentAspects.AspectOptions.ProxyFactory = AspectCoreProxyFactory.Instance;
return builder;
}
}
}
| mit | C# |
cedf36e1b9080fac01905bcf960475a85934b8f6 | Remove accidental partial line | kswoll/WootzJs,x335/WootzJs,kswoll/WootzJs,kswoll/WootzJs,x335/WootzJs,x335/WootzJs | WootzJs.Web/FileReader.cs | WootzJs.Web/FileReader.cs | using System;
using System.Runtime.WootzJs;
namespace WootzJs.Web
{
[Js(Name = "FileReader", Export = false)]
public class FileReader
{
[Js(Name = "error")]
public extern DOMError Error { get; }
[Js(Name = "readyState")]
public extern int ReadyState { get; }
[Js(Name = "readAsDataURL")]
public extern void ReadAsDataURL(Blob blob);
[Js(Name = "readAsText")]
public extern void ReadAsText(Blob blob);
[Js(Name = "result")]
public extern JsObject Result { get; }
[Js(Name = "onload")]
public Action<Event> OnLoad { get; set; }
[Js(Name = "abort")]
public extern void Abort();
}
} | using System;
using System.Runtime.WootzJs;
namespace WootzJs.Web
{
[Js(Name = "FileReader", Export = false)]
public class FileReader
{
[Js(Name = "error")]
public extern DOMError Error { get; }
[Js(Name = "readyState")]
public extern int ReadyState { get; }
[Js(Name = "readAsDataURL")]
public extern void ReadAsDataURL(Blob blob);
[Js(Name = "readAsText")]
public extern void ReadAsText(Blob blob);
public extern
[Js(Name = "result")]
public extern JsObject Result { get; }
[Js(Name = "onload")]
public Action<Event> OnLoad { get; set; }
[Js(Name = "abort")]
public extern void Abort();
}
} | mit | C# |
a4d1d1bcfa4fffcc07ea7d7c2c8fbd14abe48710 | Fix storage handler for Richtung property and remove unnecessary navigation properties | christophwille/viennarealtime,christophwille/viennarealtime | Source/MundlTransit.WP8/StorageHandlers/LineInfoPageViewModelStorage.cs | Source/MundlTransit.WP8/StorageHandlers/LineInfoPageViewModelStorage.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using MundlTransit.WP8.ViewModels.LineInfo;
namespace MundlTransit.WP8.StorageHandlers
{
public class LineInfoPageViewModelStorage : StorageHandler<LineInfoPageViewModel>
{
public override void Configure()
{
// No need to store navigation properties
Property(vm => vm.Richtung)
.InPhoneState()
.RestoreAfterActivation(); // this property is needed in OnActivate
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using MundlTransit.WP8.ViewModels.LineInfo;
namespace MundlTransit.WP8.StorageHandlers
{
public class LineInfoPageViewModelStorage : StorageHandler<LineInfoPageViewModel>
{
public override void Configure()
{
Property(vm => vm.NavigationLineId)
.InPhoneState()
.RestoreAfterViewLoad();
Property(vm => vm.NavigationLineName)
.InPhoneState()
.RestoreAfterViewLoad();
Property(vm => vm.Richtung)
.InPhoneState()
.RestoreAfterViewLoad();
}
}
}
| mit | C# |
e1c6d50f33af01abc2af517d00d05e53182582a8 | create action | lastr2d2/guesswhat_wordservice,atwayne/guesswhat_wordservice | WayneStudio.WordService/WayneStudio.WordService/DataStore/WordEngine.cs | WayneStudio.WordService/WayneStudio.WordService/DataStore/WordEngine.cs | using System;
using System.Linq;
using System.Data;
using System.Collections.Generic;
using WayneStudio.WordService.Core;
using WayneStudio.WordService.Models;
using System.Data.SQLite;
namespace WayneStudio.WordService.DataStore
{
public class WordEngine
{
public void AddWords(UpdateWordRequest request)
{
var query = @"
INSERT INTO Word (Word, CreatedBy)
VALUES (@Word,@CreatedBy)";
var existed = GetAllWords()
.Select(l => l.Text).ToList();
var wordsToBeSaved = request.Words
.Where(l => !existed.Contains(l, StringComparer.OrdinalIgnoreCase))
.ToList();
foreach (var item in wordsToBeSaved)
{
var parameters = new List<SQLiteParameter>();
parameters.Add(new SQLiteParameter("Word", item));
parameters.Add(new SQLiteParameter("CreatedBy", request.CreatedBy));
try
{
SQLiteHelper.ExecuteNonQuery(query, parameters.ToArray());
}
catch (SQLiteException) { }
}
}
public List<Word> GetWordList()
{
var query = @"
SELECT Word AS Text, CreatedBy
FROM Word
WHERE IsBlocked = 0 AND IsExpired = 0";
return GetWordListByQuery(query);
}
private List<Word> GetAllWords()
{
var query = @"
SELECT Word AS Text, CreatedBy
FROM Word";
return GetWordListByQuery(query);
}
private static List<Word> GetWordListByQuery(string query)
{
var queryResult = SQLiteHelper.ExecuteDataTable(query);
return queryResult.AsEnumerable()
.Select(l =>
{
var word = new Word();
word.LoadFromDataTable(l);
return word;
})
.ToList();
}
public void Expire(UpdateWordRequest request)
{
throw new NotImplementedException();
}
public void Block(UpdateWordRequest request)
{
throw new NotImplementedException();
}
}
} | using System;
using System.Linq;
using System.Data;
using System.Collections.Generic;
using WayneStudio.WordService.Core;
using WayneStudio.WordService.Models;
namespace WayneStudio.WordService.DataStore
{
public class WordEngine
{
public void AddWords(UpdateWordRequest request)
{
throw new NotImplementedException();
}
public List<Word> GetWordList()
{
var query = @"
SELECT Word AS Text, CreatedBy
FROM Word
WHERE IsBlocked = 0 AND IsExpired = 0";
var queryResult = SQLiteHelper.ExecuteDataTable(query);
return queryResult.AsEnumerable()
.Select(l =>
{
var word = new Word();
word.LoadFromDataTable(l);
return word;
})
.ToList();
}
public void Expire(UpdateWordRequest request)
{
throw new NotImplementedException();
}
public void Block(UpdateWordRequest request)
{
throw new NotImplementedException();
}
}
} | apache-2.0 | C# |
3c4c79dcb83d0f2af05f15da28173e91831b47f0 | Implement UnitTest for ReportPageViewModel#Name. | ProjectBlueMonkey/BlueMonkey,ProjectBlueMonkey/BlueMonkey | client/BlueMonkey/BlueMonkey.ViewModel.Tests/ReportPageViewModelTest.cs | client/BlueMonkey/BlueMonkey.ViewModel.Tests/ReportPageViewModelTest.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BlueMonkey.Model;
using BlueMonkey.ViewModels;
using Moq;
using Prism.Navigation;
using Xunit;
namespace BlueMonkey.ViewModel.Tests
{
public class ReportPageViewModelTest
{
[Fact]
public void Constructor()
{
var navigationService = new Mock<INavigationService>();
var editReport = new Mock<IEditReport>();
editReport.Setup(m => m.Name).Returns("Name");
editReport.Setup(m => m.Date).Returns(DateTime.Today);
var actual = new ReportPageViewModel(navigationService.Object, editReport.Object);
Assert.NotNull(actual.Name);
Assert.Equal("Name", actual.Name.Value);
Assert.NotNull(actual.Date);
Assert.Equal(DateTime.Today, actual.Date.Value);
Assert.Null(actual.Expenses);
Assert.NotNull(actual.InitializeCommand);
Assert.True(actual.InitializeCommand.CanExecute());
Assert.NotNull(actual.NavigateExpenseSelectionCommand);
Assert.True(actual.NavigateExpenseSelectionCommand.CanExecute());
Assert.NotNull(actual.SaveReportCommand);
Assert.True(actual.SaveReportCommand.CanExecute());
}
[Fact]
public void NameProperty()
{
var navigationService = new Mock<INavigationService>();
var editReport = new Mock<IEditReport>();
var actual = new ReportPageViewModel(navigationService.Object, editReport.Object);
Assert.Null(actual.Name.Value);
// Update model.
editReport.Setup(m => m.Name).Returns("Name");
editReport
.Raise(m => m.PropertyChanged += null, new PropertyChangedEventArgs("Name"));
Assert.Equal("Name", actual.Name.Value);
// Update ViewModel.
actual.Name.Value = "Update name";
editReport
.VerifySet(m => m.Name = "Update name", Times.Once);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BlueMonkey.Model;
using BlueMonkey.ViewModels;
using Moq;
using Prism.Navigation;
using Xunit;
namespace BlueMonkey.ViewModel.Tests
{
public class ReportPageViewModelTest
{
[Fact]
public void Constructor()
{
var navigationService = new Mock<INavigationService>();
var editReport = new Mock<IEditReport>();
editReport.Setup(m => m.Name).Returns("Name");
editReport.Setup(m => m.Date).Returns(DateTime.Today);
var actual = new ReportPageViewModel(navigationService.Object, editReport.Object);
Assert.NotNull(actual.Name);
Assert.Equal("Name", actual.Name.Value);
Assert.NotNull(actual.Date);
Assert.Equal(DateTime.Today, actual.Date.Value);
Assert.Null(actual.Expenses);
Assert.NotNull(actual.InitializeCommand);
Assert.True(actual.InitializeCommand.CanExecute());
Assert.NotNull(actual.NavigateExpenseSelectionCommand);
Assert.True(actual.NavigateExpenseSelectionCommand.CanExecute());
Assert.NotNull(actual.SaveReportCommand);
Assert.True(actual.SaveReportCommand.CanExecute());
}
}
}
| mit | C# |
e77560eb9d39706bac1a841b34698faeea938e84 | comment more | SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake | src/Snowflake.Framework.Primitives/Execution/Extensibility/IEmulator.cs | src/Snowflake.Framework.Primitives/Execution/Extensibility/IEmulator.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Configuration;
using Snowflake.Configuration.Input;
using Snowflake.Execution.Saving;
using Snowflake.Extensibility;
using Snowflake.Platform;
using Snowflake.Records.Game;
namespace Snowflake.Execution.Extensibility
{
/// <summary>
/// An <see cref="IEmulator"/> handles execution of a game by creating tasks with
/// contextual information to execute with the provided task runner.
/// </summary>
public interface IEmulator : IPlugin
{
/// <summary>
/// Gets the task runner that this emulator plugin delegates.
/// </summary>
IEmulatorTaskRunner Runner { get; }
/// <summary>
/// Gets the emulator specific properties for this emulator.
/// </summary>
IEmulatorProperties Properties { get; }
/// <summary>
/// Creates a task to exeut
/// </summary>
/// <param name="executingGame"></param>
/// <param name="saveLocation"></param>
/// <param name="controllerConfiguration"></param>
/// <param name="profileContext"></param>
/// <returns></returns>
IEmulatorTask CreateTask(IGameRecord executingGame,
ISaveLocation saveLocation,
IList<IEmulatedController> controllerConfiguration,
string profileContext = "default");
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Snowflake.Configuration;
using Snowflake.Configuration.Input;
using Snowflake.Execution.Saving;
using Snowflake.Extensibility;
using Snowflake.Platform;
using Snowflake.Records.Game;
namespace Snowflake.Execution.Extensibility
{
public interface IEmulator : IPlugin
{
IEmulatorTaskRunner Runner { get; }
IEmulatorProperties Properties { get; }
IEmulatorTask CreateTask(IGameRecord executingGame,
ISaveLocation saveLocation,
IList<IEmulatedController> controllerConfiguration,
string profileContext = "default");
}
}
| mpl-2.0 | C# |
f673647e09c9ef93706e1d9c1942ab5f116b0bb4 | refactor usage of Screen | tibel/Caliburn.Light | samples/Demo.SimpleMDI/ShellViewModel.cs | samples/Demo.SimpleMDI/ShellViewModel.cs | using Caliburn.Light;
namespace Demo.SimpleMDI
{
public class ShellViewModel : Conductor<TabViewModel>.Collection.OneActive
{
int _count = 1;
public void OpenTab()
{
var tab = IoC.GetInstance<TabViewModel>();
tab.DisplayName = "Tab " + _count++;
ActivateItem(tab);
}
}
}
| using Caliburn.Light;
namespace Demo.SimpleMDI
{
public class ShellViewModel : Conductor<Screen>.Collection.OneActive
{
int _count = 1;
public void OpenTab()
{
var tab = IoC.GetInstance<TabViewModel>();
tab.DisplayName = "Tab " + _count++;
ActivateItem(tab);
}
}
}
| mit | C# |
e20298db61ea37fa1a91eeb34595d71b48608d3e | Write != Read. | dpurge/GitVersion,pascalberger/GitVersion,JakeGinnivan/GitVersion,JakeGinnivan/GitVersion,ermshiperete/GitVersion,ermshiperete/GitVersion,Philo/GitVersion,DanielRose/GitVersion,dpurge/GitVersion,onovotny/GitVersion,DanielRose/GitVersion,ParticularLabs/GitVersion,JakeGinnivan/GitVersion,gep13/GitVersion,dpurge/GitVersion,DanielRose/GitVersion,pascalberger/GitVersion,Philo/GitVersion,FireHost/GitVersion,asbjornu/GitVersion,GitTools/GitVersion,dazinator/GitVersion,asbjornu/GitVersion,onovotny/GitVersion,pascalberger/GitVersion,ermshiperete/GitVersion,dazinator/GitVersion,ParticularLabs/GitVersion,gep13/GitVersion,JakeGinnivan/GitVersion,onovotny/GitVersion,FireHost/GitVersion,dpurge/GitVersion,ermshiperete/GitVersion,GitTools/GitVersion | src/GitVersionCore/Helpers/FileSystem.cs | src/GitVersionCore/Helpers/FileSystem.cs | namespace GitVersion.Helpers
{
using System.Collections.Generic;
using System.IO;
public class FileSystem : IFileSystem
{
public void Copy(string @from, string to, bool overwrite)
{
File.Copy(from, to, overwrite);
}
public void Move(string @from, string to)
{
File.Move(from, to);
}
public bool Exists(string file)
{
return File.Exists(file);
}
public void Delete(string path)
{
File.Delete(path);
}
public string ReadAllText(string path)
{
return File.ReadAllText(path);
}
public void WriteAllText(string file, string fileContents)
{
File.WriteAllText(file, fileContents);
}
public IEnumerable<string> DirectoryGetFiles(string directory, string searchPattern, SearchOption searchOption)
{
return Directory.GetFiles(directory, searchPattern, searchOption);
}
public Stream OpenWrite(string path)
{
return File.OpenWrite(path);
}
public Stream OpenRead(string path)
{
return File.OpenRead(path);
}
public void CreateDirectory(string path)
{
Directory.CreateDirectory(path);
}
}
} | namespace GitVersion.Helpers
{
using System.Collections.Generic;
using System.IO;
public class FileSystem : IFileSystem
{
public void Copy(string @from, string to, bool overwrite)
{
File.Copy(from, to, overwrite);
}
public void Move(string @from, string to)
{
File.Move(from, to);
}
public bool Exists(string file)
{
return File.Exists(file);
}
public void Delete(string path)
{
File.Delete(path);
}
public string ReadAllText(string path)
{
return File.ReadAllText(path);
}
public void WriteAllText(string file, string fileContents)
{
File.WriteAllText(file, fileContents);
}
public IEnumerable<string> DirectoryGetFiles(string directory, string searchPattern, SearchOption searchOption)
{
return Directory.GetFiles(directory, searchPattern, searchOption);
}
public Stream OpenWrite(string path)
{
return File.OpenWrite(path);
}
public Stream OpenRead(string path)
{
return File.OpenWrite(path);
}
public void CreateDirectory(string path)
{
Directory.CreateDirectory(path);
}
}
} | mit | C# |
ee8ff6335ccae5267f616054a2d2db6d7a8808a2 | Reduce size of code generated for Contract methods. | stephentoub/corefxlab,stephentoub/corefxlab,ericstj/corefxlab,ericstj/corefxlab,VSadov/corefxlab,ericstj/corefxlab,benaadams/corefxlab,ravimeda/corefxlab,Vedin/corefxlab,ericstj/corefxlab,VSadov/corefxlab,joshfree/corefxlab,VSadov/corefxlab,VSadov/corefxlab,Vedin/corefxlab,VSadov/corefxlab,Vedin/corefxlab,dotnet/corefxlab,alexperovich/corefxlab,hanblee/corefxlab,ericstj/corefxlab,stephentoub/corefxlab,Vedin/corefxlab,livarcocc/corefxlab,adamsitnik/corefxlab,Vedin/corefxlab,KrzysztofCwalina/corefxlab,dotnet/corefxlab,ericstj/corefxlab,VSadov/corefxlab,stephentoub/corefxlab,ahsonkhan/corefxlab,tarekgh/corefxlab,Vedin/corefxlab,weshaggard/corefxlab,benaadams/corefxlab,adamsitnik/corefxlab,whoisj/corefxlab,stephentoub/corefxlab,tarekgh/corefxlab,stephentoub/corefxlab,KrzysztofCwalina/corefxlab,ahsonkhan/corefxlab,joshfree/corefxlab,nguerrera/corefxlab,whoisj/corefxlab,hanblee/corefxlab | src/System.Slices/src/System/Contract.cs | src/System.Slices/src/System/Contract.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
namespace System
{
static class Contract
{
public static void Requires(bool condition)
{
if (!condition)
{
throw NewArgumentException();
}
}
public static void RequiresNonNegative(int n)
{
if (n < 0)
{
throw NewArgumentOutOfRangeException();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void RequiresInRange(int start, int length)
{
if ((uint)start >= (uint)length)
{
throw NewArgumentOutOfRangeException();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void RequiresInInclusiveRange(int start, int length)
{
if ((uint)start > (uint)length)
{
throw NewArgumentOutOfRangeException();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static Exception NewArgumentException()
{
return new ArgumentException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static Exception NewArgumentOutOfRangeException()
{
return new ArgumentOutOfRangeException();
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
namespace System
{
static class Contract
{
public static void Requires(bool condition)
{
if (!condition)
{
throw new ArgumentException();
}
}
public static void RequiresNonNegative(int n)
{
if (n < 0)
{
throw new ArgumentOutOfRangeException();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void RequiresInRange(int start, int length)
{
if (!(start >= 0 && start < length))
{
throw new ArgumentOutOfRangeException();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void RequiresInInclusiveRange(int start, int length)
{
if (!(start >= 0 && start <= length))
{
throw new ArgumentOutOfRangeException();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void RequiresInInclusiveRange(int start, int end, int length)
{
if (!(start >= 0 && start <= end && end >= 0 && end <= length))
{
throw new ArgumentOutOfRangeException();
}
}
}
}
| mit | C# |
c19b17b3379ce32c5731dc5348cf39ef0e276211 | remove param from hide menu (unneeded) | StefanoFiumara/Harry-Potter-Unity | Assets/Scripts/HarryPotterUnity/UI/MenuManager.cs | Assets/Scripts/HarryPotterUnity/UI/MenuManager.cs | using System.Linq;
using HarryPotterUnity.UI.Menu;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.UI;
namespace HarryPotterUnity.UI
{
public class MenuManager : MonoBehaviour
{
[SerializeField]
private BaseMenu _currentMenu;
[SerializeField]
private SubMenuManager _subMenuManager;
private Text _networkStatus;
private Text _playersOnline;
private void Awake()
{
_subMenuManager = GetComponent<SubMenuManager>();
var allTextObjects = FindObjectsOfType<Text>();
_networkStatus = allTextObjects.SingleOrDefault(t => t.name.Contains("NetworkStatusDetailed"));
_playersOnline = allTextObjects.SingleOrDefault(t => t.name.Contains("PlayersOnlineLabel"));
}
[UsedImplicitly]
public void OnJoinedLobby()
{
ShowMenu(_currentMenu);
}
public void ShowMenu(BaseMenu menu)
{
if (_currentMenu != null)
{
_currentMenu.IsOpen = false;
}
_currentMenu = menu;
_currentMenu.IsOpen = true;
_subMenuManager.HideMenu();
}
[UsedImplicitly]
public void HideMenu()
{
if (_currentMenu != null)
{
_currentMenu.IsOpen = false;
}
_currentMenu = null;
}
private void Update()
{
_playersOnline.text = string.Format("Players Online: {0}", PhotonNetwork.countOfPlayers);
_networkStatus.text = string.Format("Network Status: {0}", PhotonNetwork.connectionStateDetailed);
}
}
}
| using System.Linq;
using HarryPotterUnity.UI.Menu;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.UI;
namespace HarryPotterUnity.UI
{
public class MenuManager : MonoBehaviour
{
[SerializeField]
private BaseMenu _currentMenu;
[SerializeField]
private SubMenuManager _subMenuManager;
private Text _networkStatus;
private Text _playersOnline;
private void Awake()
{
_subMenuManager = GetComponent<SubMenuManager>();
var allTextObjects = FindObjectsOfType<Text>();
_networkStatus = allTextObjects.SingleOrDefault(t => t.name.Contains("NetworkStatusDetailed"));
_playersOnline = allTextObjects.SingleOrDefault(t => t.name.Contains("PlayersOnlineLabel"));
}
[UsedImplicitly]
public void OnJoinedLobby()
{
ShowMenu(_currentMenu);
}
public void ShowMenu(BaseMenu menu)
{
if (_currentMenu != null)
{
_currentMenu.IsOpen = false;
}
_currentMenu = menu;
_currentMenu.IsOpen = true;
_subMenuManager.HideMenu();
}
//TODO: Remove parameter and fix all links in scene
[UsedImplicitly]
public void HideMenu(BaseMenu menu)
{
if (menu.IsOpen)
{
menu.IsOpen = false;
_currentMenu = null;
}
}
private void Update()
{
_playersOnline.text = string.Format("Players Online: {0}", PhotonNetwork.countOfPlayers);
_networkStatus.text = string.Format("Network Status: {0}", PhotonNetwork.connectionStateDetailed);
}
}
}
| mit | C# |
7c6e3e166270f394cf33cc047c5971f58d423d95 | fix security issue | marinoscar/loadimpact | Program.cs | Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LoadImpact
{
class Program
{
static void Main(string[] args)
{
var consoleArgs = new Arguments(args);
var apiKey = "";
if (!consoleArgs.IsSwitchPresent("/apiKey"))
{
Console.WriteLine("Enter your api key");
apiKey = Console.ReadLine();
}
Console.WriteLine("Enter your api key");
var api = new RestApi(apiKey);
var start = DateTime.Now;
Console.WriteLine("Starting to get data at {0}", start);
api.StoreResultsInFile(@"C:\EWM\TestResults.csv");
Console.WriteLine("\n\nCompleted at {0} duration of {1}", DateTime.Now, DateTime.Now.Subtract(start));
Console.ReadKey();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LoadImpact
{
class Program
{
static void Main(string[] args)
{
var api = new RestApi("0dfb7b336a3d1ed03d16f9e00ab0791356814de2317f46498d12434a3a4c82f9");
var start = DateTime.Now;
Console.WriteLine("Starting to get data at {0}", start);
api.StoreResultsInFile(@"C:\EWM\TestResults.csv");
Console.WriteLine("\n\nCompleted at {0} duration of {1}", DateTime.Now, DateTime.Now.Subtract(start));
Console.ReadKey();
}
}
}
| mit | C# |
8897fe3e6ae26efbccdd251e857fb47b5e38e944 | Add handling of deletions to MessageDistributer | thijser/ARGAME,thijser/ARGAME,thijser/ARGAME | ARGame/Assets/Scripts/Network/MessageDistributer.cs | ARGame/Assets/Scripts/Network/MessageDistributer.cs | //----------------------------------------------------------------------------
// <copyright file="MessageDistributer.cs" company="Delft University of Technology">
// Copyright 2015, Delft University of Technology
//
// This software is licensed under the terms of the MIT License.
// A copy of the license should be included with this software. If not,
// see http://opensource.org/licenses/MIT for the full license.
// </copyright>
//----------------------------------------------------------------------------
namespace Network
{
using System;
using UnityEngine;
/// <summary>
/// Distributes general messages from the server as specific messages.
/// </summary>
public class MessageDistributer : MonoBehaviour
{
/// <summary>
/// Receives and handles all server updates, by sending them forward to other handlers
/// </summary>
/// <param name="update">The serverUpdate to be handled.</param>
public void OnServerUpdate(AbstractUpdate update)
{
if (update == null)
{
throw new ArgumentNullException("update");
}
if (update.Type == UpdateType.UpdatePosition || update.Type == UpdateType.DeletePosition)
{
this.SendMessage("OnPositionUpdate", update as PositionUpdate);
}
else if (update.Type == UpdateType.UpdateRotation)
{
this.SendMessage("OnRotationUpdate", update as RotationUpdate);
}
else if (update.Type == UpdateType.Level)
{
this.SendMessage("OnLevelUpdate", update as LevelUpdate);
}
}
}
}
| //----------------------------------------------------------------------------
// <copyright file="MessageDistributer.cs" company="Delft University of Technology">
// Copyright 2015, Delft University of Technology
//
// This software is licensed under the terms of the MIT License.
// A copy of the license should be included with this software. If not,
// see http://opensource.org/licenses/MIT for the full license.
// </copyright>
//----------------------------------------------------------------------------
namespace Network
{
using System;
using UnityEngine;
/// <summary>
/// Distributes general messages from the server as specific messages.
/// </summary>
public class MessageDistributer : MonoBehaviour
{
/// <summary>
/// Receives and handles all server updates, by sending them forward to other handlers
/// </summary>
/// <param name="update">The serverUpdate to be handled.</param>
public void OnServerUpdate(AbstractUpdate update)
{
if (update == null)
{
throw new ArgumentNullException("update");
}
if (update.Type == UpdateType.UpdatePosition)
{
this.SendMessage("OnPositionUpdate", update as PositionUpdate);
}
else if (update.Type == UpdateType.UpdateRotation)
{
this.SendMessage("OnRotationUpdate", update as RotationUpdate);
}
else if (update.Type == UpdateType.Level)
{
this.SendMessage("OnLevelUpdate", update as LevelUpdate);
}
}
}
}
| mit | C# |
39767aef67f39558c0c9b10e41d38b8db5c0a43a | Prepare for April 2016 release | Oaden/PnP-Sites-Core,phillipharding/PnP-Sites-Core,rajashekarusa/PnP-Sites-Core,phillipharding/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,Oaden/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,rajashekarusa/PnP-Sites-Core,rajashekarusa/PnP-Sites-Core | Core/OfficeDevPnP.Core/Properties/AssemblyInfo.cs | Core/OfficeDevPnP.Core/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
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("OfficeDevPnP.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OfficeDevPnP.Core")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
// 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("065331b6-0540-44e1-84d5-d38f09f17f9e")]
// 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:
// Convention:
// Major version = current version 2
// Minor version = Sequence...version 0 was with January release...so 1=Feb 2=Mar, 3=Apr, 4=May, 6=Jun, 7=Jul, 8=Aug, 9=Sept,...
// Third part = version indenpendant showing the release month in YYMM
// Fourth part = 0 normally or a sequence number when we do an emergency release
[assembly: AssemblyVersion("2.3.1604.0")]
[assembly: AssemblyFileVersion("2.3.1604.0")]
[assembly: InternalsVisibleTo("OfficeDevPnP.Core.Tests")] | using System.Reflection;
using System.Resources;
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("OfficeDevPnP.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OfficeDevPnP.Core")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
// 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("065331b6-0540-44e1-84d5-d38f09f17f9e")]
// 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:
// Convention:
// Major version = current version 2
// Minor version = Sequence...version 0 was with January release...so 1=Feb 2=Mar, 3=Apr, 4=May, 6=Jun, 7=Jul, 8=Aug, 9=Sept,...
// Third part = version indenpendant showing the release month in YYMM
// Fourth part = 0 normally or a sequence number when we do an emergency release
[assembly: AssemblyVersion("2.2.1603.0")]
[assembly: AssemblyFileVersion("2.2.1603.0")]
[assembly: InternalsVisibleTo("OfficeDevPnP.Core.Tests")] | mit | C# |
7227d014c601bcad62ae7f768499865d4d36d01c | Revert "Update Examples/.vs/Aspose.Email.Examples.CSharp/v15/Server/sqlite3/storage.ide-wal" | asposeemail/Aspose_Email_NET,aspose-email/Aspose.Email-for-.NET | Examples/CSharp/Outlook/OLM/LoadAndReadOLMFile.cs | Examples/CSharp/Outlook/OLM/LoadAndReadOLMFile.cs | using System;
using Aspose.Email.Storage.Olm;
using Aspose.Email.Mapi;
namespace Aspose.Email.Examples.CSharp.Email.Outlook.OLM
{
class LoadAndReadOLMFile
{
public static void Run()
{
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Outlook();
string dst = dataDir + "OutlookforMac.olm";
// ExStart:LoadAndReadOLMFile
using (OlmStorage storage = new OlmStorage(dst))
{
foreach (OlmFolder folder in storage.FolderHierarchy)
{
if (folder.HasMessages)
{
// extract messages from folder
foreach (MapiMessage msg in storage.EnumerateMessages(folder))
{
Console.WriteLine("Subject: " + msg.Subject);
}
}
// read sub-folders
if (folder.SubFolders.Count > 0)
{
foreach (OlmFolder sub_folder in folder.SubFolders)
{
Console.WriteLine("Subfolder: " + sub_folder.Name);
}
}
}
}
// ExEnd:LoadAndReadOLMFile
}
}
}
| using System;
using Aspose.Email.Storage.Olm;
using Aspose.Email.Mapi;
namespace Aspose.Email.Examples.CSharp.Email.Outlook.OLM
{
class LoadAndReadOLMFile
{
public static void Run()
{
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Outlook();
string dst = dataDir + "OutlookforMac.olm";
// ExStart:LoadAndReadOLMFile
using (OlmStorage storage = new OlmStorage(dst))
{
foreach (OlmFolder folder in storage.FolderHierarchy)
{
if (folder.HasMessages)
{
// extract messages from folder
foreach (MapiMessage msg in storage.EnumerateMessages(folder))
{
Console.WriteLine("Subject: " + msg.Subject);
}
}
// read sub-folders
if (folder.SubFolders.Count > 0)
{
foreach (OlmFolder sub_folder in folder.SubFolders)
{
Console.WriteLine("Subfolder: " + sub_folder.Name);
}
}
}
}
// ExEnd:LoadAndReadOLMFile
}
}
}
| mit | C# |
722acd98f7a5b70c27304f10171921f36ae88399 | Add ids from service endpoint | andyfmiller/LtiLibrary | LtiLibrary.AspNet/Outcomes/v2/PutResultContext.cs | LtiLibrary.AspNet/Outcomes/v2/PutResultContext.cs | using System.Net;
using LtiLibrary.Core.Outcomes.v2;
namespace LtiLibrary.AspNet.Outcomes.v2
{
public class PutResultContext
{
public PutResultContext(string contextId, string lineItemId, string id, LisResult result)
{
ContextId = contextId;
LineItemId = lineItemId;
Id = id;
Result = result;
StatusCode = HttpStatusCode.OK;
}
public string ContextId { get; set; }
public string LineItemId { get; set; }
public string Id { get; set; }
public LisResult Result { get; private set; }
public HttpStatusCode StatusCode { get; set; }
}
}
| using System.Net;
using LtiLibrary.Core.Outcomes.v2;
namespace LtiLibrary.AspNet.Outcomes.v2
{
public class PutResultContext
{
public PutResultContext(LisResult result)
{
Result = result;
StatusCode = HttpStatusCode.OK;
}
public LisResult Result { get; private set; }
public HttpStatusCode StatusCode { get; set; }
}
}
| apache-2.0 | C# |
0d555a2e680d7068298dc0e7daa5c84bba037aa0 | Rewrite LodViewQueryable Class | inohiro/LodViewProvider | LodViewProvider/LodViewProvider/LodViewQueryable.cs | LodViewProvider/LodViewProvider/LodViewQueryable.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Objects;
namespace LodViewProvider {
public class LodViewQueryable : IQueryable<Resource> { // IOrderedQueryable<Resource> {
public string ViewUrl { get; private set; }
public IQueryProvider Provider { get; private set; }
public Expression Expression { get; private set; }
public LodViewQueryable( LodViewContext context, string viewUrl ) {
ViewUrl = viewUrl;
Provider = new LodViewQueryProvider( viewUrl );
Expression = Expression.Constant( this );
}
internal LodViewQueryable( LodViewQueryProvider provider, Expression expression ) {
// TODO: Error processing is required
Provider = provider;
Expression = expression;
}
public IEnumerator<Resource> GetEnumerator() {
return Provider.Execute<IEnumerable<Resource>>( Expression ).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return ( Provider.Execute<IEnumerable>( Expression ) ).GetEnumerator();
}
public Type ElementType {
get { return typeof( Resource ); }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Objects;
namespace LodViewProvider {
public class LodViewExecute : IQueryable<Resource> { // IOrderedQueryable<Resource> {
public string ViewUrl { get; private set; }
public IQueryProvider Provider { get; private set; }
public Expression Expression { get; private set; }
public LodViewExecute( string viewUrl ) {
ViewUrl = viewUrl;
Provider = new LodViewQueryProvider( viewUrl );
Expression = Expression.Constant( this );
}
internal LodViewExecute( IQueryProvider provider, Expression expression ) {
Provider = provider;
Expression = expression;
}
public IEnumerator<Resource> GetEnumerator() {
return ( Provider.Execute<IEnumerable<Resource>>( Expression ) ).GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
// return Provider.Execute<System.Collections.IEnumerable>( Expression ).GetEnumerator();
return GetEnumerator();
}
public Type ElementType {
get { return typeof( Resource ); }
}
}
}
| mit | C# |
9c6d9e7085445a5b17a120ce08235277d65f3ede | Update XML comments | atata-framework/atata,atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata | src/Atata/Attributes/ControlSearch/FindSettingsAttribute.cs | src/Atata/Attributes/ControlSearch/FindSettingsAttribute.cs | using System;
namespace Atata
{
/// <summary>
/// Defines the settings to apply for the specified finding strategy of a control.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
public class FindSettingsAttribute : Attribute, IPropertySettings
{
public FindSettingsAttribute(FindTermBy by)
: this(by.ResolveFindAttributeType())
{
}
public FindSettingsAttribute(Type findAttributeType)
{
FindAttributeType = findAttributeType;
}
public PropertyBag Properties { get; } = new PropertyBag();
/// <summary>
/// Gets the type of the attribute to use for the control finding. Type should be inherited from <see cref="FindAttribute"/>.
/// </summary>
public Type FindAttributeType { get; private set; }
/// <summary>
/// Gets or sets the index of the control. The default value is -1, meaning that the index is not used.
/// </summary>
public int Index
{
get { return Properties.Get(nameof(Index), -1); }
set { Properties[nameof(Index)] = value; }
}
/// <summary>
/// Gets or sets the scope source. The default value is Parent.
/// </summary>
public ScopeSource ScopeSource
{
get { return Properties.Get(nameof(ScopeSource), ScopeSource.Parent); }
set { Properties[nameof(ScopeSource)] = value; }
}
/// <summary>
/// Gets or sets the strategy type for the control search. Strategy type should implement <see cref="IComponentScopeLocateStrategy"/>. The default value is null, meaning that the default strategy of the specific <see cref="FindAttribute"/> should be used.
/// </summary>
public Type Strategy
{
get { return Properties.Get<Type>(nameof(Strategy)); }
set { Properties[nameof(Strategy)] = value; }
}
/// <summary>
/// Gets or sets the visibility. The default value is Visible.
/// </summary>
public Visibility Visibility
{
get { return Properties.Get(nameof(Visibility), Visibility.Visible); }
set { Properties[nameof(Visibility)] = value; }
}
}
}
| using System;
namespace Atata
{
/// <summary>
/// Defines the settings to apply for the specified finding strategy of a control.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
public class FindSettingsAttribute : Attribute, IPropertySettings
{
public FindSettingsAttribute(FindTermBy by)
: this(by.ResolveFindAttributeType())
{
}
public FindSettingsAttribute(Type findAttributeType)
{
FindAttributeType = findAttributeType;
}
public PropertyBag Properties { get; } = new PropertyBag();
/// <summary>
/// Gets the type of the attribute to use for the control finding. Type should be inherited from <see cref="FindAttribute"/>.
/// </summary>
public Type FindAttributeType { get; private set; }
/// <summary>
/// Gets or sets the index of the control. The default value is -1, meaning that the index is not used.
/// </summary>
public int Index
{
get { return Properties.Get(nameof(Index), -1); }
set { Properties[nameof(Index)] = value; }
}
/// <summary>
/// Gets or sets the scope source. The default value is Parent.
/// </summary>
public ScopeSource ScopeSource
{
get { return Properties.Get(nameof(ScopeSource), ScopeSource.Parent); }
set { Properties[nameof(ScopeSource)] = value; }
}
/// <summary>
/// Gets or sets the strategy type for the control finding. Strategy type should implement <see cref="IComponentScopeLocateStrategy"/>. The default value is null, meaning that the default strategy of the specific <see cref="FindAttribute"/> should be used.
/// </summary>
public Type Strategy
{
get { return Properties.Get<Type>(nameof(Strategy)); }
set { Properties[nameof(Strategy)] = value; }
}
/// <summary>
/// Gets or sets the visibility. The default value is Visible.
/// </summary>
public Visibility Visibility
{
get { return Properties.Get(nameof(Visibility), Visibility.Visible); }
set { Properties[nameof(Visibility)] = value; }
}
}
}
| apache-2.0 | C# |
b372d8d533a30b5d613c50a476dcb32da68b83cc | Initialize gstreamer | Carbenium/banshee,arfbtwn/banshee,Dynalon/banshee-osx,petejohanson/banshee,stsundermann/banshee,mono-soc-2011/banshee,Dynalon/banshee-osx,lamalex/Banshee,lamalex/Banshee,stsundermann/banshee,Dynalon/banshee-osx,ixfalia/banshee,mono-soc-2011/banshee,lamalex/Banshee,allquixotic/banshee-gst-sharp-work,Carbenium/banshee,dufoli/banshee,dufoli/banshee,mono-soc-2011/banshee,arfbtwn/banshee,petejohanson/banshee,Carbenium/banshee,eeejay/banshee,GNOME/banshee,babycaseny/banshee,arfbtwn/banshee,directhex/banshee-hacks,allquixotic/banshee-gst-sharp-work,dufoli/banshee,ixfalia/banshee,mono-soc-2011/banshee,GNOME/banshee,GNOME/banshee,Dynalon/banshee-osx,babycaseny/banshee,petejohanson/banshee,GNOME/banshee,eeejay/banshee,GNOME/banshee,Carbenium/banshee,mono-soc-2011/banshee,Dynalon/banshee-osx,ixfalia/banshee,directhex/banshee-hacks,petejohanson/banshee,eeejay/banshee,allquixotic/banshee-gst-sharp-work,stsundermann/banshee,directhex/banshee-hacks,arfbtwn/banshee,stsundermann/banshee,directhex/banshee-hacks,lamalex/Banshee,mono-soc-2011/banshee,ixfalia/banshee,ixfalia/banshee,Dynalon/banshee-osx,allquixotic/banshee-gst-sharp-work,arfbtwn/banshee,lamalex/Banshee,Carbenium/banshee,GNOME/banshee,arfbtwn/banshee,ixfalia/banshee,allquixotic/banshee-gst-sharp-work,lamalex/Banshee,dufoli/banshee,eeejay/banshee,petejohanson/banshee,petejohanson/banshee,babycaseny/banshee,babycaseny/banshee,stsundermann/banshee,arfbtwn/banshee,ixfalia/banshee,stsundermann/banshee,Carbenium/banshee,babycaseny/banshee,mono-soc-2011/banshee,directhex/banshee-hacks,directhex/banshee-hacks,stsundermann/banshee,eeejay/banshee,dufoli/banshee,arfbtwn/banshee,babycaseny/banshee,GNOME/banshee,babycaseny/banshee,Dynalon/banshee-osx,ixfalia/banshee,Dynalon/banshee-osx,babycaseny/banshee,stsundermann/banshee,allquixotic/banshee-gst-sharp-work,dufoli/banshee,dufoli/banshee,dufoli/banshee,GNOME/banshee | src/Backends/Banshee.GStreamer/Banshee.GStreamer/Service.cs | src/Backends/Banshee.GStreamer/Banshee.GStreamer/Service.cs | //
// Service.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2007 Novell, Inc.
//
// 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.Runtime.InteropServices;
using Banshee.ServiceStack;
namespace Banshee.GStreamer
{
public class Service : IService
{
public Service ()
{
gstreamer_initialize ();
}
string IService.ServiceName {
get { return "GStreamerCoreService"; }
}
[DllImport("libbanshee")]
private static extern void gstreamer_initialize ();
}
}
| //
// Service.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2007 Novell, Inc.
//
// 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 Banshee.ServiceStack;
namespace Banshee.GStreamer
{
public class Service : IService
{
public Service()
{
Console.WriteLine ("Hello from GStreamer service");
}
string IService.ServiceName {
get { return "GStreamerCoreService"; }
}
}
}
| mit | C# |
cf7eb385fce5d124b256b129dc168b3fdd57da1d | Add message id to the log message | SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments | src/CommitmentsV2/SFA.DAS.CommitmentsV2.TestSubscriber/GenericHandler.cs | src/CommitmentsV2/SFA.DAS.CommitmentsV2.TestSubscriber/GenericHandler.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NServiceBus;
using SFA.DAS.CommitmentsV2.Messages.Events;
namespace SFA.DAS.CommitmentsV2.TestSubscriber
{
class GenericHandler
{
public Task Log(object message, IMessageHandlerContext context)
{
Console.WriteLine($"Received message id:{context.MessageId} type:{message.GetType().FullName} received:{DateTime.Now:T} Content: {JsonConvert.SerializeObject(message)}");
return Task.CompletedTask;
}
}
class ApprenticeshipCreatedEventHandler : GenericHandler, IHandleMessages<SFA.DAS.CommitmentsV2.Messages.Events.IApprenticeshipCreatedEvent>
{
public Task Handle(IApprenticeshipCreatedEvent message, IMessageHandlerContext context)
{
return Log(message, context);
}
}
class DataLockTriageApprovedEventHandler : GenericHandler, IHandleMessages<SFA.DAS.CommitmentsV2.Messages.Events.IDataLockTriageApprovedEvent>
{
public Task Handle(IDataLockTriageApprovedEvent message, IMessageHandlerContext context)
{
return Log(message, context);
}
}
class ApprenticeshipStoppedEventHandler : GenericHandler, IHandleMessages<SFA.DAS.CommitmentsV2.Messages.Events.IApprenticeshipStoppedEvent>
{
public Task Handle(IApprenticeshipStoppedEvent message, IMessageHandlerContext context)
{
return Log(message, context);
}
}
class DraftApprenticeshipDeletedEventHandler : GenericHandler, IHandleMessages<SFA.DAS.CommitmentsV2.Messages.Events.IDraftApprenticeshipDeletedEvent>
{
public Task Handle(IDraftApprenticeshipDeletedEvent message, IMessageHandlerContext context)
{
return Log(message, context);
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NServiceBus;
using SFA.DAS.CommitmentsV2.Messages.Events;
namespace SFA.DAS.CommitmentsV2.TestSubscriber
{
class GenericHandler
{
public Task Log(object message, IMessageHandlerContext context)
{
Console.WriteLine($"Received message type {message.GetType().FullName} : Content: {JsonConvert.SerializeObject(message)}");
return Task.CompletedTask;
}
}
class ApprenticeshipCreatedEventHandler : GenericHandler, IHandleMessages<SFA.DAS.CommitmentsV2.Messages.Events.IApprenticeshipCreatedEvent>
{
public Task Handle(IApprenticeshipCreatedEvent message, IMessageHandlerContext context)
{
return Log(message, context);
}
}
class DataLockTriageApprovedEventHandler : GenericHandler, IHandleMessages<SFA.DAS.CommitmentsV2.Messages.Events.IDataLockTriageApprovedEvent>
{
public Task Handle(IDataLockTriageApprovedEvent message, IMessageHandlerContext context)
{
return Log(message, context);
}
}
class ApprenticeshipStoppedEventHandler : GenericHandler, IHandleMessages<SFA.DAS.CommitmentsV2.Messages.Events.IApprenticeshipStoppedEvent>
{
public Task Handle(IApprenticeshipStoppedEvent message, IMessageHandlerContext context)
{
return Log(message, context);
}
}
class DraftApprenticeshipDeletedEventHandler : GenericHandler, IHandleMessages<SFA.DAS.CommitmentsV2.Messages.Events.IDraftApprenticeshipDeletedEvent>
{
public Task Handle(IDraftApprenticeshipDeletedEvent message, IMessageHandlerContext context)
{
return Log(message, context);
}
}
}
| mit | C# |
34568d2fc94aa2d02f58e3b61d4a263ff9ddcce0 | Stop wrapping exceptions we don't know about and let them throw at the point of error. | danhaller/SevenDigital.Api.Wrapper,knocte/SevenDigital.Api.Wrapper,raoulmillais/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,mattgray/SevenDigital.Api.Wrapper,gregsochanik/SevenDigital.Api.Wrapper,actionshrimp/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,danbadge/SevenDigital.Api.Wrapper,bnathyuw/SevenDigital.Api.Wrapper | src/SevenDigital.Api.Wrapper/Utility/Serialization/ApiXmlDeSerializer.cs | src/SevenDigital.Api.Wrapper/Utility/Serialization/ApiXmlDeSerializer.cs | namespace SevenDigital.Api.Wrapper.Utility.Serialization
{
public class ApiXmlDeSerializer<T> : IDeSerializer<T> where T : class
{
private readonly IDeSerializer<T> _deSerializer;
private readonly IXmlErrorHandler _xmlErrorHandler;
public ApiXmlDeSerializer(IDeSerializer<T> deSerializer, IXmlErrorHandler xmlErrorHandler) {
_deSerializer = deSerializer;
_xmlErrorHandler = xmlErrorHandler;
}
public T DeSerialize(string response)
{
var responseNode = _xmlErrorHandler.GetResponseAsXml(response);
_xmlErrorHandler.AssertError(responseNode);
var resourceNode = responseNode.FirstNode.ToString();
return _deSerializer.DeSerialize(resourceNode);
}
}
} | using System;
using SevenDigital.Api.Wrapper.Exceptions;
namespace SevenDigital.Api.Wrapper.Utility.Serialization
{
public class ApiXmlDeSerializer<T> : IDeSerializer<T> where T : class
{
private readonly IDeSerializer<T> _deSerializer;
private readonly IXmlErrorHandler _xmlErrorHandler;
public ApiXmlDeSerializer(IDeSerializer<T> deSerializer, IXmlErrorHandler xmlErrorHandler) {
_deSerializer = deSerializer;
_xmlErrorHandler = xmlErrorHandler;
}
public T DeSerialize(string response)
{
try
{
var responseNode = _xmlErrorHandler.GetResponseAsXml(response);
_xmlErrorHandler.AssertError(responseNode);
var resourceNode = responseNode.FirstNode.ToString();
return _deSerializer.DeSerialize(resourceNode);
}
catch (Exception e)
{
if (e is ApiXmlException)
throw;
throw new ApplicationException("Internal error while deserializing response " + response, e);
}
}
}
} | mit | C# |
553bd6c2b5c0e7c38d37d29a5b5eb10accaffedf | Rename LWM to Privacy Mode | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/WalletViewModel.cs | WalletWasabi.Fluent/ViewModels/WalletViewModel.cs | using NBitcoin;
using ReactiveUI;
using Splat;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using WalletWasabi.Gui;
using WalletWasabi.Logging;
using WalletWasabi.Wallets;
namespace WalletWasabi.Fluent.ViewModels
{
public class WalletViewModel : WalletViewModelBase
{
private ObservableCollection<ViewModelBase> _actions;
protected WalletViewModel(IScreen screen, UiConfig uiConfig, Wallet wallet) : base(screen, wallet)
{
Disposables = Disposables is null ? new CompositeDisposable() : throw new NotSupportedException($"Cannot open {GetType().Name} before closing it.");
Actions = new ObservableCollection<ViewModelBase>();
uiConfig = Locator.Current.GetService<Global>().UiConfig;
Observable.Merge(
Observable.FromEventPattern(Wallet.TransactionProcessor, nameof(Wallet.TransactionProcessor.WalletRelevantTransactionProcessed)).Select(_ => Unit.Default))
.Throttle(TimeSpan.FromSeconds(0.1))
.Merge(uiConfig.WhenAnyValue(x => x.PrivacyMode).Select(_ => Unit.Default))
.Merge(Wallet.Synchronizer.WhenAnyValue(x => x.UsdExchangeRate).Select(_ => Unit.Default))
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(_ =>
{
try
{
var balance = Wallet.Coins.TotalAmount();
Title = $"{WalletName} ({(uiConfig.PrivacyMode ? "#########" : balance.ToString(false, true))} BTC)";
TitleTip = balance.ToUsdString(Wallet.Synchronizer.UsdExchangeRate, uiConfig.PrivacyMode);
}
catch (Exception ex)
{
Logger.LogError(ex);
}
})
.DisposeWith(Disposables);
if (Wallet.KeyManager.IsHardwareWallet || !Wallet.KeyManager.IsWatchOnly)
{
}
if (!Wallet.KeyManager.IsWatchOnly)
{
}
}
private CompositeDisposable Disposables { get; set; }
public ObservableCollection<ViewModelBase> Actions
{
get => _actions;
set => this.RaiseAndSetIfChanged(ref _actions, value);
}
public override string IconName => "web_asset_regular";
public static WalletViewModel Create(IScreen screen, UiConfig uiConfig, Wallet wallet)
{
return wallet.KeyManager.IsHardwareWallet
? new HardwareWalletViewModel(screen, uiConfig, wallet)
: wallet.KeyManager.IsWatchOnly
? new WatchOnlyWalletViewModel(screen, uiConfig, wallet)
: new WalletViewModel(screen, uiConfig, wallet);
}
public void OpenWalletTabs()
{
// TODO: Implement.
}
}
}
| using NBitcoin;
using ReactiveUI;
using Splat;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using WalletWasabi.Gui;
using WalletWasabi.Logging;
using WalletWasabi.Wallets;
namespace WalletWasabi.Fluent.ViewModels
{
public class WalletViewModel : WalletViewModelBase
{
private ObservableCollection<ViewModelBase> _actions;
protected WalletViewModel(IScreen screen, UiConfig uiConfig, Wallet wallet) : base(screen, wallet)
{
Disposables = Disposables is null ? new CompositeDisposable() : throw new NotSupportedException($"Cannot open {GetType().Name} before closing it.");
Actions = new ObservableCollection<ViewModelBase>();
uiConfig = Locator.Current.GetService<Global>().UiConfig;
Observable.Merge(
Observable.FromEventPattern(Wallet.TransactionProcessor, nameof(Wallet.TransactionProcessor.WalletRelevantTransactionProcessed)).Select(_ => Unit.Default))
.Throttle(TimeSpan.FromSeconds(0.1))
.Merge(uiConfig.WhenAnyValue(x => x.LurkingWifeMode).Select(_ => Unit.Default))
.Merge(Wallet.Synchronizer.WhenAnyValue(x => x.UsdExchangeRate).Select(_ => Unit.Default))
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(_ =>
{
try
{
var balance = Wallet.Coins.TotalAmount();
Title = $"{WalletName} ({(uiConfig.LurkingWifeMode ? "#########" : balance.ToString(false, true))} BTC)";
TitleTip = balance.ToUsdString(Wallet.Synchronizer.UsdExchangeRate, uiConfig.LurkingWifeMode);
}
catch (Exception ex)
{
Logger.LogError(ex);
}
})
.DisposeWith(Disposables);
if (Wallet.KeyManager.IsHardwareWallet || !Wallet.KeyManager.IsWatchOnly)
{
}
if (!Wallet.KeyManager.IsWatchOnly)
{
}
}
private CompositeDisposable Disposables { get; set; }
public ObservableCollection<ViewModelBase> Actions
{
get => _actions;
set => this.RaiseAndSetIfChanged(ref _actions, value);
}
public override string IconName => "web_asset_regular";
public static WalletViewModel Create(IScreen screen, UiConfig uiConfig, Wallet wallet)
{
return wallet.KeyManager.IsHardwareWallet
? new HardwareWalletViewModel(screen, uiConfig, wallet)
: wallet.KeyManager.IsWatchOnly
? new WatchOnlyWalletViewModel(screen, uiConfig, wallet)
: new WalletViewModel(screen, uiConfig, wallet);
}
public void OpenWalletTabs()
{
// TODO: Implement.
}
}
}
| mit | C# |
dcf7049b07f09fe7b2b1d04ad3152d27cd4b402e | Support flags enums | lazlo-bonin/fullserializer,jacobdufault/fullserializer,Ksubaka/fullserializer,Ksubaka/fullserializer,nuverian/fullserializer,zodsoft/fullserializer,shadowmint/fullserializer,shadowmint/fullserializer,jagt/fullserializer,shadowmint/fullserializer,karlgluck/fullserializer,jacobdufault/fullserializer,Ksubaka/fullserializer,jagt/fullserializer,jagt/fullserializer,darress/fullserializer,jacobdufault/fullserializer,caiguihou/myprj_02 | src/Converters/EnumConverter.cs | src/Converters/EnumConverter.cs | using System;
namespace FullJson {
/// <summary>
/// Serializes and deserializes enums by their current name.
/// </summary>
public class EnumConverter : ISerializationConverter {
public SerializationConverterChain Converters {
get;
set;
}
public JsonConverter Converter {
get;
set;
}
public bool CanProcess(Type type) {
return type.IsEnum;
}
public JsonFailure TrySerialize(object instance, out JsonData serialized, Type storageType) {
if (Attribute.IsDefined(storageType, typeof(FlagsAttribute))) {
serialized = new JsonData(Convert.ToInt32(instance));
}
else {
serialized = new JsonData(Enum.GetName(storageType, instance));
}
return JsonFailure.Success;
}
public JsonFailure TryDeserialize(JsonData data, ref object instance, Type storageType) {
if (data.IsString) {
string enumValue = data.AsString;
instance = Enum.Parse(storageType, enumValue);
return JsonFailure.Success;
}
else if (data.IsFloat) {
int enumValue = (int)data.AsFloat;
instance = Enum.ToObject(storageType, enumValue);
return JsonFailure.Success;
}
return JsonFailure.Fail("EnumConverter encountered an unknown JSON data type");
}
public object CreateInstance(JsonData data, Type storageType) {
return 0;
}
}
} | using System;
namespace FullJson {
/// <summary>
/// Serializes and deserializes enums by their current name.
/// </summary>
public class EnumConverter : ISerializationConverter {
public SerializationConverterChain Converters {
get;
set;
}
public JsonConverter Converter {
get;
set;
}
public bool CanProcess(Type type) {
return type.IsEnum;
}
public JsonFailure TrySerialize(object instance, out JsonData serialized, Type storageType) {
serialized = new JsonData(Enum.GetName(storageType, instance));
return JsonFailure.Success;
}
public JsonFailure TryDeserialize(JsonData data, ref object instance, Type storageType) {
if (data.IsString == false) return JsonFailure.Fail("Enum converter can only deserialize strings");
string enumValue = data.AsString;
instance = Enum.Parse(storageType, enumValue);
return JsonFailure.Success;
}
public object CreateInstance(JsonData data, Type storageType) {
return 0;
}
}
} | mit | C# |
4d3328d4ad2c8d8a2d6337ac3acb37cd0d033f2a | implement a QByteArray ctor that takes a byte[] and a QByteArray.ToArray() method which returns a byte[]. | KDE/qyoto,KDE/qyoto | qyoto/core/QByteArrayExtras.cs | qyoto/core/QByteArrayExtras.cs | namespace Qyoto {
using System;
public partial class QByteArray : Object, IDisposable {
public QByteArray(byte[] array) : this(array.Length, '\0') {
Pointer<sbyte> p = Data();
for (int i = 0; i < array.Length; i++) {
p[i] = (sbyte) array[i];
}
}
public byte[] ToArray() {
Pointer<sbyte> p = Data();
byte[] array = new byte[Size()];
for (int i = 0; i < Size(); i++) {
array[i] = (byte) p[i];
}
return array;
}
public static implicit operator QByteArray(string arg) {
return new QByteArray(arg);
}
}
}
| namespace Qyoto {
using System;
public partial class QByteArray : Object, IDisposable {
public static implicit operator QByteArray(string arg) {
return new QByteArray(arg);
}
}
}
| lgpl-2.1 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.