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 |
|---|---|---|---|---|---|---|---|---|
e4fd4728d2e103db74ccbf6b978dde1c40aef417 | Fix brazier image loading bug | MoyTW/MTW_AncestorSpirits | Source/MTW_AncestorSpirits/Building_Brazier.cs | Source/MTW_AncestorSpirits/Building_Brazier.cs | using RimWorld;
using Verse;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MTW_AncestorSpirits
{
[StaticConstructorOnStartup]
class Building_Brazier : Building
{
private CompFlickable flickableComp;
private static Graphic graphicOn;
private static Graphic graphicOff;
public override Graphic Graphic
{
get
{
if (this.flickableComp.SwitchIsOn)
{
return Building_Brazier.graphicOn;
}
return Building_Brazier.graphicOff;
}
}
public bool IsActive { get { return this.flickableComp.SwitchIsOn; } }
static Building_Brazier()
{
graphicOn = GraphicDatabase.Get<Graphic_Single>("PlaceholderBrazierFrontFire");
graphicOff = GraphicDatabase.Get<Graphic_Single>("PlaceholderBrazierFront");
}
public override void SpawnSetup()
{
base.SpawnSetup();
this.flickableComp = base.GetComp<CompFlickable>();
}
public override void ExposeData()
{
base.ExposeData();
if (Scribe.mode == LoadSaveMode.PostLoadInit)
{
if (this.flickableComp == null)
{
this.flickableComp = base.GetComp<CompFlickable>();
}
}
}
public override string GetInspectString()
{
if (this.flickableComp.SwitchIsOn)
{
return "Active: Yes";
}
else
{
return "Active: No";
}
}
}
}
| using RimWorld;
using Verse;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MTW_AncestorSpirits
{
class Building_Brazier : Building
{
private CompFlickable flickableComp;
private static Graphic graphicOn;
private static Graphic graphicOff;
public override Graphic Graphic
{
get
{
if (this.flickableComp.SwitchIsOn)
{
return Building_Brazier.graphicOn;
}
return Building_Brazier.graphicOff;
}
}
public bool IsActive { get { return this.flickableComp.SwitchIsOn; } }
static Building_Brazier()
{
graphicOn = GraphicDatabase.Get<Graphic_Single>("PlaceholderBrazierFrontFire");
graphicOff = GraphicDatabase.Get<Graphic_Single>("PlaceholderBrazierFront");
}
public override void SpawnSetup()
{
base.SpawnSetup();
this.flickableComp = base.GetComp<CompFlickable>();
}
public override void ExposeData()
{
base.ExposeData();
if (Scribe.mode == LoadSaveMode.PostLoadInit)
{
if (this.flickableComp == null)
{
this.flickableComp = base.GetComp<CompFlickable>();
}
}
}
public override string GetInspectString()
{
if (this.flickableComp.SwitchIsOn)
{
return "Active: Yes";
}
else
{
return "Active: No";
}
}
}
}
| mit | C# |
19e8e1eafbc7de491db98290ce27f3c1522146d8 | Remove DocumentationRepository NotImplementedException() calls | Ontica/Empiria.Extended | Storage/Integration/DocumentationRepository.cs | Storage/Integration/DocumentationRepository.cs | /* Empiria Storage *******************************************************************************************
* *
* Module : Document Management Component : Domain Layer *
* Assembly : Empiria.Storage.dll Pattern : Service provider *
* Type : DocumentationRepository p[ara manLicense : Please read LICENSE.txt file *
* *
* Summary : Provides services to fill out the defined documentation of an entity in a given context. *
* *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
using System.Collections.Generic;
namespace Empiria.Storage.Documents {
static internal class DocumentationRepository {
internal static List<DocumentationRule> GetDocumentationRules(IIdentifiable definer) {
return new List<DocumentationRule>();
}
internal static List<Document> GetDocuments(IIdentifiable target) {
return new List<Document>();
}
} // class DocumentationRepository
} // namespace Empiria.Storage.Documents
| /* Empiria Storage *******************************************************************************************
* *
* Module : Document Management Component : Domain Layer *
* Assembly : Empiria.Storage.dll Pattern : Service provider *
* Type : DocumentationRepository p[ara manLicense : Please read LICENSE.txt file *
* *
* Summary : Provides services to fill out the defined documentation of an entity in a given context. *
* *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
using System.Collections.Generic;
namespace Empiria.Storage.Documents {
static internal class DocumentationRepository {
internal static List<DocumentationRule> GetDocumentationRules(IIdentifiable definer) {
throw new NotImplementedException();
}
internal static List<Document> GetDocuments(IIdentifiable target) {
throw new NotImplementedException();
}
} // class DocumentationRepository
} // namespace Empiria.Storage.Documents
| agpl-3.0 | C# |
37803f6362a9055b2020d497dee25a558f200980 | Resolve #423 -- Added direction data in coords command (#983) | LeagueSandbox/GameServer | GameServerLib/Chatbox/Commands/CoordsCommand.cs | GameServerLib/Chatbox/Commands/CoordsCommand.cs | using GameServerCore;
using LeagueSandbox.GameServer.Logging;
using log4net;
using System.Numerics;
using System;
namespace LeagueSandbox.GameServer.Chatbox.Commands
{
public class CoordsCommand : ChatCommandBase
{
private readonly ILog _logger;
private readonly IPlayerManager _playerManager;
public override string Command => "coords";
public override string Syntax => $"{Command}";
public CoordsCommand(ChatCommandManager chatCommandManager, Game game)
: base(chatCommandManager, game)
{
_logger = LoggerProvider.GetLogger();
_playerManager = game.PlayerManager;
}
public override void Execute(int userId, bool hasReceivedArguments, string arguments = "")
{
var champion = _playerManager.GetPeerInfo((ulong)userId).Champion;
_logger.Debug($"At {champion.X}; {champion.Y}");
var dirMsg = "Not moving anywhere";
if (!champion.IsPathEnded())
{
Vector2 dir = champion.GetDirection();
// Angle measured between [1, 0] and player direction vectors (to X axis)
double ang = Math.Acos(dir.X / dir.Length()) * (180 / Math.PI);
dirMsg = $"dirX: {dir.X} dirY: {dir.Y} dirAngle (to X axis): {ang}";
}
var msg = $"At Coords - X: {champion.X} Y: {champion.Y} Z: {champion.GetZ()} "+dirMsg;
ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.NORMAL, msg);
}
}
}
| using GameServerCore;
using LeagueSandbox.GameServer.Logging;
using log4net;
namespace LeagueSandbox.GameServer.Chatbox.Commands
{
public class CoordsCommand : ChatCommandBase
{
private readonly ILog _logger;
private readonly IPlayerManager _playerManager;
public override string Command => "coords";
public override string Syntax => $"{Command}";
public CoordsCommand(ChatCommandManager chatCommandManager, Game game)
: base(chatCommandManager, game)
{
_logger = LoggerProvider.GetLogger();
_playerManager = game.PlayerManager;
}
public override void Execute(int userId, bool hasReceivedArguments, string arguments = "")
{
var champion = _playerManager.GetPeerInfo((ulong)userId).Champion;
_logger.Debug($"At {champion.X}; {champion.Y}");
var msg = $"At Coords - X: {champion.X} Y: {champion.Y} Z: {champion.GetZ()}";
ChatCommandManager.SendDebugMsgFormatted(DebugMsgType.NORMAL, msg);
}
}
}
| agpl-3.0 | C# |
a24fac79011ccb878da898942ef2e3f94735a559 | Update some access modifiers to fix CA1401 violations | EMarshal/LockShowWindowContents | LockShowWindowContents/Helpers/NativeMethods.cs | LockShowWindowContents/Helpers/NativeMethods.cs | // <copyright file="NativeMethods.cs" company="Éli Marshal">
// Copyright (c) Éli Marshal. All rights reserved.
// </copyright>
namespace LockShowWindowContents.Helpers
{
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
/// <summary>
/// Contains native methods for SystemParametersInfo to use for SPI_SETDRAGFULLWINDOWS and SPI_GETDRAGFULLWINDOWS
/// </summary>
internal static class NativeMethods
{
/// <summary>
/// Constant 0x01.
/// </summary>
internal const short SPIF_UPDATEINIFILE = 0x01;
/// <summary>
/// Constant 0x02.
/// </summary>
internal const short SPIF_SENDCHANGE = 0x02;
/// <summary>
/// Constant 0x25.
/// </summary>
internal const short SPI_SETDRAGFULLWINDOWS = 0x25;
/// <summary>
/// Constant 0x26.
/// </summary>
internal const short SPI_GETDRAGFULLWINDOWS = 0x26;
/// <summary>
/// SystemParametersInfo call.
/// </summary>
/// <param name="uAction">System parameter to query or set.</param>
/// <param name="uParam">Depends on system parameter.</param>
/// <param name="lpvParam">Depends on system parameter.</param>
/// <param name="fuWinIni">WIN.INI update flag.</param>
/// <returns>True if successful</returns>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1625:ElementDocumentationMustNotBeCopiedAndPasted",
Justification = "Standard documentation.")]
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool SystemParametersInfo(int uAction, int uParam, ref bool lpvParam, int fuWinIni);
/// <summary>
/// SystemParametersInfo call.
/// </summary>
/// <param name="uAction">System parameter to query or set.</param>
/// <param name="uParam">Depends on system parameter.</param>
/// <param name="lpvParam">Depends on system parameter.</param>
/// <param name="fuWinIni">WIN.INI update flag.</param>
/// <returns>True if successful</returns>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1625:ElementDocumentationMustNotBeCopiedAndPasted",
Justification = "Standard documentation.")]
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool SystemParametersInfo(int uAction, bool uParam, string lpvParam, int fuWinIni);
}
}
| // <copyright file="NativeMethods.cs" company="Éli Marshal">
// Copyright (c) Éli Marshal. All rights reserved.
// </copyright>
namespace LockShowWindowContents.Helpers
{
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
/// <summary>
/// Contains native methods for SystemParametersInfo to use for SPI_SETDRAGFULLWINDOWS and SPI_GETDRAGFULLWINDOWS
/// </summary>
public static class NativeMethods
{
/// <summary>
/// Constant 0x01.
/// </summary>
public const short SPIF_UPDATEINIFILE = 0x01;
/// <summary>
/// Constant 0x02.
/// </summary>
public const short SPIF_SENDCHANGE = 0x02;
/// <summary>
/// Constant 0x25.
/// </summary>
public const short SPI_SETDRAGFULLWINDOWS = 0x25;
/// <summary>
/// Constant 0x26.
/// </summary>
public const short SPI_GETDRAGFULLWINDOWS = 0x26;
/// <summary>
/// SystemParametersInfo call.
/// </summary>
/// <param name="uAction">System parameter to query or set.</param>
/// <param name="uParam">Depends on system parameter.</param>
/// <param name="lpvParam">Depends on system parameter.</param>
/// <param name="fuWinIni">WIN.INI update flag.</param>
/// <returns>True if successful</returns>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1625:ElementDocumentationMustNotBeCopiedAndPasted",
Justification = "Standard documentation.")]
[DllImport("user32.dll", SetLastError = true)]
public static extern bool SystemParametersInfo(int uAction, int uParam, ref bool lpvParam, int fuWinIni);
/// <summary>
/// SystemParametersInfo call.
/// </summary>
/// <param name="uAction">System parameter to query or set.</param>
/// <param name="uParam">Depends on system parameter.</param>
/// <param name="lpvParam">Depends on system parameter.</param>
/// <param name="fuWinIni">WIN.INI update flag.</param>
/// <returns>True if successful</returns>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1625:ElementDocumentationMustNotBeCopiedAndPasted",
Justification = "Standard documentation.")]
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool SystemParametersInfo(int uAction, bool uParam, string lpvParam, int fuWinIni);
}
}
| isc | C# |
bf3f20a818b5c452da1060780f7a515f172d076e | Write out the number of arguments in the allocate instruction (I think we'll need these) | Logicalshift/Reason | LogicalShift.Reason/Solvers/ClauseCompiler.cs | LogicalShift.Reason/Solvers/ClauseCompiler.cs | using LogicalShift.Reason.Api;
using System;
using System.Collections.Generic;
using System.Linq;
namespace LogicalShift.Reason.Solvers
{
/// <summary>
/// Methods for compiling clauses to a bytecode program
/// </summary>
public static class ClauseCompiler
{
/// <summary>
/// Compiles a clause to a bytecode program
/// </summary>
public static void Compile(this IClause clause, ByteCodeProgram program)
{
var unifier = new ByteCodeUnifier(program);
// Take each part of the clause and retrieve the assignments for it, with the 'implies' set at the start
var allPredicates = new[] { clause.Implies }.Concat(clause.If).ToArray();
var assignmentList = allPredicates
.Select(predicate => new
{
Assignments = PredicateAssignmentList.FromPredicate(predicate),
UnificationKey = predicate.UnificationKey
})
.ToArray();
// Allocate space for the arguments and any permanent variables
var permanentVariables = PermanentVariableAssignments.PermanentVariables(assignmentList.Select(assign => assign.Assignments));
var numArguments = assignmentList[0].Assignments.CountArguments();
if (permanentVariables.Count > 0)
{
program.Write(Operation.Allocate, permanentVariables.Count, numArguments);
}
// Unify with the predicate first
unifier.ProgramUnifier.Bind(assignmentList[0].Assignments.Assignments, permanentVariables);
unifier.ProgramUnifier.Compile(assignmentList[0].Assignments.Assignments);
// Call the clauses
foreach (var assignment in assignmentList.Skip(1))
{
unifier.QueryUnifier.Bind(assignment.Assignments.Assignments, permanentVariables);
unifier.QueryUnifier.Compile(assignment.Assignments.Assignments);
program.Write(Operation.Call, assignment.UnificationKey);
}
// Deallocate any permanent variables that we might have found
if (permanentVariables.Count > 0)
{
program.Write(Operation.Deallocate);
}
}
}
}
| using LogicalShift.Reason.Api;
using System;
using System.Collections.Generic;
using System.Linq;
namespace LogicalShift.Reason.Solvers
{
/// <summary>
/// Methods for compiling clauses to a bytecode program
/// </summary>
public static class ClauseCompiler
{
/// <summary>
/// Compiles a clause to a bytecode program
/// </summary>
public static void Compile(this IClause clause, ByteCodeProgram program)
{
var unifier = new ByteCodeUnifier(program);
// Take each part of the clause and retrieve the assignments for it, with the 'implies' set at the start
var allPredicates = new[] { clause.Implies }.Concat(clause.If).ToArray();
var assignmentList = allPredicates
.Select(predicate => new
{
Assignments = PredicateAssignmentList.FromPredicate(predicate),
UnificationKey = predicate.UnificationKey
})
.ToArray();
// Allocate space for the arguments and any permanent variables
var permanentVariables = PermanentVariableAssignments.PermanentVariables(assignmentList.Select(assign => assign.Assignments));
if (permanentVariables.Count > 0)
{
program.Write(Operation.Allocate, permanentVariables.Count);
}
// Unify with the predicate first
unifier.ProgramUnifier.Bind(assignmentList[0].Assignments.Assignments, permanentVariables);
unifier.ProgramUnifier.Compile(assignmentList[0].Assignments.Assignments);
// Call the clauses
foreach (var assignment in assignmentList.Skip(1))
{
unifier.QueryUnifier.Bind(assignment.Assignments.Assignments, permanentVariables);
unifier.QueryUnifier.Compile(assignment.Assignments.Assignments);
program.Write(Operation.Call, assignment.UnificationKey);
}
// Deallocate any permanent variables that we might have found
if (permanentVariables.Count > 0)
{
program.Write(Operation.Deallocate);
}
}
}
}
| apache-2.0 | C# |
13044abd9a4d3c401d8259af9fef9512faf37f2e | Fix type of the serialized resource version | k-t/SharpHaven | MonoHaven.Lib/Resources/ResourceSerializer.cs | MonoHaven.Lib/Resources/ResourceSerializer.cs | using System;
using System.Collections.Generic;
using System.IO;
using C5;
namespace MonoHaven.Resources
{
public class ResourceSerializer
{
private const string Signature = "Haven Resource 1";
private readonly TreeDictionary<string, IDataLayerSerializer> serializers;
public ResourceSerializer()
{
serializers = new TreeDictionary<string, IDataLayerSerializer>();
// register default serializers
Register(new ActionDataSerializer());
Register(new AnimDataSerializer());
Register(new ImageDataSerializer());
Register(new NegDataSerializer());
Register(new TextDataSerializer());
Register(new TileDataSerializer());
Register(new TilesetDataSerializer());
Register(new TooltipSerializer());
}
public void Register(IDataLayerSerializer serializer)
{
serializers[serializer.LayerName] = serializer;
}
public Resource Deserialize(Stream stream)
{
var reader = new BinaryReader(stream);
var sig = new String(reader.ReadChars(Signature.Length));
if (sig != Signature)
throw new ResourceException("Invalid signature");
var version = reader.ReadUInt16();
var layers = new List<object>();
while (true)
{
var layer = ReadLayer(reader);
if (layer == null)
break;
layers.Add(layer);
}
return new Resource(version, layers);
}
private object ReadLayer(BinaryReader reader)
{
var type = reader.ReadCString();
if (string.IsNullOrEmpty(type))
return null;
var size = reader.ReadInt32();
var serializer = GetSerializer(type);
if (serializer == null)
{
// skip layer data
reader.ReadBytes(size);
return new UnknownDataLayer(type);
}
return serializer.Deserialize(size, reader);
}
private IDataLayerSerializer GetSerializer(string layerName)
{
IDataLayerSerializer serializer;
return serializers.Find(ref layerName, out serializer) ? serializer : null;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using C5;
namespace MonoHaven.Resources
{
public class ResourceSerializer
{
private const string Signature = "Haven Resource 1";
private readonly TreeDictionary<string, IDataLayerSerializer> serializers;
public ResourceSerializer()
{
serializers = new TreeDictionary<string, IDataLayerSerializer>();
// register default serializers
Register(new ActionDataSerializer());
Register(new AnimDataSerializer());
Register(new ImageDataSerializer());
Register(new NegDataSerializer());
Register(new TextDataSerializer());
Register(new TileDataSerializer());
Register(new TilesetDataSerializer());
Register(new TooltipSerializer());
}
public void Register(IDataLayerSerializer serializer)
{
serializers[serializer.LayerName] = serializer;
}
public Resource Deserialize(Stream stream)
{
var reader = new BinaryReader(stream);
var sig = new String(reader.ReadChars(Signature.Length));
if (sig != Signature)
throw new ResourceException("Invalid signature");
var version = reader.ReadInt16();
var layers = new List<object>();
while (true)
{
var layer = ReadLayer(reader);
if (layer == null)
break;
layers.Add(layer);
}
return new Resource(version, layers);
}
private object ReadLayer(BinaryReader reader)
{
var type = reader.ReadCString();
if (string.IsNullOrEmpty(type))
return null;
var size = reader.ReadInt32();
var serializer = GetSerializer(type);
if (serializer == null)
{
// skip layer data
reader.ReadBytes(size);
return new UnknownDataLayer(type);
}
return serializer.Deserialize(size, reader);
}
private IDataLayerSerializer GetSerializer(string layerName)
{
IDataLayerSerializer serializer;
return serializers.Find(ref layerName, out serializer) ? serializer : null;
}
}
}
| mit | C# |
84c0ff1e9cd1a425c67837cb56676ce4ff4052d5 | simplify method to fill MongoDB with data | Team-LemonDrop/NBA-Statistics | NBAStatistics.Data.FillMongoDB/FillMongoDB.cs | NBAStatistics.Data.FillMongoDB/FillMongoDB.cs | using MongoDB.Bson;
using MongoDB.Driver;
using NBAStatistics.Models;
using NBAStatistics.Data.FillMongoDB.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBAStatistics.Data.FillMongoDB
{
public class FillMongoDB
{
private const string User = "miro";
private const string Pass = "1qazcde3";
private const string DbHost = "ds029565.mlab.com";
private const int DbPort = 29565;
private const string DbName = "appharbor_5cwg75nh";
public async static Task FillDatabase(IEnumerable<BsonDocument> bsonDocument, string collectionName)
{
await Task.Run(() =>
{
var credentials = MongoCredential.CreateCredential(DbName, User, Pass);
var settings = new MongoClientSettings
{
Server = new MongoServerAddress(DbHost, DbPort),
Credentials = new List<MongoCredential> { credentials }
};
var client = new MongoClient(settings);
var db = client.GetDatabase(DbName);
if (bsonDocument.Count() > 0)
{
var collection = db.GetCollection<BsonDocument>(collectionName);
collection.InsertMany(bsonDocument);
}
});
}
}
}
| using MongoDB.Bson;
using MongoDB.Driver;
using NBAStatistics.Models;
using NBAStatistics.Data.FillMongoDB.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBAStatistics.Data.FillMongoDB
{
public class FillMongoDB
{
private const string User = "miro";
private const string Pass = "1qazcde3";
private const string DbHost = "ds029565.mlab.com";
private const int DbPort = 29565;
private const string DbName = "appharbor_5cwg75nh";
public async static Task FillDatabase(
IEnumerable<BsonDocument> seasons,
IEnumerable<BsonDocument> players,
IEnumerable<BsonDocument> coaches)
{
await Task.Run(() =>
{
var credentials = MongoCredential.CreateCredential(DbName, User, Pass);
var settings = new MongoClientSettings
{
Server = new MongoServerAddress(DbHost, DbPort),
Credentials = new List<MongoCredential> { credentials }
};
var client = new MongoClient(settings);
var db = client.GetDatabase(DbName);
var seasonsCollection = db.GetCollection<BsonDocument>("Seasons");
seasonsCollection.InsertMany(seasons);
var playersCollection = db.GetCollection<BsonDocument>("Players");
playersCollection.InsertMany(players);
var coachesCollection = db.GetCollection<BsonDocument>("Coaches");
coachesCollection.InsertMany(coaches);
});
}
}
}
| mit | C# |
d4cb1c078cbfdb409191290015a0bda6e78d08a1 | fix StateMachineBuildHierarchy Test | appccelerate/statemachine | source/Appccelerate.StateMachine.Facts/Machine/StateMachineBuildHierarchyTest.cs | source/Appccelerate.StateMachine.Facts/Machine/StateMachineBuildHierarchyTest.cs | //-------------------------------------------------------------------------------
// <copyright file="StateMachineBuildHierarchyTest.cs" company="Appccelerate">
// Copyright (c) 2008-2017 Appccelerate
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace Appccelerate.StateMachine.Facts.Machine
{
using System;
using FluentAssertions;
using StateMachine.Machine;
using Xunit;
/// <summary>
/// Tests hierarchy building in the <see cref="StateMachine{TState,TEvent}"/>.
/// </summary>
public class StateMachineBuildHierarchyTest
{
/// <summary>
/// If the super-state is specified as the initial state of its sub-states then an <see cref="ArgumentException"/> is thrown.
/// </summary>
[Fact]
public void AddHierarchicalStatesInitialStateIsSuperStateItself()
{
var stateMachineDefinitionBuilder = new StateMachineDefinitionBuilder<StateMachine.States, Events>()
.WithConfiguration(sm =>
sm
.DefineHierarchyOn(StateMachine.States.B)
.WithHistoryType(HistoryType.None)
.WithInitialSubState(StateMachine.States.B)
.WithSubState(StateMachine.States.B1)
.WithSubState(StateMachine.States.B2));
Action a = () => stateMachineDefinitionBuilder.Build();
a.Should().Throw<ArgumentException>();
}
}
} | //-------------------------------------------------------------------------------
// <copyright file="StateMachineBuildHierarchyTest.cs" company="Appccelerate">
// Copyright (c) 2008-2017 Appccelerate
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace Appccelerate.StateMachine.Machine
{
using System;
using FluentAssertions;
using Xunit;
/// <summary>
/// Tests hierarchy building in the <see cref="StateMachine{TState,TEvent}"/>.
/// </summary>
public class StateMachineBuildHierarchyTest
{
/// <summary>
/// Object under test.
/// </summary>
private readonly StateMachine<StateMachine.States, StateMachine.Events> testee;
/// <summary>
/// Initializes a new instance of the <see cref="StateMachineBuildHierarchyTest"/> class.
/// </summary>
public StateMachineBuildHierarchyTest()
{
this.testee = new StateMachine<StateMachine.States, StateMachine.Events>();
}
/// <summary>
/// If the super-state is specified as the initial state of its sub-states then an <see cref="ArgumentException"/> is thrown.
/// </summary>
[Fact]
public void AddHierarchicalStatesInitialStateIsSuperStateItself()
{
Action action = () => this.testee.DefineHierarchyOn(StateMachine.States.B)
.WithHistoryType(HistoryType.None)
.WithInitialSubState(StateMachine.States.B)
.WithSubState(StateMachine.States.B1)
.WithSubState(StateMachine.States.B2);
action.Should().Throw<ArgumentException>();
}
}
} | apache-2.0 | C# |
8df8a167abd82dc53c2a33f0ea8b2326fb8d7855 | Update SerializationRestFactory.cs | tiksn/TIKSN-Framework | TIKSN.Core/Web/Rest/SerializationRestFactory.cs | TIKSN.Core/Web/Rest/SerializationRestFactory.cs | using System;
using System.Collections.Generic;
using TIKSN.Serialization;
namespace TIKSN.Web.Rest
{
public class SerializationRestFactory : ISerializerRestFactory, IDeserializerRestFactory
{
private readonly IDictionary<string, Tuple<ISerializer<string>, IDeserializer<string>>> map;
public SerializationRestFactory(JsonSerializer jsonSerializer, JsonDeserializer jsonDeserializer,
DotNetXmlSerializer dotNetXmlSerializer, DotNetXmlDeserializer dotNetXmlDeserializer) => this.map = new Dictionary<string, Tuple<ISerializer<string>, IDeserializer<string>>>
{
{
"application/json",
new Tuple<ISerializer<string>, IDeserializer<string>>(jsonSerializer, jsonDeserializer)
},
{
"application/xml",
new Tuple<ISerializer<string>, IDeserializer<string>>(dotNetXmlSerializer, dotNetXmlDeserializer)
}
};
IDeserializer<string> IDeserializerRestFactory.Create(string mediaType) => this.map[mediaType].Item2;
ISerializer<string> ISerializerRestFactory.Create(string mediaType) => this.map[mediaType].Item1;
}
}
| using System;
using System.Collections.Generic;
using TIKSN.Serialization;
namespace TIKSN.Web.Rest
{
public class SerializationRestFactory : ISerializerRestFactory, IDeserializerRestFactory
{
private readonly IDictionary<string, Tuple<ISerializer<string>, IDeserializer<string>>> map;
public SerializationRestFactory(JsonSerializer jsonSerializer, JsonDeserializer jsonDeserializer,
DotNetXmlSerializer dotNetXmlSerializer, DotNetXmlDeserializer dotNetXmlDeserializer)
{
this.map = new Dictionary<string, Tuple<ISerializer<string>, IDeserializer<string>>>();
this.map.Add("application/json",
new Tuple<ISerializer<string>, IDeserializer<string>>(jsonSerializer, jsonDeserializer));
this.map.Add("application/xml",
new Tuple<ISerializer<string>, IDeserializer<string>>(dotNetXmlSerializer, dotNetXmlDeserializer));
}
IDeserializer<string> IDeserializerRestFactory.Create(string mediaType) => this.map[mediaType].Item2;
ISerializer<string> ISerializerRestFactory.Create(string mediaType) => this.map[mediaType].Item1;
}
}
| mit | C# |
7a3cc5207ead6d56ce0d114d8093ca23feb94994 | Extend color selector example | residuum/xwt,iainx/xwt,lytico/xwt,hamekoz/xwt,mminns/xwt,mono/xwt,sevoku/xwt,directhex/xwt,steffenWi/xwt,akrisiun/xwt,TheBrainTech/xwt,mminns/xwt,cra0zy/xwt,hwthomas/xwt,antmicro/xwt | TestApps/Samples/Samples/ColorSelectorSample.cs | TestApps/Samples/Samples/ColorSelectorSample.cs | //
// ColorSelectorSample.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2012 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 ColorSelectorSample: VBox
{
public ColorSelectorSample ()
{
ColorSelector sel = new ColorSelector ();
sel.Color = Xwt.Drawing.Colors.AliceBlue;
Label l1 = new Label (sel.Color.ToString ());
Label l2 = new Label ();
l2.BackgroundColor = sel.Color;
sel.ColorChanged += (sender, e) => {
l2.BackgroundColor = sel.Color;
l1.Text = sel.Color.ToString ();
};
PackStart (sel);
PackStart (l1);
PackStart (l2);
}
}
}
| //
// ColorSelectorSample.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2012 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 ColorSelectorSample: VBox
{
public ColorSelectorSample ()
{
ColorSelector sel = new ColorSelector ();
sel.Color = Xwt.Drawing.Colors.AliceBlue;
PackStart (sel);
}
}
}
| mit | C# |
06606dd8767f3181eb8394d81d6a6c1b904efc96 | Fix regression with collection functions (not properly encoding the "IN" portion) | couchbase/couchbase-lite-net,couchbase/couchbase-lite-net,couchbase/couchbase-lite-net | src/Couchbase.Lite/Query/QueryTernaryExpression.cs | src/Couchbase.Lite/Query/QueryTernaryExpression.cs | //
// QueryTernaryExpression.cs
//
// Author:
// Jim Borden <jim.borden@couchbase.com>
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using Couchbase.Lite.Query;
using Couchbase.Lite.Util;
namespace Couchbase.Lite.Internal.Query
{
internal sealed class QueryTernaryExpression : QueryExpression, IExpressionIn, IExpressionSatisfies
{
#region Variables
private readonly string _function;
private readonly string _variableName;
private object _in;
private QueryExpression _predicate;
#endregion
#region Constructors
internal QueryTernaryExpression(string function, string variableName)
{
_function = function;
_variableName = variableName;
}
#endregion
#region Overrides
protected override object ToJSON()
{
var inObj = _in;
if (_in is QueryExpression e) {
inObj = e.ConvertToJSON();
}
return new[] {
_function,
_variableName,
inObj,
_predicate?.ConvertToJSON()
};
}
#endregion
#region IExpressionIn
public IExpressionSatisfies In(object expression)
{
_in = expression;
return this;
}
#endregion
#region IExpressionSatisfies
public IExpression Satisfies(IExpression expression)
{
_predicate = Misc.TryCast<IExpression, QueryExpression>(expression);
return this;
}
#endregion
}
} | //
// QueryTernaryExpression.cs
//
// Author:
// Jim Borden <jim.borden@couchbase.com>
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using Couchbase.Lite.Query;
using Couchbase.Lite.Util;
namespace Couchbase.Lite.Internal.Query
{
internal sealed class QueryTernaryExpression : QueryExpression, IExpressionIn, IExpressionSatisfies
{
#region Variables
private readonly string _function;
private readonly string _variableName;
private object _in;
private QueryExpression _predicate;
#endregion
#region Constructors
internal QueryTernaryExpression(string function, string variableName)
{
_function = function;
_variableName = variableName;
}
#endregion
#region Overrides
protected override object ToJSON()
{
return new[] {
_function,
_variableName,
_in,
_predicate?.ConvertToJSON()
};
}
#endregion
#region IExpressionIn
public IExpressionSatisfies In(object expression)
{
_in = expression;
return this;
}
#endregion
#region IExpressionSatisfies
public IExpression Satisfies(IExpression expression)
{
_predicate = Misc.TryCast<IExpression, QueryExpression>(expression);
return this;
}
#endregion
}
} | apache-2.0 | C# |
2be00db09bfefd185d2f4960152a613f4eb6d06a | remove Destination from connection to make generic | LagoVista/DeviceAdmin | src/LagoVista.IoT.DeviceAdmin/Models/Connection.cs | src/LagoVista.IoT.DeviceAdmin/Models/Connection.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LagoVista.IoT.DeviceAdmin.Models
{
public class Connection
{
public String NodeKey { get; set; }
public String NodeName { get; set; }
public String NodeType { get; set; }
public String Script { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LagoVista.IoT.DeviceAdmin.Models
{
public class Connection
{
public String DestinationKey { get; set; }
public String DestinationName { get; set; }
public String DestinationType { get; set; }
public String Script { get; set; }
}
}
| mit | C# |
070270f1b2b640a8293a957ca0d77a1c6f8f9405 | test - ToClr, FromClr | iolevel/peachpie,peachpiecompiler/peachpie,iolevel/peachpie-concept,peachpiecompiler/peachpie,peachpiecompiler/peachpie,iolevel/peachpie,iolevel/peachpie,iolevel/peachpie-concept,iolevel/peachpie-concept | src/Tests/Peachpie.Runtime.Tests/PhpValue.Tests.cs | src/Tests/Peachpie.Runtime.Tests/PhpValue.Tests.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Pchp.Core;
namespace Peachpie.Runtime.Tests
{
[TestClass]
public class PhpValueTest
{
[TestMethod]
public void StringLongConversion()
{
Assert.AreEqual(Pchp.Core.Convert.StringToLongInteger("1"), 1);
}
[TestMethod]
public void ClrConversion()
{
// CLR -> Value -> CLR
var objects = new object[] { 0L, 1L, true, 1.2, new object(), "Hello", new PhpArray() };
var values = PhpValue.FromClr(objects);
Assert.AreEqual(objects.Length, values.Length);
for (int i = 0; i < objects.Length; i++)
{
Assert.AreEqual(objects[i], values[i].ToClr());
}
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Pchp.Core;
namespace Peachpie.Runtime.Tests
{
[TestClass]
public class PhpValueTest
{
[TestMethod]
public void StringLongConversion()
{
Assert.AreEqual(Pchp.Core.Convert.StringToLongInteger("1"), 1);
}
}
}
| apache-2.0 | C# |
5faa74ebca05b9656c1c5fda5e41a6cf419b31d0 | Update StructuredLoggerCheckerUtil.cs | jasonmalinowski/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,mavasani/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,dotnet/roslyn | src/Tools/BuildBoss/StructuredLoggerCheckerUtil.cs | src/Tools/BuildBoss/StructuredLoggerCheckerUtil.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.IO;
using System.Linq;
using Microsoft.Build.Logging.StructuredLogger;
namespace BuildBoss
{
/// <summary>
/// This type invokes the analyzer here:
///
/// https://github.com/KirillOsenkov/MSBuildStructuredLog/blob/master/src/StructuredLogger/Analyzers/DoubleWritesAnalyzer.cs
///
/// </summary>
internal sealed class StructuredLoggerCheckerUtil : ICheckerUtil
{
private readonly string _logFilePath;
internal StructuredLoggerCheckerUtil(string logFilePath)
{
_logFilePath = logFilePath;
}
public bool Check(TextWriter textWriter)
{
try
{
var build = Serialization.Read(_logFilePath);
var doubleWrites = DoubleWritesAnalyzer.GetDoubleWrites(build).ToArray();
// Issue https://github.com/dotnet/roslyn/issues/62372
if (doubleWrites.Any(doubleWrite => Path.GetFileName(doubleWrite.Key) != "Microsoft.VisualStudio.Text.Internal.dll"))
{
foreach (var doubleWrite in doubleWrites)
{
textWriter.WriteLine($"Multiple writes to {doubleWrite.Key}");
foreach (var source in doubleWrite.Value)
{
textWriter.WriteLine($"\t{source}");
}
textWriter.WriteLine();
}
return false;
}
return true;
}
catch (Exception ex)
{
textWriter.WriteLine($"Error processing binary log file: {ex.Message}");
return false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.IO;
using System.Linq;
using Microsoft.Build.Logging.StructuredLogger;
namespace BuildBoss
{
/// <summary>
/// This type invokes the analyzer here:
///
/// https://github.com/KirillOsenkov/MSBuildStructuredLog/blob/master/src/StructuredLogger/Analyzers/DoubleWritesAnalyzer.cs
///
/// </summary>
internal sealed class StructuredLoggerCheckerUtil : ICheckerUtil
{
private readonly string _logFilePath;
internal StructuredLoggerCheckerUtil(string logFilePath)
{
_logFilePath = logFilePath;
}
public bool Check(TextWriter textWriter)
{
try
{
var build = Serialization.Read(_logFilePath);
var doubleWrites = DoubleWritesAnalyzer.GetDoubleWrites(build).ToArray();
if (doubleWrites.Any())
{
foreach (var doubleWrite in doubleWrites)
{
// Issue https://github.com/dotnet/roslyn/issues/62372
if (Path.GetFileName(doubleWrite.Key) == "Microsoft.VisualStudio.Text.Internal.dll")
{
continue;
}
textWriter.WriteLine($"Multiple writes to {doubleWrite.Key}");
foreach (var source in doubleWrite.Value)
{
textWriter.WriteLine($"\t{source}");
}
textWriter.WriteLine();
}
return false;
}
return true;
}
catch (Exception ex)
{
textWriter.WriteLine($"Error processing binary log file: {ex.Message}");
return false;
}
}
}
}
| mit | C# |
7c6eb461ca925c6eb006f587ca1ad94c6a4f00ef | fix build after merge | dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS | src/Umbraco.Core/Packaging/PackageMigrationPlan.cs | src/Umbraco.Core/Packaging/PackageMigrationPlan.cs | using System;
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.Migrations;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Packaging
{
/// <summary>
/// Base class for package migration plans
/// </summary>
public abstract class PackageMigrationPlan : MigrationPlan, IDiscoverable
{
/// <summary>
/// Creates a package migration plan
/// </summary>
/// <param name="packageName">The name of the package. If the package has a package.manifest these must match.</param>
protected PackageMigrationPlan(string packageName) : this(packageName, packageName)
{
}
/// <summary>
/// Create a plan for a Package Name
/// </summary>
/// <param name="packageName">The package name that the plan is for. If the package has a package.manifest these must match.</param>
/// <param name="planName">
/// The plan name for the package. This should be the same name as the
/// package name if there is only one plan in the package.
/// </param>
protected PackageMigrationPlan(string packageName, string planName) : base(planName)
{
// A call to From must be done first
From(string.Empty);
DefinePlan();
PackageName = packageName;
}
/// <summary>
/// Inform the plan executor to ignore all saved package state and
/// run the migration from initial state to it's end state.
/// </summary>
public override bool IgnoreCurrentState => true;
/// <summary>
/// Returns the Package Name for this plan
/// </summary>
public string PackageName { get; }
protected abstract void DefinePlan();
}
}
| using System;
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.Migrations;
using Umbraco.Extensions;
namespace Umbraco.Cms.Core.Packaging
{
/// <summary>
/// Base class for package migration plans
/// </summary>
public abstract class PackageMigrationPlan : MigrationPlan, IDiscoverable
{
/// <summary>
/// Creates a package migration plan
/// </summary>
/// <param name="packageName">The name of the package. If the package has a package.manifest these must match.</param>
protected PackageMigrationPlan(string packageName) : this(packageName, packageName)
{
}
/// <summary>
/// Create a plan for a Package Name
/// </summary>
/// <param name="packageName">The package name that the plan is for. If the package has a package.manifest these must match.</param>
/// <param name="planName">
/// The plan name for the package. This should be the same name as the
/// package name if there is only one plan in the package.
/// </param>
protected PackageMigrationPlan(string packageName, string planName) : base(planName)
{
// A call to From must be done first
From(string.Empty);
DefinePlan();
PackageName = packageName;
}
/// <summary>
/// Inform the plan executor to ignore all saved package state and
/// run the migration from initial state to it's end state.
/// </summary>
public override bool IgnoreCurrentState => true;
/// <summary>
/// Returns the Package Name for this plan
/// </summary>
public string PackageName { get; }
/// <summary>
/// Inform the plan executor to ignore all saved package state and
/// run the migration from initial state to it's end state.
/// </summary>
public override bool IgnoreCurrentState => true;
protected abstract void DefinePlan();
}
}
| mit | C# |
0f6f7428564a2fd3fac0f0ebbc6ada098312415d | apply pattern to switch | bgTeamDev/bgTeam.Core,bgTeamDev/bgTeam.Core | src/bgTeam.Prometheus.Impl/PrometheusExtensions.cs | src/bgTeam.Prometheus.Impl/PrometheusExtensions.cs | using System;
using Prometheus;
namespace bgTeam.Prometheus.Impl
{
public static class PrometheusExtensions
{
public static IDisposable MeasureDuration<T>(this T @this, params string[] labels)
where T : Collector
{
switch (@this)
{
case Histogram histogram: return new HistogramWatcher(histogram, labels);
default: throw new NotSupportedException(typeof(T).Name);
}
}
}
}
| using System;
using Prometheus;
namespace bgTeam.Prometheus.Impl
{
public static class PrometheusExtensions
{
public static IDisposable MeasureDuration<T>(this T @this, params string[] labels)
where T : Collector
{
switch (typeof(T))
{
case Type type when type == typeof(Histogram): return new HistogramWatcher(@this as Histogram, labels);
default: throw new NotSupportedException(typeof(T).Name);
}
}
}
}
| mit | C# |
2ffa2555550f11fda1988794b2fa72cdf3206bfb | Update Viktor.cs | FireBuddy/adevade | AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs | AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs | using System;
using EloBuddy;
using EloBuddy.SDK;
namespace AdEvade.Data.Spells.SpecialSpells
{
class Viktor : IChampionPlugin
{
static Viktor()
{
}
public const string ChampionName = "Viktor";
public string GetChampionName()
{
return ChampionName;
}
public void LoadSpecialSpell(SpellData spellData)
{
if (spellData.SpellName == "ViktorDeathRay")
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3;
}
}
private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender != null && sender.Team != ObjectManager.Player.Team &&
args.SData.Name != null && args.SData.Name == "ViktorDeathRay")
{
. var End = sender.GetWaypoints().Last();
// var missileDist = End.To2D().Distance(args.Start.To2D());
// var delay = missileDist / 1.5f + 600;
// spellData.SpellDelay = delay;
// SpellDetector.CreateSpellData(sender, args.Start, End, spellData);
}
}
}
}
| using System;
using EloBuddy;
using EloBuddy.SDK;
namespace AdEvade.Data.Spells.SpecialSpells
{
class Viktor : IChampionPlugin
{
static Viktor()
{
}
public const string ChampionName = "Viktor";
public string GetChampionName()
{
return ChampionName;
}
public void LoadSpecialSpell(SpellData spellData)
{
if (spellData.SpellName == "ViktorDeathRay")
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3;
}
}
private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender != null && sender.Team != ObjectManager.Player.Team &&
args.SData.Name != null && args.SData.Name == "ViktorDeathRay")
{
. var End = new vector3 => sender.GetWaypoints().Last();
// var missileDist = End.To2D().Distance(args.Start.To2D());
// var delay = missileDist / 1.5f + 600;
// spellData.SpellDelay = delay;
// SpellDetector.CreateSpellData(sender, args.Start, End, spellData);
}
}
}
}
| mit | C# |
329b2468fc874aab65d6afc11f6af0530c8865c9 | Allow Extensions for Media | clusta/scaffoldr | ScaffoldR/Media.cs | ScaffoldR/Media.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ScaffoldR
{
public class Media
{
[JsonProperty("source")]
public string Source { get; set; }
[JsonProperty("uri")]
public string Uri { get; set; }
[JsonProperty("content_type")]
public string ContentType { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("video")]
public Video Video { get; set; }
[JsonProperty("action")]
public Action Action { get; set; }
[JsonExtensionData]
public IDictionary<string, object> Extensions { get; set; }
}
}
| using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ScaffoldR
{
public class Media
{
[JsonProperty("source")]
public string Source { get; set; }
[JsonProperty("uri")]
public string Uri { get; set; }
[JsonProperty("content_type")]
public string ContentType { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("video")]
public Video Video { get; set; }
[JsonProperty("action")]
public Action Action { get; set; }
}
}
| apache-2.0 | C# |
bcc556e7ea8159d9a6e9d522db5fda9befc43d3a | Move details to first column on evals list Fixes #86 | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/Evaluations/List.cshtml | Battery-Commander.Web/Views/Evaluations/List.cshtml | @model IEnumerable<Evaluation>
<h2>Evaluations @Html.ActionLink("Add New", "New", "Evaluations", null, new { @class = "btn btn-default" })</h2>
<table class="table table-striped">
<thead>
<tr>
<th></th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Ratee)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().ThruDate)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Status)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Delinquency)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastUpdated)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Type)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rater)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().SeniorRater)</th>
</tr>
</thead>
<tbody>
@foreach (var evaluation in Model)
{
<tr>
<td>@Html.ActionLink("Details", "Details", new { evaluation.Id })</td>
<td>@Html.DisplayFor(_ => evaluation.Ratee)</td>
<td>@Html.DisplayFor(_ => evaluation.ThruDate)</td>
<td>@Html.DisplayFor(_ => evaluation.Status)</td>
<td>@Html.DisplayFor(_ => evaluation.Delinquency)</td>
<td>@Html.DisplayFor(_ => evaluation.LastUpdated)</td>
<td>@Html.DisplayFor(_ => evaluation.Type)</td>
<td>@Html.DisplayFor(_ => evaluation.Rater)</td>
<td>@Html.DisplayFor(_ => evaluation.SeniorRater)</td>
</tr>
}
</tbody>
</table> | @model IEnumerable<Evaluation>
<h2>Evaluations @Html.ActionLink("Add New", "New", "Evaluations", null, new { @class = "btn btn-default" })</h2>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Ratee)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().ThruDate)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Status)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Delinquency)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastUpdated)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Type)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rater)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().SeniorRater)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var evaluation in Model)
{
<tr>
<td>@Html.DisplayFor(_ => evaluation.Ratee)</td>
<td>@Html.DisplayFor(_ => evaluation.ThruDate)</td>
<td>@Html.DisplayFor(_ => evaluation.Status)</td>
<td>@Html.DisplayFor(_ => evaluation.Delinquency)</td>
<td>@Html.DisplayFor(_ => evaluation.LastUpdated)</td>
<td>@Html.DisplayFor(_ => evaluation.Type)</td>
<td>@Html.DisplayFor(_ => evaluation.Rater)</td>
<td>@Html.DisplayFor(_ => evaluation.SeniorRater)</td>
<td>@Html.ActionLink("Details", "Details", new { evaluation.Id })</td>
</tr>
}
</tbody>
</table> | mit | C# |
e70fde432c01b7ff233b3b1a8de7a49a11bdb82f | Change message about AnalysisContext | SpotLabsNET/roslyn-analyzers,qinxgit/roslyn-analyzers,pakdev/roslyn-analyzers,srivatsn/roslyn-analyzers,tmeschter/roslyn-analyzers-1,dotnet/roslyn-analyzers,jasonmalinowski/roslyn-analyzers,mattwar/roslyn-analyzers,Anniepoh/roslyn-analyzers,modulexcite/roslyn-analyzers,natidea/roslyn-analyzers,jaredpar/roslyn-analyzers,bkoelman/roslyn-analyzers,heejaechang/roslyn-analyzers,pakdev/roslyn-analyzers,genlu/roslyn-analyzers,VitalyTVA/roslyn-analyzers,mavasani/roslyn-analyzers,jepetty/roslyn-analyzers,dotnet/roslyn-analyzers,jinujoseph/roslyn-analyzers,mavasani/roslyn-analyzers | NewAnalyzerTemplate/NewAnalyzerTemplate/NewAnalyzerTemplate/DiagnosticAnalyzer.cs | NewAnalyzerTemplate/NewAnalyzerTemplate/NewAnalyzerTemplate/DiagnosticAnalyzer.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
/*This tutorial is going to guide you to write a diagnostic analyzer that enforces the placement of a single space between the if keyword of an if statement and the
open parenthesis of the condition.
For more information, please reference the ReadMe.
Before you begin, go to Tools->Extensions and Updates->Online, and install .NET compiler SDK
*/
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace NewAnalyzerTemplate
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class NewAnalyzerTemplateAnalyzer : DiagnosticAnalyzer
{
//The SupportedDiagnostics property stores an ImmutableArray containing any diagnostics that can be reported by this analyzer
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
throw new NotImplementedException();
}
}
//The Initialize method is used to register methods to perform analysis of the Syntax Tree when there is a change to the Syntax Tree
//The AnalysisContext parameter has members, such as RegisterSyntaxNodeAction, that perform the registering mentioned above
public override void Initialize(AnalysisContext context)
{
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
/*This tutorial is going to guide you to write a diagnostic analyzer that enforces the placement of a single space between the if keyword of an if statement and the
open parenthesis of the condition.
For more information, please reference the ReadMe.
Before you begin, go to Tools->Extensions and Updates->Online, and install .NET compiler SDK
*/
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace NewAnalyzerTemplate
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class NewAnalyzerTemplateAnalyzer : DiagnosticAnalyzer
{
//The SupportedDiagnostics property stores an ImmutableArray containing any diagnostics that can be reported by this analyzer
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
throw new NotImplementedException();
}
}
//The Initialize method is used to register methods to perform analysis of the Syntax Tree or Semantic Model when there is a change to the SyntaxTree or Semantic Model
//The AnalysisContext parameter has members that facilitate the registering mentioned above
public override void Initialize(AnalysisContext context)
{
}
}
}
| mit | C# |
348839846a1acae12393910ef61107122c611a09 | increase version | gigya/microdot | SolutionVersion.cs | SolutionVersion.cs | #region Copyright
// Copyright 2017 Gigya 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
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Gigya Inc.")]
[assembly: AssemblyCopyright("© 2018 Gigya Inc.")]
[assembly: AssemblyDescription("Microdot Framework")]
[assembly: AssemblyVersion("1.9.6.0")]
[assembly: AssemblyFileVersion("1.9.6.0")]
[assembly: AssemblyInformationalVersion("1.9.6.0")]
// 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)]
[assembly: CLSCompliant(false)]
| #region Copyright
// Copyright 2017 Gigya 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
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Gigya Inc.")]
[assembly: AssemblyCopyright("© 2018 Gigya Inc.")]
[assembly: AssemblyDescription("Microdot Framework")]
[assembly: AssemblyVersion("1.9.5.0")]
[assembly: AssemblyFileVersion("1.9.5.0")]
[assembly: AssemblyInformationalVersion("1.9.5.0")]
// 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)]
[assembly: CLSCompliant(false)]
| apache-2.0 | C# |
ae891facb7cd003b5d2732a3e2e86455a0cd3e64 | Update AngryProfessor.cs | costincaraivan/hackerrank,costincaraivan/hackerrank | algorithms/implementation/C#/AngryProfessor.cs | algorithms/implementation/C#/AngryProfessor.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static void Main(String[] args) {
int t = Convert.ToInt32(Console.ReadLine());
for(int a0 = 0; a0 < t; a0++){
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int k = Convert.ToInt32(tokens_n[1]);
string[] a_temp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(a_temp,Int32.Parse);
var arrivedOnTime = 0;
foreach(var studentArrival in a)
{
if(studentArrival <= 0)
{
arrivedOnTime += 1;
}
}
if (arrivedOnTime >= k)
{
Console.WriteLine("NO");
}
else
{
Console.WriteLine("YES");
}
}
}
}
| mit | C# | |
3ddefadbe87272ad1f0eff6a743bb8c27d1a67b5 | Update SharpVk.Glfw AssemblyInfo | FacticiusVir/SharpVk | SharpVk/SharpVk.Glfw/Properties/AssemblyInfo.cs | SharpVk/SharpVk.Glfw/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("SharpVk.Glfw")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SharpVk.Glfw")]
[assembly: AssemblyCopyright("Copyright © Andrew Armstrong/FacticiusVir 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e61d7715-892d-4438-b6ed-08aa7bf1fb93")]
// 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.3.3.0")]
[assembly: AssemblyFileVersion("0.3.3.0")]
[assembly: AssemblyInformationalVersion("0.3.3-dev")] | 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("SharpVk.Glfw")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SharpVk.Glfw")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e61d7715-892d-4438-b6ed-08aa7bf1fb93")]
// 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# |
695d4c3173ad1f277c6cb43d955befc014c7c69e | Prepare for next development iteration. | SolinkCorp/Solink.AddIn.Helpers | Solink.AddIn.Helpers/Properties/AssemblyInfo.cs | Solink.AddIn.Helpers/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("Solink.AddIn.Helpers")]
[assembly: AssemblyDescription("A class library to help with System.AddIn")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Solink Corporation")]
[assembly: AssemblyProduct("Solink.AddIn.Helpers")]
[assembly: AssemblyCopyright("Copyright © Solink Corporation 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("956b811b-1344-406d-bed3-6458e51c358a")]
// 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")]
[assembly: AssemblyFileVersion("1.0.1")]
[assembly: AssemblyInformationalVersion("1.0.1" + "-SNAPSHOT")]
[assembly: InternalsVisibleTo("Solink.AddIn.Helpers.Test")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Solink.AddIn.Helpers")]
[assembly: AssemblyDescription("A class library to help with System.AddIn")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Solink Corporation")]
[assembly: AssemblyProduct("Solink.AddIn.Helpers")]
[assembly: AssemblyCopyright("Copyright © Solink Corporation 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("956b811b-1344-406d-bed3-6458e51c358a")]
// 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")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.1" + "-SNAPSHOT")]
[assembly: InternalsVisibleTo("Solink.AddIn.Helpers.Test")]
| mit | C# |
b6788916856c16d1246450bd1308c16c504eb7f9 | Update enum for VS 2017 | Sam13/cake,cake-build/cake,mholo65/cake,gep13/cake,robgha01/cake,daveaglick/cake,gep13/cake,mholo65/cake,Sam13/cake,vlesierse/cake,cake-build/cake,Julien-Mialon/cake,phenixdotnet/cake,adamhathcock/cake,patriksvensson/cake,robgha01/cake,ferventcoder/cake,devlead/cake,patriksvensson/cake,thomaslevesque/cake,adamhathcock/cake,devlead/cake,ferventcoder/cake,phenixdotnet/cake,daveaglick/cake,vlesierse/cake,thomaslevesque/cake,Julien-Mialon/cake,DixonD-git/cake | src/Cake.Common/Tools/NuGet/NuGetMSBuildVersion.cs | src/Cake.Common/Tools/NuGet/NuGetMSBuildVersion.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Cake.Common.Tools.NuGet
{
/// <summary>
/// NuGet MSBuild version
/// </summary>
public enum NuGetMSBuildVersion
{
/// <summary>
/// MSBuildVersion : <c>4</c>
/// </summary>
MSBuild4 = 4,
/// <summary>
/// MSBuildVersion : <c>12</c>
/// </summary>
MSBuild12 = 12,
/// <summary>
/// MSBuildVersion : <c>14</c>
/// </summary>
MSBuild14 = 14,
/// <summary>
/// MSBuildVersion : <c>15</c>
/// </summary>
MSBuild15 = 15
}
} | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Cake.Common.Tools.NuGet
{
/// <summary>
/// NuGet MSBuild version
/// </summary>
public enum NuGetMSBuildVersion
{
/// <summary>
/// MSBuildVersion : <c>4</c>
/// </summary>
MSBuild4 = 4,
/// <summary>
/// MSBuildVersion : <c>12</c>
/// </summary>
MSBuild12 = 12,
/// <summary>
/// MSBuildVersion : <c>14</c>
/// </summary>
MSBuild14 = 14
}
} | mit | C# |
dac9b00b907b1259d45783f05edd011345d02f3c | Update BaseShapeIconConverter.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Converters/BaseShapeIconConverter.cs | src/Core2D/Converters/BaseShapeIconConverter.cs | #nullable enable
using System;
using System.Globalization;
using Avalonia;
using Avalonia.Data.Converters;
using Core2D.ViewModels.Shapes;
namespace Core2D.Converters;
public class BaseShapeIconConverter : IValueConverter
{
public static BaseShapeIconConverter Instance = new();
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is BaseShapeViewModel shape)
{
var key = value.GetType().Name.Replace("ShapeViewModel", "");
if (Application.Current is { } application)
{
if (application.Styles.TryGetResource(key, out var resource))
{
return resource;
}
}
}
return AvaloniaProperty.UnsetValue;
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
| #nullable enable
using System;
using System.Globalization;
using Avalonia;
using Avalonia.Data.Converters;
using Core2D.ViewModels.Shapes;
namespace Core2D.Converters;
public class BaseShapeIconConverter : IValueConverter
{
public static BaseShapeIconConverter Instance = new();
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is BaseShapeViewModel shape)
{
var key = value.GetType().Name.Replace("ShapeViewModel", "");
if (Application.Current.Styles.TryGetResource(key, out var resource))
{
return resource;
}
}
return AvaloniaProperty.UnsetValue;
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
} | mit | C# |
9bdbd17964ea71ea1c51a4b7c94f942483a835ce | Fix setup not being able to start for first 10s | Piotrekol/StreamCompanion,Piotrekol/StreamCompanion | Updater/Program.cs | Updater/Program.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Updater
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
TryStartSc();
}
if (args.Length != 2)
return;
var setupExe= args[0];
var setupExeArgs = args[1];
if (!File.Exists(setupExe))
{
Environment.ExitCode = -1;
return;
}
//Console.WriteLine("Updating...");
var p = Process.Start(setupExe, setupExeArgs);
}
public static bool TryStartSc()
{
var scExe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "osu!StreamCompanion.exe");
if (File.Exists(scExe))
{
Process.Start(scExe);
return true;
}
return false;
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Updater
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
TryStartSc();
}
if (args.Length != 2)
return;
var setupExe= args[0];
var setupExeArgs = args[1];
if (!File.Exists(setupExe))
{
Environment.ExitCode = -1;
return;
}
//Console.WriteLine("Updating...");
var p = Process.Start(setupExe, setupExeArgs);
if (p.WaitForExit(10000))
{
TryStartSc();
}
}
public static bool TryStartSc()
{
var scExe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "osu!StreamCompanion.exe");
if (File.Exists(scExe))
{
Process.Start(scExe);
return true;
}
return false;
}
}
}
| mit | C# |
8965d1c6f8e2b2bc9d1eb2882b2029769200da4d | Fix spelling of SuccessfulShards in CatSnapshots | elastic/elasticsearch-net,elastic/elasticsearch-net | src/Nest/Cat/CatSnapshots/CatSnapshotsRecord.cs | src/Nest/Cat/CatSnapshots/CatSnapshotsRecord.cs | using System.Runtime.Serialization;
using Elasticsearch.Net.Utf8Json;
namespace Nest
{
[DataContract]
public class CatSnapshotsRecord : ICatRecord
{
[DataMember(Name ="duration")]
public Time Duration { get; set; }
[DataMember(Name ="end_epoch")]
[JsonFormatter(typeof(StringLongFormatter))]
public long EndEpoch { get; set; }
[DataMember(Name ="end_time")]
public string EndTime { get; set; }
[DataMember(Name ="failed_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long FailedShards { get; set; }
// duration indices successful_shards failed_shards total_shards
[DataMember(Name ="id")]
public string Id { get; set; }
[DataMember(Name ="indices")]
[JsonFormatter(typeof(StringLongFormatter))]
public long Indices { get; set; }
[DataMember(Name ="start_epoch")]
[JsonFormatter(typeof(StringLongFormatter))]
public long StartEpoch { get; set; }
[DataMember(Name ="start_time")]
public string StartTime { get; set; }
[DataMember(Name ="status")]
public string Status { get; set; }
[DataMember(Name ="successful_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long SuccessfulShards { get; set; }
[DataMember(Name ="total_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long TotalShards { get; set; }
}
}
| using System.Runtime.Serialization;
using Elasticsearch.Net.Utf8Json;
namespace Nest
{
[DataContract]
public class CatSnapshotsRecord : ICatRecord
{
[DataMember(Name ="duration")]
public Time Duration { get; set; }
[DataMember(Name ="end_epoch")]
[JsonFormatter(typeof(StringLongFormatter))]
public long EndEpoch { get; set; }
[DataMember(Name ="end_time")]
public string EndTime { get; set; }
[DataMember(Name ="failed_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long FailedShards { get; set; }
// duration indices successful_shards failed_shards total_shards
[DataMember(Name ="id")]
public string Id { get; set; }
[DataMember(Name ="indices")]
[JsonFormatter(typeof(StringLongFormatter))]
public long Indices { get; set; }
[DataMember(Name ="start_epoch")]
[JsonFormatter(typeof(StringLongFormatter))]
public long StartEpoch { get; set; }
[DataMember(Name ="start_time")]
public string StartTime { get; set; }
[DataMember(Name ="status")]
public string Status { get; set; }
[DataMember(Name ="succesful_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long SuccesfulShards { get; set; }
[DataMember(Name ="total_shards")]
[JsonFormatter(typeof(StringLongFormatter))]
public long TotalShards { get; set; }
}
}
| apache-2.0 | C# |
8a95913afaaefa158131dd28d966d53d3e8b3125 | Fix test | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/UnitTests/GitHub.Exports/VSServicesTests.cs | src/UnitTests/GitHub.Exports/VSServicesTests.cs | using System;
using GitHub.Services;
using Microsoft.TeamFoundation.Git.Controls.Extensibility;
using NSubstitute;
using Xunit;
public class VSServicesTests
{
public class TheCloneMethod : TestBaseClass
{
[Theory]
[InlineData(true, CloneOptions.RecurseSubmodule)]
[InlineData(false, CloneOptions.None)]
public void CallsCloneOnVsProvidedCloneService(bool recurseSubmodules, CloneOptions expectedCloneOptions)
{
var provider = Substitute.For<IUIProvider>();
var gitRepositoriesExt = Substitute.For<IGitRepositoriesExt>();
provider.GetService(typeof(IGitRepositoriesExt)).Returns(gitRepositoriesExt);
provider.TryGetService(typeof(IGitRepositoriesExt)).Returns(gitRepositoriesExt);
var vsServices = new VSServices(provider);
vsServices.Clone("https://github.com/github/visualstudio", @"c:\fake\ghfvs", recurseSubmodules);
gitRepositoriesExt.Received()
.Clone("https://github.com/github/visualstudio", @"c:\fake\ghfvs", expectedCloneOptions);
}
}
}
| using System;
using GitHub.Services;
using Microsoft.TeamFoundation.Git.Controls.Extensibility;
using NSubstitute;
using Xunit;
public class VSServicesTests
{
public class TheCloneMethod : TestBaseClass
{
[Theory]
[InlineData(true, CloneOptions.RecurseSubmodule)]
[InlineData(false, CloneOptions.None)]
public void CallsCloneOnVsProvidedCloneService(bool recurseSubmodules, CloneOptions expectedCloneOptions)
{
var provider = Substitute.For<IUIProvider>();
var gitRepositoriesExt = Substitute.For<IGitRepositoriesExt>();
provider.GetService(typeof(IGitRepositoriesExt)).Returns(gitRepositoriesExt);
var vsServices = new VSServices(provider);
vsServices.Clone("https://github.com/github/visualstudio", @"c:\fake\ghfvs", recurseSubmodules);
gitRepositoriesExt.Received()
.Clone("https://github.com/github/visualstudio", @"c:\fake\ghfvs", expectedCloneOptions);
}
}
}
| mit | C# |
7ca6e77dd447fdd9bd4d8f4ed4fe5340c6e2cdd1 | Correct domain name to example domain | openengsb/loom-csharp | bridge/ServiceTestConsole/Program.cs | bridge/ServiceTestConsole/Program.cs | /***
* Licensed to the Austrian Association for Software Tool Integration (AASTI)
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. The AASTI licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using Bridge.Implementation;
using Bridge.Interface;
using ExampleDomain;
using ExampleDomainEvents;
namespace Bridge.ServiceTestConsole
{
class Program
{
/// <summary>
/// This version works with the OpenEngS 3.0.0-Snapshot Framwork
/// </summary>
/// <param name="args">System Arguments</param>
static void Main(string[] args)
{
log4net.Config.BasicConfigurator.Configure();
string destination = "tcp://localhost.:6549";
string domainName = "example";
IDomainFactory factory = DomainFactoryProvider.GetDomainFactoryInstance("3.0.0");
IExampleDomainSoap11Binding localDomain = new ExampleDomainConnector();
//Register the connecter on the osenEngSB
factory.RegisterDomainService(destination, localDomain, domainName);
//Get a remote handler, to raise events on obenEngSB
IExampleDomainEventsSoap11Binding remotedomain = factory.getEventhandler<IExampleDomainEventsSoap11Binding>(destination);
ExampleDomainEvents.LogEvent logEvent = new ExampleDomainEvents.LogEvent();
logEvent.name = "Example";
logEvent.processId = 0;
logEvent.level = new ExampleDomainEvents.LogEvent_LogLevel();
logEvent.message = "remoteTestEventLog";
remotedomain.raiseEvent(logEvent);
Console.ReadKey();
factory.UnregisterDomainService(localDomain);
}
}
}
| /***
* Licensed to the Austrian Association for Software Tool Integration (AASTI)
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. The AASTI licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using Bridge.Implementation;
using Bridge.Interface;
using ExampleDomain;
using ExampleDomainEvents;
namespace Bridge.ServiceTestConsole
{
class Program
{
/// <summary>
/// This version works with the OpenEngS 3.0.0-Snapshot Framwork
/// </summary>
/// <param name="args">System Arguments</param>
static void Main(string[] args)
{
log4net.Config.BasicConfigurator.Configure();
string destination = "tcp://localhost.:6549";
string domainName = "test";
IDomainFactory factory = DomainFactoryProvider.GetDomainFactoryInstance("3.0.0");
IExampleDomainSoap11Binding localDomain = new ExampleDomainConnector();
//Register the connecter on the osenEngSB
factory.RegisterDomainService(destination, localDomain, domainName);
//Get a remote handler, to raise events on obenEngSB
IExampleDomainEventsSoap11Binding remotedomain = factory.getEventhandler<IExampleDomainEventsSoap11Binding>(destination);
ExampleDomainEvents.LogEvent logEvent = new ExampleDomainEvents.LogEvent();
logEvent.name = "Example";
logEvent.processId = 0;
logEvent.level = new ExampleDomainEvents.LogEvent_LogLevel();
logEvent.message = "remoteTestEventLog";
remotedomain.raiseEvent(logEvent);
Console.ReadKey();
factory.UnregisterDomainService(localDomain);
}
}
}
| apache-2.0 | C# |
995c610dcca9b1dfd74af355ea980fcaf5e0f241 | mark clock implementations as sealed | alhardy/Metrics.NET,DeonHeyns/Metrics.NET,etishor/Metrics.NET,ntent-ad/Metrics.NET,mnadel/Metrics.NET,huoxudong125/Metrics.NET,Recognos/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,Liwoj/Metrics.NET,ntent-ad/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,alhardy/Metrics.NET,huoxudong125/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,Liwoj/Metrics.NET | Src/Metrics/Utils/Clock.cs | Src/Metrics/Utils/Clock.cs |
using System;
namespace Metrics.Utils
{
public abstract class Clock
{
private sealed class SystemClock : Clock
{
public override long Nanoseconds { get { return DateTime.UtcNow.Ticks * 100L; } }
}
public sealed class TestClock : Clock
{
private long nanoseconds = 0;
public override long Nanoseconds { get { return this.nanoseconds; } }
public void Advance(TimeUnit unit, long value)
{
this.nanoseconds += unit.ToNanoseconds(value);
}
}
public static readonly Clock System = new SystemClock();
public abstract long Nanoseconds { get; }
public long Seconds { get { return TimeUnit.Nanoseconds.ToSeconds(Nanoseconds); } }
}
}
|
using System;
namespace Metrics.Utils
{
public abstract class Clock
{
private class SystemClock : Clock
{
public override long Nanoseconds { get { return DateTime.UtcNow.Ticks * 100L; } }
}
public class TestClock : Clock
{
private long nanoseconds = 0;
public override long Nanoseconds { get { return this.nanoseconds; } }
public void Advance(TimeUnit unit, long value)
{
this.nanoseconds += unit.ToNanoseconds(value);
}
}
public static readonly Clock System = new SystemClock();
public abstract long Nanoseconds { get; }
public long Seconds { get { return TimeUnit.Nanoseconds.ToSeconds(Nanoseconds); } }
}
}
| apache-2.0 | C# |
a99d2bb7401915d547b5446d8bb3c837dcc05a26 | Update XPathFinder.cs | thelgevold/xpathitup | XPathFinder/XPathFinder.cs | XPathFinder/XPathFinder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace XPathItUp
{
public class XPathFinder
{
public static Finder Find
{
get
{
Finder finder = new Finder();
return finder;
}
}
}
}
| /*
Copyright (C) 2010 Torgeir Helgevold
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace XPathItUp
{
public class XPathFinder
{
public static Finder Find
{
get
{
Finder finder = new Finder();
return finder;
}
}
}
}
| mit | C# |
842a66aae1045f9df29bbf80bf993ab259962984 | change the text a little | SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery | AstroPhotoGallery/AstroPhotoGallery/Views/Home/About.cshtml | AstroPhotoGallery/AstroPhotoGallery/Views/Home/About.cshtml | @{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title</h2>
<br />
<div class="panel panel-default">
<div class="panel-heading resume-heading">
<div class="row">
<div class="col-sm-12">
<div>
<div class="well well-sm text-center" style="font-size: 25px; word-wrap: break-word;">Astro gallery project</div>
<br />
<p>The project was part of the course "Software technologies" in Software University Bulgaria. It has been developed by 2 software development students with less than a year experience. The inspiration came from a website for astronomy pictures: <a style="word-break: break-all; display: inline-block" href="http://www.emilivanov.com/index2.htm" target="_blank">http://www.emilivanov.com/index2.htm</a>. The rights to use the pictures for this project has been given by Emil Ivanov and the project will be presented to him too. This project will not be used for any commercial purposes - it is a non-profit student project.</p>
<p>Due to the small experience of the developers when the project was created, it does not pretend to be perfect from software engineering point of view. However, many hours have been dedicated to it in order to work, look and feel good.</p>
<p>The beautiful pictures are separated by categories. They can be searched by tags or by categories. Enjoy!</p>
<p>GitHub repository of the project: <a style="word-break: break-all; display: inline-block" href="https://github.com/SoftwareFans/AstroPhotoGallery" target="_blank">https://github.com/SoftwareFans/AstroPhotoGallery </a></p>
<p>Development team: @Html.ActionLink("Contacts", "Contacts", "Home")</p>
</div>
</div>
</div>
<br />
</div>
</div>
| @{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title</h2>
<br />
<div class="panel panel-default">
<div class="panel-heading resume-heading">
<div class="row">
<div class="col-sm-12">
<div>
<div class="well well-sm text-center" style="font-size: 25px; word-wrap: break-word;">Astro gallery project</div>
<br />
<p>The project was part of the course "Software technologies" in Software University Bulgaria. It has been developed by 2 software development students with less than a year experience. The inspiration came from a website for astronomy pictures: <a style="word-break: break-all; display: inline-block" href="http://www.emilivanov.com/index2.htm" target="_blank">http://www.emilivanov.com/index2.htm</a>. The rights to use the pictures for this project has been given by Emil Ivanov and the project will be presented to him too. This project will not be used for any commercial purposes - it is a non-profit school project.</p>
<p>Due to the small experience of the developers when the project was created, it does not pretend to be perfect from software engineering point of view. However, many hours have been dedicated to it in order to work, look and feel good.</p>
<p>The beautiful pictures are separated by categories. They can be searched by tags or by categories.</p>
<p>GitHub repository of the project: <a style="word-break: break-all; display: inline-block" href="https://github.com/SoftwareFans/AstroPhotoGallery" target="_blank">https://github.com/SoftwareFans/AstroPhotoGallery </a></p>
<p>Development team: @Html.ActionLink("Contacts", "Contacts", "Home")</p>
</div>
</div>
</div>
<br />
</div>
</div>
| mit | C# |
ee43c3effcd64781e4d9d604385c734af92de91d | Add missing documentation comment. | txdv/CppSharp,SonyaSa/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp,mydogisbox/CppSharp,ddobrev/CppSharp,zillemarco/CppSharp,ktopouzi/CppSharp,mydogisbox/CppSharp,txdv/CppSharp,xistoso/CppSharp,nalkaro/CppSharp,nalkaro/CppSharp,KonajuGames/CppSharp,SonyaSa/CppSharp,xistoso/CppSharp,mydogisbox/CppSharp,inordertotest/CppSharp,nalkaro/CppSharp,u255436/CppSharp,xistoso/CppSharp,SonyaSa/CppSharp,zillemarco/CppSharp,u255436/CppSharp,Samana/CppSharp,genuinelucifer/CppSharp,genuinelucifer/CppSharp,imazen/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,mydogisbox/CppSharp,mono/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,txdv/CppSharp,mydogisbox/CppSharp,ddobrev/CppSharp,u255436/CppSharp,Samana/CppSharp,ddobrev/CppSharp,imazen/CppSharp,genuinelucifer/CppSharp,KonajuGames/CppSharp,mohtamohit/CppSharp,KonajuGames/CppSharp,Samana/CppSharp,imazen/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,imazen/CppSharp,zillemarco/CppSharp,mono/CppSharp,u255436/CppSharp,inordertotest/CppSharp,nalkaro/CppSharp,ktopouzi/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,imazen/CppSharp,zillemarco/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,mono/CppSharp,txdv/CppSharp,ktopouzi/CppSharp,SonyaSa/CppSharp,KonajuGames/CppSharp,Samana/CppSharp,nalkaro/CppSharp,mohtamohit/CppSharp,txdv/CppSharp,mono/CppSharp,SonyaSa/CppSharp,ktopouzi/CppSharp,KonajuGames/CppSharp,xistoso/CppSharp,mono/CppSharp,xistoso/CppSharp,Samana/CppSharp,inordertotest/CppSharp | src/Generator/Passes/PassBuilder.cs | src/Generator/Passes/PassBuilder.cs | using System.Collections.Generic;
using System.Linq;
using CppSharp.Passes;
namespace CppSharp
{
/// <summary>
/// This class is used to build passes that will be run against the AST
/// that comes from C++.
/// </summary>
public class PassBuilder
{
public List<TranslationUnitPass> Passes { get; private set; }
public Driver Driver { get; private set; }
public PassBuilder(Driver driver)
{
Passes = new List<TranslationUnitPass>();
Driver = driver;
}
/// <summary>
/// Adds a new pass to the builder.
/// </summary>
public void AddPass(TranslationUnitPass pass)
{
pass.Driver = Driver;
pass.Library = Driver.Library;
Passes.Add(pass);
}
/// <summary>
/// Finds a previously-added pass of the given type.
/// </summary>
public T FindPass<T>() where T : TranslationUnitPass
{
return Passes.OfType<T>().Select(pass => pass as T).FirstOrDefault();
}
}
}
| using System.Collections.Generic;
using System.Linq;
using CppSharp.Passes;
namespace CppSharp
{
/// <summary>
/// This class is used to build passes that will be run against the AST
/// that comes from C++.
/// </summary>
public class PassBuilder
{
public List<TranslationUnitPass> Passes { get; private set; }
public Driver Driver { get; private set; }
public PassBuilder(Driver driver)
{
Passes = new List<TranslationUnitPass>();
Driver = driver;
}
public void AddPass(TranslationUnitPass pass)
{
pass.Driver = Driver;
pass.Library = Driver.Library;
Passes.Add(pass);
}
/// <summary>
/// Finds a previously-added pass of the given type.
/// </summary>
public T FindPass<T>() where T : TranslationUnitPass
{
return Passes.OfType<T>().Select(pass => pass as T).FirstOrDefault();
}
}
}
| mit | C# |
b8b869e8b76ce041fb065071cfe637141353f5d2 | Remove now unused property | peppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,Nabile-Rahmani/osu,smoogipooo/osu,johnneijzen/osu,DrabWeb/osu,EVAST9919/osu,smoogipoo/osu,DrabWeb/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,2yangk23/osu,2yangk23/osu,johnneijzen/osu,naoey/osu,UselessToucan/osu,DrabWeb/osu,ZLima12/osu,Frontear/osuKyzer,ZLima12/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,naoey/osu,peppy/osu,naoey/osu,smoogipoo/osu,EVAST9919/osu,ppy/osu | osu.Game.Rulesets.Mania/Beatmaps/StageDefinition.cs | osu.Game.Rulesets.Mania/Beatmaps/StageDefinition.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Beatmaps
{
/// <summary>
/// Defines properties for each stage in a <see cref="ManiaPlayfield"/>.
/// </summary>
public struct StageDefinition
{
/// <summary>
/// The number of <see cref="Column"/>s which this stage contains.
/// </summary>
public int Columns;
/// <summary>
/// Whether the column index is a special column for this stage.
/// </summary>
/// <param name="column">The 0-based column index.</param>
/// <returns>Whether the column is a special column.</returns>
public bool IsSpecialColumn(int column) => Columns % 2 == 1 && column == Columns / 2;
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Beatmaps
{
/// <summary>
/// Defines properties for each stage in a <see cref="ManiaPlayfield"/>.
/// </summary>
public struct StageDefinition
{
/// <summary>
/// The number of <see cref="Column"/>s which this stage contains.
/// </summary>
public int Columns;
/// <summary>
/// Whether this stage has a special column.
/// </summary>
public bool HasSpecialColumn => Columns % 2 == 1;
/// <summary>
/// Whether the column index is a special column for this stage.
/// </summary>
/// <param name="column">The 0-based column index.</param>
/// <returns>Whether the column is a special column.</returns>
public bool IsSpecialColumn(int column) => Columns % 2 == 1 && column == Columns / 2;
}
}
| mit | C# |
c65f792838e247755ec37e6cb48a7c8ec8586fb0 | Refactor TypeRefHash | secana/PeNet | src/PeNet/Header/Net/TypeRefHash.cs | src/PeNet/Header/Net/TypeRefHash.cs | using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace PeNet.Header.Net
{
public class TypeRefHash
{
public MetaDataTablesHdr? MdtHdr { get; }
public MetaDataStreamString? MdsStream { get; }
public TypeRefHash(MetaDataTablesHdr? mdtHdr, MetaDataStreamString? mdsStream)
=> (MdtHdr, MdsStream) = (mdtHdr, mdsStream);
public string? ComputeHash()
{
static string GetSha256(string typeRefsAsString)
{
using var sha256 = new SHA256Managed();
var bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(typeRefsAsString));
var stringBuilder = new StringBuilder();
foreach (var b in bytes)
stringBuilder.AppendFormat("{0:x2}", b);
return stringBuilder.ToString();
}
var typeRefs = MdtHdr?.Tables.TypeRef;
if (typeRefs is null || MdsStream is null) return null;
try
{
var namespacesAndTypes = typeRefs
.OrderBy(t => MdsStream.GetStringAtIndex(t.TypeNamespace))
.ThenBy(t => MdsStream.GetStringAtIndex(t.TypeName))
.Select(t => string.Join("-",
MdsStream.GetStringAtIndex(t.TypeNamespace),
MdsStream.GetStringAtIndex(t.TypeName)
))
.ToList();
var typeRefsAsString = string.Join(",", namespacesAndTypes);
return GetSha256(typeRefsAsString);
}
catch (Exception) { return null; }
}
}
}
| using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace PeNet.Header.Net
{
public class TypeRefHash
{
public MetaDataTablesHdr? MdtHdr { get; }
public MetaDataStreamString? MdsStream { get; }
public TypeRefHash(MetaDataTablesHdr? mdtHdr, MetaDataStreamString? mdsStream)
=> (MdtHdr, MdsStream) = (mdtHdr, mdsStream);
public string? ComputeHash()
{
try
{
var typeRefs = MdtHdr?.Tables.TypeRef;
if (typeRefs is null || MdsStream is null) return null;
var noNamespace = typeRefs
.OrderBy(t => MdsStream.GetStringAtIndex(t.TypeNamespace))
.ThenBy(t => MdsStream.GetStringAtIndex(t.TypeName))
.Select(t => string.Join("-",
MdsStream.GetStringAtIndex(t.TypeNamespace),
MdsStream.GetStringAtIndex(t.TypeName)
))
.ToList();
var typeRefsAsString = string.Join(",", noNamespace);
using var sha256 = new SHA256Managed();
var bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(typeRefsAsString));
var stringBuilder = new StringBuilder();
foreach (var b in bytes)
{
stringBuilder.AppendFormat("{0:x2}", b);
}
return stringBuilder.ToString();
}
catch (Exception)
{
return null;
}
}
}
}
| apache-2.0 | C# |
ad16632c8ebfc781c9cfdd63b7c1080096da2c98 | Comment code that should be commented | JetBrains/resharper-workshop,yskatsumata/resharper-workshop,yskatsumata/resharper-workshop,JetBrains/resharper-workshop,gorohoroh/resharper-workshop,gorohoroh/resharper-workshop,yskatsumata/resharper-workshop,gorohoroh/resharper-workshop,JetBrains/resharper-workshop | 3-Editing/1-Code_completion/1.3-Smart_completion.cs | 3-Editing/1-Code_completion/1.3-Smart_completion.cs | namespace JetBrains.ReSharper.Koans.Editing
{
// Smart Completion
//
// Narrows candidates to those that best suit the current context
//
// Ctrl+Alt+Space (VS)
// Ctrl+Shift+Space (IntelliJ)
public class SmartCompletion
{
// 1. Start typing: string s =
// Automatic Completion offers Smart Completion items first (string items)
// (followed by local Basic items, wider Basic and then Import items)
// 2. Uncomment: string s2 =
// Invoke Smart Completion at the end of the line
// Smart Completion only shows string based candidates
// (Including methods that return string, such as String.Concat)
// 3. Uncomment: string s3 = this.
// Invoke Smart Completion at the end of the line
// Smart Completion only shows string based candidates for the this parameter
// Note that the Age property isn't used
public void SmartUseString(string stringParameter)
{
//string s2 =
//string s3 = this.
}
public int Age { get; set; }
#region Implementation details
public string Name { get; set; }
public string GetGreeting()
{
return "hello";
}
#endregion
}
} | namespace JetBrains.ReSharper.Koans.Editing
{
// Smart Completion
//
// Narrows candidates to those that best suit the current context
//
// Ctrl+Alt+Space (VS)
// Ctrl+Shift+Space (IntelliJ)
public class SmartCompletion
{
// 1. Start typing: string s =
// Automatic Completion offers Smart Completion items first (string items)
// (followed by local Basic items, wider Basic and then Import items)
// 2. Uncomment: string s2 =
// Invoke Smart Completion at the end of the line
// Smart Completion only shows string based candidates
// (Including methods that return string, such as String.Concat)
// 3. Uncomment: string s3 = this.
// Invoke Smart Completion at the end of the line
// Smart Completion only shows string based candidates for the this parameter
// Note that the Age property isn't used
public void SmartUseString(string stringParameter)
{
//string s2 =
string s3 = this.
}
public int Age { get; set; }
#region Implementation details
public string Name { get; set; }
public string GetGreeting()
{
return "hello";
}
#endregion
}
} | apache-2.0 | C# |
da667f5251eec16aefd4b2d254ab76ff363da42f | Update Viktor.cs | FireBuddy/adevade | AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs | AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs | using System;
using EloBuddy;
using EloBuddy.SDK;
namespace AdEvade.Data.Spells.SpecialSpells
{
class Viktor : IChampionPlugin
{
static Viktor()
{
}
public const string ChampionName = "Viktor";
public string GetChampionName()
{
return ChampionName;
}
public void LoadSpecialSpell(SpellData spellData)
{
if (spellData.SpellName == "ViktorDeathRay")
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3;
}
}
private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender != null && sender.Team != ObjectManager.Player.Team &&
args.SData.Name != null && args.SData.Name == "ViktorDeathRay")
{
var end = sender.GetWaypoints().Last().To3D();
// var missileDist = End.To2D().Distance(args.Start.To2D());
// var delay = missileDist / 1.5f + 600;
// spellData.SpellDelay = delay;
// SpellDetector.CreateSpellData(sender, args.Start, End, spellData);
}
}
}
}
| using System;
using EloBuddy;
using EloBuddy.SDK;
namespace AdEvade.Data.Spells.SpecialSpells
{
class Viktor : IChampionPlugin
{
static Viktor()
{
}
public const string ChampionName = "Viktor";
public string GetChampionName()
{
return ChampionName;
}
public void LoadSpecialSpell(SpellData spellData)
{
if (spellData.SpellName == "ViktorDeathRay")
{
Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3;
}
}
private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
{
if (sender != null && sender.Team != ObjectManager.Player.Team &&
args.SData.Name != null && args.SData.Name == "ViktorDeathRay")
{
var end = sender.Path.Last().To3D();
// var missileDist = End.To2D().Distance(args.Start.To2D());
// var delay = missileDist / 1.5f + 600;
// spellData.SpellDelay = delay;
// SpellDetector.CreateSpellData(sender, args.Start, End, spellData);
}
}
}
}
| mit | C# |
4fc56ab529f0712485922717d6d256ad8f32d2f3 | Fix safety test description | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | BatteryCommander.Common/Migrations/Configuration.cs | BatteryCommander.Common/Migrations/Configuration.cs | namespace BatteryCommander.Common.Migrations
{
using BatteryCommander.Common.Models;
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<BatteryCommander.Common.DataContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(BatteryCommander.Common.DataContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
context.Qualifications.AddOrUpdate(
q => new { q.Name, q.Description },
// Field Artillery Qual Events
new Qualification { Name = "FA Safety", Description = "BN Safety Test" },
new Qualification { Name = "ASPT", Description = "Artillery Skills Proficiency Test" },
new Qualification { Name = "GQT", Description = "Gunner's Qualification Test" },
new Qualification { Name = "LDR VAL", Description = "Leader's Validation" },
// Weapon Qual Events
new Qualification { Name = "M-4 IWQ", Description = "M-4 Individual Weapons Qual" },
new Qualification { Name = "M-240B", Description = "M-240B Crew Serve Weapons Qual" },
new Qualification { Name = "M-2", Description = "M-2 Crew Serve Weapons Qual" },
// Driver Quals
// Otther individual warrior task quals
new Qualification { Name = "CLS", Description = "Combat Life Saver" },
new Qualification { Name = "DSCA", Description = "Defense Support of Civil authorities" }
);
context.Users.AddOrUpdate(
u => u.UserName,
new AppUser
{
UserName = "mattgwagner@gmail.com",
Password = "AAFQO/7w4afWBCkdBYKVX+MmmFYneGIQv6W8cPYAU/S16yLKYkkR3zQbudWmqIvXag==",
EmailAddressConfirmed = true,
PhoneNumber = "8134136839",
PhoneNumberConfirmed = true
});
}
}
} | namespace BatteryCommander.Common.Migrations
{
using BatteryCommander.Common.Models;
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<BatteryCommander.Common.DataContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(BatteryCommander.Common.DataContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
context.Qualifications.AddOrUpdate(
q => new { q.Name, q.Description },
// Field Artillery Qual Events
new Qualification { Name = "FA Safety" },
new Qualification { Name = "ASPT", Description = "Artillery Skills Proficiency Test" },
new Qualification { Name = "GQT", Description = "Gunner's Qualification Test" },
new Qualification { Name = "LDR VAL", Description = "Leader's Validation" },
// Weapon Qual Events
new Qualification { Name = "M-4 IWQ", Description = "M-4 Individual Weapons Qual" },
new Qualification { Name = "M-240B", Description = "M-240B Crew Serve Weapons Qual" },
new Qualification { Name = "M-2", Description = "M-2 Crew Serve Weapons Qual" },
// Driver Quals
// Otther individual warrior task quals
new Qualification { Name = "CLS", Description = "Combat Life Saver" },
new Qualification { Name = "DSCA", Description = "Defense Support of Civil authorities" }
);
context.Users.AddOrUpdate(
u => u.UserName,
new AppUser
{
UserName = "mattgwagner@gmail.com",
Password = "AAFQO/7w4afWBCkdBYKVX+MmmFYneGIQv6W8cPYAU/S16yLKYkkR3zQbudWmqIvXag==",
EmailAddressConfirmed = true,
PhoneNumber = "8134136839",
PhoneNumberConfirmed = true
});
}
}
} | mit | C# |
a462d81fef65540afe15e0e772b3276cac320aea | Rename settings to I do nothing | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Shell/Commands/ToolCommands.cs | WalletWasabi.Gui/Shell/Commands/ToolCommands.cs | using System.Composition;
using AvalonStudio.Commands;
using AvalonStudio.Documents;
using AvalonStudio.Extensibility;
using AvalonStudio.Shell;
using ReactiveUI;
using System.IO;
using System.Linq;
using WalletWasabi.Gui.Tabs.WalletManager;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class ToolCommands
{
[ImportingConstructor]
public ToolCommands(CommandIconService commandIconService)
{
WalletManagerCommand = new CommandDefinition(
"Wallet Manager",
commandIconService.GetCompletionKindImage("WalletManager"),
ReactiveCommand.Create(OnWalletManager));
SettingsCommand = new CommandDefinition(
"I Do Nothing",
commandIconService.GetCompletionKindImage("Settings"),
ReactiveCommand.Create(() => { }));
}
private void OnWalletManager()
{
var isAnyWalletAvailable = Directory.Exists(Global.WalletsDir) && Directory.EnumerateFiles(Global.WalletsDir).Any();
var walletManagerViewModel = IoC.Get<IShell>().GetOrCreate<WalletManagerViewModel>();
if (Directory.Exists(Global.WalletsDir) && Directory.EnumerateFiles(Global.WalletsDir).Any())
{
walletManagerViewModel.SelectLoadWallet();
}
else
{
walletManagerViewModel.SelectGenerateWallet();
}
}
[ExportCommandDefinition("Tools.WalletManager")]
public CommandDefinition WalletManagerCommand { get; }
[ExportCommandDefinition("Tools.Settings")]
public CommandDefinition SettingsCommand { get; }
}
}
| using System.Composition;
using AvalonStudio.Commands;
using AvalonStudio.Documents;
using AvalonStudio.Extensibility;
using AvalonStudio.Shell;
using ReactiveUI;
using System.IO;
using System.Linq;
using WalletWasabi.Gui.Tabs.WalletManager;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class ToolCommands
{
[ImportingConstructor]
public ToolCommands(CommandIconService commandIconService)
{
WalletManagerCommand = new CommandDefinition(
"Wallet Manager",
commandIconService.GetCompletionKindImage("WalletManager"),
ReactiveCommand.Create(OnWalletManager));
SettingsCommand = new CommandDefinition(
"Settings",
commandIconService.GetCompletionKindImage("Settings"),
ReactiveCommand.Create(() => { }));
}
private void OnWalletManager()
{
var isAnyWalletAvailable = Directory.Exists(Global.WalletsDir) && Directory.EnumerateFiles(Global.WalletsDir).Any();
var walletManagerViewModel = IoC.Get<IShell>().GetOrCreate<WalletManagerViewModel>();
if (Directory.Exists(Global.WalletsDir) && Directory.EnumerateFiles(Global.WalletsDir).Any())
{
walletManagerViewModel.SelectLoadWallet();
}
else
{
walletManagerViewModel.SelectGenerateWallet();
}
}
[ExportCommandDefinition("Tools.WalletManager")]
public CommandDefinition WalletManagerCommand { get; }
[ExportCommandDefinition("Tools.Settings")]
public CommandDefinition SettingsCommand { get; }
}
}
| mit | C# |
5bc04b1402ed49164b5a344946aa5c27d4a9ae6e | Test QuoteConstant will only be for NET35 | theraot/Theraot | Tests/System/Linq/Expressions/ExpressionTest_Quote.net35.cs | Tests/System/Linq/Expressions/ExpressionTest_Quote.net35.cs | // <auto-generated />
// 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
//
// Authors:
// Federico Di Gregorio <fog@initd.org>
using System;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions
{
[TestFixture]
public class ExpressionTest_Quote
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg1Null ()
{
Expression.Quote (null);
}
#if NET35
[Test]
public void QuoteConstant ()
{
UnaryExpression expr = Expression.Quote (Expression.Constant (1));
Assert.AreEqual (ExpressionType.Quote, expr.NodeType, "Quote#01");
Assert.AreEqual (typeof (ConstantExpression), expr.Type, "Quote#02");
Assert.AreEqual ("1", expr.ToString(), "Quote#03");
}
#else
[Test]
[ExpectedException (typeof (ArgumentException))]
public void QuoteConstant ()
{
Expression.Quote (Expression.Constant (1));
}
#endif
[Test]
public void CompiledQuote ()
{
var quote42 = Expression.Lambda<Func<Expression<Func<int>>>> (
Expression.Quote (
Expression.Lambda<Func<int>> (
42.ToConstant ()))).Compile ();
var get42 = quote42 ().Compile ();
Assert.AreEqual (42, get42 ());
}
[Test]
[Category ("NotWorkingInterpreter")]
public void ParameterInQuotedExpression () // #550722
{
// Expression<Func<string, Expression<Func<string>>>> e = (string s) => () => s;
var s = Expression.Parameter (typeof (string), "s");
var lambda = Expression.Lambda<Func<string, Expression<Func<string>>>> (
Expression.Quote (
Expression.Lambda<Func<string>> (s, new ParameterExpression [0])),
s);
var fs = lambda.Compile () ("bingo").Compile ();
Assert.AreEqual ("bingo", fs ());
}
}
} | // <auto-generated />
// 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
//
// Authors:
// Federico Di Gregorio <fog@initd.org>
using System;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
namespace MonoTests.System.Linq.Expressions
{
[TestFixture]
public class ExpressionTest_Quote
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Arg1Null ()
{
Expression.Quote (null);
}
#if NET20 || NET30 || NET35
[Test]
public void QuoteConstant ()
{
UnaryExpression expr = Expression.Quote (Expression.Constant (1));
Assert.AreEqual (ExpressionType.Quote, expr.NodeType, "Quote#01");
Assert.AreEqual (typeof (ConstantExpression), expr.Type, "Quote#02");
Assert.AreEqual ("1", expr.ToString(), "Quote#03");
}
#else
[Test]
[ExpectedException (typeof (ArgumentException))]
public void QuoteConstant ()
{
Expression.Quote (Expression.Constant (1));
}
#endif
[Test]
public void CompiledQuote ()
{
var quote42 = Expression.Lambda<Func<Expression<Func<int>>>> (
Expression.Quote (
Expression.Lambda<Func<int>> (
42.ToConstant ()))).Compile ();
var get42 = quote42 ().Compile ();
Assert.AreEqual (42, get42 ());
}
[Test]
[Category ("NotWorkingInterpreter")]
public void ParameterInQuotedExpression () // #550722
{
// Expression<Func<string, Expression<Func<string>>>> e = (string s) => () => s;
var s = Expression.Parameter (typeof (string), "s");
var lambda = Expression.Lambda<Func<string, Expression<Func<string>>>> (
Expression.Quote (
Expression.Lambda<Func<string>> (s, new ParameterExpression [0])),
s);
var fs = lambda.Compile () ("bingo").Compile ();
Assert.AreEqual ("bingo", fs ());
}
}
} | mit | C# |
99b61722383e4f6bfcd260d01ab76e0fad83ee7a | Add Bitrise custom summary draft | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/OutputSinks/BitriseOutputSink.cs | source/Nuke.Common/OutputSinks/BitriseOutputSink.cs | // Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.Utilities;
namespace Nuke.Common.OutputSinks
{
[UsedImplicitly]
[ExcludeFromCodeCoverage]
internal class BitriseOutputSink : ConsoleOutputSink
{
public override IDisposable WriteBlock(string text)
{
Info(FigletTransform.GetText(text, "ansi-shadow"));
return DelegateDisposable.CreateBracket();
}
// public override void WriteSummary(IReadOnlyCollection<TargetDefinition> executionList)
// {
// string CreateLine(string target, string executionStatus, string duration)
// => new StringBuilder()
// .Append("| ")
// .Append(target.PadRight(42, ' '))
// .Append(executionStatus.PadRight(19, paddingChar: ' '))
// .Append((duration + " min").PadRight(15, paddingChar: ' '))
// .Append(" |").ToString();
//
// string ToMinutesAndSeconds(TimeSpan duration)
// => $"{(int) duration.TotalMinutes}:{duration:ss}";
//
// Logger.Log("+------------------------------------------------------------------------------+");
// Logger.Log("| build summary |");
// Logger.Log("+---+---------------------------------------------------------------+----------+");
// Logger.Log("| | target | time (s) |");
// Logger.Log("+---+---------------------------------------------------------------+----------+");
//
//
// Logger.Log("| Target Status Duration |");
// Logger.Log("+" + new string(c: '-', count: 78) + "+");
//
// foreach (var target in executionList)
// {
// var line = CreateLine(target.Name, target.Status.ToString(), ToMinutesAndSeconds(target.Duration));
// switch (target.Status)
// {
// case ExecutionStatus.Absent:
// case ExecutionStatus.NotRun:
// case ExecutionStatus.Skipped:
// Logger.Trace(line);
// break;
// case ExecutionStatus.Executed:
// Logger.Success(line);
// break;
// case ExecutionStatus.Failed:
// Logger.Error(line);
// break;
// }
// }
//
// Logger.Log("+" + new string(c: '-', count: 78) + "+");
// Logger.Log(CreateLine("Total", "", ToMinutesAndSeconds(executionList.Aggregate(TimeSpan.Zero, (t, x) => t.Add(x.Duration)))));
// Logger.Log("+---+---------------------------------------------------------------+----------+");
// Logger.Log("| ✓ | Run build.sh | 130 sec |");
// Logger.Log("+---+---------------------------------------------------------------+----------+");
// }
}
}
| // Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.Utilities;
namespace Nuke.Common.OutputSinks
{
[UsedImplicitly]
[ExcludeFromCodeCoverage]
internal class BitriseOutputSink : ConsoleOutputSink
{
public override IDisposable WriteBlock(string text)
{
Info(FigletTransform.GetText(text, "ansi-shadow"));
return DelegateDisposable.CreateBracket();
}
}
}
| mit | C# |
fdaa05460f39fc591394a808b654dcafb4be6d24 | Increment assembly version. | MatthewKing/SkypeQuoteCreator | source/SkypeQuoteCreator/Properties/AssemblyInfo.cs | source/SkypeQuoteCreator/Properties/AssemblyInfo.cs | [assembly: System.Reflection.AssemblyTitle("Skype Quote Creator")]
[assembly: System.Reflection.AssemblyCompany("Matthew King")]
[assembly: System.Reflection.AssemblyProduct("SkypeQuoteCreator")]
[assembly: System.Reflection.AssemblyCopyright("Copyright © Matthew King 2013")]
[assembly: System.Runtime.InteropServices.ComVisible(false)]
[assembly: System.Runtime.InteropServices.Guid("3390defc-1f8d-4166-8e29-2aa1b29d1e06")]
[assembly: System.Reflection.AssemblyInformationalVersion("1.0.7")]
[assembly: System.Reflection.AssemblyVersion("1.0.7.0")]
[assembly: System.Reflection.AssemblyFileVersion("1.0.7.0")]
| [assembly: System.Reflection.AssemblyTitle("Skype Quote Creator")]
[assembly: System.Reflection.AssemblyCompany("Matthew King")]
[assembly: System.Reflection.AssemblyProduct("SkypeQuoteCreator")]
[assembly: System.Reflection.AssemblyCopyright("Copyright © Matthew King 2013")]
[assembly: System.Runtime.InteropServices.ComVisible(false)]
[assembly: System.Runtime.InteropServices.Guid("3390defc-1f8d-4166-8e29-2aa1b29d1e06")]
[assembly: System.Reflection.AssemblyInformationalVersion("1.0.6")]
[assembly: System.Reflection.AssemblyVersion("1.0.6.0")]
[assembly: System.Reflection.AssemblyFileVersion("1.0.6.0")]
| mit | C# |
e8843254d3fc421115257ff912a4e08a7e4cf843 | Add input management to ShipManager | Voxelgon/Voxelgon,Voxelgon/Voxelgon | Assets/Plugins/Voxelgon/Spacecraft/ShipManager.cs | Assets/Plugins/Voxelgon/Spacecraft/ShipManager.cs | using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Voxelgon;
[RequireComponent (typeof (Rigidbody))]
public class ShipManager : MonoBehaviour {
public float portTransCutoff = 5;
//input Variables
public float linAxis;
public float latAxis;
public float yawAxis;
//Setup Variables for gathering Ports
public enum Direction{
YawLeft,
YawRight,
TransLeft,
TransRight,
TransForw,
TransBack
}
//dictionary of ports
public Dictionary<Direction, List<GameObject> > portGroups = new Dictionary<Direction, List<GameObject> > ();
public void SetupPorts(){
portGroups.Add( Direction.YawLeft, new List<GameObject>() );
portGroups.Add( Direction.YawRight, new List<GameObject>() );
portGroups.Add( Direction.TransLeft, new List<GameObject>() );
portGroups.Add( Direction.TransRight, new List<GameObject>() );
portGroups.Add( Direction.TransForw, new List<GameObject>() );
portGroups.Add( Direction.TransBack, new List<GameObject>() );
Vector3 origin = transform.rigidbody.centerOfMass;
//Debug.Log(origin);
Component[] PortScripts = gameObject.GetComponentsInChildren(typeof(RCSport));
foreach(Component i in PortScripts) {
float angle = Voxelgon.Math.RelativeAngle(origin, i.transform);
//Debug.Log(angle);
if(angle > portTransCutoff){
portGroups[Direction.YawLeft].Add(i.gameObject);
//Debug.Log("This port is for turning Left!");
} else if(angle < (-1 * portTransCutoff)){
portGroups[Direction.YawRight].Add(i.gameObject);
//Debug.Log("This port is for turning right!");
}
}
}
//updates input variables
public void UpdateInputs() {
linAxis = Input.GetAxis("Thrust");
latAxis = Input.GetAxis("Strafe");
yawAxis = Input.GetAxis("Yaw");
}
//Called every frame
public void Update() {
UpdateInputs();
}
//Startup Script
public void Start() {
SetupPorts();
}
} | using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Voxelgon;
[RequireComponent (typeof (Rigidbody))]
public class ShipManager : MonoBehaviour {
public float portTransCutoff = 5;
//Setup Variables for gathering Ports
public enum Direction{
YawLeft,
YawRight,
TransLeft,
TransRight,
TransForw,
TransBack
}
//dictionary of ports
public Dictionary<Direction, List<GameObject> > portGroups = new Dictionary<Direction, List<GameObject> > ();
public void SetupPorts(){
portGroups.Add( Direction.YawLeft, new List<GameObject>() );
portGroups.Add( Direction.YawRight, new List<GameObject>() );
portGroups.Add( Direction.TransLeft, new List<GameObject>() );
portGroups.Add( Direction.TransRight, new List<GameObject>() );
portGroups.Add( Direction.TransForw, new List<GameObject>() );
portGroups.Add( Direction.TransBack, new List<GameObject>() );
Vector3 origin = transform.rigidbody.centerOfMass;
//Debug.Log(origin);
Component[] PortScripts = gameObject.GetComponentsInChildren(typeof(RCSport));
foreach(Component i in PortScripts) {
float angle = Voxelgon.Math.RelativeAngle(origin, i.transform);
//Debug.Log(angle);
if(angle > portTransCutoff){
portGroups[Direction.YawLeft].Add(i.gameObject);
//Debug.Log("This port is for turning Left!");
} else if(angle < (-1 * portTransCutoff)){
portGroups[Direction.YawRight].Add(i.gameObject);
//Debug.Log("This port is for turning right!");
}
}
}
//Startup Script
public void Start() {
SetupPorts();
}
} | apache-2.0 | C# |
1e9a5f462ad5e5db4ed29dc9c4c0f477453cbc83 | Adjust namespaces for Data.NHibernate4 unit tests. | aranasoft/cobweb | src/Tests/Data.NHibernate4.Tests/CompileTests.cs | src/Tests/Data.NHibernate4.Tests/CompileTests.cs | using System;
using System.Data;
using System.Linq;
using NHibernate;
namespace Cobweb.Data.NHibernate.Tests {
/// <summary>
/// These tests are not executed by NUnit. They are here for compile-time checking. 'If it builds, ship it.'
/// </summary>
public class CompileTests {
internal class SessionBuilder : NHibernateSessionBuilder {
public override IDataTransaction BeginTransaction() {
return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction());
}
public override IDataTransaction BeginTransaction(IsolationLevel isolationLevel) {
return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction());
}
public override ISession GetCurrentSession() {
throw new NotImplementedException();
}
}
}
}
| using System;
using System.Data;
using System.Linq;
using Cobweb.Data;
using Cobweb.Data.NHibernate;
using NHibernate;
namespace Data.NHibernate.Tests {
/// <summary>
/// These tests are not executed by NUnit. They are here for compile-time checking. 'If it builds, ship it.'
/// </summary>
public class CompileTests {
internal class SessionBuilder : NHibernateSessionBuilder {
public override IDataTransaction BeginTransaction() {
return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction());
}
public override IDataTransaction BeginTransaction(IsolationLevel isolationLevel) {
return new NHibernateTransactionHandler(GetCurrentSession().BeginTransaction());
}
public override ISession GetCurrentSession() {
throw new NotImplementedException();
}
}
}
}
| bsd-3-clause | C# |
59d4744c84c2fa35b26b54722f0c9f650587e9e5 | Extend the boxing/unboxing test with a primitive value unbox | jonathanvdc/ecsc | tests/cs/boxing/Boxing.cs | tests/cs/boxing/Boxing.cs | using System;
public struct Foo : ICloneable
{
public int CloneCounter { get; private set; }
public object Clone()
{
CloneCounter++;
return this;
}
}
public static class Program
{
public static ICloneable BoxAndCast<T>(T Value)
{
return (ICloneable)Value;
}
public static void Main(string[] Args)
{
var foo = default(Foo);
Console.WriteLine(((Foo)foo.Clone()).CloneCounter);
Console.WriteLine(((Foo)BoxAndCast<Foo>(foo).Clone()).CloneCounter);
Console.WriteLine(foo.CloneCounter);
object i = 42;
Console.WriteLine((int)i);
}
}
| using System;
public struct Foo : ICloneable
{
public int CloneCounter { get; private set; }
public object Clone()
{
CloneCounter++;
return this;
}
}
public static class Program
{
public static ICloneable BoxAndCast<T>(T Value)
{
return (ICloneable)Value;
}
public static void Main(string[] Args)
{
var foo = default(Foo);
Console.WriteLine(((Foo)foo.Clone()).CloneCounter);
Console.WriteLine(((Foo)BoxAndCast<Foo>(foo).Clone()).CloneCounter);
Console.WriteLine(foo.CloneCounter);
}
}
| mit | C# |
48887ebf49e0bdd33581bb587385bc63897a7e57 | Fix issue with test class | generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork | Smoother.IoC.Dapper.Repository.UnitOfWork.Tests/TestClasses/Migrations/MigrateDb.cs | Smoother.IoC.Dapper.Repository.UnitOfWork.Tests/TestClasses/Migrations/MigrateDb.cs | using System.Data;
using System.Data.SQLite;
using System.Reflection;
using FakeItEasy;
using FakeItEasy.Core;
using SimpleMigrations;
using SimpleMigrations.VersionProvider;
using Smoother.IoC.Dapper.Repository.UnitOfWork.Data;
using Smoother.IoC.Dapper.Repository.UnitOfWork.UoW;
namespace Smoother.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestClasses.Migrations
{
public class MigrateDb
{
public ISession Connection { get; }
public MigrateDb()
{
var migrationsAssembly = Assembly.GetExecutingAssembly();
var versionProvider = new SqliteVersionProvider();
var factory = A.Fake<IDbFactory>();
Connection = new TestSession(factory, "Data Source=:memory:;Version=3;New=True;");
A.CallTo(() => factory.CreateUnitOwWork<IUnitOfWork>(A<IDbFactory>._, A<ISession>._))
.ReturnsLazily(CreateUnitOrWork);
var migrator = new SimpleMigrator(migrationsAssembly, Connection, versionProvider);
migrator.Load();
migrator.MigrateToLatest();
}
private IUnitOfWork CreateUnitOrWork(IFakeObjectCall arg)
{
return new Dapper.Repository.UnitOfWork.Data.UnitOfWork((IDbFactory) arg.FakedObject, Connection);
}
}
internal class TestSession : SqliteSession<SQLiteConnection>
{
public TestSession(IDbFactory factory, string connectionString) : base(factory, connectionString)
{
}
}
}
| using System.Data;
using System.Data.SQLite;
using System.Reflection;
using FakeItEasy;
using FakeItEasy.Core;
using SimpleMigrations;
using SimpleMigrations.VersionProvider;
using Smoother.IoC.Dapper.Repository.UnitOfWork.Data;
using Smoother.IoC.Dapper.Repository.UnitOfWork.UoW;
namespace Smoother.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestClasses.Migrations
{
public class MigrateDb
{
public ISession Connection { get; }
public MigrateDb()
{
var migrationsAssembly = Assembly.GetExecutingAssembly();
var versionProvider = new SqliteVersionProvider();
var factory = A.Fake<IDbFactory>();
Connection = new TestSession(factory, "Data Source=:memory:;Version=3;New=True;");
A.CallTo(() => factory.CreateUnitOwWork<IUnitOfWork>(A<IDbFactory>._, A<ISession>._))
.ReturnsLazily(CreateUnitOrWork);
var migrator = new SimpleMigrator(migrationsAssembly, Connection, versionProvider);
migrator.Load();
migrator.MigrateToLatest();
}
private IUnitOfWork CreateUnitOrWork(IFakeObjectCall arg)
{
return new Dapper.Repository.UnitOfWork.Data.UnitOfWork((IDbFactory) arg.FakedObject, Connection);
}
}
public class TestSession : SqliteSession<SQLiteConnection>
{
public TestSession(IDbFactory factory, string connectionString) : base(factory, connectionString)
{
}
}
}
| mit | C# |
3e37ac8e84045cab392cb877506eaa0df3a44cfb | Prepare for next release | Puzzlepart/PnP-Sites-Core,comblox/PnP-Sites-Core,comblox/PnP-Sites-Core,PieterVeenstra/PnP-Sites-Core,phillipharding/PnP-Sites-Core,m-carter1/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,Puzzlepart/PnP-Sites-Core,m-carter1/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,rajashekarusa/PnP-Sites-Core,phillipharding/PnP-Sites-Core,Oaden/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,rajashekarusa/PnP-Sites-Core,rajashekarusa/PnP-Sites-Core,Oaden/PnP-Sites-Core,PieterVeenstra/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 2015")]
[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.0.1601.0")]
[assembly: AssemblyFileVersion("2.0.1601.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 2015")]
[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 1
// Minor version = Sequence...version 0 was with March release...so 1=April, 2=May, 3=June, 4=August, 6=September, 7=October, 8=November, 9=December
// Third part = version indenpendant showing the release month in MMYY
// Fourth part = 0 normally or a sequence number when we do an emergency release
[assembly: AssemblyVersion("1.9.1215.0")]
[assembly: AssemblyFileVersion("1.9.1215.0")]
[assembly: InternalsVisibleTo("OfficeDevPnP.Core.Tests")] | mit | C# |
440cf8d2f54e9df44080923f458b3db272cf35b0 | Remove not used import | Lc5/CurrencyRates,Lc5/CurrencyRates,Lc5/CurrencyRates | CurrencyRates.Web/Installers/ContextInstaller.cs | CurrencyRates.Web/Installers/ContextInstaller.cs | namespace CurrencyRates.Web.Installers
{
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using CurrencyRates.Model;
public class ContextInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component
.For<Context>()
.LifestyleTransient()
.OnCreate(c => c.Configuration.ProxyCreationEnabled = false));
}
}
}
| namespace CurrencyRates.Web.Installers
{
using Castle.Facilities.WcfIntegration;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using CurrencyRates.Model;
public class ContextInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component
.For<Context>()
.LifestyleTransient()
.OnCreate(c => c.Configuration.ProxyCreationEnabled = false));
}
}
}
| mit | C# |
25ad63d7fa6a892616aff6622c2f297fb8362a7a | Extend the indexing test | jonathanvdc/ecsc | tests/cs/index/Index.cs | tests/cs/index/Index.cs | using System;
using System.Collections.Generic;
public static class Program
{
public static void Main()
{
int[] arr = new int[1];
arr[0] = 1;
Console.WriteLine(arr[0]);
var list = new List<int>() { 0 };
list[0] = 1;
Console.WriteLine(list[0]);
}
}
| using System;
public static class Program
{
public static void Main()
{
int[] arr = new int[1];
arr[0] = 1;
Console.WriteLine(arr[0]);
}
}
| mit | C# |
4fb2c2d6cc731e990880acda7a8492ccf8c99e03 | Modify mappings for Departments | denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs | src/Diploms.Services/Departments/DepartmentsMappings.cs | src/Diploms.Services/Departments/DepartmentsMappings.cs | using AutoMapper;
using Diploms.Core;
using Diploms.Dto.Departments;
namespace Diploms.Services.Departments
{
public class DepartmentsMappings : Profile
{
public DepartmentsMappings()
{
CreateMap<DepartmentEditDto, Department>();
CreateMap<Department, DepartmentEditDto>();
}
}
} | using AutoMapper;
using Diploms.Core;
using Diploms.Dto.Departments;
namespace Diploms.Services.Departments
{
public class DepartmentsMappings : Profile
{
public DepartmentsMappings()
{
CreateMap<DepartmentEditDto, Department>();
}
}
} | mit | C# |
3c62b9c84bb9a8164efd2f63c30c38f54d31f653 | Fix NH-2840 - SetFirstResult and SetMaxResults do not work correctly on Oracle (ODP.NET) | ngbrown/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,alobakov/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,ngbrown/nhibernate-core,nkreipke/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core | src/NHibernate/Param/QueryTakeParameterSpecification.cs | src/NHibernate/Param/QueryTakeParameterSpecification.cs | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using NHibernate.Engine;
using NHibernate.SqlCommand;
using NHibernate.Type;
namespace NHibernate.Param
{
/// <summary>
/// Autogenerated parameter for <see cref="IQuery.SetMaxResults"/>.
/// </summary>
public class QueryTakeParameterSpecification : IParameterSpecification
{
// NOTE: don't use this for HQL take clause
private readonly string[] idTrack;
private readonly string limitParametersNameForThisQuery = "<nhtake" + Guid.NewGuid().ToString("N"); // NH_note: to avoid conflicts using MultiQuery/Future
private readonly IType type = NHibernateUtil.Int32;
public QueryTakeParameterSpecification()
{
idTrack = new[] { limitParametersNameForThisQuery };
}
#region IParameterSpecification Members
public void Bind(IDbCommand command, IList<Parameter> sqlQueryParametersList, QueryParameters queryParameters, ISessionImplementor session)
{
Bind(command, sqlQueryParametersList, 0, sqlQueryParametersList, queryParameters, session);
}
public void Bind(IDbCommand command, IList<Parameter> multiSqlQueryParametersList, int singleSqlParametersOffset, IList<Parameter> sqlQueryParametersList, QueryParameters queryParameters, ISessionImplementor session)
{
// The QueryTakeParameterSpecification is unique so we can use multiSqlQueryParametersList
var effectiveParameterLocations = multiSqlQueryParametersList.GetEffectiveParameterLocations(limitParametersNameForThisQuery).ToArray();
if (effectiveParameterLocations.Any())
{
// if the dialect does not support variable limits the parameter may was removed
int value = Loader.Loader.GetLimitUsingDialect(queryParameters.RowSelection, session.Factory.Dialect) ?? queryParameters.RowSelection.MaxRows;
int position = effectiveParameterLocations.Single();
type.NullSafeSet(command, value, position, session);
}
}
public IType ExpectedType
{
get { return type; }
set { throw new InvalidOperationException(); }
}
public string RenderDisplayInfo()
{
return "query-take";
}
public IEnumerable<string> GetIdsForBackTrack(IMapping sessionFactory)
{
return idTrack;
}
#endregion
public override bool Equals(object obj)
{
return Equals(obj as QueryTakeParameterSpecification);
}
public bool Equals(QueryTakeParameterSpecification other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Equals(other.limitParametersNameForThisQuery, limitParametersNameForThisQuery);
}
public override int GetHashCode()
{
return limitParametersNameForThisQuery.GetHashCode();
}
}
} | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using NHibernate.Engine;
using NHibernate.SqlCommand;
using NHibernate.Type;
namespace NHibernate.Param
{
/// <summary>
/// Autogenerated parameter for <see cref="IQuery.SetMaxResults"/>.
/// </summary>
public class QueryTakeParameterSpecification : IParameterSpecification
{
// NOTE: don't use this for HQL take clause
private readonly string[] idTrack;
private readonly string limitParametersNameForThisQuery = "<nhtake" + Guid.NewGuid().ToString("N"); // NH_note: to avoid conflicts using MultiQuery/Future
private readonly IType type = NHibernateUtil.Int32;
public QueryTakeParameterSpecification()
{
idTrack = new[] { limitParametersNameForThisQuery };
}
#region IParameterSpecification Members
public void Bind(IDbCommand command, IList<Parameter> sqlQueryParametersList, QueryParameters queryParameters, ISessionImplementor session)
{
Bind(command, sqlQueryParametersList, 0, sqlQueryParametersList, queryParameters, session);
}
public void Bind(IDbCommand command, IList<Parameter> multiSqlQueryParametersList, int singleSqlParametersOffset, IList<Parameter> sqlQueryParametersList, QueryParameters queryParameters, ISessionImplementor session)
{
// The QueryTakeParameterSpecification is unique so we can use multiSqlQueryParametersList
var effectiveParameterLocations = multiSqlQueryParametersList.GetEffectiveParameterLocations(limitParametersNameForThisQuery).ToArray();
if (effectiveParameterLocations.Any())
{
// if the dialect does not support variable limits the parameter may was removed
int value = queryParameters.RowSelection.MaxRows;
int position = effectiveParameterLocations.Single();
type.NullSafeSet(command, value, position, session);
}
}
public IType ExpectedType
{
get { return type; }
set { throw new InvalidOperationException(); }
}
public string RenderDisplayInfo()
{
return "query-take";
}
public IEnumerable<string> GetIdsForBackTrack(IMapping sessionFactory)
{
return idTrack;
}
#endregion
public override bool Equals(object obj)
{
return Equals(obj as QueryTakeParameterSpecification);
}
public bool Equals(QueryTakeParameterSpecification other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Equals(other.limitParametersNameForThisQuery, limitParametersNameForThisQuery);
}
public override int GetHashCode()
{
return limitParametersNameForThisQuery.GetHashCode();
}
}
} | lgpl-2.1 | C# |
6d539f72447d99e8b18bcd05359834e32faf75fa | Change "Folder Watcher" widget default size | danielchalmers/DesktopWidgets | DesktopWidgets/Widgets/FolderWatcher/Settings.cs | DesktopWidgets/Widgets/FolderWatcher/Settings.cs | using System;
using System.ComponentModel;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Widgets.FolderWatcher
{
public class Settings : WidgetSettingsBase, IEventWidget
{
public Settings()
{
Width = 384;
Height = 216;
}
[Category("General")]
[DisplayName("Folder Check Interval")]
public TimeSpan FolderCheckInterval { get; set; } = TimeSpan.FromMilliseconds(500);
[Category("General")]
[DisplayName("Folder To Watch")]
public string WatchFolder { get; set; } = "";
[Category("General")]
[DisplayName("Include Filter")]
public string IncludeFilter { get; set; } = "*.*";
[Category("General")]
[DisplayName("Exclude Filter")]
public string ExcludeFilter { get; set; } = "";
[Category("Style")]
[DisplayName("Show File Name")]
public bool ShowFileName { get; set; } = true;
[Category("Style")]
[DisplayName("Show Mute")]
public bool ShowMute { get; set; } = true;
[Category("Style")]
[DisplayName("Show Dismiss")]
public bool ShowDismiss { get; set; } = true;
[DisplayName("Mute End Time")]
public DateTime MuteEndTime { get; set; } = DateTime.Now;
[DisplayName("Mute Duration")]
public TimeSpan MuteDuration { get; set; } = TimeSpan.FromHours(1);
[Category("General")]
[DisplayName("Timeout Duration")]
public TimeSpan TimeoutDuration { get; set; } = TimeSpan.FromMinutes(1);
[DisplayName("Last File Check")]
public DateTime LastCheck { get; set; } = DateTime.Now;
[Category("General")]
[DisplayName("Enable Timeout")]
public bool EnableTimeout { get; set; } = false;
[Category("Behavior (Hideable)")]
[DisplayName("Open On Event")]
public bool OpenOnEvent { get; set; } = true;
[Category("Behavior (Hideable)")]
[DisplayName("Stay Open On Event")]
public bool OpenOnEventStay { get; set; } = false;
[Category("Behavior (Hideable)")]
[DisplayName("Open On Event Duration")]
public TimeSpan OpenOnEventDuration { get; set; } = TimeSpan.FromSeconds(10);
}
} | using System;
using System.ComponentModel;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Widgets.FolderWatcher
{
public class Settings : WidgetSettingsBase, IEventWidget
{
[Category("General")]
[DisplayName("Folder Check Interval")]
public TimeSpan FolderCheckInterval { get; set; } = TimeSpan.FromMilliseconds(500);
[Category("General")]
[DisplayName("Folder To Watch")]
public string WatchFolder { get; set; } = "";
[Category("General")]
[DisplayName("Include Filter")]
public string IncludeFilter { get; set; } = "*.*";
[Category("General")]
[DisplayName("Exclude Filter")]
public string ExcludeFilter { get; set; } = "";
[Category("Style")]
[DisplayName("Show File Name")]
public bool ShowFileName { get; set; } = true;
[Category("Style")]
[DisplayName("Show Mute")]
public bool ShowMute { get; set; } = true;
[Category("Style")]
[DisplayName("Show Dismiss")]
public bool ShowDismiss { get; set; } = true;
[DisplayName("Mute End Time")]
public DateTime MuteEndTime { get; set; } = DateTime.Now;
[DisplayName("Mute Duration")]
public TimeSpan MuteDuration { get; set; } = TimeSpan.FromHours(1);
[Category("General")]
[DisplayName("Timeout Duration")]
public TimeSpan TimeoutDuration { get; set; } = TimeSpan.FromMinutes(1);
[DisplayName("Last File Check")]
public DateTime LastCheck { get; set; } = DateTime.Now;
[Category("General")]
[DisplayName("Enable Timeout")]
public bool EnableTimeout { get; set; } = false;
[Category("Behavior (Hideable)")]
[DisplayName("Open On Event")]
public bool OpenOnEvent { get; set; } = true;
[Category("Behavior (Hideable)")]
[DisplayName("Stay Open On Event")]
public bool OpenOnEventStay { get; set; } = false;
[Category("Behavior (Hideable)")]
[DisplayName("Open On Event Duration")]
public TimeSpan OpenOnEventDuration { get; set; } = TimeSpan.FromSeconds(10);
}
} | apache-2.0 | C# |
37611b467b6dec0f659eee2b9b127170668e0e97 | Repair error in Console Writeline | pkindalov/beginner_exercises | DisplayCurrentTime/DisplayCurrentTime/Program.cs | DisplayCurrentTime/DisplayCurrentTime/Program.cs | using System;
class Program
{
static void Main()
{
Console.WriteLine(DateTime.Now);
}
}
| using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, C#!");
}
}
| mit | C# |
9161300ea8f1ab11b3c594b84c706b80dcc8e742 | Allow internal classes to set the value of a XmlNode. | nohros/must,nohros/must,nohros/must | src/base/common/configuration/common/XmlElementsNode.cs | src/base/common/configuration/common/XmlElementsNode.cs | using System;
using System.Xml;
namespace Nohros.Configuration
{
/// <summary>
/// Provides a default implementation of the <see cref="IXmlElementsNode"/>
/// interface.
/// </summary>
public partial class XmlElementsNode : AbstractHierarchicalConfigurationNode,
IXmlElementsNode
{
#region XmlElementNode
class XmlElementNode : AbstractConfigurationNode
{
readonly XmlElement xml_element_;
#region .ctor
public XmlElementNode(XmlElement xml_element) : base(xml_element.Name) {
xml_element_ = xml_element;
}
#endregion
public XmlElement XmlElement {
get { return xml_element_; }
}
}
#endregion
#region .ctor
/// <summary>
/// Initializes a new instance of the <see cref="XmlElementsNode"/> class.
/// </summary>
public XmlElementsNode() : base(Strings.kXmlElementsNodeName) {
}
#endregion
#region IXmlElementsNode Members
/// <inheritdoc/>
public XmlElement GetXmlElement(string xml_element_name) {
return GetChildNode<XmlElementNode>(xml_element_name).XmlElement;
}
/// <inheritdoc/>
public bool GetXmlElement(string xml_element_name,
out XmlElement xml_element) {
XmlElementNode xml_element_node;
if (GetChildNode(xml_element_name, out xml_element_node)) {
xml_element = xml_element_node.XmlElement;
return true;
}
xml_element = default(XmlElement);
return false;
}
/// <inheritdoc/>
public new XmlElement this[string xml_element_name] {
get { return GetXmlElement(xml_element_name); }
internal set { base[xml_element_name] = new XmlElementNode(value); }
}
#endregion
}
}
| using System;
using System.Xml;
namespace Nohros.Configuration
{
/// <summary>
/// Provides a default implementation of the <see cref="IXmlElementsNode"/>
/// interface.
/// </summary>
public partial class XmlElementsNode : AbstractHierarchicalConfigurationNode,
IXmlElementsNode
{
#region XmlElementNode
class XmlElementNode : AbstractConfigurationNode
{
readonly XmlElement xml_element_;
#region .ctor
public XmlElementNode(XmlElement xml_element) : base(xml_element.Name) {
xml_element_ = xml_element;
}
#endregion
public XmlElement XmlElement {
get { return xml_element_; }
}
}
#endregion
#region .ctor
/// <summary>
/// Initializes a new instance of the <see cref="XmlElementsNode"/> class.
/// </summary>
public XmlElementsNode() : base(Strings.kXmlElementsNodeName) {
}
#endregion
#region IXmlElementsNode Members
/// <inheritdoc/>
public XmlElement GetXmlElement(string xml_element_name) {
return GetChildNode<XmlElementNode>(xml_element_name).XmlElement;
}
/// <inheritdoc/>
public bool GetXmlElement(string xml_element_name,
out XmlElement xml_element) {
XmlElementNode xml_element_node;
if (GetChildNode(xml_element_name, out xml_element_node)) {
xml_element = xml_element_node.XmlElement;
return true;
}
xml_element = default(XmlElement);
return false;
}
/// <inheritdoc/>
public new XmlElement this[string xml_element_name] {
get { return GetXmlElement(xml_element_name); }
}
#endregion
}
}
| mit | C# |
786da529363496eb6acfb1d5edad33351abecf44 | Add Reset event to Form | praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui | Ooui/Form.cs | Ooui/Form.cs | using System;
namespace Ooui
{
public class Form : Element
{
public event EventHandler Submitted {
add => AddEventListener ("submit", value);
remove => RemoveEventListener ("submit", value);
}
public event EventHandler Reset {
add => AddEventListener ("reset", value);
remove => RemoveEventListener ("reset", value);
}
public Form ()
: base ("form")
{
}
}
}
| using System;
namespace Ooui
{
public class Form : Element
{
public event EventHandler Submitted {
add => AddEventListener ("submit", value);
remove => RemoveEventListener ("submit", value);
}
public Form ()
: base ("form")
{
}
}
}
| mit | C# |
fd7107667471ab7fb47d1fa53eeccdf18d18f5c9 | Improve zoom panning | EvanHahn/Unity-RTS-camera | RTSCamera.cs | RTSCamera.cs | using UnityEngine;
using System.Collections;
public class RTSCamera : MonoBehaviour {
public bool disablePanning = false;
public bool disableSelect = false;
public bool disableZoom = false;
public float maximumZoom = 1f;
public float minimumZoom = 20f;
public Color selectColor = Color.green;
public float selectLineWidth = 2f;
public float lookDamper = 5f;
private readonly string[] INPUT_MOUSE_BUTTONS = {"Mouse Look", "Mouse Select"};
private bool[] isDragging = new bool[2];
private Vector3 selectStartPosition;
private Texture2D pixel;
void Start() {
if (!camera) {
throw new MissingComponentException("RTS Camera must be attached to a camera.");
}
setPixel(selectColor);
}
void Update() {
updateDragging();
updateLook();
updateZoom();
}
void OnGUI() {
updateSelect();
}
private void updateDragging() {
for (int index = 0; index <= 1; index ++) {
if (isClicking(index) && !isDragging[index]) {
isDragging[index] = true;
if (index == 1) {
selectStartPosition = getMousePosition();
}
} else if (!isClicking(index) && isDragging[index]) {
isDragging[index] = false;
}
}
}
private void updateLook() {
if (!isDragging[0] || disablePanning) { return; }
var newPosition = transform.position;
var mousePosition = getMouseMovement();
newPosition.x = newPosition.x - (mousePosition.x * camera.orthographicSize / lookDamper);
newPosition.y = newPosition.y - (mousePosition.y * camera.orthographicSize / lookDamper);
transform.position = newPosition;
}
private void updateSelect() {
if (!isDragging[1] || disableSelect) { return; }
var x = selectStartPosition.x;
var y = selectStartPosition.y;
var width = getMousePosition().x - selectStartPosition.x;
var height = getMousePosition().y - selectStartPosition.y;
GUI.DrawTexture(new Rect(x, y, width, selectLineWidth), pixel);
GUI.DrawTexture(new Rect(x, y, selectLineWidth, height), pixel);
GUI.DrawTexture(new Rect(x, y + height, width, selectLineWidth), pixel);
GUI.DrawTexture(new Rect(x + width, y, selectLineWidth, height), pixel);
}
private void updateZoom() {
if (disableZoom) { return; }
var newSize = camera.orthographicSize - Input.GetAxis("Mouse ScrollWheel");
newSize = Mathf.Clamp(newSize, maximumZoom, minimumZoom);
camera.orthographicSize = newSize;
}
private bool isClicking(int index) {
return Input.GetAxis(INPUT_MOUSE_BUTTONS[index]) == 1;
}
private Vector2 getMouseMovement() {
return new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
}
private void setPixel(Color color) {
pixel = new Texture2D(1, 1);
pixel.SetPixel(0, 0, color);
pixel.Apply();
}
private Vector3 getMousePosition() {
var result = Input.mousePosition;
result.y = Screen.height - result.y;
return result;
}
}
| using UnityEngine;
using System.Collections;
public class RTSCamera : MonoBehaviour {
public bool disablePanning = false;
public bool disableSelect = false;
public float maximumZoom = 1f;
public float minimumZoom = 20f;
public Color selectColor = Color.green;
public float selectLineWidth = 2f;
private readonly string[] INPUT_MOUSE_BUTTONS = {"Mouse Look", "Mouse Select"};
private bool[] isDragging = new bool[2];
private Vector3 selectStartPosition;
private Texture2D pixel;
void Start() {
if (!camera) {
throw new MissingComponentException("RTS Camera must be attached to a camera.");
}
setPixel(selectColor);
}
void Update() {
updateDragging();
updateLook();
updateZoom();
}
void OnGUI() {
updateSelect();
}
private void updateDragging() {
for (int index = 0; index <= 1; index ++) {
if (isClicking(index) && !isDragging[index]) {
isDragging[index] = true;
if (index == 1) {
selectStartPosition = getMousePosition();
}
} else if (!isClicking(index) && isDragging[index]) {
isDragging[index] = false;
}
}
}
private void updateLook() {
if (!isDragging[0] || disablePanning) { return; }
var newPosition = transform.position;
var mousePosition = getMouseMovement();
newPosition.x = newPosition.x - mousePosition.x;
newPosition.y = newPosition.y - mousePosition.y;
transform.position = newPosition;
}
private void updateSelect() {
if (!isDragging[1] || disableSelect) { return; }
var x = selectStartPosition.x;
var y = selectStartPosition.y;
var width = getMousePosition().x - selectStartPosition.x;
var height = getMousePosition().y - selectStartPosition.y;
GUI.DrawTexture(new Rect(x, y, width, selectLineWidth), pixel);
GUI.DrawTexture(new Rect(x, y, selectLineWidth, height), pixel);
GUI.DrawTexture(new Rect(x, y + height, width, selectLineWidth), pixel);
GUI.DrawTexture(new Rect(x + width, y, selectLineWidth, height), pixel);
}
private void updateZoom() {
var newSize = camera.orthographicSize - Input.GetAxis("Mouse ScrollWheel");
newSize = Mathf.Clamp(newSize, maximumZoom, minimumZoom);
camera.orthographicSize = newSize;
}
private bool isClicking(int index) {
return Input.GetAxis(INPUT_MOUSE_BUTTONS[index]) == 1;
}
private Vector2 getMouseMovement() {
return new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
}
private void setPixel(Color color) {
pixel = new Texture2D(1, 1);
pixel.SetPixel(0, 0, color);
pixel.Apply();
}
private Vector3 getMousePosition() {
var result = Input.mousePosition;
result.y = Screen.height - result.y;
return result;
}
}
| mit | C# |
c809b662c08b0c843d3b8d2360ddd027e93b0dcc | Add remarks about non-UI thread | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.Exports/Services/ITeamExplorerContext.cs | src/GitHub.Exports/Services/ITeamExplorerContext.cs | using System;
using System.ComponentModel;
using GitHub.Models;
namespace GitHub.Services
{
/// <summary>
/// Responsible for watching the active repository in Team Explorer.
/// </summary>
/// <remarks>
/// A <see cref="PropertyChanged"/> event is fired when moving to a new repository.
/// A <see cref="StatusChanged"/> event is fired when the CurrentBranch or HeadSha changes.
/// </remarks>
public interface ITeamExplorerContext : INotifyPropertyChanged
{
/// <summary>
/// The active Git repository in Team Explorer.
/// This will be null if no repository is active.
/// </summary>
/// <remarks>
/// This property might be changed by a non-UI thread.
/// </remarks>
ILocalRepositoryModel ActiveRepository { get; }
/// <summary>
/// Fired when the CurrentBranch or HeadSha changes.
/// </summary>
/// <remarks>
/// This event might fire on a non-UI thread.
/// </remarks>
event EventHandler StatusChanged;
}
}
| using System;
using System.ComponentModel;
using GitHub.Models;
namespace GitHub.Services
{
/// <summary>
/// Responsible for watching the active repository in Team Explorer.
/// </summary>
/// <remarks>
/// A <see cref="PropertyChanged"/> event is fired when moving to a new repository.
/// A <see cref="StatusChanged"/> event is fired when the CurrentBranch or HeadSha changes.
/// </remarks>
public interface ITeamExplorerContext : INotifyPropertyChanged
{
/// <summary>
/// The active Git repository in Team Explorer.
/// This will be null if no repository is active.
/// </summary>
ILocalRepositoryModel ActiveRepository { get; }
/// <summary>
/// Fired when the CurrentBranch or HeadSha changes.
/// </summary>
event EventHandler StatusChanged;
}
}
| mit | C# |
4db6c08be5d9c903daffc8141e133c24f945171f | remove superfluous test | Pondidum/Jess,Pondidum/Jess | Jess.Tests/Acceptance/Hydration/WhenHydrating.cs | Jess.Tests/Acceptance/Hydration/WhenHydrating.cs | using System.Net.Http;
using Jess.Tests.Util;
using Shouldly;
using Xunit;
namespace Jess.Tests.Acceptance.Hydration
{
public class WhenHydrating : AcceptanceBase
{
public WhenHydrating()
{
Remote.RespondsTo(
"/candidate/ref/123",
request => new DehydratedResponse(Resource.PersonWithOneRef));
Remote.RespondsTo(
"/candidate/ref/456",
request => new JsonResponse(Resource.PersonWithOneRef));
}
[Fact]
public void Without_a_hydrate_header()
{
var response = Hydrator.MakeRequest("/candidate/ref/456", new HttpRequestMessage());
var body = response.Content.ReadAsStringAsync().Result;
body.ShouldNotBeEmpty();
body.ShouldBe(Resource.PersonWithOneRef);
}
}
}
| using System.Net.Http;
using Jess.Tests.Util;
using Shouldly;
using Xunit;
namespace Jess.Tests.Acceptance.Hydration
{
public class WhenHydrating : AcceptanceBase
{
public WhenHydrating()
{
Remote.RespondsTo(
"/candidate/ref/123",
request => new DehydratedResponse(Resource.PersonWithOneRef));
Remote.RespondsTo(
"/candidate/ref/456",
request => new JsonResponse(Resource.PersonWithOneRef));
}
[Fact]
public void A_valid_request()
{
var response = Hydrator.MakeRequest("/candidate/ref/123", new HttpRequestMessage());
var body = response.Content.ReadAsStringAsync().Result;
body.ShouldNotBeEmpty();
body.ShouldNotContain("!ref");
body.ShouldNotBe(Resource.PersonWithOneRef);
}
[Fact]
public void Without_a_hydrate_header()
{
var response = Hydrator.MakeRequest("/candidate/ref/456", new HttpRequestMessage());
var body = response.Content.ReadAsStringAsync().Result;
body.ShouldNotBeEmpty();
body.ShouldBe(Resource.PersonWithOneRef);
}
}
}
| lgpl-2.1 | C# |
6a80922767f0088a750efe3820017bb2a891ba94 | Delete stuff | TeamLeoTolstoy/Leo | Game/StopTheBunny/Score.cs | Game/StopTheBunny/Score.cs | namespace StopTheBunny
{
using System;
public class Score
{
private int scorePoints;
public Score()
{
}
public Score(int score)
{
this.ScorePoints = score;
}
public int ScorePoints
{
get
{
return this.scorePoints;
}
set
{
if (value < 0)
{
throw new ArgumentException();
}
this.scorePoints = value;
}
}
public void AddPoints(int points)
{
this.ScorePoints += points;
}
}
} | namespace StopTheBunny
{
using System;
public class Score
{
private int scorePoints;
public Score()
{
}
public Score(int score)
{
this.ScorePoints = score;
}
public int ScorePoints
{
get
{
return this.scorePoints;
}
set
{
if (value < 0)
{
throw new ArgumentException();
}
this.scorePoints = value;
}
}
public void AddPoints(int points)
{
this.ScorePoints += points;
}
public void WriteScore()
{
}
}
} | mit | C# |
6fbf25e8f6c60665f3951abe3c2d94f8a9734898 | reduce looping, use defaultInstanceCreator on null param | Pondidum/Finite,Pondidum/Finite | Finite/StateProviders/ManualStateProvider.cs | Finite/StateProviders/ManualStateProvider.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Finite.Infrastructure;
using Finite.InstanceCreators;
namespace Finite.StateProviders
{
public class ManualStateProvider<T> : IStateProvider<T>
{
private readonly IInstanceCreator _instanceCreator;
private readonly IDictionary<Type, State<T>> _states;
public ManualStateProvider(IEnumerable<Type> states)
: this(null, states)
{
}
public ManualStateProvider(IInstanceCreator instanceCreator, IEnumerable<Type> states)
{
_instanceCreator = instanceCreator ?? new DefaultInstanceCreator();
_states = states
.Where(t => typeof(State<T>).IsAssignableFrom(t))
.ToDictionary(t => t, t => _instanceCreator.Create<T>(t));
_states.ForEach(i => i.Value.Configure(this));
}
public State<T> GetStateFor(Type stateType)
{
if (_states.ContainsKey(stateType) == false)
{
throw new UnknownStateException(stateType);
}
return _states[stateType];
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Finite.Infrastructure;
using Finite.InstanceCreators;
namespace Finite.StateProviders
{
public class ManualStateProvider<T> : IStateProvider<T>
{
private readonly IInstanceCreator _instanceCreator;
private readonly IDictionary<Type, State<T>> _states;
public ManualStateProvider(IInstanceCreator instanceCreator)
{
_instanceCreator = instanceCreator;
_states = new Dictionary<Type, State<T>>();
}
public ManualStateProvider(IInstanceCreator instanceCreator, IEnumerable<Type> states)
: this(instanceCreator)
{
AddRange(states);
}
public ManualStateProvider<T> AddRange(IEnumerable<Type> types)
{
var instances = types
.Where(t => typeof(State<T>).IsAssignableFrom(t))
.ToDictionary(
t => t,
t => _instanceCreator.Create<T>(t));
instances.ForEach(_states.Add);
instances.ForEach(i => i.Value.Configure(this));
return this;
}
public State<T> GetStateFor(Type stateType)
{
if (_states.ContainsKey(stateType) == false)
{
throw new UnknownStateException(stateType);
}
return _states[stateType];
}
}
}
| lgpl-2.1 | C# |
0ccfa73a6a1e51ab01ec0ff8f0b8e7a916cf36f2 | Add bindings in settings viewmodel for user alert | dukemiller/twitch-tv-viewer | twitch-tv-viewer/ViewModels/SettingsViewModel.cs | twitch-tv-viewer/ViewModels/SettingsViewModel.cs | using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using twitch_tv_viewer.Repositories;
namespace twitch_tv_viewer.ViewModels
{
internal class SettingsViewModel : ViewModelBase
{
private ObservableCollection<string> _items;
private string _selected;
private readonly ISettingsRepository _settings;
private bool _checked;
//
public SettingsViewModel()
{
_settings = new SettingsRepository();
Items = new ObservableCollection<string> {"Source", "Low"};
Selected = _settings.Quality;
Checked = _settings.UserAlert;
ApplyCommand = new RelayCommand(Apply);
CancelCommand = new RelayCommand(Cancel);
}
//
public Action Close { get; set; }
public ObservableCollection<string> Items
{
get { return _items; }
set
{
_items = value;
RaisePropertyChanged();
}
}
public string Selected
{
get { return _selected; }
set
{
_selected = value;
RaisePropertyChanged();
}
}
public bool Checked
{
get { return _checked; }
set
{
_checked = value;
RaisePropertyChanged();
}
}
public ICommand ApplyCommand { get; set; }
public ICommand CancelCommand { get; set; }
//
private void Cancel() => Close();
private void Apply()
{
_settings.UserAlert = Checked;
_settings.Quality = Selected;
Close();
}
}
} | using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using twitch_tv_viewer.Repositories;
namespace twitch_tv_viewer.ViewModels
{
internal class SettingsViewModel : ViewModelBase
{
private ObservableCollection<string> _items;
private string _selected;
private readonly ISettingsRepository _settings;
//
public SettingsViewModel()
{
_settings = new SettingsRepository();
Items = new ObservableCollection<string> {"Source", "Low"};
Selected = _settings.Quality;
ApplyCommand = new RelayCommand(Apply);
CancelCommand = new RelayCommand(Cancel);
}
//
public Action Close { get; set; }
public ObservableCollection<string> Items
{
get { return _items; }
set
{
_items = value;
RaisePropertyChanged();
}
}
public string Selected
{
get { return _selected; }
set
{
_selected = value;
RaisePropertyChanged();
}
}
public ICommand ApplyCommand { get; set; }
public ICommand CancelCommand { get; set; }
//
private void Cancel() => Close();
private void Apply()
{
_settings.Quality = Selected;
Close();
}
}
} | mit | C# |
32325a28b410cab11b5f9c9ad995bcac881d58e0 | update project version | hermsdorff/ODataSelectToWebAPI,hermsdorff/ODataSelectToWebAPI | ODataSelectForWebAPI1/Properties/AssemblyInfo.cs | ODataSelectForWebAPI1/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("ODataSelectForWebAPI1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ODataSelectForWebAPI1")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a28eb844-3271-44e3-89be-736d08fac436")]
// 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.3.1510")]
[assembly: AssemblyFileVersion("1.0.3.1510")]
| 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("ODataSelectForWebAPI1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ODataSelectForWebAPI1")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a28eb844-3271-44e3-89be-736d08fac436")]
// 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.2.1510")]
[assembly: AssemblyFileVersion("1.0.2.1510")]
| bsd-3-clause | C# |
12548e04cb10199151cdaf85b01fcaf393bca3b7 | Make GetAndFlatten public | gdziadkiewicz/octokit.net,dampir/octokit.net,adamralph/octokit.net,fffej/octokit.net,octokit-net-test/octokit.net,M-Zuber/octokit.net,mminns/octokit.net,kdolan/octokit.net,TattsGroup/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,SLdragon1989/octokit.net,dlsteuer/octokit.net,gdziadkiewicz/octokit.net,octokit/octokit.net,forki/octokit.net,michaKFromParis/octokit.net,geek0r/octokit.net,editor-tools/octokit.net,TattsGroup/octokit.net,octokit/octokit.net,devkhan/octokit.net,mminns/octokit.net,darrelmiller/octokit.net,octokit-net-test-org/octokit.net,shiftkey/octokit.net,brramos/octokit.net,ivandrofly/octokit.net,hahmed/octokit.net,rlugojr/octokit.net,gabrielweyer/octokit.net,SmithAndr/octokit.net,fake-organization/octokit.net,chunkychode/octokit.net,magoswiat/octokit.net,shiftkey/octokit.net,editor-tools/octokit.net,alfhenrik/octokit.net,hitesh97/octokit.net,ChrisMissal/octokit.net,SamTheDev/octokit.net,SamTheDev/octokit.net,Red-Folder/octokit.net,alfhenrik/octokit.net,shiftkey-tester/octokit.net,cH40z-Lord/octokit.net,dampir/octokit.net,daukantas/octokit.net,khellang/octokit.net,shana/octokit.net,SmithAndr/octokit.net,thedillonb/octokit.net,M-Zuber/octokit.net,thedillonb/octokit.net,shana/octokit.net,nsrnnnnn/octokit.net,naveensrinivasan/octokit.net,hahmed/octokit.net,gabrielweyer/octokit.net,Sarmad93/octokit.net,octokit-net-test-org/octokit.net,Sarmad93/octokit.net,bslliw/octokit.net,ivandrofly/octokit.net,chunkychode/octokit.net,shiftkey-tester/octokit.net,takumikub/octokit.net,nsnnnnrn/octokit.net,rlugojr/octokit.net,khellang/octokit.net,kolbasov/octokit.net,devkhan/octokit.net,eriawan/octokit.net,eriawan/octokit.net,shiftkey-tester-org-blah-blah/octokit.net | Octokit.Reactive/Helpers/ConnectionExtensions.cs | Octokit.Reactive/Helpers/ConnectionExtensions.cs | using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
namespace Octokit.Reactive.Internal
{
public static class ConnectionExtensions
{
public static IObservable<T> GetAndFlattenAllPages<T>(this IConnection connection, Uri url)
{
return GetPages(url, null, (pageUrl, pageParams) => connection.Get<List<T>>(pageUrl, null, null).ToObservable());
}
public static IObservable<T> GetAndFlattenAllPages<T>(this IConnection connection, Uri url, IDictionary<string, string> parameters)
{
return GetPages(url, parameters, (pageUrl, pageParams) => connection.Get<List<T>>(pageUrl, pageParams, null).ToObservable());
}
public static IObservable<T> GetAndFlattenAllPages<T>(this IConnection connection, Uri url, IDictionary<string, string> parameters, string accepts)
{
return GetPages(url, parameters, (pageUrl, pageParams) => connection.Get<List<T>>(pageUrl, pageParams, accepts).ToObservable());
}
static IObservable<T> GetPages<T>(Uri uri, IDictionary<string, string> parameters,
Func<Uri, IDictionary<string, string>, IObservable<IResponse<List<T>>>> getPageFunc)
{
return getPageFunc(uri, parameters).Expand(resp =>
{
var nextPageUrl = resp.ApiInfo.GetNextPageUrl();
return nextPageUrl == null
? Observable.Empty<IResponse<List<T>>>()
: Observable.Defer(() => getPageFunc(nextPageUrl, null));
})
.Where(resp => resp != null)
.SelectMany(resp => resp.BodyAsObject);
}
}
}
| using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
namespace Octokit.Reactive.Internal
{
internal static class ConnectionExtensions
{
public static IObservable<T> GetAndFlattenAllPages<T>(this IConnection connection, Uri url, IDictionary<string, string> parameters = null, string accepts = null)
{
return GetPages(url, parameters, (pageUrl, pageParams) => connection.Get<List<T>>(pageUrl, pageParams, accepts).ToObservable());
}
static IObservable<T> GetPages<T>(Uri uri, IDictionary<string, string> parameters,
Func<Uri, IDictionary<string, string>, IObservable<IResponse<List<T>>>> getPageFunc)
{
return getPageFunc(uri, parameters).Expand(resp =>
{
var nextPageUrl = resp.ApiInfo.GetNextPageUrl();
return nextPageUrl == null
? Observable.Empty<IResponse<List<T>>>()
: Observable.Defer(() => getPageFunc(nextPageUrl, null));
})
.Where(resp => resp != null)
.SelectMany(resp => resp.BodyAsObject);
}
}
}
| mit | C# |
04c562014eea077b581fb1a7d4c05695789839f8 | check string for CoordinateFormatter | CGX-GROUP/DotSpatial,CGX-GROUP/DotSpatial,CGX-GROUP/DotSpatial | Source/DotSpatial.Controls/CoordinateFormatter.cs | Source/DotSpatial.Controls/CoordinateFormatter.cs | using System;
using System.Text.RegularExpressions;
using DotSpatial.Serialization;
using GeoAPI.Geometries;
namespace DotSpatial.Controls
{
public class CoordinateFormatter : SerializationFormatter
{
public override object FromString(string value)
{
value = value.Trim();
//Something like "(12.5, 2.0, NaN, NaN)"
Regex rx = new Regex(@"^\((\s*(([0-9]+(\.+[0-9]+)?)|(NaN))\s*,){3}(\s*(([0-9]+(\.+[0-9]+)?)|(NaN)))\s*\)$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (rx.IsMatch(value))
{
var xyzm = value.Split(',');
double x = parse(xyzm[0]);
double y = parse(xyzm[1]);
double z = parse(xyzm[2]);
double m = parse(xyzm[3]);
return new Coordinate(x, y, z, m);
}
else
{
throw new FormatException(value + "is not a coordinate");
}
}
private double parse(string val)
{
try
{
return double.Parse(val.Trim(' ', '(', ')'));
}
catch (FormatException e)
{
return double.NaN;
}
}
public override string ToString(object value)
{
if (value is Coordinate)
{
return ((Coordinate)value).ToString();
}
else
{
throw new ArgumentException("Must be a Coordinate");
}
}
}
}
| using System;
using DotSpatial.Serialization;
using GeoAPI.Geometries;
namespace DotSpatial.Controls
{
public class CoordinateFormatter : SerializationFormatter
{
public override object FromString(string value)
{
var xyzm = value.Split(',');
double x = parse(xyzm[0]);
double y = parse(xyzm[1]);
double z = parse(xyzm[2]);
double m = parse(xyzm[3]);
return new Coordinate(x, y, z, m);
}
private double parse(string val)
{
try
{
return double.Parse(val.Trim(' ', '(', ')'));
}
catch (FormatException e)
{
return double.NaN;
}
}
public override string ToString(object value)
{
if (value is Coordinate)
{
return ((Coordinate)value).ToString();
}
else
{
throw new ArgumentException("Must be a Coordinate");
}
}
}
}
| mit | C# |
8d787c688e2b0b06e4e3f05922d4a4696cdea610 | set event fire date to datetime.now | albx/CorePatterns | src/CorePatterns/Events/DomainEvent.cs | src/CorePatterns/Events/DomainEvent.cs | using System;
namespace CorePatterns.Events
{
/// <summary>
/// Represents a generic domain event
/// </summary>
public abstract class DomainEvent
{
/// <summary>
/// Get the aggregate's id which raise the event
/// </summary>
public Guid AggregateId { get; }
/// <summary>
/// Get the aggregate's type which raise the event
/// </summary>
public Type AggregateType { get; }
/// <summary>
/// Get the date and time of when the event was fired
/// </summary>
public DateTime FiredOn { get; }
public DomainEvent(Guid aggregateId, Type aggregateType)
{
AggregateId = aggregateId;
AggregateType = aggregateType;
FiredOn = DateTime.Now;
}
}
}
| using System;
namespace CorePatterns.Events
{
/// <summary>
/// Represents a generic domain event
/// </summary>
public abstract class DomainEvent
{
/// <summary>
/// Get the aggregate's id which raise the event
/// </summary>
public Guid AggregateId { get; }
/// <summary>
/// Get the aggregate's type which raise the event
/// </summary>
public Type AggregateType { get; }
/// <summary>
/// Get the date and time of when the event was fired
/// </summary>
public DateTime FiredOn { get; }
public DomainEvent(Guid aggregateId, Type aggregateType, DateTime firedOn)
{
AggregateId = aggregateId;
AggregateType = aggregateType;
FiredOn = firedOn;
}
}
}
| mit | C# |
21a0b6bdfdcae74a9923632187e3d4d49c258a2a | add missing fields to seal status | rajanadar/VaultSharp | src/VaultSharp/Backends/System/Models/SealStatus.cs | src/VaultSharp/Backends/System/Models/SealStatus.cs | using Newtonsoft.Json;
namespace VaultSharp.Backends.System.Models
{
/// <summary>
/// Represents the Seal status of the Vault.
/// </summary>
public class SealStatus
{
/// <summary>
/// Gets or sets a value indicating about the <see cref="SealStatus"/>.
/// </summary>
/// <value>
/// <c>true</c> if sealed; otherwise, <c>false</c>.
/// </value>
[JsonProperty("sealed")]
public bool Sealed { get; set; }
/// <summary>
/// Gets or sets the number of shares required to reconstruct the master key.
/// </summary>
/// <value>
/// The secret threshold.
/// </value>
[JsonProperty("t")]
public int SecretThreshold { get; set; }
/// <summary>
/// Gets or sets the number of shares to split the master key into.
/// </summary>
/// <value>
/// The secret shares.
/// </value>
[JsonProperty("n")]
public int SecretShares { get; set; }
/// <summary>
/// Gets or sets the number of shares that have been successfully applied to reconstruct the master key.
/// When the value is about to reach <see cref="SecretThreshold"/>, the Vault will be unsealed and the value will become <value>0</value>.
/// </summary>
/// <value>
/// The progress count.
/// </value>
[JsonProperty("progress")]
public int Progress { get; set; }
/// <summary>
/// Gets or sets the vault version.
/// </summary>
/// <value>
/// The version.
/// </value>
[JsonProperty("version")]
public string Version { get; set; }
/// <summary>
/// Gets or sets the name of the cluster.
/// </summary>
/// <value>
/// The name of the cluster.
/// </value>
[JsonProperty("cluster_name")]
public string ClusterName { get; set; }
/// <summary>
/// Gets or sets the cluster identifier.
/// </summary>
/// <value>
/// The cluster identifier.
/// </value>
[JsonProperty("cluster_id")]
public string ClusterId { get; set; }
}
} | using Newtonsoft.Json;
namespace VaultSharp.Backends.System.Models
{
/// <summary>
/// Represents the Seal status of the Vault.
/// </summary>
public class SealStatus
{
/// <summary>
/// Gets or sets a value indicating about the <see cref="SealStatus"/>.
/// </summary>
/// <value>
/// <c>true</c> if sealed; otherwise, <c>false</c>.
/// </value>
[JsonProperty("sealed")]
public bool Sealed { get; set; }
/// <summary>
/// Gets or sets the number of shares required to reconstruct the master key.
/// </summary>
/// <value>
/// The secret threshold.
/// </value>
[JsonProperty("t")]
public int SecretThreshold { get; set; }
/// <summary>
/// Gets or sets the number of shares to split the master key into.
/// </summary>
/// <value>
/// The secret shares.
/// </value>
[JsonProperty("n")]
public int SecretShares { get; set; }
/// <summary>
/// Gets or sets the number of shares that have been successfully applied to reconstruct the master key.
/// When the value is about to reach <see cref="SecretThreshold"/>, the Vault will be unsealed and the value will become <value>0</value>.
/// </summary>
/// <value>
/// The progress count.
/// </value>
[JsonProperty("progress")]
public int Progress { get; set; }
/// <summary>
/// Gets or sets the vault version.
/// </summary>
/// <value>
/// The version.
/// </value>
[JsonProperty("version")]
public string Version { get; set; }
}
} | apache-2.0 | C# |
0032f358fb95647936eee1a0e3c9208ee9a98454 | Fix Mahmoud Ali author filter (#400) | planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Authors/MahmoudAli.cs | src/Firehose.Web/Authors/MahmoudAli.cs | using Firehose.Web.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Syndication;
namespace Firehose.Web.Authors
{
public class MahmoudAli : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Mahmoud";
public string LastName => "Ali";
public string StateOrRegion => "São Paulo, Brasil";
public string EmailAddress => "muddibr@gmail.com";
public string ShortBioOrTagLine => "Web and Mobile Developer";
public Uri WebSite => new Uri("https://www.lambda3.com.br/blog");
public string TwitterHandle => "akamud";
public string GitHubHandle => "akamud";
public string GravatarHash => "";
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.lambda3.com.br/feed/"); } }
public GeoPosition Position => new GeoPosition(-23.552339, -46.661393);
public bool Filter(SyndicationItem item)
=> item.Title.Text.ToLowerInvariant().Contains("xamarin") ||
item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin"));
}
} | using Firehose.Web.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Syndication;
namespace Firehose.Web.Authors
{
public class MahmoudAli : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Mahmoud";
public string LastName => "Ali";
public string StateOrRegion => "São Paulo, Brasil";
public string EmailAddress => "muddibr@gmail.com";
public string ShortBioOrTagLine => "Web and Mobile Developer";
public Uri WebSite => new Uri("https://www.lambda3.com.br/blog");
public string TwitterHandle => "akamud";
public string GitHubHandle => "akamud";
public string GravatarHash => "";
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.lambda3.com.br/feed/"); } }
public GeoPosition Position => new GeoPosition(-23.552339, -46.661393);
public bool Filter(SyndicationItem item)
=> item.Authors.Any(a => a.Name.ToLowerInvariant().Contains("mahmoud")) &&
(item.Title.Text.ToLowerInvariant().Contains("xamarin") ||
item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin")));
}
} | mit | C# |
e6bcea5f7e9117bffd083a2143bf7550dbc73c9c | Remove unused class variable | schwamster/HttpService,schwamster/HttpService | src/HttpService/HttpService.cs | src/HttpService/HttpService.cs | using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Net.Http;
using Microsoft.AspNetCore.Authentication;
namespace HttpService
{
public class HttpService : IHttpService
{
private readonly IContextReader _tokenExtractor;
private HttpClient _client;
public HttpService(IHttpContextAccessor accessor)
{
this._tokenExtractor = new HttpContextReader(accessor);
_client = new HttpClient();
}
public HttpService(IContextReader tokenExtractor)
{
_tokenExtractor = tokenExtractor;
}
public async Task<HttpResponseMessage> GetAsync(string requestUri, bool passToken) =>
await SendAsync(HttpMethod.Get, requestUri, passToken);
public async Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content, bool passToken) =>
await SendAsync(HttpMethod.Post, requestUri, passToken, content);
public async Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content, bool passToken) =>
await SendAsync(HttpMethod.Put, requestUri, passToken, content);
public async Task<HttpResponseMessage> DeleteAsync(string requestUri, bool passToken) =>
await SendAsync(HttpMethod.Delete, requestUri, passToken);
private async Task<HttpResponseMessage> SendAsync(HttpMethod method, string requestUri, bool passToken, HttpContent content = null)
{
var msg = new HttpRequestMessage(method, requestUri);
if (passToken)
{
var token = await _tokenExtractor.GetTokenAsync();
if (!string.IsNullOrEmpty(token))
{
msg.Headers.Add("Authorization", $"Bearer {token}");
}
}
if (content != null)
{
msg.Content = content;
}
return await _client.SendAsync(msg);
}
}
public interface IContextReader
{
Task<string> GetTokenAsync();
}
public class HttpContextReader : IContextReader
{
private readonly IHttpContextAccessor _accessor;
public HttpContextReader(IHttpContextAccessor accessor)
{
this._accessor = accessor;
}
public async Task<string> GetTokenAsync()
{
var token = await this._accessor.HttpContext.GetTokenAsync("access_token");
return token;
}
}
} | using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Net.Http;
using Microsoft.AspNetCore.Authentication;
namespace HttpService
{
public class HttpService : IHttpService
{
private readonly IContextReader _tokenExtractor;
private HttpClient _tracedClient;
private HttpClient _client;
public HttpService(IHttpContextAccessor accessor)
{
this._tokenExtractor = new HttpContextReader(accessor);
_client = new HttpClient();
}
public HttpService(IContextReader tokenExtractor)
{
_tokenExtractor = tokenExtractor;
}
public async Task<HttpResponseMessage> GetAsync(string requestUri, bool passToken) =>
await SendAsync(HttpMethod.Get, requestUri, passToken);
public async Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content, bool passToken) =>
await SendAsync(HttpMethod.Post, requestUri, passToken, content);
public async Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content, bool passToken) =>
await SendAsync(HttpMethod.Put, requestUri, passToken, content);
public async Task<HttpResponseMessage> DeleteAsync(string requestUri, bool passToken) =>
await SendAsync(HttpMethod.Delete, requestUri, passToken);
private async Task<HttpResponseMessage> SendAsync(HttpMethod method, string requestUri, bool passToken, HttpContent content = null)
{
var msg = new HttpRequestMessage(method, requestUri);
if (passToken)
{
var token = await _tokenExtractor.GetTokenAsync();
if (!string.IsNullOrEmpty(token))
{
msg.Headers.Add("Authorization", $"Bearer {token}");
}
}
if (content != null)
{
msg.Content = content;
}
return await _client.SendAsync(msg);
}
}
public interface IContextReader
{
Task<string> GetTokenAsync();
}
public class HttpContextReader : IContextReader
{
private readonly IHttpContextAccessor _accessor;
public HttpContextReader(IHttpContextAccessor accessor)
{
this._accessor = accessor;
}
public async Task<string> GetTokenAsync()
{
var token = await this._accessor.HttpContext.GetTokenAsync("access_token");
return token;
}
}
} | mit | C# |
29d6d939f65223c05d1f8befa533e8de9fc13073 | Remove new line. | sharwell/roslyn,KirillOsenkov/roslyn,abock/roslyn,khyperia/roslyn,heejaechang/roslyn,cston/roslyn,wvdd007/roslyn,DustinCampbell/roslyn,weltkante/roslyn,pdelvo/roslyn,jkotas/roslyn,shyamnamboodiripad/roslyn,tvand7093/roslyn,mgoertz-msft/roslyn,MattWindsor91/roslyn,kelltrick/roslyn,MichalStrehovsky/roslyn,davkean/roslyn,brettfo/roslyn,jcouv/roslyn,panopticoncentral/roslyn,mmitche/roslyn,dotnet/roslyn,eriawan/roslyn,AnthonyDGreen/roslyn,tmeschter/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,kelltrick/roslyn,KevinRansom/roslyn,MattWindsor91/roslyn,MichalStrehovsky/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,swaroop-sridhar/roslyn,jcouv/roslyn,wvdd007/roslyn,mmitche/roslyn,tannergooding/roslyn,eriawan/roslyn,tmeschter/roslyn,Giftednewt/roslyn,paulvanbrenk/roslyn,dpoeschl/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,agocke/roslyn,xasx/roslyn,mavasani/roslyn,AnthonyDGreen/roslyn,OmarTawfik/roslyn,brettfo/roslyn,srivatsn/roslyn,CaptainHayashi/roslyn,orthoxerox/roslyn,panopticoncentral/roslyn,paulvanbrenk/roslyn,khyperia/roslyn,stephentoub/roslyn,davkean/roslyn,sharwell/roslyn,bartdesmet/roslyn,lorcanmooney/roslyn,agocke/roslyn,panopticoncentral/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,MichalStrehovsky/roslyn,TyOverby/roslyn,lorcanmooney/roslyn,jcouv/roslyn,xasx/roslyn,mavasani/roslyn,davkean/roslyn,stephentoub/roslyn,reaction1989/roslyn,physhi/roslyn,DustinCampbell/roslyn,robinsedlaczek/roslyn,aelij/roslyn,mmitche/roslyn,sharwell/roslyn,tvand7093/roslyn,weltkante/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,dpoeschl/roslyn,pdelvo/roslyn,KevinRansom/roslyn,jamesqo/roslyn,VSadov/roslyn,mattscheffer/roslyn,bkoelman/roslyn,CaptainHayashi/roslyn,shyamnamboodiripad/roslyn,mattscheffer/roslyn,VSadov/roslyn,Giftednewt/roslyn,CaptainHayashi/roslyn,diryboy/roslyn,heejaechang/roslyn,Hosch250/roslyn,agocke/roslyn,stephentoub/roslyn,tmat/roslyn,bartdesmet/roslyn,tmat/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,genlu/roslyn,diryboy/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jasonmalinowski/roslyn,ErikSchierboom/roslyn,abock/roslyn,KirillOsenkov/roslyn,orthoxerox/roslyn,jasonmalinowski/roslyn,gafter/roslyn,srivatsn/roslyn,genlu/roslyn,AmadeusW/roslyn,jmarolf/roslyn,kelltrick/roslyn,physhi/roslyn,reaction1989/roslyn,tmeschter/roslyn,OmarTawfik/roslyn,aelij/roslyn,Hosch250/roslyn,mgoertz-msft/roslyn,jkotas/roslyn,mattscheffer/roslyn,pdelvo/roslyn,Hosch250/roslyn,robinsedlaczek/roslyn,MattWindsor91/roslyn,nguerrera/roslyn,jmarolf/roslyn,khyperia/roslyn,robinsedlaczek/roslyn,physhi/roslyn,tannergooding/roslyn,nguerrera/roslyn,gafter/roslyn,AlekseyTs/roslyn,DustinCampbell/roslyn,tannergooding/roslyn,genlu/roslyn,wvdd007/roslyn,AnthonyDGreen/roslyn,aelij/roslyn,mavasani/roslyn,cston/roslyn,paulvanbrenk/roslyn,xasx/roslyn,jkotas/roslyn,TyOverby/roslyn,cston/roslyn,bkoelman/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,MattWindsor91/roslyn,jamesqo/roslyn,VSadov/roslyn,tvand7093/roslyn,srivatsn/roslyn,diryboy/roslyn,nguerrera/roslyn,CyrusNajmabadi/roslyn,lorcanmooney/roslyn,CyrusNajmabadi/roslyn,gafter/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,KirillOsenkov/roslyn,swaroop-sridhar/roslyn,jamesqo/roslyn,jmarolf/roslyn,weltkante/roslyn,TyOverby/roslyn,Giftednewt/roslyn,bkoelman/roslyn,eriawan/roslyn,tmat/roslyn,abock/roslyn,swaroop-sridhar/roslyn,brettfo/roslyn,KevinRansom/roslyn,dpoeschl/roslyn,OmarTawfik/roslyn,orthoxerox/roslyn | src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorage.cs | src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorage.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Host
{
public interface IPersistentStorage : IDisposable
{
Task<Stream> ReadStreamAsync(string name, CancellationToken cancellationToken = default(CancellationToken));
Task<Stream> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default(CancellationToken));
Task<Stream> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken));
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Host
{
public interface IPersistentStorage : IDisposable
{
Task<Stream> ReadStreamAsync(string name, CancellationToken cancellationToken = default(CancellationToken));
Task<Stream> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default(CancellationToken));
Task<Stream> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken));
Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken));
}
}
| mit | C# |
ce2630e984c0b6179f6cdb1349b0a141d4796398 | move to 3.9.9.4 | MutonUfoAI/pgina,daviddumas/pgina,daviddumas/pgina,daviddumas/pgina,MutonUfoAI/pgina,MutonUfoAI/pgina | Plugins/pgSMB2/pgSMB2/Properties/AssemblyInfo.cs | Plugins/pgSMB2/pgSMB2/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("pgSMB2.Management")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Medical University of Vienna")]
[assembly: AssemblyProduct("pgSMB2.Management")]
[assembly: AssemblyCopyright("Copyright © Medical University of Vienna 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("d7664100-0021-4f04-b98e-057d1659f2bc")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.9.9.4")]
[assembly: AssemblyFileVersion("3.9.9.4")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("pgSMB2.Management")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Medical University of Vienna")]
[assembly: AssemblyProduct("pgSMB2.Management")]
[assembly: AssemblyCopyright("Copyright © Medical University of Vienna 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("d7664100-0021-4f04-b98e-057d1659f2bc")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.9.9.3")]
[assembly: AssemblyFileVersion("3.9.9.3")]
| bsd-3-clause | C# |
e41c1d077038219a01fa2b4fef7f49944ec57ee1 | Fix the handler to allow it usage with httpclientfactory | criteo/zipkin4net,criteo/zipkin4net | Src/zipkin4net/Src/Transport/Http/TracingHandler.cs | Src/zipkin4net/Src/Transport/Http/TracingHandler.cs | using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using zipkin4net.Propagation;
namespace zipkin4net.Transport.Http
{
public class TracingHandler : DelegatingHandler
{
private readonly IInjector<HttpHeaders> _injector;
private readonly string _serviceName;
private readonly Func<HttpRequestMessage, string> _getClientTraceRpc;
public TracingHandler(string serviceName, HttpMessageHandler httpMessageHandler, Func<HttpRequestMessage, string> getClientTraceRpc = null)
: this(Propagations.B3String.Injector<HttpHeaders>((carrier, key, value) => carrier.Add(key, value)), serviceName, httpMessageHandler, getClientTraceRpc)
{ }
public TracingHandler(string serviceName, Func<HttpRequestMessage, string> getClientTraceRpc = null)
: this(Propagations.B3String.Injector<HttpHeaders>((carrier, key, value) => carrier.Add(key, value)), serviceName, getClientTraceRpc)
{ }
private TracingHandler(IInjector<HttpHeaders> injector, string serviceName, HttpMessageHandler httpMessageHandler, Func<HttpRequestMessage, string> getClientTraceRpc = null)
: base(httpMessageHandler)
{
_injector = injector;
_serviceName = serviceName;
_getClientTraceRpc = getClientTraceRpc ?? (request => request.Method.ToString());
}
private TracingHandler(IInjector<HttpHeaders> injector, string serviceName, Func<HttpRequestMessage, string> getClientTraceRpc = null)
{
_injector = injector;
_serviceName = serviceName;
_getClientTraceRpc = getClientTraceRpc ?? (request => request.Method.ToString());
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
using (var clientTrace = new ClientTrace(_serviceName, _getClientTraceRpc(request)))
{
if (clientTrace.Trace != null)
{
_injector.Inject(clientTrace.Trace.CurrentSpan, request.Headers);
}
return await clientTrace.TracedActionAsync(base.SendAsync(request, cancellationToken));
}
}
}
}
| using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using zipkin4net.Propagation;
namespace zipkin4net.Transport.Http
{
public class TracingHandler : DelegatingHandler
{
private readonly IInjector<HttpHeaders> _injector;
private readonly string _serviceName;
private readonly Func<HttpRequestMessage, string> _getClientTraceRpc;
public TracingHandler(string serviceName, HttpMessageHandler httpMessageHandler = null, Func<HttpRequestMessage, string> getClientTraceRpc = null)
: this(Propagations.B3String.Injector<HttpHeaders>((carrier, key, value) => carrier.Add(key, value)), serviceName, httpMessageHandler, getClientTraceRpc)
{ }
private TracingHandler(IInjector<HttpHeaders> injector, string serviceName, HttpMessageHandler httpMessageHandler = null, Func<HttpRequestMessage, string> getClientTraceRpc = null)
{
_injector = injector;
_serviceName = serviceName;
_getClientTraceRpc = getClientTraceRpc ?? (request => request.Method.ToString());
InnerHandler = httpMessageHandler ?? new HttpClientHandler();
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
using (var clientTrace = new ClientTrace(_serviceName, _getClientTraceRpc(request)))
{
if (clientTrace.Trace != null)
{
_injector.Inject(clientTrace.Trace.CurrentSpan, request.Headers);
}
return await clientTrace.TracedActionAsync(base.SendAsync(request, cancellationToken));
}
}
}
}
| apache-2.0 | C# |
bbb35a9e939cc19ac6070f7679d680191407921e | Fix formatting. | ridercz/ValidationToolkit | Altairis.ValidationToolkit/YearOffsetAttribute.cs | Altairis.ValidationToolkit/YearOffsetAttribute.cs | using System;
using System.ComponentModel.DataAnnotations;
namespace Altairis.ValidationToolkit {
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class YearOffsetAttribute : ValidationAttribute {
public YearOffsetAttribute(int beforeCurrent, int afterCurrent, Func<string> errorMessageAccessor) : base(errorMessageAccessor) {
this.MinimumYear = DateTime.Today.Year + beforeCurrent;
this.MaximumYear = DateTime.Today.Year + afterCurrent;
}
public YearOffsetAttribute(int beforeCurrent, int afterCurrent, string errorMessage) : base(errorMessage) {
this.MinimumYear = DateTime.Today.Year + beforeCurrent;
this.MaximumYear = DateTime.Today.Year + afterCurrent;
}
public YearOffsetAttribute(int beforeCurrent, int afterCurrent)
: this(beforeCurrent, afterCurrent, "{0} must be between {1} and {2}.") { }
public int MaximumYear { get; private set; }
public int MinimumYear { get; private set; }
public override string FormatErrorMessage(string name) => string.Format(this.ErrorMessageString, name, this.MinimumYear, this.MaximumYear);
public override bool IsValid(object value) {
// Empty value is always valid
if (value == null) return true;
// Convert value to integer
int intValue;
try {
intValue = Convert.ToInt32(value);
#pragma warning disable CA1031 // Do not catch general exception types
} catch (Exception) {
// Value cannot be processed as int - let other attributes handle that
return true;
}
#pragma warning restore CA1031 // Do not catch general exception types
return intValue >= this.MinimumYear && intValue <= this.MaximumYear;
}
}
} | using System;
using System.ComponentModel.DataAnnotations;
namespace Altairis.ValidationToolkit {
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class YearOffsetAttribute : ValidationAttribute {
public YearOffsetAttribute(int beforeCurrent, int afterCurrent, Func<string> errorMessageAccessor) : base(errorMessageAccessor) {
this.MinimumYear = DateTime.Today.Year + beforeCurrent;
this.MaximumYear = DateTime.Today.Year + afterCurrent;
}
public YearOffsetAttribute(int beforeCurrent, int afterCurrent, string errorMessage) : base(errorMessage) {
this.MinimumYear = DateTime.Today.Year + beforeCurrent;
this.MaximumYear = DateTime.Today.Year + afterCurrent;
}
public YearOffsetAttribute(int beforeCurrent, int afterCurrent)
: this(beforeCurrent, afterCurrent, "{0} must be between {1} and {2}.") { }
public int MaximumYear { get; private set; }
public int MinimumYear { get; private set; }
public override string FormatErrorMessage(string name) => string.Format(this.ErrorMessageString, name, this.MinimumYear, this.MaximumYear);
public override bool IsValid(object value) {
// Empty value is always valid
if (value == null) return true;
// Convert value to integer
int intValue;
try {
intValue = Convert.ToInt32(value);
#pragma warning disable CA1031 // Do not catch general exception types
} catch (Exception) {
// Value cannot be processed as int - let other attributes handle that
return true;
}
#pragma warning restore CA1031 // Do not catch general exception types
return intValue >= this.MinimumYear && intValue <= this.MaximumYear;
}
}
} | mit | C# |
dd6052b1696cf890e0d91e5daccf9414587e1005 | Remove Id from ICommand | kennytordeur/CQRS | src/Torken.CQRS.Interfaces/ICommand.cs | src/Torken.CQRS.Interfaces/ICommand.cs | namespace Torken.CQRS.Interfaces
{
public interface ICommand
{
}
} | using System;
namespace Torken.CQRS.Interfaces
{
public interface ICommand
{
Guid Id { get; }
}
} | mit | C# |
c8fc4d9e44889d9730866b6bcca68bf055c54fc7 | Bump version to 0.4.5 | fsprojects/Paket.VisualStudio,mrinaldi/Paket.VisualStudio,baronfel/Paket.VisualStudio,hmemcpy/Paket.VisualStudio | src/Paket.VisualStudio/Properties/AssemblyInfo.cs | src/Paket.VisualStudio/Properties/AssemblyInfo.cs | // <auto-generated/>
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleToAttribute("Paket.VisualStudio.Tests")]
[assembly: AssemblyTitleAttribute("Paket.VisualStudio")]
[assembly: AssemblyProductAttribute("Paket.VisualStudio")]
[assembly: AssemblyDescriptionAttribute("Manage your Paket dependencies from Visual Studio!")]
[assembly: AssemblyVersionAttribute("0.4.5")]
[assembly: AssemblyFileVersionAttribute("0.4.5")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.4.5";
}
}
| // <auto-generated/>
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleToAttribute("Paket.VisualStudio.Tests")]
[assembly: AssemblyTitleAttribute("Paket.VisualStudio")]
[assembly: AssemblyProductAttribute("Paket.VisualStudio")]
[assembly: AssemblyDescriptionAttribute("Manage your Paket dependencies from Visual Studio!")]
[assembly: AssemblyVersionAttribute("0.4.4")]
[assembly: AssemblyFileVersionAttribute("0.4.4")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.4.4";
}
}
| mit | C# |
8e59a019b50c428fb50478c292c96b1a7cd57aa4 | Update GameMaster.cs | erdenbatuhan/Venture | Assets/Scripts/GameMaster.cs | Assets/Scripts/GameMaster.cs | //
// GameMaster.cs
// Venture
//
// Created by Batuhan Erden.
// Copyright © 2016 Batuhan Erden. All rights reserved.
//
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameMaster : MonoBehaviour {
private const int COIN_VALUE = 1;
public const string CONSOLE_INITIAL = " ~ Vaila Console: ";
public const int MAXIMUM_LEVEL = 16;
public static int currentScore;
public static int currentLevel;
public static int coinAmount;
public static float timer;
public static User loggedUser;
public static List<User> users;
public bool isMenu;
private void OnGUI() {
if (loggedUser != null)
generateUsernameBox();
if (!isMenu) {
GUI.Box(new Rect(((Screen.width / 2) - 70), 10, 140, 25), "' " + timer.ToString("0") + " ' Seconds Left");
GUI.Box(new Rect(((Screen.width / 2) - 70), 45, 140, 25), "Coin Bag: " + currentScore + "/" + coinAmount);
}
}
private void generateUsernameBox() {
if (loggedUser != null) {
int length = loggedUser.getUsername().Length;
int width = (length < 10) ? ((length < 6) ? 50 : 75) : 100;
GUI.Box(new Rect(10, 10, width, 25), loggedUser.getUsername());
}
}
private void Start() {
currentScore = 0;
}
private void Update() {
if (!isMenu) {
checkCoinAmount();
checkTimer();
}
}
private void checkCoinAmount() {
if (currentScore >= coinAmount)
Application.LoadLevel("TransactionScene");
}
private void checkTimer() {
if (timer <= 0)
restartLevel();
else
timer -= Time.deltaTime;
}
public static void restartLevel() {
loadLevel(currentLevel);
}
private static void loadLevel(int level) {
Application.LoadLevel(level % (MAXIMUM_LEVEL + 1));
}
public static void addCoin() {
currentScore += COIN_VALUE;
}
}
| //
// GameMaster.cs
// A Vaila Ball - Computer
//
// Created by Batuhan Erden.
// Copyright © 2016 Batuhan Erden. All rights reserved.
//
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameMaster : MonoBehaviour {
private const int COIN_VALUE = 1;
public const string CONSOLE_INITIAL = " ~ Vaila Console: ";
public const int MAXIMUM_LEVEL = 16;
public static int currentScore;
public static int currentLevel;
public static int coinAmount;
public static float timer;
public static User loggedUser;
public static List<User> users;
public bool isMenu;
private void OnGUI() {
if (loggedUser != null)
generateUsernameBox();
if (!isMenu) {
GUI.Box(new Rect(((Screen.width / 2) - 70), 10, 140, 25), "' " + timer.ToString("0") + " ' Seconds Left");
GUI.Box(new Rect(((Screen.width / 2) - 70), 45, 140, 25), "Coin Bag: " + currentScore + "/" + coinAmount);
}
}
private void generateUsernameBox() {
if (loggedUser != null) {
int length = loggedUser.getUsername().Length;
int width = (length < 10) ? ((length < 6) ? 50 : 75) : 100;
GUI.Box(new Rect(10, 10, width, 25), loggedUser.getUsername());
}
}
private void Start() {
currentScore = 0;
}
private void Update() {
if (!isMenu) {
checkCoinAmount();
checkTimer();
}
}
private void checkCoinAmount() {
if (currentScore >= coinAmount)
Application.LoadLevel("TransactionScene");
}
private void checkTimer() {
if (timer <= 0)
restartLevel();
else
timer -= Time.deltaTime;
}
public static void restartLevel() {
loadLevel(currentLevel);
}
private static void loadLevel(int level) {
Application.LoadLevel(level % (MAXIMUM_LEVEL + 1));
}
public static void addCoin() {
currentScore += COIN_VALUE;
}
} | mit | C# |
f77e60d90b4f04c768feee6ca380a7621e150aaf | Update Knight.cs (#42) | BosslandGmbH/BuddyWing.DefaultCombat | trunk/DefaultCombat/Routines/Basic/Knight.cs | trunk/DefaultCombat/Routines/Basic/Knight.cs | // Copyright (C) 2011-2016 Bossland GmbH
// See the file LICENSE for the source code's detailed license
using Buddy.BehaviorTree;
using DefaultCombat.Core;
using DefaultCombat.Helpers;
namespace DefaultCombat.Routines
{
public class Knight : RotationBase
{
public override string Name
{
get { return "Basic Knight"; }
}
public override Composite Buffs
{
get
{
return new PrioritySelector(
Spell.Buff("Shii-Cho Form")
);
}
}
public override Composite Cooldowns
{
get
{
return new PrioritySelector(
Spell.Cast("Saber Ward", ret => Me.HealthPercent <= 70)
);
}
}
public override Composite SingleTarget
{
get
{
return new PrioritySelector(
Spell.Cast("Force Leap", ret => !DefaultCombat.MovementDisabled && Me.CurrentTarget.Distance > 1f && Me.CurrentTarget.Distance <= 3f), CombatMovement.CloseDistance(Distance.Melee),
Spell.Cast("Master Strike"),
Spell.Cast("Blade Storm"),
Spell.Cast("Riposte"),
Spell.Cast("Slash", ret => Me.ActionPoints >= 7),
Spell.Cast("Strike")
);
}
}
public override Composite AreaOfEffect
{
get
{
return new Decorator(ret => Targeting.ShouldAoe,
new PrioritySelector(
Spell.Cast("Force Sweep", ret => Me.CurrentTarget.Distance <= Distance.MeleeAoE))
);
}
}
}
}
| // Copyright (C) 2011-2016 Bossland GmbH
// See the file LICENSE for the source code's detailed license
using Buddy.BehaviorTree;
using DefaultCombat.Core;
using DefaultCombat.Helpers;
namespace DefaultCombat.Routines
{
public class Knight : RotationBase
{
public override string Name
{
get { return "Basic Knight"; }
}
public override Composite Buffs
{
get
{
return new PrioritySelector(
Spell.Buff("Shii-Cho Form")
);
}
}
public override Composite Cooldowns
{
get
{
return new PrioritySelector(
Spell.Cast("Saber Ward", ret => Me.HealthPercent <= 70)
);
}
}
public override Composite SingleTarget
{
get
{
return new PrioritySelector(
Spell.Cast("Force Leap",
ret => !DefaultCombat.MovementDisabled && Me.CurrentTarget.Distance > 1f && Me.CurrentTarget.Distance <= 3f),
CombatMovement.CloseDistance(Distance.Melee),
Spell.Cast("Master Strike"),
Spell.Cast("Blade Storm"),
Spell.Cast("Riposte"),
Spell.Cast("Slash", ret => Me.ActionPoints >= 7),
Spell.Cast("Strike")
);
}
}
public override Composite AreaOfEffect
{
get
{
return new Decorator(ret => Targeting.ShouldAoe,
new PrioritySelector(
Spell.Cast("Force Sweep", ret => Me.CurrentTarget.Distance <= Distance.MeleeAoE))
);
}
}
}
} | apache-2.0 | C# |
4dc0b83b280395bc114c5530fa9843a244804f9b | Add commandline switch to benchmark to avoid need for rebuilds | andrasm/prometheus-net | Benchmark.NetCore/Program.cs | Benchmark.NetCore/Program.cs | using BenchmarkDotNet.Running;
namespace Benchmark.NetCore
{
internal class Program
{
private static void Main(string[] args)
{
// Give user possibility to choose which benchmark to run.
// Can be overridden from the command line with the --filter option.
new BenchmarkSwitcher(typeof(Program).Assembly).Run(args);
}
}
}
| using BenchmarkDotNet.Running;
namespace Benchmark.NetCore
{
internal class Program
{
private static void Main(string[] args)
{
//BenchmarkRunner.Run<MetricCreationBenchmarks>();
//BenchmarkRunner.Run<SerializationBenchmarks>();
//BenchmarkRunner.Run<LabelBenchmarks>();
//BenchmarkRunner.Run<HttpExporterBenchmarks>();
//BenchmarkRunner.Run<SummaryBenchmarks>();
BenchmarkRunner.Run<MetricPusherBenchmarks>();
}
}
}
| mit | C# |
7bf7e9ab16c68f00e49bc45748c65707150a8de5 | Check for invalid chars in uploaded file name - Resolves #579 | n2cms/n2cms,VoidPointerAB/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms,n2cms/n2cms,nicklv/n2cms,nimore/n2cms,nimore/n2cms,SntsDev/n2cms,nimore/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms,EzyWebwerkstaden/n2cms,SntsDev/n2cms,nicklv/n2cms,bussemac/n2cms,VoidPointerAB/n2cms,bussemac/n2cms,bussemac/n2cms,SntsDev/n2cms,bussemac/n2cms,nicklv/n2cms,nimore/n2cms,nicklv/n2cms,VoidPointerAB/n2cms,n2cms/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms,n2cms/n2cms,VoidPointerAB/n2cms,SntsDev/n2cms,EzyWebwerkstaden/n2cms,bussemac/n2cms,nicklv/n2cms,DejanMilicic/n2cms | src/Framework/N2/Configuration/RootFileSystemFolderCollection.cs | src/Framework/N2/Configuration/RootFileSystemFolderCollection.cs | using System.Collections.Generic;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
namespace N2.Configuration
{
[ConfigurationCollection(typeof(FolderElement))]
public class RootFileSystemFolderCollection : FileSystemFolderCollection
{
public RootFileSystemFolderCollection()
{
FolderElement folder = new FolderElement();
folder.Path = "~/upload/";
AddDefault(folder);
}
[ConfigurationProperty("uploadsWhitelistExpression")]
public string UploadsWhitelistExpression
{
get { return (string)base["uploadsWhitelistExpression"]; }
set { base["uploadsWhitelistExpression"] = value; }
}
[ConfigurationProperty("uploadsBlacklistExpression", DefaultValue = "[.](armx|asax|asbx|axhx|asmx|asp|aspx|axd|cshtml|master|vsdisco|cfm|pl|cgi|ad|adp|crt|ins|mde|msc|sct|vb|swc|wsf|cpl|shs|bas|bat|cmd|com|hlp|hta|isp|js|jse|lnk|mst|pcd|pif|reg|scr|url|vbe|vbs|ws|wsh|php)$")]
public string UploadsBlacklistExpression
{
get { return (string)base["uploadsBlacklistExpression"]; }
set { base["uploadsBlacklistExpression"] = value; }
}
public bool IsTrusted(string filename)
{
if (!string.IsNullOrEmpty(UploadsWhitelistExpression))
return Regex.IsMatch(filename, UploadsWhitelistExpression, RegexOptions.IgnoreCase);
if (!string.IsNullOrEmpty(UploadsBlacklistExpression))
return !Regex.IsMatch(filename, UploadsBlacklistExpression, RegexOptions.IgnoreCase);
//DefaultRequestPathInvalidCharacters
foreach (var ch in "<>*%&:\\?,") { //TODO: Do something better with HttpRuntimeConfig, see https://github.com/Microsoft/referencesource/blob/fa352bbcac7dd189f66546297afaffc98f6a7d15/System.Web/Configuration/HttpRuntimeSection.cs#L48
if (filename.IndexOf(ch) >= 0)
return false;
return true;
}
}
}
| using System.Collections.Generic;
using System.Configuration;
using System.Text.RegularExpressions;
namespace N2.Configuration
{
[ConfigurationCollection(typeof(FolderElement))]
public class RootFileSystemFolderCollection : FileSystemFolderCollection
{
public RootFileSystemFolderCollection()
{
FolderElement folder = new FolderElement();
folder.Path = "~/upload/";
AddDefault(folder);
}
[ConfigurationProperty("uploadsWhitelistExpression")]
public string UploadsWhitelistExpression
{
get { return (string)base["uploadsWhitelistExpression"]; }
set { base["uploadsWhitelistExpression"] = value; }
}
[ConfigurationProperty("uploadsBlacklistExpression", DefaultValue = "[.](armx|asax|asbx|axhx|asmx|asp|aspx|axd|cshtml|master|vsdisco|cfm|pl|cgi|ad|adp|crt|ins|mde|msc|sct|vb|swc|wsf|cpl|shs|bas|bat|cmd|com|hlp|hta|isp|js|jse|lnk|mst|pcd|pif|reg|scr|url|vbe|vbs|ws|wsh|php)$")]
public string UploadsBlacklistExpression
{
get { return (string)base["uploadsBlacklistExpression"]; }
set { base["uploadsBlacklistExpression"] = value; }
}
public bool IsTrusted(string filename)
{
if (!string.IsNullOrEmpty(UploadsWhitelistExpression))
return Regex.IsMatch(filename, UploadsWhitelistExpression, RegexOptions.IgnoreCase);
if (!string.IsNullOrEmpty(UploadsBlacklistExpression))
return !Regex.IsMatch(filename, UploadsBlacklistExpression, RegexOptions.IgnoreCase);
return true;
}
}
}
| lgpl-2.1 | C# |
c4efc8121f4f3ccf9e38710cbfcca43ebed18ec5 | Increase the default Cloud Files connection limit | rackerlabs/rax-vsix | Rackspace.VisualStudio.CloudExplorer/Files/CloudFilesEndpointNode.cs | Rackspace.VisualStudio.CloudExplorer/Files/CloudFilesEndpointNode.cs | namespace Rackspace.VisualStudio.CloudExplorer.Files
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VSDesigner.ServerExplorer;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;
public class CloudFilesEndpointNode : EndpointNode
{
public CloudFilesEndpointNode(CloudIdentity identity, ServiceCatalog serviceCatalog, Endpoint endpoint)
: base(identity, serviceCatalog, endpoint)
{
}
protected override async Task<Node[]> CreateChildrenAsync(CancellationToken cancellationToken)
{
Tuple<CloudFilesProvider, Container[]> containers = await ListContainersAsync(cancellationToken);
return Array.ConvertAll(containers.Item2, i => CreateContainerNode(containers.Item1, i, null));
}
private CloudFilesContainerNode CreateContainerNode(CloudFilesProvider provider, Container container, ContainerCDN containerCdn)
{
return new CloudFilesContainerNode(provider, container, containerCdn);
}
private async Task<Tuple<CloudFilesProvider, Container[]>> ListContainersAsync(CancellationToken cancellationToken)
{
CloudFilesProvider provider = CreateProvider();
List<Container> containers = new List<Container>();
containers.AddRange(await Task.Run(() => provider.ListContainers()));
return Tuple.Create(provider, containers.ToArray());
}
private CloudFilesProvider CreateProvider()
{
CloudFilesProvider provider = new CloudFilesProvider(Identity, Endpoint.Region, null, null);
provider.ConnectionLimit = 50;
return provider;
}
}
}
| namespace Rackspace.VisualStudio.CloudExplorer.Files
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VSDesigner.ServerExplorer;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;
public class CloudFilesEndpointNode : EndpointNode
{
public CloudFilesEndpointNode(CloudIdentity identity, ServiceCatalog serviceCatalog, Endpoint endpoint)
: base(identity, serviceCatalog, endpoint)
{
}
protected override async Task<Node[]> CreateChildrenAsync(CancellationToken cancellationToken)
{
Tuple<CloudFilesProvider, Container[]> containers = await ListContainersAsync(cancellationToken);
return Array.ConvertAll(containers.Item2, i => CreateContainerNode(containers.Item1, i, null));
}
private CloudFilesContainerNode CreateContainerNode(CloudFilesProvider provider, Container container, ContainerCDN containerCdn)
{
return new CloudFilesContainerNode(provider, container, containerCdn);
}
private async Task<Tuple<CloudFilesProvider, Container[]>> ListContainersAsync(CancellationToken cancellationToken)
{
CloudFilesProvider provider = CreateProvider();
List<Container> containers = new List<Container>();
containers.AddRange(await Task.Run(() => provider.ListContainers()));
return Tuple.Create(provider, containers.ToArray());
}
private CloudFilesProvider CreateProvider()
{
return new CloudFilesProvider(Identity, Endpoint.Region, null, null);
}
}
}
| apache-2.0 | C# |
40dcddb49a9b2b7e094d79fed4ae8d79e895e3f4 | fix print typo and fix issue where path change could be the first one, being index 0, we therefore need the error case to be -1 | Willster419/RelicModManager,Willster419/RelhaxModpack,Willster419/RelhaxModpack | RelhaxModpack/RelhaxModpack/Automation/AutomationCompareDirectory.cs | RelhaxModpack/RelhaxModpack/Automation/AutomationCompareDirectory.cs | using RelhaxModpack.Utilities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RelhaxModpack.Automation.Tasks
{
public class AutomationCompareDirectory : AutomationCompare
{
public AutomationCompareDirectory(string directoryA, string directoryB, AutomationCompareMode compareMode, int numFilesA, int numFilesB, int indexOfFilenameChange = -1) : base(directoryA, directoryB, compareMode)
{
this.CompareANumFiles = numFilesA;
this.CompareBNumFiles = numFilesB;
this.IndexOfFilenameChange = indexOfFilenameChange;
}
public override bool CompareResult
{
get
{
if (CompareBNumFiles != CompareANumFiles)
return false;
else if (IndexOfFilenameChange != -1)
return false;
else return true;
}
}
public int CompareANumFiles;
public int CompareBNumFiles;
public int IndexOfFilenameChange = 0;
public override void PrintToLog()
{
Logging.Debug("A Directory {0}, Count {1}", CompareAPath, CompareANumFiles);
Logging.Debug("B Directory {0}, Count {1}", CompareBPath, CompareBNumFiles);
}
}
}
| using RelhaxModpack.Utilities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RelhaxModpack.Automation.Tasks
{
public class AutomationCompareDirectory : AutomationCompare
{
public AutomationCompareDirectory(string directoryA, string directoryB, AutomationCompareMode compareMode, int numFilesA, int numFilesB, int indexOfFilenameChange = 0) : base(directoryA, directoryB, compareMode)
{
this.CompareANumFiles = numFilesA;
this.CompareBNumFiles = numFilesB;
this.IndexOfFilenameChange = indexOfFilenameChange;
}
public override bool CompareResult
{
get
{
if (CompareBNumFiles != CompareANumFiles)
return false;
else if (IndexOfFilenameChange != 0)
return false;
else return true;
}
}
public int CompareANumFiles;
public int CompareBNumFiles;
public int IndexOfFilenameChange = 0;
public override void PrintToLog()
{
Logging.Debug("A Directory {0}, Count {1}", CompareAPath, CompareANumFiles);
Logging.Debug("B File {0}, Count {1}", CompareBPath, CompareBNumFiles);
}
}
}
| apache-2.0 | C# |
cf09805f8baf075a1b54cab37cab0920a83f4fda | Resolve #17 | Seaal/disclose | src/Disclose/IDataStore.cs | src/Disclose/IDataStore.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Disclose.DiscordClient;
namespace Disclose
{
public interface IDataStore
{
Task<TData> GetServerData<TData>(IServer server, string key);
Task SetServerData<TData>(IServer server, string key, TData data);
Task<TData> GetUserData<TData>(IUser user, string key);
Task SetUserData<TData>(IUser user, string key, TData data);
Task<TData> GetUserDataForServer<TData>(IServer server, IUser user, string key, TData data);
Task SetUserData<TData>(IServer server, IUser user, string key, TData data);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Disclose.DiscordClient;
namespace Disclose
{
public interface IDataStore
{
TData GetServerData<TData>(IServer server, string key);
void SetServerData<TData>(IServer server, string key, TData data);
TData GetUserData<TData>(IUser user, string key);
void SetUserData<TData>(IUser user, string key, TData data);
TData GetUserDataForServer<TData>(IServer server, IUser user, string key, TData data);
void SetUserData<TData>(IServer server, IUser user, string key, TData data);
}
}
| mit | C# |
7ac6edcb667c3acdb2ed9f0ad6c1843eede9ed8e | Make fields private | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/DrawDemo/DrawCanvas.cs | src/DrawDemo/DrawCanvas.cs | using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace DrawDemo
{
public class DrawCanvas : Canvas
{
private bool _draw = false;
private Point _point;
protected override void OnMouseEnter(MouseEventArgs e)
{
base.OnMouseEnter(e);
_point = e.GetPosition(this);
_draw = true;
this.InvalidateVisual();
}
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
_draw = false;
this.InvalidateVisual();
}
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnPreviewMouseLeftButtonDown(e);
}
protected override void OnPreviewMouseMove(MouseEventArgs e)
{
base.OnPreviewMouseMove(e);
_point = e.GetPosition(this);
this.InvalidateVisual();
}
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
if (_draw)
{
var pen = new Pen(Brushes.Cyan, 2);
var a0 = new Point(0, _point.Y);
var b0 = new Point(this.ActualWidth, _point.Y);
var a1 = new Point(_point.X, 0);
var b1 = new Point(_point.X, this.ActualHeight);
dc.DrawLine(pen, a0, b0);
dc.DrawLine(pen, a1, b1);
dc.DrawEllipse(Brushes.Yellow, null, _point, 5, 5);
}
}
}
}
| using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace DrawDemo
{
public class DrawCanvas : Canvas
{
bool _draw = false;
Point _point;
protected override void OnMouseEnter(MouseEventArgs e)
{
base.OnMouseEnter(e);
_point = e.GetPosition(this);
_draw = true;
this.InvalidateVisual();
}
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
_draw = false;
this.InvalidateVisual();
}
protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnPreviewMouseLeftButtonDown(e);
}
protected override void OnPreviewMouseMove(MouseEventArgs e)
{
base.OnPreviewMouseMove(e);
_point = e.GetPosition(this);
this.InvalidateVisual();
}
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
if (_draw)
{
var pen = new Pen(Brushes.Cyan, 2);
var a0 = new Point(0, _point.Y);
var b0 = new Point(this.ActualWidth, _point.Y);
var a1 = new Point(_point.X, 0);
var b1 = new Point(_point.X, this.ActualHeight);
dc.DrawLine(pen, a0, b0);
dc.DrawLine(pen, a1, b1);
dc.DrawEllipse(Brushes.Yellow, null, _point, 5, 5);
}
}
}
}
| mit | C# |
3d8d3c8518d41eb8288c3fde3d81d3bf2e3eb74d | Add code for animation switching | Barleytree/NitoriWare,uulltt/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,plrusek/NitoriWare | Assets/Resources/Microgames/RockBand/Scripts/RockBandContoller.cs | Assets/Resources/Microgames/RockBand/Scripts/RockBandContoller.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RockBandContoller : MonoBehaviour
{
public static RockBandContoller instance;
public RockBandNote[] notes;
public Animator kyoani;
private State state;
public enum State
{
Default,
Victory,
Failure,
Hit
}
void Awake()
{
instance = this;
}
public void victory()
{
setState(State.Victory);
MicrogameController.instance.setVictory(true, true);
}
public void failure()
{
setState(State.Failure);
MicrogameController.instance.setVictory(false, true);
for (int i = 0; i < notes.Length; i++)
{
notes[i].gameObject.SetActive(false);
}
}
void Update ()
{
if (state == State.Hit)
setState(State.Default);
if (state == State.Default && MicrogameTimer.instance.beatsLeft < 7f)
checkForInput();
}
void checkForInput()
{
if (Input.GetKeyDown(KeyCode.RightArrow)
|| Input.GetKeyDown(KeyCode.UpArrow)
|| Input.GetKeyDown(KeyCode.LeftArrow)
|| Input.GetKeyDown(KeyCode.DownArrow))
{
for (int i = 0; i < notes.Length; i++)
{
if (notes[i].state == RockBandNote.State.InRange)
{
if (Input.GetKeyDown(notes[i].key))
{
notes[i].playNote();
if (i == notes.Length - 1)
victory();
else
setState(State.Hit);
}
else
{
failure();
}
return;
}
}
failure();
}
}
void setState(State state)
{
this.state = state;
kyoani.SetInteger("state", (int)state);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RockBandContoller : MonoBehaviour
{
public static RockBandContoller instance;
public RockBandNote[] notes;
public State state;
public enum State
{
Default,
Victory,
Failure
}
void Awake()
{
instance = this;
}
public void victory()
{
state = State.Victory;
MicrogameController.instance.setVictory(true, true);
//TODO Victory animations for scene
}
public void failure()
{
state = State.Failure;
MicrogameController.instance.setVictory(false, true);
for (int i = 0; i < notes.Length; i++)
{
//TODO Failure animations for notes
notes[i].gameObject.SetActive(false);
}
//TODO Failure animations for scene
}
void Update ()
{
if (state == State.Default && MicrogameTimer.instance.beatsLeft < 7f)
checkForInput();
}
void checkForInput()
{
if (Input.GetKeyDown(KeyCode.RightArrow)
|| Input.GetKeyDown(KeyCode.UpArrow)
|| Input.GetKeyDown(KeyCode.LeftArrow)
|| Input.GetKeyDown(KeyCode.DownArrow))
{
for (int i = 0; i < notes.Length; i++)
{
if (notes[i].state == RockBandNote.State.InRange)
{
if (Input.GetKeyDown(notes[i].key))
{
notes[i].playNote();
if (i == notes.Length - 1)
victory();
}
else
{
failure();
}
return;
}
}
failure();
}
}
}
| mit | C# |
237a8040255473a81c68c5d01191eaf896ccb8ab | Simplify AddAuthentication call | JasonBock/csla,rockfordlhotka/csla,MarimerLLC/csla,rockfordlhotka/csla,MarimerLLC/csla,JasonBock/csla,MarimerLLC/csla,rockfordlhotka/csla,JasonBock/csla | Samples/ProjectTracker/ProjectTracker.Ui.Blazor.Server/Startup.cs | Samples/ProjectTracker/ProjectTracker.Ui.Blazor.Server/Startup.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Csla.Blazor;
using Csla.Configuration;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace ProjectTracker.Ui.Blazor
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddHttpContextAccessor();
services.AddCsla().WithBlazorServerSupport();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
//// use in-proc data portal
//app.UseCsla();
//ConfigurationManager.AppSettings["DalManagerType"] =
// "ProjectTracker.DalMock.DalManager,ProjectTracker.DalMock";
// use remote data portal server
app.UseCsla(c => c
.DataPortal()
.DefaultProxy(typeof(Csla.DataPortalClient.HttpProxy), "http://localhost:8040/api/dataportal/"));
ProjectTracker.Library.RoleList.CacheListAsync();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Csla.Blazor;
using Csla.Configuration;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace ProjectTracker.Ui.Blazor
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddHttpContextAccessor();
services.AddCsla().WithBlazorServerSupport();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
// use in-proc data portal
app.UseCsla();
ConfigurationManager.AppSettings["DalManagerType"] =
"ProjectTracker.DalMock.DalManager,ProjectTracker.DalMock";
//// use remote data portal server
//app.UseCsla(c => c
// .DataPortal()
// .DefaultProxy(typeof(Csla.DataPortalClient.HttpProxy), "http://localhost:8040/api/dataportal/"));
ProjectTracker.Library.RoleList.CacheListAsync();
}
}
}
| mit | C# |
782b158852aa5bc9cceae37be4f9f282666009a2 | Update Elise.cs | metaphorce/leaguesharp | MetaSmite/Champions/Elise.cs | MetaSmite/Champions/Elise.cs | using System;
using LeagueSharp;
using LeagueSharp.Common;
using SharpDX;
namespace MetaSmite.Champions
{
public static class Elise
{
internal static Spell champSpell;
private static Menu Config = MetaSmite.Config;
private static double totalDamage;
private static double spellDamage;
public static void Load()
{
//Load spells
champSpell = new Spell(SpellSlot.Q, 475f);
//Spell usage.
Config.AddItem(new MenuItem("Enabled-" + MetaSmite.Player.ChampionName, MetaSmite.Player.ChampionName + "-" + champSpell.Slot)).SetValue(true);
//Events
Game.OnUpdate += OnGameUpdate;
}
private static void OnGameUpdate(EventArgs args)
{
if (Config.Item("Enabled").GetValue<KeyBind>().Active || Config.Item("EnabledH").GetValue<KeyBind>().Active)
{
if (SmiteManager.mob != null && Config.Item(SmiteManager.mob.BaseSkinName).GetValue<bool>() && Vector3.Distance(MetaSmite.Player.ServerPosition, SmiteManager.mob.ServerPosition) <= champSpell.Range)
{
spellDamage = MetaSmite.Player.GetSpellDamage(SmiteManager.mob, champSpell.Slot);
totalDamage = spellDamage + SmiteManager.damage;
if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() &&
SmiteManager.smite.IsReady() &&
champSpell.IsReady() && totalDamage >= SmiteManager.mob.Health)
{
MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob);
}
if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() &&
champSpell.IsReady() && spellDamage >= SmiteManager.mob.Health)
{
MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob);
}
}
}
}
}
}
| using System;
using LeagueSharp;
using LeagueSharp.Common;
using SharpDX;
namespace MetaSmite.Champions
{
public static class Elise
{
internal static Spell champSpell;
private static Menu Config = MetaSmite.Config;
private static double totalDamage;
private static double spellDamage;
public static void Load()
{
//Load spells
champSpell = new Spell(SpellSlot.Q, 475f);
//Spell usage.
Config.AddItem(new MenuItem("Enabled-" + MetaSmite.Player.ChampionName, MetaSmite.Player.ChampionName + "-" + champSpell.Slot)).SetValue(true);
//Events
Game.OnGameUpdate += OnGameUpdate;
}
private static void OnGameUpdate(EventArgs args)
{
if (Config.Item("Enabled").GetValue<KeyBind>().Active || Config.Item("EnabledH").GetValue<KeyBind>().Active)
{
if (SmiteManager.mob != null && Config.Item(SmiteManager.mob.BaseSkinName).GetValue<bool>() && Vector3.Distance(MetaSmite.Player.ServerPosition, SmiteManager.mob.ServerPosition) <= champSpell.Range)
{
spellDamage = MetaSmite.Player.GetSpellDamage(SmiteManager.mob, champSpell.Slot);
totalDamage = spellDamage + SmiteManager.damage;
if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() &&
SmiteManager.smite.IsReady() &&
champSpell.IsReady() && totalDamage >= SmiteManager.mob.Health)
{
MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob);
}
if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() &&
champSpell.IsReady() && spellDamage >= SmiteManager.mob.Health)
{
MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob);
}
}
}
}
}
}
| mit | C# |
708e4238d4c31696da3673f85ef509794e6fd1a1 | Remove missed empty xml comment. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Gma/QrCodeNet/Encoding/DataEncodation/EncoderBase.cs | WalletWasabi/Gma/QrCodeNet/Encoding/DataEncodation/EncoderBase.cs | namespace Gma.QrCodeNet.Encoding.DataEncodation
{
public abstract class EncoderBase
{
internal EncoderBase()
{
}
protected virtual int GetDataLength(string content) => content.Length;
/// <summary>
/// Returns the bit representation of input data.
/// </summary>
internal abstract BitList GetDataBits(string content);
/// <summary>
/// Returns bit representation of Modevalue.
/// </summary>
/// <returns></returns>
/// <remarks>See Chapter 8.4 Data encodation, Table 2 — Mode indicators</remarks>
internal BitList GetModeIndicator()
{
BitList modeIndicatorBits = new BitList
{
{ 0001 << 2, 4 }
};
return modeIndicatorBits;
}
/// <param name="characterCount"></param>
internal BitList GetCharCountIndicator(int characterCount, int version)
{
BitList characterCountBits = new BitList();
int bitCount = GetBitCountInCharCountIndicator(version);
characterCountBits.Add(characterCount, bitCount);
return characterCountBits;
}
/// <summary>
/// Defines the length of the Character Count Indicator,
/// which varies according to the mode and the symbol version in use
/// </summary>
/// <returns>Number of bits in Character Count Indicator.</returns>
/// <remarks>
/// See Chapter 8.4 Data encodation, Table 3 — Number of bits in Character Count Indicator.
/// </remarks>
protected abstract int GetBitCountInCharCountIndicator(int version);
}
}
| namespace Gma.QrCodeNet.Encoding.DataEncodation
{
public abstract class EncoderBase
{
internal EncoderBase()
{
}
protected virtual int GetDataLength(string content) => content.Length;
/// <summary>
/// Returns the bit representation of input data.
/// </summary>
internal abstract BitList GetDataBits(string content);
/// <summary>
/// Returns bit representation of Modevalue.
/// </summary>
/// <returns></returns>
/// <remarks>See Chapter 8.4 Data encodation, Table 2 — Mode indicators</remarks>
internal BitList GetModeIndicator()
{
BitList modeIndicatorBits = new BitList
{
{ 0001 << 2, 4 }
};
return modeIndicatorBits;
}
/// <summary>
///
/// </summary>
/// <param name="characterCount"></param>
/// <returns></returns>
internal BitList GetCharCountIndicator(int characterCount, int version)
{
BitList characterCountBits = new BitList();
int bitCount = GetBitCountInCharCountIndicator(version);
characterCountBits.Add(characterCount, bitCount);
return characterCountBits;
}
/// <summary>
/// Defines the length of the Character Count Indicator,
/// which varies according to the mode and the symbol version in use
/// </summary>
/// <returns>Number of bits in Character Count Indicator.</returns>
/// <remarks>
/// See Chapter 8.4 Data encodation, Table 3 — Number of bits in Character Count Indicator.
/// </remarks>
protected abstract int GetBitCountInCharCountIndicator(int version);
}
}
| mit | C# |
3fde05d6550f1ed792cf2736f2d989de60b47537 | fix comment | Tom94/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,ppy/osu-framework | osu.Framework/Input/Bindings/IScrollBindingHandler.cs | osu.Framework/Input/Bindings/IScrollBindingHandler.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Framework.Input.Bindings
{
/// <summary>
/// A drawable that handles scroll actions.
/// </summary>
/// <typeparam name="T">The type of bindings.</typeparam>
public interface IScrollBindingHandler<in T> : IKeyBindingHandler<T>
where T : struct
{
/// <summary>
/// Triggered when a scroll action is pressed.
/// </summary>
/// <remarks>
/// When the action is not handled by any <see cref="IScrollBindingHandler{T}"/>, <see cref="IKeyBindingHandler{T}.OnPressed"/> is called.
/// In either cases, <see cref="IKeyBindingHandler{T}.OnReleased"/> will be called once.</remarks>
/// <param name="action">The action.</param>
/// <param name="amount">The amount of mouse scroll.</param>
/// <param name="isPrecise">Whether the action is from a precise scrolling.</param>
/// <returns>True if this Drawable handled the event. If false, then the event
/// is propagated up the scene graph to the next eligible Drawable.</returns>
bool OnScroll(T action, float amount, bool isPrecise);
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Framework.Input.Bindings
{
/// <summary>
/// A drawable that handles mouse wheel actions.
/// </summary>
/// <typeparam name="T">The type of bindings.</typeparam>
public interface IScrollBindingHandler<in T> : IKeyBindingHandler<T>
where T : struct
{
/// <summary>
/// Triggered when a scroll action is pressed.
/// </summary>
/// <remarks>
/// When the action is not handled by any <see cref="IScrollBindingHandler{T}"/>, <see cref="IKeyBindingHandler{T}.OnPressed"/> is called.
/// In either cases, <see cref="IKeyBindingHandler{T}.OnReleased"/> will be called once.</remarks>
/// <param name="action">The action.</param>
/// <param name="amount">The amount of mouse scroll.</param>
/// <param name="isPrecise">Whether the action is from a precise scrolling.</param>
/// <returns>True if this Drawable handled the event. If false, then the event
/// is propagated up the scene graph to the next eligible Drawable.</returns>
bool OnScroll(T action, float amount, bool isPrecise);
}
}
| mit | C# |
83d8153c164c99069f131a95bca6e1238264f171 | Make TestCaseSmoothedEdges rotation frame-rate independent | EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework | osu.Framework.Tests/Visual/TestCaseSprites/TestCaseSmoothedEdges.cs | osu.Framework.Tests/Visual/TestCaseSprites/TestCaseSmoothedEdges.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Testing;
using osuTK;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.TestCaseSprites
{
public class TestCaseSmoothedEdges : GridTestCase
{
public TestCaseSmoothedEdges() : base(2, 2)
{
Vector2[] smoothnesses =
{
new Vector2(0, 0),
new Vector2(0, 2),
new Vector2(1, 1),
new Vector2(2, 2),
};
for (int i = 0; i < Rows * Cols; ++i)
{
Cell(i).AddRange(new Drawable[]
{
new SpriteText
{
Text = $"{nameof(Sprite.EdgeSmoothness)}={smoothnesses[i]}",
Font = new FontUsage(size: 20),
},
boxes[i] = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.White,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(0.5f),
EdgeSmoothness = smoothnesses[i],
},
});
}
}
protected override void LoadComplete()
{
base.LoadComplete();
for (int i = 0; i < Rows * Cols; ++i)
boxes[i].Spin(10000, RotationDirection.Clockwise);
}
private readonly Box[] boxes = new Box[4];
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Testing;
using osuTK;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.TestCaseSprites
{
public class TestCaseSmoothedEdges : GridTestCase
{
public TestCaseSmoothedEdges() : base(2, 2)
{
Vector2[] smoothnesses =
{
new Vector2(0, 0),
new Vector2(0, 2),
new Vector2(1, 1),
new Vector2(2, 2),
};
for (int i = 0; i < Rows * Cols; ++i)
{
Cell(i).AddRange(new Drawable[]
{
new SpriteText
{
Text = $"{nameof(Sprite.EdgeSmoothness)}={smoothnesses[i]}",
Font = new FontUsage(size: 20),
},
boxes[i] = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.White,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(0.5f),
EdgeSmoothness = smoothnesses[i],
},
});
}
}
private readonly Box[] boxes = new Box[4];
protected override void Update()
{
base.Update();
foreach (Box box in boxes)
box.Rotation += 0.01f;
}
}
}
| mit | C# |
98f3810a4276caa0bef6adf95499288b7f0a6398 | Correct namespace of DotConnnectOracleDbFactory | spaccabit/fluentmigrator,vgrigoriu/fluentmigrator,dealproc/fluentmigrator,schambers/fluentmigrator,DefiSolutions/fluentmigrator,lcharlebois/fluentmigrator,MetSystem/fluentmigrator,IRlyDontKnow/fluentmigrator,mstancombe/fluentmig,drmohundro/fluentmigrator,tommarien/fluentmigrator,akema-fr/fluentmigrator,spaccabit/fluentmigrator,fluentmigrator/fluentmigrator,istaheev/fluentmigrator,istaheev/fluentmigrator,wolfascu/fluentmigrator,itn3000/fluentmigrator,itn3000/fluentmigrator,amroel/fluentmigrator,DefiSolutions/fluentmigrator,tommarien/fluentmigrator,KaraokeStu/fluentmigrator,schambers/fluentmigrator,alphamc/fluentmigrator,swalters/fluentmigrator,vgrigoriu/fluentmigrator,FabioNascimento/fluentmigrator,lcharlebois/fluentmigrator,lahma/fluentmigrator,bluefalcon/fluentmigrator,tohagan/fluentmigrator,jogibear9988/fluentmigrator,mstancombe/fluentmigrator,lahma/fluentmigrator,jogibear9988/fluentmigrator,stsrki/fluentmigrator,bluefalcon/fluentmigrator,modulexcite/fluentmigrator,dealproc/fluentmigrator,daniellee/fluentmigrator,istaheev/fluentmigrator,stsrki/fluentmigrator,drmohundro/fluentmigrator,daniellee/fluentmigrator,IRlyDontKnow/fluentmigrator,igitur/fluentmigrator,modulexcite/fluentmigrator,amroel/fluentmigrator,fluentmigrator/fluentmigrator,eloekset/fluentmigrator,eloekset/fluentmigrator,wolfascu/fluentmigrator,DefiSolutions/fluentmigrator,daniellee/fluentmigrator,alphamc/fluentmigrator,KaraokeStu/fluentmigrator,mstancombe/fluentmig,mstancombe/fluentmigrator,tohagan/fluentmigrator,igitur/fluentmigrator,FabioNascimento/fluentmigrator,MetSystem/fluentmigrator,akema-fr/fluentmigrator,lahma/fluentmigrator,tohagan/fluentmigrator,barser/fluentmigrator,swalters/fluentmigrator,barser/fluentmigrator,mstancombe/fluentmig | src/FluentMigrator.Runner/Processors/DotConnectOracle/DotConnectOracleDbFactory.cs | src/FluentMigrator.Runner/Processors/DotConnectOracle/DotConnectOracleDbFactory.cs | #region License
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace FluentMigrator.Runner.Processors.DotConnectOracle
{
public class DotConnectOracleDbFactory : ReflectionBasedDbFactory
{
public DotConnectOracleDbFactory()
: base("DevArt.Data.Oracle", "Devart.Data.Oracle.OracleProviderFactory")
{
}
}
} | #region License
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace FluentMigrator.Runner.Processors.Oracle
{
public class DotConnectOracleDbFactory : ReflectionBasedDbFactory
{
public DotConnectOracleDbFactory()
: base("DevArt.Data.Oracle", "Devart.Data.Oracle.OracleProviderFactory")
{
}
}
} | apache-2.0 | C# |
6a0ae974de25258e91573ffbd395e681349a6243 | remove unused fields | gregsochanik/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,knocte/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,bnathyuw/SevenDigital.Api.Wrapper,danbadge/SevenDigital.Api.Wrapper,mattgray/SevenDigital.Api.Wrapper,raoulmillais/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper,actionshrimp/SevenDigital.Api.Wrapper | src/SevenDigital.Api.Wrapper.Unit.Tests/EndpointResolution/OAuth/UrlSignerTests.cs | src/SevenDigital.Api.Wrapper.Unit.Tests/EndpointResolution/OAuth/UrlSignerTests.cs | using System;
using System.Collections.Generic;
using FakeItEasy;
using NUnit.Framework;
using SevenDigital.Api.Wrapper.EndpointResolution.OAuth;
namespace SevenDigital.Api.Wrapper.Unit.Tests.EndpointResolution.OAuth
{
[TestFixture]
public class UrlSignerTests
{
private string _consumerKey = "key";
private string _consumerSecret = "secret";
[Test]
public void SignUrlAsString_escapes_those_stupid_plus_signs_and_other_evils_in_signature()
{
var url = "http://www.example.com?parameter=hello&again=there";
for (int i = 0; i < 50; i++)
{
var signedUrl = new UrlSigner().SignUrlAsString(url, null, null, GetOAuthCredentials());
var index = signedUrl.IndexOf("oauth_signature");
var signature = signedUrl.Substring(index + "oauth_signature".Length);
Assert.That(!signature.Contains("+"), "signature contains a '+' character and isn't being encoded properly");
}
}
[Test]
public void SignUrl_adds_oauth_signature()
{
var url = "http://www.example.com?parameter=hello&again=there";
var signedUrl = new UrlSigner().SignUrl(url, null, null, GetOAuthCredentials());
Assert.That(signedUrl.Query.Contains("oauth_signature"));
}
private IOAuthCredentials GetOAuthCredentials()
{
var oAuthCredentials = A.Fake<IOAuthCredentials>();
A.CallTo(() => oAuthCredentials.ConsumerKey).Returns(_consumerKey);
A.CallTo(() => oAuthCredentials.ConsumerKey).Returns(_consumerSecret);
return oAuthCredentials;
}
}
}
| using System;
using System.Collections.Generic;
using FakeItEasy;
using NUnit.Framework;
using SevenDigital.Api.Wrapper.EndpointResolution.OAuth;
namespace SevenDigital.Api.Wrapper.Unit.Tests.EndpointResolution.OAuth
{
[TestFixture]
public class UrlSignerTests
{
private string _consumerKey = "key";
private string _consumerSecret = "secret";
private string userToken;
private string userSecret;
[Test]
public void SignUrlAsString_escapes_those_stupid_plus_signs_and_other_evils_in_signature()
{
var url = "http://www.example.com?parameter=hello&again=there";
for (int i = 0; i < 50; i++)
{
var signedUrl = new UrlSigner().SignUrlAsString(url, null, null, GetOAuthCredentials());
var index = signedUrl.IndexOf("oauth_signature");
var signature = signedUrl.Substring(index + "oauth_signature".Length);
Assert.That(!signature.Contains("+"), "signature contains a '+' character and isn't being encoded properly");
}
}
[Test]
public void SignUrl_adds_oauth_signature()
{
var url = "http://www.example.com?parameter=hello&again=there";
var signedUrl = new UrlSigner().SignUrl(url, null, null, GetOAuthCredentials());
Assert.That(signedUrl.Query.Contains("oauth_signature"));
}
private IOAuthCredentials GetOAuthCredentials()
{
var oAuthCredentials = A.Fake<IOAuthCredentials>();
A.CallTo(() => oAuthCredentials.ConsumerKey).Returns(_consumerKey);
A.CallTo(() => oAuthCredentials.ConsumerKey).Returns(_consumerSecret);
return oAuthCredentials;
}
}
}
| mit | C# |
fe3e54268c5a8f36f33d8f9e475396398178df3e | Clear Game.unity | sfc-sdp/GameCanvas-Unity | Assets/Scripts/Game.cs | Assets/Scripts/Game.cs | using GameCanvas;
public class Game : GameBase
{
override public void Start()
{
// ここに初期化処理を書きます
}
override public void Calc()
{
// ここに更新処理を書きます
}
override public void Draw()
{
// ここに描画処理を書きます
}
override public void Pause()
{
// ここに中断処理を書きます
}
override public void Final()
{
// ここに終了処理を書きます
}
}
| using System;
using GameCanvas;
using UnityEngine;
public class Game : GameBase
{
private int frame;
override public void Start()
{
frame = 0;
}
override public void Calc()
{
++frame;
if (frame > 50) frame = 0;
}
override public void Draw()
{
// 画面を白で塗りつぶします
gc.ClearScreen();
// 2番の画像を描画します
gc.SetColor(1f, 1f, 1f);
gc.DrawImage(2, 0, 0);
// 0番の画像を描画します
gc.SetColor(1f, 1f, 1f);
gc.DrawImage(0, 400, 160);
// 赤い長方形(塗り)を描画します
gc.SetColor(1f, 0f, 0f);
gc.FillRect(100, 100, 120, 120);
// 黒い長方形(線)を描画します
gc.SetColor(0f, 0f, 0f);
gc.DrawRect(40, 40, 440, 280);
// 青い直線を描画します
gc.SetColor(0f, 0f, 1f);
gc.DrawLine(60, 380, 220, 10);
// 緑の円を描画します
gc.SetLineWidth(2);
gc.SetColor(0.25f, 1f, 0.25f);
gc.DrawCircle(320, 240, 150 + frame);
// タッチ位置に赤い円を描画します
if (gc.isTouch)
{
gc.SetLineWidth(1);
gc.SetColor(1f, 0f, 0f);
gc.DrawCircle(gc.touchX, gc.touchY, 10);
}
}
override public void Pause()
{
//
}
override public void Final()
{
//
}
}
| mit | C# |
ec79f8a73247d99964f4e95e7af39f6ade4f548e | Allow console to be transparent again. | eightyeight/t3d-bones,eightyeight/t3d-bones | console/profiles.cs | console/profiles.cs | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
if(!isObject(GuiConsoleProfile))
new GuiControlProfile(GuiConsoleProfile)
{
fontType = ($platform $= "macos") ? "Monaco" : "Lucida Console";
fontSize = ($platform $= "macos") ? 13 : 12;
fontColor = "255 255 255";
fontColorHL = "0 255 255";
fontColorNA = "255 0 0";
fontColors[6] = "100 100 100";
fontColors[7] = "100 100 0";
fontColors[8] = "100 100 200";
fontColors[9] = "50 200 50";
category = "Core";
};
if(!isObject(GuiConsoleTextProfile))
new GuiControlProfile(GuiConsoleTextProfile)
{
fontColor = "0 0 0";
autoSizeWidth = true;
autoSizeHeight = true;
textOffset = "2 2";
opaque = true;
fillColor = "255 255 255";
border = true;
borderThickness = 1;
borderColor = "0 0 0";
category = "Core";
};
if(!isObject(ConsoleScrollProfile))
new GuiControlProfile(ConsoleScrollProfile : GuiScrollProfile)
{
opaque = true;
fillColor = "20 20 20 128";
border = 1;
//borderThickness = 0;
borderColor = "0 0 0";
category = "Core";
};
if(!isObject(ConsoleTextEditProfile))
new GuiControlProfile(ConsoleTextEditProfile : GuiTextEditProfile)
{
fillColor = "242 241 240 255";
fillColorHL = "255 255 255";
category = "Core";
};
| //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
if(!isObject(GuiConsoleProfile))
new GuiControlProfile(GuiConsoleProfile)
{
fontType = ($platform $= "macos") ? "Monaco" : "Lucida Console";
fontSize = ($platform $= "macos") ? 13 : 12;
fontColor = "255 255 255";
fontColorHL = "0 255 255";
fontColorNA = "255 0 0";
fontColors[6] = "100 100 100";
fontColors[7] = "100 100 0";
fontColors[8] = "100 100 200";
fontColors[9] = "50 200 50";
category = "Core";
};
if(!isObject(GuiConsoleTextProfile))
new GuiControlProfile(GuiConsoleTextProfile)
{
fontColor = "0 0 0";
autoSizeWidth = true;
autoSizeHeight = true;
textOffset = "2 2";
opaque = true;
fillColor = "255 255 255";
border = true;
borderThickness = 1;
borderColor = "0 0 0";
category = "Core";
};
if(!isObject(ConsoleScrollProfile))
new GuiControlProfile(ConsoleScrollProfile : GuiScrollProfile)
{
opaque = true;
fillColor = "20 20 20";
border = 1;
//borderThickness = 0;
borderColor = "0 0 0";
category = "Core";
};
if(!isObject(ConsoleTextEditProfile))
new GuiControlProfile(ConsoleTextEditProfile : GuiTextEditProfile)
{
fillColor = "242 241 240 255";
fillColorHL = "255 255 255";
category = "Core";
};
| mit | C# |
058d87009294889495552ad21230875787157346 | Disable Context_based_client_method test. Having DbContext property on entity is not supported. | azabluda/InfoCarrier.Core | test/InfoCarrier.Core.FunctionalTests/InMemory/Query/SimpleQueryInfoCarrierTest.cs | test/InfoCarrier.Core.FunctionalTests/InMemory/Query/SimpleQueryInfoCarrierTest.cs | // Copyright (c) on/off it-solutions gmbh. All rights reserved.
// Licensed under the MIT license. See license.txt file in the project root for license information.
namespace InfoCarrier.Core.FunctionalTests.InMemory.Query
{
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.EntityFrameworkCore.TestUtilities.Xunit;
using Xunit;
using Xunit.Abstractions;
public class SimpleQueryInfoCarrierTest : SimpleQueryTestBase<NorthwindQueryInfoCarrierFixture<NoopModelCustomizer>>
{
public SimpleQueryInfoCarrierTest(
NorthwindQueryInfoCarrierFixture<NoopModelCustomizer> fixture,
ITestOutputHelper testOutputHelper)
: base(fixture)
{
}
public override void Where_navigation_contains()
{
using (var context = this.CreateContext())
{
var customer = context.Customers.Include(c => c.Orders).Single(c => c.CustomerID == "ALFKI");
customer.Context = null; // Prevent Remote.Linq from serializing the entire DbContext
var orderDetails = context.OrderDetails.Where(od => customer.Orders.Contains(od.Order)).ToList();
Assert.Equal(12, orderDetails.Count);
}
}
[ConditionalTheory(Skip = "Self referencing loop because of Customer.Context property. Not supported.")]
[MemberData(nameof(IsAsyncData))]
public override Task Context_based_client_method(bool isAsync)
{
return base.Context_based_client_method(isAsync);
}
[ConditionalFact(Skip = "Concurrency detection mechanism cannot be used")]
public override void Throws_on_concurrent_query_list()
{
base.Throws_on_concurrent_query_list();
}
[ConditionalFact(Skip = "Concurrency detection mechanism cannot be used")]
public override void Throws_on_concurrent_query_first()
{
base.Throws_on_concurrent_query_first();
}
//[ConditionalTheory(Skip = "Client-side evaluation is not supported")]
//public override Task Client_OrderBy_GroupBy_Group_ordering_works(bool isAsync)
//{
// return base.Client_OrderBy_GroupBy_Group_ordering_works(isAsync);
//}
}
}
| // Copyright (c) on/off it-solutions gmbh. All rights reserved.
// Licensed under the MIT license. See license.txt file in the project root for license information.
namespace InfoCarrier.Core.FunctionalTests.InMemory.Query
{
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.EntityFrameworkCore.TestUtilities.Xunit;
using Xunit;
using Xunit.Abstractions;
public class SimpleQueryInfoCarrierTest : SimpleQueryTestBase<NorthwindQueryInfoCarrierFixture<NoopModelCustomizer>>
{
public SimpleQueryInfoCarrierTest(
NorthwindQueryInfoCarrierFixture<NoopModelCustomizer> fixture,
ITestOutputHelper testOutputHelper)
: base(fixture)
{
}
public override void Where_navigation_contains()
{
using (var context = this.CreateContext())
{
var customer = context.Customers.Include(c => c.Orders).Single(c => c.CustomerID == "ALFKI");
customer.Context = null; // Prevent Remote.Linq from serializing the entire DbContext
var orderDetails = context.OrderDetails.Where(od => customer.Orders.Contains(od.Order)).ToList();
Assert.Equal(12, orderDetails.Count);
}
}
[ConditionalFact(Skip = "Concurrency detection mechanism cannot be used")]
public override void Throws_on_concurrent_query_list()
{
base.Throws_on_concurrent_query_list();
}
[ConditionalFact(Skip = "Concurrency detection mechanism cannot be used")]
public override void Throws_on_concurrent_query_first()
{
base.Throws_on_concurrent_query_first();
}
//[ConditionalTheory(Skip = "Client-side evaluation is not supported")]
//public override Task Client_OrderBy_GroupBy_Group_ordering_works(bool isAsync)
//{
// return base.Client_OrderBy_GroupBy_Group_ordering_works(isAsync);
//}
}
}
| mit | C# |
8c96a1a3fe456f38362e1d8a2f50881df48fad9c | Update AssemblyInfo.cs | tiernano/b2uploader | B2Uploader/Properties/AssemblyInfo.cs | B2Uploader/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("B2Uploader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("B2Uploader")]
[assembly: AssemblyCopyright("Copyright Tiernan OToole © 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("a5d41169-c2ee-4b5e-a2d8-b63e485597a6")]
// 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("B2Uploader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("B2Uploader")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a5d41169-c2ee-4b5e-a2d8-b63e485597a6")]
// 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# |
e6cf424ffa0f9c5e9770dff5580d53e91a53c229 | comment out schedule for now as its not being used | Appleseed/base,Appleseed/base | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/Constants.cs | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/Constants.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
public class Constants
{
#region App Config Values
// Test Settings
public static string Mode = System.Configuration.ConfigurationManager.AppSettings["Mode"];
public static string TestEmail = System.Configuration.ConfigurationManager.AppSettings["TestEmail"];
public static string TestSearchQuery = System.Configuration.ConfigurationManager.AppSettings["TestSearchQuery"];
public static string TestSearchLink = System.Configuration.ConfigurationManager.AppSettings["TestSearchLink"];
public static string StringLimit = System.Configuration.ConfigurationManager.AppSettings["StringLimit"];
//SendGridAPI Key
public static string APIKey = System.Configuration.ConfigurationManager.AppSettings["SendGridAPIKey"];
//Mail Settings
public static string MailFrom = System.Configuration.ConfigurationManager.AppSettings["MailFrom"];
public static string MailFromName = System.Configuration.ConfigurationManager.AppSettings["MailFromName"];
public static string MailSubject = System.Configuration.ConfigurationManager.AppSettings["MailSubject"];
public static string MailHeaderText = System.Configuration.ConfigurationManager.AppSettings["MailHeaderText"];
//public static string MailSchedule = System.Configuration.ConfigurationManager.AppSettings["MailSchedule"];
public static string GetUserAlertQuery = System.Configuration.ConfigurationManager.AppSettings["GetUserAlertQuery"];
public static string UpdateUserSendQuery = System.Configuration.ConfigurationManager.AppSettings["UpdateUserSendQuery"];
//Search Settings
public static string SiteSearchLink = System.Configuration.ConfigurationManager.AppSettings["SiteSearchLink"];
public static string SolrURL = System.Configuration.ConfigurationManager.AppSettings["SolrURL"];
public static string RefreshQuery = System.Configuration.ConfigurationManager.AppSettings["RefreshQuery"];
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
public class Constants
{
#region App Config Values
// Test Settings
public static string Mode = System.Configuration.ConfigurationManager.AppSettings["Mode"];
public static string TestEmail = System.Configuration.ConfigurationManager.AppSettings["TestEmail"];
public static string TestSearchQuery = System.Configuration.ConfigurationManager.AppSettings["TestSearchQuery"];
public static string TestSearchLink = System.Configuration.ConfigurationManager.AppSettings["TestSearchLink"];
public static string StringLimit = System.Configuration.ConfigurationManager.AppSettings["StringLimit"];
//SendGridAPI Key
public static string APIKey = System.Configuration.ConfigurationManager.AppSettings["SendGridAPIKey"];
//Mail Settings
public static string MailFrom = System.Configuration.ConfigurationManager.AppSettings["MailFrom"];
public static string MailFromName = System.Configuration.ConfigurationManager.AppSettings["MailFromName"];
public static string MailSubject = System.Configuration.ConfigurationManager.AppSettings["MailSubject"];
public static string MailHeaderText = System.Configuration.ConfigurationManager.AppSettings["MailHeaderText"];
public static string MailSchedule = System.Configuration.ConfigurationManager.AppSettings["MailSchedule"];
public static string GetUserAlertQuery = System.Configuration.ConfigurationManager.AppSettings["GetUserAlertQuery"];
public static string UpdateUserSendQuery = System.Configuration.ConfigurationManager.AppSettings["UpdateUserSendQuery"];
//Search Settings
public static string SiteSearchLink = System.Configuration.ConfigurationManager.AppSettings["SiteSearchLink"];
public static string SolrURL = System.Configuration.ConfigurationManager.AppSettings["SolrURL"];
public static string RefreshQuery = System.Configuration.ConfigurationManager.AppSettings["RefreshQuery"];
#endregion
}
}
| apache-2.0 | C# |
5fdae42bafceb2362697222a2cb5d7a47c72a4ab | fix SpawnPopupDialog | henrybauer/AutoAsparagus | AutoAsparagus/ASPInstallChecker.cs | AutoAsparagus/ASPInstallChecker.cs | /*
* Originally based on the InstallChecker from the Kethane mod for Kerbal Space Program.
* This version is based off taraniselsu's version from https://github.com/Majiir/Kethane/blob/b93b1171ec42b4be6c44b257ad31c7efd7ea1702/Plugin/InstallChecker.cs
*
* Original is (C) Copyright Majiir.
* CC0 Public Domain (http://creativecommons.org/publicdomain/zero/1.0/)
* http://forum.kerbalspaceprogram.com/threads/65395-CompatibilityChecker-Discussion-Thread?p=899895&viewfull=1#post899895
*
* This file has been modified extensively and is released under the same license.
*/
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEngine;
//#if DEBUG
//using KramaxReloadExtensions;
//#endif
namespace AutoAsparagus
{
// Be sure to target .NET 3.5 or you'll get some bogus error on startup!
[KSPAddon(KSPAddon.Startup.MainMenu, true)]
// #if DEBUG
// internal class ASPInstallChecker: ReloadableMonoBehaviour
// #else
internal class ASPInstallChecker: MonoBehaviour
// #endif
{
protected void Start()
{
const string modName = "AutoAsparagus";
const string expectedPath = "AutoAsparagus";
// Search for this mod's DLL existing in the wrong location. This will also detect duplicate copies because only one can be in the right place.
var assemblies = AssemblyLoader.loadedAssemblies.Where (a => a.assembly.GetName ().Name == Assembly.GetExecutingAssembly ().GetName ().Name).Where (a => a.url != expectedPath);
if (assemblies.Any()) {
var badPaths = assemblies.Select(a => a.path).Select(
p => Uri.UnescapeDataString(new Uri(Path.GetFullPath(KSPUtil.ApplicationRootPath)).MakeRelativeUri(new Uri(p)).ToString().Replace('/', Path.DirectorySeparatorChar))
);
PopupDialog.SpawnPopupDialog( new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "AutoAsparagusBadInstallDialog",
"Incorrect " + modName + " Installation",
modName + " has been installed incorrectly and will not function properly. All files should be located in KSP/GameData/" +
expectedPath + ". Do not move any files from inside that folder.\n\nIncorrect path(s):\n" +
String.Join("\n", badPaths.ToArray()),
"OK", false, HighLogic.UISkin);
}
}
}
}
| /*
* Originally based on the InstallChecker from the Kethane mod for Kerbal Space Program.
* This version is based off taraniselsu's version from https://github.com/Majiir/Kethane/blob/b93b1171ec42b4be6c44b257ad31c7efd7ea1702/Plugin/InstallChecker.cs
*
* Original is (C) Copyright Majiir.
* CC0 Public Domain (http://creativecommons.org/publicdomain/zero/1.0/)
* http://forum.kerbalspaceprogram.com/threads/65395-CompatibilityChecker-Discussion-Thread?p=899895&viewfull=1#post899895
*
* This file has been modified extensively and is released under the same license.
*/
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEngine;
//#if DEBUG
//using KramaxReloadExtensions;
//#endif
namespace AutoAsparagus
{
// Be sure to target .NET 3.5 or you'll get some bogus error on startup!
[KSPAddon(KSPAddon.Startup.MainMenu, true)]
// #if DEBUG
// internal class ASPInstallChecker: ReloadableMonoBehaviour
// #else
internal class ASPInstallChecker: MonoBehaviour
// #endif
{
protected void Start()
{
const string modName = "AutoAsparagus";
const string expectedPath = "AutoAsparagus";
// Search for this mod's DLL existing in the wrong location. This will also detect duplicate copies because only one can be in the right place.
var assemblies = AssemblyLoader.loadedAssemblies.Where (a => a.assembly.GetName ().Name == Assembly.GetExecutingAssembly ().GetName ().Name).Where (a => a.url != expectedPath);
if (assemblies.Any()) {
var badPaths = assemblies.Select(a => a.path).Select(
p => Uri.UnescapeDataString(new Uri(Path.GetFullPath(KSPUtil.ApplicationRootPath)).MakeRelativeUri(new Uri(p)).ToString().Replace('/', Path.DirectorySeparatorChar))
);
PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "Incorrect " + modName + " Installation",
modName + " has been installed incorrectly and will not function properly. All files should be located in KSP/GameData/" +
expectedPath + ". Do not move any files from inside that folder.\n\nIncorrect path(s):\n" +
String.Join("\n", badPaths.ToArray()),
"OK", false, HighLogic.UISkin);
}
}
}
}
| apache-2.0 | C# |
02a84bcedd3736db179023928e6c61d3d4fc055b | Simplify MfA sample an add Addresses and InstantMessaging | xamarin/Xamarin.Mobile,xamarin/Xamarin.Mobile,haithemaraissia/Xamarin.Mobile,nexussays/Xamarin.Mobile,moljac/Xamarin.Mobile,orand/Xamarin.Mobile | MonoDroid/Samples/ContactsSample/Activity1.cs | MonoDroid/Samples/ContactsSample/Activity1.cs | using System;
using System.Text;
using Android.App;
using Android.Database;
using Android.Net;
using Android.OS;
using Android.Provider;
using Android.Widget;
using Xamarin.Contacts;
using System.Linq;
namespace ContactsSample
{
[Activity(Label = "ContactsSample", MainLauncher = true, Icon = "@drawable/icon")]
public class Activity1 : Activity
{
int count = 1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var book = new AddressBook (this);
StringBuilder builder = new StringBuilder();
foreach (Contact contact in book.Where (c => c.Phones.Any() || c.Emails.Any()).OrderBy (c => c.LastName))
{
builder.AppendLine (contact.DisplayName);
if (contact.Organizations.Any())
{
builder.AppendLine();
builder.AppendLine ("Organizations:");
foreach (Organization o in contact.Organizations)
{
builder.Append (o.Label + ": " + o.Name);
if (o.ContactTitle != null)
builder.Append (", " + o.ContactTitle);
builder.AppendLine();
}
}
if (contact.Phones.Any())
{
builder.AppendLine();
builder.AppendLine ("Phones:");
foreach (Phone p in contact.Phones)
builder.AppendLine (p.Label + ": " + p.Number);
}
if (contact.Emails.Any())
{
builder.AppendLine();
builder.AppendLine ("Emails:");
foreach (Email e in contact.Emails)
builder.AppendLine (e.Label + ": " + e.Address);
}
if (contact.Addresses.Any())
{
builder.AppendLine();
builder.AppendLine ("Addresses:");
foreach (Address a in contact.Addresses)
{
builder.AppendLine();
builder.AppendLine (a.Label + ":");
builder.AppendLine (a.StreetAddress);
builder.AppendLine (String.Format ("{0}, {1} {2}", a.City, a.Region, a.PostalCode));
builder.AppendLine (a.Country);
}
}
if (contact.InstantMessagingAccounts.Any())
{
builder.AppendLine();
builder.AppendLine ("Instant Messaging Accounts:");
foreach (InstantMessagingAccount imAccount in contact.InstantMessagingAccounts)
builder.AppendLine (String.Format ("{0}: {1}", imAccount.ServiceLabel, imAccount.Account));
}
if (contact.Notes.Any())
{
builder.AppendLine();
builder.AppendLine ("Notes:");
foreach (string n in contact.Notes)
builder.AppendLine (" - " + n);
}
builder.AppendLine();
}
FindViewById<TextView> (Resource.Id.contacts).Text = builder.ToString();
}
}
} | using System.Text;
using Android.App;
using Android.Database;
using Android.Net;
using Android.OS;
using Android.Provider;
using Android.Widget;
using Xamarin.Contacts;
using System.Linq;
namespace ContactsSample
{
[Activity(Label = "ContactsSample", MainLauncher = true, Icon = "@drawable/icon")]
public class Activity1 : Activity
{
int count = 1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var book = new AddressBook (this);
StringBuilder builder = new StringBuilder();
foreach (Contact contact in book.Where (c => c.Phones.Any() || c.Emails.Any()).OrderBy (c => c.LastName))
{
builder.AppendLine ("Display name: " + contact.DisplayName);
builder.AppendLine ("Nickname: " + contact.Nickname);
builder.AppendLine ("Prefix: " + contact.Prefix);
builder.AppendLine ("First name: " + contact.FirstName);
builder.AppendLine ("Middle name: " + contact.MiddleName);
builder.AppendLine ("Last name: " + contact.LastName);
builder.AppendLine ("Suffix:" + contact.Suffix);
builder.AppendLine();
builder.AppendLine ("Phones:");
foreach (Phone p in contact.Phones)
builder.AppendLine (p.Label + ": " + p.Number);
builder.AppendLine();
builder.AppendLine ("Emails:");
foreach (Email e in contact.Emails)
builder.AppendLine (e.Label + ": " + e.Address);
builder.AppendLine();
builder.AppendLine ("Notes:");
foreach (string n in contact.Notes)
builder.AppendLine (" - " + n);
builder.AppendLine();
}
FindViewById<TextView> (Resource.Id.contacts).Text = builder.ToString();
}
}
} | apache-2.0 | C# |
1bae096d861fd19ccb3c2a7d66c277295b2dfc6f | Fix unused imports noise | peterblazejewicz/aspnet5-docker-boilerplate | AspNetDockerBoilerplate/Startup.cs | AspNetDockerBoilerplate/Startup.cs | using Microsoft.AspNet.Builder;
namespace AspNetDockerBoilerplate
{
public class Startup
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void Configure(IApplicationBuilder app)
{
app.UseWelcomePage();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.Framework.DependencyInjection;
namespace AspNetDockerBoilerplate
{
public class Startup
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void Configure(IApplicationBuilder app)
{
app.UseWelcomePage();
}
}
}
| unlicense | C# |
9022dbc8f774275bebb318ac22464570bbbe0027 | Add LineRenderers | EightBitBoy/EcoRealms | Assets/Scripts/Map/GridRenderer.cs | Assets/Scripts/Map/GridRenderer.cs | using UnityEngine;
using System.Collections;
namespace ecorealms.map {
public class GridRenderer : MonoBehaviour {
private int linesX;
private int linesY;
public void Setup(int chunksX, int chunksY, int tilesX, int tilesY) {
this.linesX = chunksX * tilesX;
this.linesY = chunksY * tilesY;
Initialize();
}
private void Initialize() {
for(int x = 0; x < linesX; x++){
GameObject line = new GameObject("LineX" + x);
line.transform.SetParent(gameObject.transform);
LineRenderer renderer = line.AddComponent<LineRenderer>();
}
for(int y = 0; y < linesY; y++){
}
}
}
}
| using UnityEngine;
using System.Collections;
public class GridRenderer : MonoBehaviour {
private int linesX;
private int linesY;
public void Setup(int chunksX, int chunksY, int tilesX, int tilesY) {
this.linesX = chunksX * tilesX;
this.linesY = chunksY * tilesY;
Initialize();
}
private void Initialize() {
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.