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 |
---|---|---|---|---|---|---|---|---|
c68aba4f63b23a6dfd69342732b01fa85dd2094e | Test Fix | harshjain2/cli,ravimeda/cli,svick/cli,Faizan2304/cli,blackdwarf/cli,svick/cli,blackdwarf/cli,dasMulli/cli,Faizan2304/cli,svick/cli,harshjain2/cli,dasMulli/cli,blackdwarf/cli,livarcocc/cli-1,livarcocc/cli-1,johnbeisner/cli,EdwardBlair/cli,johnbeisner/cli,EdwardBlair/cli,EdwardBlair/cli,blackdwarf/cli,Faizan2304/cli,ravimeda/cli,harshjain2/cli,johnbeisner/cli,livarcocc/cli-1,dasMulli/cli,ravimeda/cli | src/dotnet/commands/dotnet-build/Program.cs | src/dotnet/commands/dotnet-build/Program.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.MSBuild;
using System.Diagnostics;
using System;
using Microsoft.DotNet.Cli;
using Parser = Microsoft.DotNet.Cli.Parser;
namespace Microsoft.DotNet.Tools.Build
{
public class BuildCommand : MSBuildForwardingApp
{
public BuildCommand(IEnumerable<string> msbuildArgs, string msbuildPath = null)
: base(msbuildArgs, msbuildPath)
{
}
public static BuildCommand FromArgs(string[] args, string msbuildPath = null)
{
var msbuildArgs = new List<string>();
var parser = Parser.Instance;
var result = parser.ParseFrom("dotnet build", args);
Reporter.Output.WriteLine(result.Diagram());
result.ShowHelpIfRequested();
var appliedBuildOptions = result["dotnet"]["build"];
if (appliedBuildOptions.HasOption("--no-incremental"))
{
msbuildArgs.Add("/t:Rebuild");
}
else
{
msbuildArgs.Add("/t:Build");
}
msbuildArgs.AddRange(appliedBuildOptions.OptionValuesToBeForwarded());
msbuildArgs.AddRange(appliedBuildOptions.Arguments);
msbuildArgs.Add($"/clp:Summary");
return new BuildCommand(msbuildArgs, msbuildPath);
}
public static int Run(string[] args)
{
DebugHelper.HandleDebugSwitch(ref args);
BuildCommand cmd;
try
{
cmd = FromArgs(args);
}
catch (CommandCreationException e)
{
return e.ExitCode;
}
return cmd.Execute();
}
}
}
| // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.MSBuild;
using System.Diagnostics;
using System;
using Microsoft.DotNet.Cli;
using Parser = Microsoft.DotNet.Cli.Parser;
namespace Microsoft.DotNet.Tools.Build
{
public class BuildCommand : MSBuildForwardingApp
{
public BuildCommand(IEnumerable<string> msbuildArgs, string msbuildPath = null)
: base(msbuildArgs, msbuildPath)
{
}
public static BuildCommand FromArgs(string[] args, string msbuildPath = null)
{
DebugHelper.HandleDebugSwitch(ref args);
var msbuildArgs = new List<string>();
var parser = Parser.Instance;
var result = parser.ParseFrom("dotnet build", args);
Reporter.Output.WriteLine(result.Diagram());
result.ShowHelpIfRequested();
var appliedBuildOptions = result["dotnet"]["build"];
if (result.HasOption("--no-incremental"))
{
msbuildArgs.Add("/t:Rebuild");
}
else
{
msbuildArgs.Add("/t:Build");
}
msbuildArgs.AddRange(appliedBuildOptions.OptionValuesToBeForwarded());
msbuildArgs.AddRange(appliedBuildOptions.Arguments);
msbuildArgs.Add($"/clp:Summary");
return new BuildCommand(msbuildArgs, msbuildPath);
}
public static int Run(string[] args)
{
DebugHelper.HandleDebugSwitch(ref args);
BuildCommand cmd;
try
{
cmd = FromArgs(args);
}
catch (CommandCreationException e)
{
return e.ExitCode;
}
return cmd.Execute();
}
}
}
| mit | C# |
76978b58c9120a85df9b9024f108df43e24ecb6b | Adjust comment for DateTimeZoneNotFoundException | malcolmr/nodatime,nodatime/nodatime,jskeet/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,nodatime/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,jskeet/nodatime,malcolmr/nodatime | src/NodaTime/TimeZones/DateTimeZoneNotFoundException.cs | src/NodaTime/TimeZones/DateTimeZoneNotFoundException.cs | // Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NodaTime.Annotations;
namespace NodaTime.TimeZones
{
/// <summary>
/// Exception thrown when time zone is requested from an <see cref="IDateTimeZoneProvider"/>,
/// but the specified ID is invalid for that provider.
/// </summary>
/// <remarks>
/// This type originally existed as <c>TimeZoneNotFoundException</c> doesn't exist in framework versions
/// targeted by earlier versions of Noda Time. It is present now solely to avoid unnecessary
/// backward incompatibility. While it could be used to distinguish between exceptions thrown by
/// Noda Time and those thrown by <c>TimeZoneInfo</c>, we recommend that you don't use it that way.
/// </remarks>
/// <threadsafety>Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
/// See the thread safety section of the user guide for more information.
/// </threadsafety>
[Mutable] // Exception itself is mutable
public sealed class DateTimeZoneNotFoundException : TimeZoneNotFoundException
{
/// <summary>
/// Creates an instance with the given message.
/// </summary>
/// <param name="message">The message for the exception.</param>
public DateTimeZoneNotFoundException(string message) : base(message) { }
}
}
| // Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NodaTime.Annotations;
namespace NodaTime.TimeZones
{
/// <summary>
/// Exception thrown when time zone is requested from an <see cref="IDateTimeZoneProvider"/>,
/// but the specified ID is invalid for that provider.
/// </summary>
/// <remarks>
/// This type only exists as <c>TimeZoneNotFoundException</c> doesn't exist in netstandard1.x.
/// By creating an exception which derives from <c>TimeZoneNotFoundException</c> on the desktop version
/// and <c>Exception</c> on the .NET Standard 1.3 version, we achieve reasonable consistency while remaining
/// backwardly compatible with Noda Time v1 (which was desktop-only, and threw <c>TimeZoneNotFoundException</c>).
/// </remarks>
/// <threadsafety>Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
/// See the thread safety section of the user guide for more information.
/// </threadsafety>
[Mutable] // Exception itself is mutable
public sealed class DateTimeZoneNotFoundException : TimeZoneNotFoundException
{
/// <summary>
/// Creates an instance with the given message.
/// </summary>
/// <param name="message">The message for the exception.</param>
public DateTimeZoneNotFoundException(string message) : base(message) { }
}
}
| apache-2.0 | C# |
b986bc4caa9b6190e72d383d6dcac7e5f9f18bc1 | Fix compile job recursion crash | Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,tgstation/tgstation-server | src/Tgstation.Server.Host/Models/RevisionInformation.cs | src/Tgstation.Server.Host/Models/RevisionInformation.cs | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace Tgstation.Server.Host.Models
{
/// <inheritdoc />
public sealed class RevisionInformation : Api.Models.Internal.RevisionInformation, IApiConvertable<Api.Models.RevisionInformation>
{
/// <summary>
/// The row Id
/// </summary>
public long Id { get; set; }
/// <summary>
/// The <see cref="Models.Instance"/> the <see cref="RevisionInformation"/> belongs to
/// </summary>
[Required]
public Instance Instance { get; set; }
/// <summary>
/// See <see cref="Api.Models.RevisionInformation.PrimaryTestMerge"/>
/// </summary>
public TestMerge PrimaryTestMerge { get; set; }
/// <summary>
/// See <see cref="Api.Models.RevisionInformation.ActiveTestMerges"/>
/// </summary>
public List<RevInfoTestMerge> ActiveTestMerges { get; set; }
/// <summary>
/// See <see cref="CompileJob"/>s made from this <see cref="RevisionInformation"/>
/// </summary>
public List<CompileJob> CompileJobs { get; set; }
/// <inheritdoc />
public Api.Models.RevisionInformation ToApi() => new Api.Models.RevisionInformation
{
CommitSha = CommitSha,
OriginCommitSha = OriginCommitSha,
PrimaryTestMerge = PrimaryTestMerge?.ToApi(),
ActiveTestMerges = ActiveTestMerges.Select(x => x.TestMerge.ToApi()).ToList(),
CompileJobs = CompileJobs.Select(x => new Api.Models.CompileJob
{
Id = x.Id //anti recursion measure
}).ToList()
};
}
}
| using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace Tgstation.Server.Host.Models
{
/// <inheritdoc />
public sealed class RevisionInformation : Api.Models.Internal.RevisionInformation, IApiConvertable<Api.Models.RevisionInformation>
{
/// <summary>
/// The row Id
/// </summary>
public long Id { get; set; }
/// <summary>
/// The <see cref="Models.Instance"/> the <see cref="RevisionInformation"/> belongs to
/// </summary>
[Required]
public Instance Instance { get; set; }
/// <summary>
/// See <see cref="Api.Models.RevisionInformation.PrimaryTestMerge"/>
/// </summary>
public TestMerge PrimaryTestMerge { get; set; }
/// <summary>
/// See <see cref="Api.Models.RevisionInformation.ActiveTestMerges"/>
/// </summary>
public List<RevInfoTestMerge> ActiveTestMerges { get; set; }
/// <summary>
/// See <see cref="CompileJob"/>s made from this <see cref="RevisionInformation"/>
/// </summary>
public List<CompileJob> CompileJobs { get; set; }
/// <inheritdoc />
public Api.Models.RevisionInformation ToApi() => new Api.Models.RevisionInformation
{
CommitSha = CommitSha,
OriginCommitSha = OriginCommitSha,
PrimaryTestMerge = PrimaryTestMerge?.ToApi(),
ActiveTestMerges = ActiveTestMerges.Select(x => x.TestMerge.ToApi()).ToList(),
CompileJobs = CompileJobs.Select(x => x.ToApi()).ToList()
};
}
}
| agpl-3.0 | C# |
7afa7f7a50aab4ec7abc4c6710ce167ca2c51429 | Remove a test Buttom | daltonbr/TopDownShooter | Assets/Editor/MapEditor.cs | Assets/Editor/MapEditor.cs | using UnityEngine;
using UnityEditor;
[CustomEditor (typeof(MapGenerator))]
public class MapEditor : Editor {
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
// Always updating ... cpu intensive sometimes
//MapGenerator map = target as MapGenerator;
//map.GenerateMap();
// just update when some value is changed in the inspector (much more effective)
if (GUI.changed)
{
//Debug.Log("GUI changed");
MapGenerator map = target as MapGenerator;
map.GenerateMap();
}
// or update just when we press this buttom
//if (GUILayout.Button("Generate Map"))
//{
// Debug.Log("Generating map");
// MapGenerator map = target as MapGenerator;
// map.GenerateMap();
//}
}
}
| using UnityEngine;
using UnityEditor;
[CustomEditor (typeof(MapGenerator))]
public class MapEditor : Editor {
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
// Always updating ... cpu intensive sometimes
//MapGenerator map = target as MapGenerator;
//map.GenerateMap();
// just update when some value is changed in the inspector (much more effective)
if (GUI.changed)
{
//Debug.Log("GUI changed");
MapGenerator map = target as MapGenerator;
map.GenerateMap();
}
// or update just when we press this buttom
if (GUILayout.Button("Generate Map"))
{
Debug.Log("Generating map");
//MapGenerator map = target as MapGenerator;
//map.GenerateMap();
}
}
}
| mit | C# |
355928ce35bfb546b284fe0b4cd9185aa7b61fa7 | fix typo | verybadcat/CSharpMath | CSharpMath/Helpers/Pair.cs | CSharpMath/Helpers/Pair.cs | namespace CSharpMath.Helpers
{
readonly struct Pair<T, K>
{
public Pair(T first, K second)
{
First = first;
Second = second;
}
public T First { get; }
public K Second { get; }
}
static class Pair
{
public static Pair<T, K> Create<T, K>(T first, K second) => new Pair<T, K>(first, second);
}
}
| namespace CSharpMath.Helpers
{
readonly struct Pair<T, K>
{
public Pair(T first, K second)
{
First = first;
Second = second;
}
public T First { get; }
public K Second { get; }
}
abstract class Pair
{
public static Pair<T, K> Create<T, K>(T first, K second) => new Pair<T, K>(first, second);
}
}
| mit | C# |
bdbed1e6656396351b62f035c61408fd07440ab1 | Allow adminnotes to use username (#9388) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/Administration/Commands/OpenAdminNotesCommand.cs | Content.Server/Administration/Commands/OpenAdminNotesCommand.cs | using Content.Server.Administration.Notes;
using Content.Server.Database;
using Content.Shared.Administration;
using Robust.Server.Player;
using Robust.Shared.Console;
namespace Content.Server.Administration.Commands;
[AdminCommand(AdminFlags.ViewNotes)]
public sealed class OpenAdminNotesCommand : IConsoleCommand
{
public const string CommandName = "adminnotes";
public string Command => CommandName;
public string Description => "Opens the admin notes panel.";
public string Help => $"Usage: {Command} <notedPlayerUserId OR notedPlayerUsername>";
public async void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (shell.Player is not IPlayerSession player)
{
shell.WriteError("This does not work from the server console.");
return;
}
Guid notedPlayer;
switch (args.Length)
{
case 1 when Guid.TryParse(args[0], out notedPlayer):
break;
case 1:
var db = IoCManager.Resolve<IServerDbManager>();
var dbGuid = await db.GetAssignedUserIdAsync(args[0]);
if (dbGuid == null)
{
shell.WriteError($"Unable to find {args[0]} netuserid");
return;
}
notedPlayer = dbGuid.Value;
break;
default:
shell.WriteError($"Invalid arguments.\n{Help}");
return;
}
await IoCManager.Resolve<IAdminNotesManager>().OpenEui(player, notedPlayer);
}
}
| using Content.Server.Administration.Notes;
using Content.Shared.Administration;
using Robust.Server.Player;
using Robust.Shared.Console;
namespace Content.Server.Administration.Commands;
[AdminCommand(AdminFlags.ViewNotes)]
public sealed class OpenAdminNotesCommand : IConsoleCommand
{
public const string CommandName = "adminnotes";
public string Command => CommandName;
public string Description => "Opens the admin notes panel.";
public string Help => $"Usage: {Command} <notedPlayerUserId>";
public async void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (shell.Player is not IPlayerSession player)
{
shell.WriteError("This does not work from the server console.");
return;
}
Guid notedPlayer;
switch (args.Length)
{
case 1 when Guid.TryParse(args[0], out notedPlayer):
break;
default:
shell.WriteError($"Invalid arguments.\n{Help}");
return;
}
await IoCManager.Resolve<IAdminNotesManager>().OpenEui(player, notedPlayer);
}
}
| mit | C# |
8639ada4cd6e600d3508e93c4b40657ae3c23de2 | Allow spaces in !meme command. | Ervie/Homunculus | Homunculus/MarekMotykaBot/ExtensionsMethods/StringExtensions.cs | Homunculus/MarekMotykaBot/ExtensionsMethods/StringExtensions.cs | using System.Text.RegularExpressions;
namespace MarekMotykaBot.ExtensionsMethods
{
public static class StringExtensions
{
public static string RemoveRepeatingChars(this string inputString)
{
string newString = string.Empty;
char[] charArray = inputString.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
if (string.IsNullOrEmpty(newString))
newString += charArray[i].ToString();
else if (newString[newString.Length - 1] != charArray[i])
newString += charArray[i].ToString();
}
return newString;
}
public static string RemoveEmojis(this string inputString)
{
return Regex.Replace(inputString, @"[^a-zA-Z0-9\s]+", "", RegexOptions.Compiled);
}
public static string RemoveEmotes(this string inputString)
{
return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled);
}
public static string RemoveEmojisAndEmotes(this string inputString)
{
return inputString.RemoveEmotes().RemoveEmojis();
}
}
} | using System.Text.RegularExpressions;
namespace MarekMotykaBot.ExtensionsMethods
{
public static class StringExtensions
{
public static string RemoveRepeatingChars(this string inputString)
{
string newString = string.Empty;
char[] charArray = inputString.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
if (string.IsNullOrEmpty(newString))
newString += charArray[i].ToString();
else if (newString[newString.Length - 1] != charArray[i])
newString += charArray[i].ToString();
}
return newString;
}
public static string RemoveEmojis(this string inputString)
{
return Regex.Replace(inputString, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}
public static string RemoveEmotes(this string inputString)
{
return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled);
}
public static string RemoveEmojisAndEmotes(this string inputString)
{
return inputString.RemoveEmotes().RemoveEmojis();
}
}
} | mit | C# |
66749653c5cb337a76b4dec8ed160a84b341611f | Test class _PersonConversion is now marked as Explicit rather than Ignored | magenta-aps/cprbroker,OS2CPRbroker/cprbroker,magenta-aps/cprbroker,magenta-aps/cprbroker,OS2CPRbroker/cprbroker | PART/Source/CprBroker/DBR.Tests/Comparison/_PersonConversion.cs | PART/Source/CprBroker/DBR.Tests/Comparison/_PersonConversion.cs | using CprBroker.DBR;
using CprBroker.Providers.CPRDirect;
using CprBroker.Providers.DPR;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CprBroker.Tests.DBR.Comparison.Person
{
[TestFixture]
[Explicit]
public class _PersonConversion : PersonComparisonTest<object>
{
public void ConvertObject(string pnr)
{
using (var fakeDprDataContext = new DPRDataContext(Properties.Settings.Default.ImitatedDprConnectionString))
{
DatabaseLoadCache.Root.Reset(fakeDprDataContext);
CprConverter.DeletePersonRecords(pnr, fakeDprDataContext);
fakeDprDataContext.SubmitChanges();
}
using (var fakeDprDataContext = new DPRDataContext(Properties.Settings.Default.ImitatedDprConnectionString))
{
var person = ExtractManager.GetPerson(pnr);
CprConverter.AppendPerson(person, fakeDprDataContext);
fakeDprDataContext.SubmitChanges();
}
KeysHolder._ConvertedPersons[pnr] = true;
}
[Test]
[TestCaseSource(nameof(LoadKeys))]
public void T0_Convert(string key)
{
ConvertObject(key);
}
public override IQueryable<object> Get(DPRDataContext dataContext, string key)
{
return new object[] { }.AsQueryable();
}
}
}
| using CprBroker.DBR;
using CprBroker.Providers.CPRDirect;
using CprBroker.Providers.DPR;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CprBroker.Tests.DBR.Comparison.Person
{
[TestFixture]
[Ignore]
public class _PersonConversion : PersonComparisonTest<object>
{
public void ConvertObject(string pnr)
{
using (var fakeDprDataContext = new DPRDataContext(Properties.Settings.Default.ImitatedDprConnectionString))
{
DatabaseLoadCache.Root.Reset(fakeDprDataContext);
CprConverter.DeletePersonRecords(pnr, fakeDprDataContext);
fakeDprDataContext.SubmitChanges();
}
using (var fakeDprDataContext = new DPRDataContext(Properties.Settings.Default.ImitatedDprConnectionString))
{
var person = ExtractManager.GetPerson(pnr);
CprConverter.AppendPerson(person, fakeDprDataContext);
fakeDprDataContext.SubmitChanges();
}
KeysHolder._ConvertedPersons[pnr] = true;
}
[Test]
[TestCaseSource("LoadKeys")]
public void T0_Convert(string key)
{
ConvertObject(key);
}
public override IQueryable<object> Get(DPRDataContext dataContext, string key)
{
return new object[] { }.AsQueryable();
}
}
}
| mpl-2.0 | C# |
2303ed3bf7329c82b684f6d24b94596bf2131e51 | Update MessagePackDeserializer.cs | tiksn/TIKSN-Framework | TIKSN.Core/Serialization/MessagePack/MessagePackDeserializer.cs | TIKSN.Core/Serialization/MessagePack/MessagePackDeserializer.cs | using System.IO;
using MsgPack.Serialization;
namespace TIKSN.Serialization.MessagePack
{
public class MessagePackDeserializer : DeserializerBase<byte[]>
{
private readonly SerializationContext _serializationContext;
public MessagePackDeserializer(SerializationContext serializationContext) =>
this._serializationContext = serializationContext;
protected override T DeserializeInternal<T>(byte[] serial)
{
var serializer = this._serializationContext.GetSerializer<T>();
using var stream = new MemoryStream(serial);
return serializer.Unpack(stream);
}
}
}
| using System.IO;
using MsgPack.Serialization;
namespace TIKSN.Serialization.MessagePack
{
public class MessagePackDeserializer : DeserializerBase<byte[]>
{
private readonly SerializationContext _serializationContext;
public MessagePackDeserializer(SerializationContext serializationContext) =>
this._serializationContext = serializationContext;
protected override T DeserializeInternal<T>(byte[] serial)
{
var serializer = this._serializationContext.GetSerializer<T>();
using (var stream = new MemoryStream(serial))
{
return serializer.Unpack(stream);
}
}
}
}
| mit | C# |
319abc63f9861e2e392a0b984366203b06575934 | fix instance id generation | ifilipenko/Building-Blocks,ifilipenko/Building-Blocks,ifilipenko/Building-Blocks | src/BuildingBlocks.CopyManagement/SmartClientApplicationIdentity.cs | src/BuildingBlocks.CopyManagement/SmartClientApplicationIdentity.cs | using System;
namespace BuildingBlocks.CopyManagement
{
public class SmartClientApplicationIdentity : IApplicationIdentity
{
private static readonly Lazy<IApplicationIdentity> _current;
static SmartClientApplicationIdentity()
{
_current = new Lazy<IApplicationIdentity>(() => new SmartClientApplicationIdentity(), true);
}
public static IApplicationIdentity Current
{
get { return _current.Value; }
}
private static readonly Guid _instanceId = Guid.NewGuid();
private readonly string _applicationUid;
private readonly string _mashineId;
private readonly DateTime _instanceStartTime;
private SmartClientApplicationIdentity()
{
_instanceStartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime;
_applicationUid = ComputeApplicationId();
_mashineId = ComputerId.Value.ToFingerPrintMd5Hash();
}
public Guid InstanceId
{
get { return _instanceId; }
}
public string ApplicationUid
{
get { return _applicationUid; }
}
public string MashineId
{
get { return _mashineId; }
}
public DateTime InstanceStartTime
{
get { return _instanceStartTime; }
}
public string LicenceKey { get; private set; }
private static string ComputeApplicationId()
{
var exeFileName = System.Reflection.Assembly.GetEntryAssembly().Location;
var value = "EXE_PATH >> " + exeFileName + "\n" + ComputerId.Value;
return value.ToFingerPrintMd5Hash();
}
}
} | using System;
namespace BuildingBlocks.CopyManagement
{
public class SmartClientApplicationIdentity : IApplicationIdentity
{
private static readonly Lazy<IApplicationIdentity> _current;
static SmartClientApplicationIdentity()
{
_current = new Lazy<IApplicationIdentity>(() => new SmartClientApplicationIdentity(), true);
}
public static IApplicationIdentity Current
{
get { return _current.Value; }
}
private static readonly Guid _instanceId = new Guid();
private readonly string _applicationUid;
private readonly string _mashineId;
private readonly DateTime _instanceStartTime;
private SmartClientApplicationIdentity()
{
_instanceStartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime;
_applicationUid = ComputeApplicationId();
_mashineId = ComputerId.Value.ToFingerPrintMd5Hash();
}
public Guid InstanceId
{
get { return _instanceId; }
}
public string ApplicationUid
{
get { return _applicationUid; }
}
public string MashineId
{
get { return _mashineId; }
}
public DateTime InstanceStartTime
{
get { return _instanceStartTime; }
}
public string LicenceKey { get; private set; }
private static string ComputeApplicationId()
{
var exeFileName = System.Reflection.Assembly.GetEntryAssembly().Location;
var value = "EXE_PATH >> " + exeFileName + "\n" + ComputerId.Value;
return value.ToFingerPrintMd5Hash();
}
}
} | apache-2.0 | C# |
7b7ff3ab99e19c8bfd8f770c1fce7a8e64b5d661 | add missing copyright message | nunit/nunit,nunit/nunit,mjedrzejek/nunit,mjedrzejek/nunit | src/NUnitFramework/framework/Internal/Execution/IMethodValidator.cs | src/NUnitFramework/framework/Internal/Execution/IMethodValidator.cs | // ***********************************************************************
// Copyright (c) 2012-2020 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System.Reflection;
namespace NUnit.Framework.Internal.Execution
{
/// <summary>
/// Validates method to execute.
/// </summary>
public interface IMethodValidator
{
/// <summary>
/// Determines whether a method is allowed to execute and throws an exception otherwise.
/// </summary>
/// <param name="method">The method to validate.</param>
void Validate(MethodInfo method);
}
}
| using System.Reflection;
namespace NUnit.Framework.Internal.Execution
{
/// <summary>
/// Validates method to execute.
/// </summary>
public interface IMethodValidator
{
/// <summary>
/// Determines whether a method is allowed to execute and throws an exception otherwise.
/// </summary>
/// <param name="method">The method to validate.</param>
void Validate(MethodInfo method);
}
}
| mit | C# |
78da8870a296a1be854933df6ae6806f5670fd90 | Change version to a reasonable value | sbennett1990/libcmdline | libcmdline/Properties/AssemblyInfo.cs | libcmdline/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("libcmdline")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("libcmdline")]
[assembly: AssemblyCopyright("")]
[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("853c7fe9-e12b-484c-93de-3f3de6907860")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.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("libcmdline")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("libcmdline")]
[assembly: AssemblyCopyright("")]
[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("853c7fe9-e12b-484c-93de-3f3de6907860")]
// 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")]
| isc | C# |
03f033508809809188cd785aa366d2e8506ec369 | clarify the meaning of 'Port'; include link to reference material | EdVinyard/DddSandbox | DomainDrivenDesign/Port.cs | DomainDrivenDesign/Port.cs | namespace DDD
{
/// <summary>
/// <p>
/// Each Port represents a reason the Domain (application) is trying
/// to talk with the outside world. That is, a Service that is
/// implemented outside the Domain. Examples include a clock, a
/// geocoding web service, and a database-backed Repository
/// implementation.
/// </p>
/// <p>
/// For further reading, start at http://wiki.c2.com/?PortsAndAdaptersArchitecture
/// </p>
/// </summary>
public interface Port : Service
{
}
}
| namespace DDD
{
/// <summary>
/// A Port is a Service that is implemented outside the Domain.
/// Examples include a clock, an outside web service, and a Repository.
/// </summary>
public interface Port : Service
{
}
}
| mit | C# |
9017fc6adbc37d0fa0457e60d5975ac6674ac882 | check note | linfx/LinFx,linfx/LinFx | src/LinFx/Check.cs | src/LinFx/Check.cs | using LinFx.Extensions;
using System;
using System.Collections.Generic;
namespace LinFx
{
/// <summary>
/// 检查
/// </summary>
public static class Check
{
public static T NotNull<T>(T value, string paramName)
{
if (value == null)
throw new ArgumentNullException(paramName);
return value;
}
public static ICollection<T> NotNullOrEmpty<T>(ICollection<T> value, string parameterName)
{
if (value.IsNullOrEmpty())
throw new ArgumentException(parameterName + " can not be null or empty!", parameterName);
return value;
}
}
}
| using LinFx.Extensions;
using System;
using System.Collections.Generic;
namespace LinFx
{
public static class Check
{
public static T NotNull<T>(T value, string paramName)
{
if (value == null)
throw new ArgumentNullException(paramName);
return value;
}
public static ICollection<T> NotNullOrEmpty<T>(ICollection<T> value, string parameterName)
{
if (value.IsNullOrEmpty())
throw new ArgumentException(parameterName + " can not be null or empty!", parameterName);
return value;
}
}
}
| mit | C# |
e755dadbc86e7c3a902534ba57196002f890d287 | fix unit test | loresoft/KickStart | test/KickStart.AutoMapper.Tests/AutoMapperKickerTest.cs | test/KickStart.AutoMapper.Tests/AutoMapperKickerTest.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using FluentAssertions;
using Test.Core;
using Xunit;
using Xunit.Abstractions;
namespace KickStart.AutoMapper.Tests
{
public class AutoMapperKickerTest
{
private readonly ITestOutputHelper _output;
public AutoMapperKickerTest(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void ConfigureBasic()
{
Mapper.Reset();
Kick.Start(config => config
.LogTo(_output.WriteLine)
.IncludeAssemblyFor<UserProfile>()
.UseAutoMapper()
);
var employee = new Employee
{
FirstName = "Test",
LastName = "User",
EmailAddress = "[email protected]",
SysVersion = BitConverter.GetBytes(8)
};
var user = Mapper.Map<User>(employee);
user.Should().NotBeNull();
user.EmailAddress.Should().Be(employee.EmailAddress);
user.SysVersion.Should().NotBeNull();
}
[Fact]
public void ConfigureFull()
{
Mapper.Reset();
Kick.Start(config => config
.LogTo(_output.WriteLine)
.IncludeAssemblyFor<UserProfile>()
.UseAutoMapper(c => c
.Validate()
)
);
var employee = new Employee
{
FirstName = "Test",
LastName = "User",
EmailAddress = "[email protected]",
SysVersion = BitConverter.GetBytes(8)
};
var user = Mapper.Map<User>(employee);
user.Should().NotBeNull();
user.EmailAddress.Should().Be(employee.EmailAddress);
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using FluentAssertions;
using Test.Core;
using Xunit;
using Xunit.Abstractions;
namespace KickStart.AutoMapper.Tests
{
public class AutoMapperKickerTest
{
private readonly ITestOutputHelper _output;
public AutoMapperKickerTest(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void ConfigureBasic()
{
Kick.Start(config => config
.LogTo(_output.WriteLine)
.IncludeAssemblyFor<UserProfile>()
.UseAutoMapper()
);
var employee = new Employee
{
FirstName = "Test",
LastName = "User",
EmailAddress = "[email protected]",
SysVersion = BitConverter.GetBytes(8)
};
var user = Mapper.Map<User>(employee);
user.Should().NotBeNull();
user.EmailAddress.Should().Be(employee.EmailAddress);
user.SysVersion.Should().NotBeNull();
}
[Fact]
public void ConfigureFull()
{
Kick.Start(config => config
.LogTo(_output.WriteLine)
.IncludeAssemblyFor<UserProfile>()
.UseAutoMapper(c => c
.Validate()
)
);
var employee = new Employee
{
FirstName = "Test",
LastName = "User",
EmailAddress = "[email protected]",
SysVersion = BitConverter.GetBytes(8)
};
var user = Mapper.Map<User>(employee);
user.Should().NotBeNull();
user.EmailAddress.Should().Be(employee.EmailAddress);
}
}
}
| mit | C# |
58b988df14f41d345bbd61a3d464b89e661b2b1b | Add call to exception logger | tuyndv/IdentityServer3,tonyeung/IdentityServer3,delRyan/IdentityServer3,Agrando/IdentityServer3,remunda/IdentityServer3,buddhike/IdentityServer3,IdentityServer/IdentityServer3,tuyndv/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,paulofoliveira/IdentityServer3,wondertrap/IdentityServer3,bestwpw/IdentityServer3,jonathankarsh/IdentityServer3,SonOfSam/IdentityServer3,remunda/IdentityServer3,chicoribas/IdentityServer3,buddhike/IdentityServer3,codeice/IdentityServer3,delloncba/IdentityServer3,jonathankarsh/IdentityServer3,tbitowner/IdentityServer3,openbizgit/IdentityServer3,angelapper/IdentityServer3,18098924759/IdentityServer3,wondertrap/IdentityServer3,SonOfSam/IdentityServer3,iamkoch/IdentityServer3,remunda/IdentityServer3,uoko-J-Go/IdentityServer,bodell/IdentityServer3,uoko-J-Go/IdentityServer,IdentityServer/IdentityServer3,18098924759/IdentityServer3,faithword/IdentityServer3,wondertrap/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,roflkins/IdentityServer3,mvalipour/IdentityServer3,olohmann/IdentityServer3,faithword/IdentityServer3,openbizgit/IdentityServer3,jackswei/IdentityServer3,olohmann/IdentityServer3,roflkins/IdentityServer3,bodell/IdentityServer3,tbitowner/IdentityServer3,charoco/IdentityServer3,kouweizhong/IdentityServer3,iamkoch/IdentityServer3,mvalipour/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,paulofoliveira/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,ryanvgates/IdentityServer3,angelapper/IdentityServer3,yanjustino/IdentityServer3,Agrando/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,bestwpw/IdentityServer3,openbizgit/IdentityServer3,paulofoliveira/IdentityServer3,yanjustino/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,jackswei/IdentityServer3,Agrando/IdentityServer3,faithword/IdentityServer3,jonathankarsh/IdentityServer3,ryanvgates/IdentityServer3,ryanvgates/IdentityServer3,delRyan/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,codeice/IdentityServer3,18098924759/IdentityServer3,EternalXw/IdentityServer3,olohmann/IdentityServer3,charoco/IdentityServer3,delloncba/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,bestwpw/IdentityServer3,tuyndv/IdentityServer3,tonyeung/IdentityServer3,EternalXw/IdentityServer3,kouweizhong/IdentityServer3,charoco/IdentityServer3,IdentityServer/IdentityServer3,buddhike/IdentityServer3,kouweizhong/IdentityServer3,bodell/IdentityServer3,jackswei/IdentityServer3,tbitowner/IdentityServer3,mvalipour/IdentityServer3,delRyan/IdentityServer3,chicoribas/IdentityServer3,chicoribas/IdentityServer3,tonyeung/IdentityServer3,roflkins/IdentityServer3,iamkoch/IdentityServer3,delloncba/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,angelapper/IdentityServer3,yanjustino/IdentityServer3,uoko-J-Go/IdentityServer,SonOfSam/IdentityServer3,EternalXw/IdentityServer3,codeice/IdentityServer3 | source/Core/Hosting/ErrorPageFilterAttribute.cs | source/Core/Hosting/ErrorPageFilterAttribute.cs | /*
* Copyright 2014 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Autofac;
using System.Net.Http;
using System.Web.Http.Filters;
using Thinktecture.IdentityServer.Core.Configuration;
using Thinktecture.IdentityServer.Core.Extensions;
using Thinktecture.IdentityServer.Core.Logging;
using Thinktecture.IdentityServer.Core.Services;
using Thinktecture.IdentityServer.Core.Views;
namespace Thinktecture.IdentityServer.Core.Hosting
{
class ErrorPageFilterAttribute : ExceptionFilterAttribute
{
private readonly static ILog Logger = LogProvider.GetCurrentClassLogger();
public override async System.Threading.Tasks.Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, System.Threading.CancellationToken cancellationToken)
{
Logger.ErrorException("Exception accessing: " + actionExecutedContext.Request.RequestUri.AbsolutePath, actionExecutedContext.Exception);
var env = actionExecutedContext.ActionContext.Request.GetOwinEnvironment();
var scope = env.GetLifetimeScope();
var options = (IdentityServerOptions)scope.ResolveOptional(typeof(IdentityServerOptions));
var viewSvc = (IViewService)scope.ResolveOptional(typeof(IViewService));
var errorModel = new ErrorViewModel
{
SiteName = options.SiteName,
SiteUrl = env.GetIdentityServerBaseUrl(),
ErrorMessage = Resources.Messages.UnexpectedError,
};
var errorResult = new ErrorActionResult(viewSvc, env, errorModel);
actionExecutedContext.Response = await errorResult.GetResponseMessage();
}
}
} | /*
* Copyright 2014 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Autofac;
using System.Net.Http;
using System.Web.Http.Filters;
using Thinktecture.IdentityServer.Core.Configuration;
using Thinktecture.IdentityServer.Core.Extensions;
using Thinktecture.IdentityServer.Core.Services;
using Thinktecture.IdentityServer.Core.Views;
namespace Thinktecture.IdentityServer.Core.Hosting
{
class ErrorPageFilterAttribute : ExceptionFilterAttribute
{
public override async System.Threading.Tasks.Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, System.Threading.CancellationToken cancellationToken)
{
var env = actionExecutedContext.ActionContext.Request.GetOwinEnvironment();
var scope = env.GetLifetimeScope();
var options = (IdentityServerOptions)scope.ResolveOptional(typeof(IdentityServerOptions));
var viewSvc = (IViewService)scope.ResolveOptional(typeof(IViewService));
var errorModel = new ErrorViewModel
{
SiteName = options.SiteName,
SiteUrl = env.GetIdentityServerBaseUrl(),
ErrorMessage = Resources.Messages.UnexpectedError,
};
var errorResult = new ErrorActionResult(viewSvc, env, errorModel);
actionExecutedContext.Response = await errorResult.GetResponseMessage();
}
}
} | apache-2.0 | C# |
c06fee285a34e0fc769051f64215984eb950d1c0 | Allow multiple response examples | martincostello/api,martincostello/api,martincostello/api | src/API/Swagger/SwaggerResponseExampleAttribute.cs | src/API/Swagger/SwaggerResponseExampleAttribute.cs | // Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the MIT license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.Api.Swagger
{
using System;
/// <summary>
/// Defines an example response for an API method. This class cannot be inherited.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
internal sealed class SwaggerResponseExampleAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="SwaggerResponseExampleAttribute"/> class.
/// </summary>
/// <param name="responseType">The type of the response.</param>
/// <param name="exampleType">The type of the example.</param>
public SwaggerResponseExampleAttribute(Type responseType, Type exampleType)
{
ResponseType = responseType;
ExampleType = exampleType;
}
/// <summary>
/// Gets the type of the response.
/// </summary>
public Type ResponseType { get; }
/// <summary>
/// Gets the type of the example.
/// </summary>
public Type ExampleType { get; }
}
}
| // Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the MIT license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.Api.Swagger
{
using System;
/// <summary>
/// Defines an example response for an API method. This class cannot be inherited.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
internal sealed class SwaggerResponseExampleAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="SwaggerResponseExampleAttribute"/> class.
/// </summary>
/// <param name="responseType">The type of the response.</param>
/// <param name="exampleType">The type of the example.</param>
public SwaggerResponseExampleAttribute(Type responseType, Type exampleType)
{
ResponseType = responseType;
ExampleType = exampleType;
}
/// <summary>
/// Gets the type of the response.
/// </summary>
public Type ResponseType { get; }
/// <summary>
/// Gets the type of the example.
/// </summary>
public Type ExampleType { get; }
}
}
| mit | C# |
03f2c80a8eccacca7b43dec769e55d2e76dd6736 | Improve event skipper | JeremyAnsel/helix-toolkit,chrkon/helix-toolkit,holance/helix-toolkit,helix-toolkit/helix-toolkit,Iluvatar82/helix-toolkit,smischke/helix-toolkit | Source/HelixToolkit.Wpf.SharpDX/Helpers/EventSkipper.cs | Source/HelixToolkit.Wpf.SharpDX/Helpers/EventSkipper.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelixToolkit.Wpf.SharpDX.Helpers
{
/// <summary>
/// Use to skip event if event frequency is too high.
/// </summary>
public sealed class EventSkipper
{
/// <summary>
/// Stopwatch
/// </summary>
private static readonly Stopwatch watch = new Stopwatch();
private long lag = 0;
/// <summary>
///
/// </summary>
static EventSkipper()
{
watch.Start();
}
/// <summary>
/// The threshold used to skip if previous event happened less than the threshold.
/// </summary>
public long Threshold = 15;
/// <summary>
/// Previous event happened.
/// </summary>
private long previous = 0;
/// <summary>
/// Determine if this event should be skipped.
/// </summary>
/// <returns>If skip, return true. Otherwise, return false.</returns>
public bool IsSkip()
{
var curr = watch.ElapsedMilliseconds;
var elpased = curr - previous;
previous = curr;
lag += elpased;
if (lag < Threshold)
{
return true;
}
else
{
lag -= Threshold;
return false;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelixToolkit.Wpf.SharpDX.Helpers
{
/// <summary>
/// Use to skip event if event frequency is too high.
/// </summary>
public sealed class EventSkipper
{
/// <summary>
/// Stopwatch
/// </summary>
private static readonly Stopwatch watch = new Stopwatch();
/// <summary>
///
/// </summary>
static EventSkipper()
{
watch.Start();
}
/// <summary>
/// The threshold used to skip if previous event happened less than the threshold.
/// </summary>
public long Threshold = 15;
/// <summary>
/// Previous event happened.
/// </summary>
private long previous = 0;
/// <summary>
/// Determine if this event should be skipped.
/// </summary>
/// <returns>If skip, return true. Otherwise, return false.</returns>
public bool IsSkip()
{
if (watch.ElapsedMilliseconds - previous < Threshold)
{
return true;
}
else
{
previous = watch.ElapsedMilliseconds;
return false;
}
}
}
}
| mit | C# |
7507314e0dd5f122a49a3dca3adcaf0bdfa9ffae | Fix a bug where dates are sometimes '-' | Genbox/VirusTotal.NET | VirusTotal.NET/DateTimeParsers/YearMonthDayConverter.cs | VirusTotal.NET/DateTimeParsers/YearMonthDayConverter.cs | using System;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using VirusTotalNET.Exceptions;
namespace VirusTotalNET.DateTimeParsers
{
public class YearMonthDayConverter : DateTimeConverterBase
{
private readonly CultureInfo _culture = new CultureInfo("en-us");
private const string _dateFormatString = "yyyyMMdd";
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.DateFormatString = _dateFormatString;
writer.WriteValue(value);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
return DateTime.MinValue;
if (!(reader.Value is string))
throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + reader.Value);
string value = (string)reader.Value;
//VT sometimes have really old data that return '-' in timestamps
if (value.Equals("-", StringComparison.OrdinalIgnoreCase))
return DateTime.MinValue;
if (DateTime.TryParseExact(value, _dateFormatString, _culture, DateTimeStyles.AllowWhiteSpaces, out DateTime result))
return result;
throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + value);
}
}
} | using System;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using VirusTotalNET.Exceptions;
namespace VirusTotalNET.DateTimeParsers
{
public class YearMonthDayConverter : DateTimeConverterBase
{
private readonly CultureInfo _culture = new CultureInfo("en-us");
private const string _dateFormatString = "yyyyMMdd";
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.DateFormatString = _dateFormatString;
writer.WriteValue(value);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null)
return DateTime.MinValue;
if (!(reader.Value is string))
throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + reader.Value);
string value = (string)reader.Value;
if (DateTime.TryParseExact(value, _dateFormatString, _culture, DateTimeStyles.AllowWhiteSpaces, out DateTime result))
return result;
throw new InvalidDateTimeException("Invalid date/time from VirusTotal. Tried to parse: " + value);
}
}
} | apache-2.0 | C# |
c69e88eb97b90c73b3e2dcd2bebe18c8aa4b8540 | Add more types to dropdown | johnneijzen/osu,smoogipooo/osu,NeoAdonis/osu,NeoAdonis/osu,EVAST9919/osu,2yangk23/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,ppy/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,2yangk23/osu,johnneijzen/osu,peppy/osu | osu.Game/Configuration/ScoreMeterType.cs | osu.Game/Configuration/ScoreMeterType.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
namespace osu.Game.Configuration
{
public enum ScoreMeterType
{
[Description("None")]
None,
[Description("Hit Error (left)")]
HitErrorLeft,
[Description("Hit Error (right)")]
HitErrorRight,
[Description("Hit Error (both)")]
HitErrorBoth,
[Description("Colour (left)")]
ColourLeft,
[Description("Colour (right)")]
ColourRight,
[Description("Colour (both)")]
ColourBoth,
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
namespace osu.Game.Configuration
{
public enum ScoreMeterType
{
[Description("None")]
None,
[Description("Hit Error (left)")]
HitErrorLeft,
[Description("Hit Error (right)")]
HitErrorRight,
[Description("Hit Error (both)")]
HitErrorBoth,
}
}
| mit | C# |
4e74b085098f7249852de8358d3e73be1f91616c | Add new refund list request without paymentId parameter | Viincenttt/MollieApi,Viincenttt/MollieApi | Mollie.Api/Client/RefundClient.cs | Mollie.Api/Client/RefundClient.cs | using System.Net.Http;
using System.Threading.Tasks;
using Mollie.Api.Client.Abstract;
using Mollie.Api.Models.List;
using Mollie.Api.Models.Refund;
using Mollie.Api.Models.Url;
namespace Mollie.Api.Client {
public class RefundClient : BaseMollieClient, IRefundClient {
public RefundClient(string apiKey, HttpClient httpClient = null) : base(apiKey, httpClient) {
}
public async Task<RefundResponse> CreateRefundAsync(string paymentId, RefundRequest refundRequest) {
return await this.PostAsync<RefundResponse>($"payments/{paymentId}/refunds", refundRequest)
.ConfigureAwait(false);
}
public async Task<ListResponse<RefundResponse>> GetRefundListAsync(string from = null, int? limit = null) {
return await this.GetListAsync<ListResponse<RefundResponse>>($"refunds", from, limit)
.ConfigureAwait(false);
}
public async Task<ListResponse<RefundResponse>> GetRefundListAsync(string paymentId, string from = null, int? limit = null) {
return await this.GetListAsync<ListResponse<RefundResponse>>($"payments/{paymentId}/refunds", from, limit)
.ConfigureAwait(false);
}
public async Task<RefundResponse> GetRefundAsync(UrlObjectLink<RefundResponse> url) {
return await this.GetAsync(url).ConfigureAwait(false);
}
public async Task<RefundResponse> GetRefundAsync(string paymentId, string refundId) {
return await this.GetAsync<RefundResponse>($"payments/{paymentId}/refunds/{refundId}")
.ConfigureAwait(false);
}
public async Task CancelRefundAsync(string paymentId, string refundId) {
await this.DeleteAsync($"payments/{paymentId}/refunds/{refundId}").ConfigureAwait(false);
}
}
} | using System.Net.Http;
using System.Threading.Tasks;
using Mollie.Api.Client.Abstract;
using Mollie.Api.Models.List;
using Mollie.Api.Models.Refund;
using Mollie.Api.Models.Url;
namespace Mollie.Api.Client {
public class RefundClient : BaseMollieClient, IRefundClient {
public RefundClient(string apiKey, HttpClient httpClient = null) : base(apiKey, httpClient) {
}
public async Task<RefundResponse> CreateRefundAsync(string paymentId, RefundRequest refundRequest) {
return await this.PostAsync<RefundResponse>($"payments/{paymentId}/refunds", refundRequest)
.ConfigureAwait(false);
}
public async Task<ListResponse<RefundResponse>> GetRefundListAsync(string paymentId, string from = null, int? limit = null) {
return await this.GetListAsync<ListResponse<RefundResponse>>($"payments/{paymentId}/refunds", from, limit)
.ConfigureAwait(false);
}
public async Task<RefundResponse> GetRefundAsync(UrlObjectLink<RefundResponse> url) {
return await this.GetAsync(url).ConfigureAwait(false);
}
public async Task<RefundResponse> GetRefundAsync(string paymentId, string refundId) {
return await this.GetAsync<RefundResponse>($"payments/{paymentId}/refunds/{refundId}")
.ConfigureAwait(false);
}
public async Task CancelRefundAsync(string paymentId, string refundId) {
await this.DeleteAsync($"payments/{paymentId}/refunds/{refundId}").ConfigureAwait(false);
}
}
} | mit | C# |
772a308b8d1587ab724ec9436ef6ee490d4f6fec | Add missing XML comments. | andyfmiller/LtiLibrary | src/LtiLibrary.NetCore/OAuth/SignatureMethod.cs | src/LtiLibrary.NetCore/OAuth/SignatureMethod.cs | namespace LtiLibrary.NetCore.OAuth
{
/// <summary>
/// LTI signature methods for computing hashes.
/// </summary>
public enum SignatureMethod
{
/// <summary>
/// Computes the <see cref="System.Security.Cryptography.SHA1"/> hash for the input data.
/// This is the default for LTI 1.1.
/// </summary>
HmacSha1,
/// <summary>
/// Computes the <see cref="System.Security.Cryptography.SHA256"/> hash for the input data.
/// </summary>
HmacSha256,
/// <summary>
/// Computes the <see cref="System.Security.Cryptography.SHA384"/> hash for the input data.
/// </summary>
HmacSha384,
/// <summary>
/// Computes the <see cref="System.Security.Cryptography.SHA512"/> hash for the input data.
/// </summary>
HmacSha512,
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace LtiLibrary.NetCore.OAuth
{
public enum SignatureMethod
{
HmacSha1,
HmacSha256,
HmacSha384,
HmacSha512,
}
}
| apache-2.0 | C# |
355dc6a634c421bdf14e8b7cbbf39a226b3d56ac | Implement compare/equality methods on UInt24 | OpensourceScape/RsCacheLibrary | src/Runescape.Cache.Structures/Common/UInt24.cs | src/Runescape.Cache.Structures/Common/UInt24.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using FreecraftCore.Serializer;
using JetBrains.Annotations;
namespace Runescape.Cache.Structures.Common
{
//Based on: https://stackoverflow.com/questions/12549197/are-there-any-int24-implementations-in-c
/// <summary>
/// An unsigned 24bit integer.
/// </summary>
[WireDataContract]
public class UInt24 : IComparable, IComparable<UInt24>, IEquatable<UInt24>
{
/// <summary>
/// Internal byte representation.
/// </summary>
[KnownSize(3)]
[WireMember(1)]
private byte[] intBytes { get; }
/// <summary>
/// <see cref="uint"/> converted value.
/// </summary>
public uint Value => (uint)(intBytes[0] | (intBytes[1] << 8) | (intBytes[2] << 16));
public UInt24(UInt32 value)
{
//Should be 3 bytes long
intBytes = new byte[3];
intBytes[0] = (byte)(value & 0xFF);
intBytes[1] = (byte)(value >> 8);
intBytes[2] = (byte)(value >> 16);
}
public UInt24(byte[] bytes)
{
if (bytes == null) throw new ArgumentNullException(nameof(bytes));
if (bytes.Length < 3) throw new ArgumentException($"Provided argument {nameof(bytes)} must be of at least size 3. Is size {bytes.Length}.", nameof(bytes));
intBytes = bytes.Length == 3 ? bytes.ToArray() : bytes.Take(3).ToArray();
}
/// <summary>
/// Protected serializer ctor.
/// </summary>
protected UInt24()
{
}
public static bool operator ==(UInt24 one, UInt24 two)
{
if (one == null)
return two == null;
if (two == null)
return false;
return one.Equals(two);
}
public static bool operator !=(UInt24 one, UInt24 two)
{
return !(one == two);
}
/// <inheritdoc />
public int CompareTo(object obj)
{
UInt24 castedObj = obj as UInt24;
if (castedObj == null)
return -1;
return CompareTo(castedObj);
}
/// <inheritdoc />
public int CompareTo(UInt24 other)
{
if (other == null)
return -1;
return Value.CompareTo(other.Value);
}
/// <inheritdoc />
public bool Equals(UInt24 other)
{
if (other == null)
return false;
return other.Value == Value;
}
/// <inheritdoc />
public override bool Equals(object obj)
{
return Equals(obj as UInt24);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using FreecraftCore.Serializer;
using JetBrains.Annotations;
namespace Runescape.Cache.Structures.Common
{
//Based on: https://stackoverflow.com/questions/12549197/are-there-any-int24-implementations-in-c
/// <summary>
/// An unsigned 24bit integer.
/// </summary>
[WireDataContract]
public class UInt24
{
/// <summary>
/// Internal byte representation.
/// </summary>
[KnownSize(3)]
[WireMember(1)]
private byte[] intBytes { get; }
/// <summary>
/// <see cref="uint"/> converted value.
/// </summary>
public uint Value => (uint)(intBytes[0] | (intBytes[1] << 8) | (intBytes[2] << 16));
public UInt24(UInt32 value)
{
//Should be 3 bytes long
intBytes = new byte[3];
intBytes[0] = (byte)(value & 0xFF);
intBytes[1] = (byte)(value >> 8);
intBytes[2] = (byte)(value >> 16);
}
public UInt24(byte[] bytes)
{
if (bytes == null) throw new ArgumentNullException(nameof(bytes));
if (bytes.Length < 3) throw new ArgumentException($"Provided argument {nameof(bytes)} must be of at least size 3. Is size {bytes.Length}.", nameof(bytes));
intBytes = bytes.Length == 3 ? bytes.ToArray() : bytes.Take(3).ToArray();
}
/// <summary>
/// Protected serializer ctor.
/// </summary>
protected UInt24()
{
}
}
}
| mit | C# |
c1fcedc7052e4a09950434a3941e61840e2af249 | fix build | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | src/WeihanLi.Common/Extensions/CronExtension.cs | src/WeihanLi.Common/Extensions/CronExtension.cs | using System;
using System.Collections.Generic;
using WeihanLi.Common.Helpers.Cron;
// ReSharper disable once CheckNamespace
namespace WeihanLi.Extensions
{
public static class CronExtension
{
/// <summary>
/// GetNextOccurrence
/// </summary>
/// <param name="expression">cron expression</param>
/// <returns>next occurrence time</returns>
public static DateTimeOffset? GetNextOccurrence(this CronExpression expression)
{
return expression?.GetNextOccurrence(DateTimeOffset.UtcNow, TimeZoneInfo.Utc);
}
/// <summary>
/// GetNextOccurrence
/// </summary>
/// <param name="expression">cron expression</param>
/// <param name="timeZoneInfo">timeZoneInfo</param>
/// <returns>next occurrence time</returns>
public static DateTimeOffset? GetNextOccurrence(this CronExpression expression, TimeZoneInfo timeZoneInfo)
{
return expression.GetNextOccurrence(DateTimeOffset.UtcNow, timeZoneInfo);
}
/// <summary>
/// GetNextOccurrence
/// </summary>
/// <param name="expression">cron expression</param>
/// <param name="period">next period</param>
/// <returns>next occurrence times</returns>
public static IEnumerable<DateTimeOffset> GetNextOccurrences(this CronExpression expression, TimeSpan period)
{
var utcNow = DateTime.UtcNow;
return expression?.GetOccurrences(utcNow, utcNow.Add(period), TimeZoneInfo.Utc);
}
/// <summary>
/// GetNextOccurrence
/// </summary>
/// <param name="expression">cron expression</param>
/// <param name="period">next period</param>
/// <param name="timeZoneInfo">timeZoneInfo</param>
/// <returns>next occurrence times</returns>
public static IEnumerable<DateTimeOffset> GetNextOccurrences(this CronExpression expression, TimeSpan period, TimeZoneInfo timeZoneInfo)
{
var utcNow = DateTime.UtcNow;
return expression.GetOccurrences(utcNow, utcNow.Add(period), timeZoneInfo);
}
}
}
| using System;
using System.Collections.Generic;
using WeihanLi.Common.Helpers.Cron;
// ReSharper disable once CheckNamespace
namespace WeihanLi.Extensions
{
public static class CronExtension
{
/// <summary>
/// GetNextOccurrence
/// </summary>
/// <param name="expression">cron expression</param>
/// <returns>next occurrence time</returns>
public static DateTimeOffset? GetNextOccurrence(this CronExpression expression)
{
return expression?.GetNextOccurrence(DateTimeOffset.UtcNow, TimeZoneInfo.Utc);
}
/// <summary>
/// GetNextOccurrence
/// </summary>
/// <param name="expression">cron expression</param>
/// <param name="timeZoneInfo">timeZoneInfo</param>
/// <returns>next occurrence time</returns>
public static DateTimeOffset? GetNextOccurrence(this CronExpression expression, TimeZoneInfo timeZoneInfo)
{
return expression.GetNextOccurrence(DateTimeOffset.UtcNow, timeZoneInfo);
}
/// <summary>
/// GetNextOccurrence
/// </summary>
/// <param name="expression">cron expression</param>
/// <param name="period">next period</param>
/// <returns>next occurrence times</returns>
public static IEnumerable<DateTimeOffset> GetNextOccurrences(this CronExpression expression, TimeSpan period)
{
return expression?.GetOccurrences(DateTime.UtcNow, fromUtc.Add(period), TimeZoneInfo.Utc);
}
/// <summary>
/// GetNextOccurrence
/// </summary>
/// <param name="expression">cron expression</param>
/// <param name="period">next period</param>
/// <param name="timeZoneInfo">timeZoneInfo</param>
/// <returns>next occurrence times</returns>
public static IEnumerable<DateTimeOffset> GetNextOccurrences(this CronExpression expression, TimeSpan period, TimeZoneInfo timeZoneInfo)
{
return expression.GetOccurrences(DateTime.UtcNow, fromUtc.Add(period), timeZoneInfo);
}
}
}
| mit | C# |
46ffed8f89aac522df2dcf9d8ee7db433ab7e439 | Fix nullref if no title is given | denxorz/HotChocolatey | HotChocolatey/Logic/ChocoItem.cs | HotChocolatey/Logic/ChocoItem.cs | using NuGet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
namespace HotChocolatey.Logic
{
[UI.Magic]
public class ChocoItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public IPackage Package { get; }
public string Name => Package.Id;
public SemanticVersion InstalledVersion { get; private set; }
public SemanticVersion LatestVersion { get; private set; }
public bool IsUpgradable { get; private set; }
public List<SemanticVersion> Versions { get; set; }
public List<IAction> Actions { get; set; }
public string Title => string.IsNullOrWhiteSpace(Package.Title) ? Package.Id : Package.Title;
public Uri Ico => Package.IconUrl == null || Path.GetExtension(Package.IconUrl.ToString()) == ".svg" ? noIconUri : Package.IconUrl;
public bool IsPreRelease => !Package.IsReleaseVersion();
public string Summary => Package.Summary;
public string Description => Package.Description;
public string Authors => Package.Authors.Aggregate((total, next) => total + ", " + next);
public string LicenseUrl => Package.LicenseUrl?.ToString();
public int DownloadCount => Package.DownloadCount;
public string ProjectUrl => Package.ProjectUrl?.ToString();
public string Tags => Package.Tags;
public string Dependencies => string.Empty; // TODO
public bool IsInstalled => InstalledVersion != null;
private readonly Uri noIconUri = new Uri("/HotChocolatey;component/Images/chocolateyicon.gif", UriKind.Relative);
public ChocoItem(IPackage package)
{
Package = package;
}
public ChocoItem(IPackage package, SemanticVersion installedVersion, SemanticVersion latestVersion)
: this(package)
{
InstalledVersion = installedVersion;
LatestVersion = latestVersion;
IsUpgradable = installedVersion != latestVersion;
}
private void RaisePropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
| using NuGet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
namespace HotChocolatey.Logic
{
[UI.Magic]
public class ChocoItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public IPackage Package { get; }
public string Name => Package.Id;
public SemanticVersion InstalledVersion { get; private set; }
public SemanticVersion LatestVersion { get; private set; }
public bool IsUpgradable { get; private set; }
public List<SemanticVersion> Versions { get; set; }
public List<IAction> Actions { get; set; }
public string Title => Package.Title;
public Uri Ico => Package.IconUrl == null || Path.GetExtension(Package.IconUrl.ToString()) == ".svg" ? noIconUri : Package.IconUrl;
public bool IsPreRelease => !Package.IsReleaseVersion();
public string Summary => Package.Summary;
public string Description => Package.Description;
public string Authors => Package.Authors.Aggregate((total, next) => total + ", " + next);
public string LicenseUrl => Package.LicenseUrl?.ToString();
public int DownloadCount => Package.DownloadCount;
public string ProjectUrl => Package.ProjectUrl?.ToString();
public string Tags => Package.Tags;
public string Dependencies => string.Empty; // TODO
public bool IsInstalled => InstalledVersion != null;
private readonly Uri noIconUri = new Uri("/HotChocolatey;component/Images/chocolateyicon.gif", UriKind.Relative);
public ChocoItem(IPackage package)
{
Package = package;
}
public ChocoItem(IPackage package, SemanticVersion installedVersion, SemanticVersion latestVersion)
: this(package)
{
InstalledVersion = installedVersion;
LatestVersion = latestVersion;
IsUpgradable = installedVersion != latestVersion;
}
private void RaisePropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
| mit | C# |
bef6e4c80e6c81b50343b7b2f0f8ce97219ccbcf | Add min-max RNG. | SaxxonPike/NextLevelSeven | NextLevelSeven.Test/Randomized.cs | NextLevelSeven.Test/Randomized.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NextLevelSeven.Test
{
static public class Randomized
{
private static readonly Random Rng = new Random();
static public int Number()
{
return Rng.Next(int.MaxValue);
}
static public int Number(int maxExclusiveValue)
{
return Rng.Next(maxExclusiveValue);
}
static public int Number(int minInclusiveValue, int maxExclusiveValue)
{
return Rng.Next(minInclusiveValue, maxExclusiveValue);
}
static public string String()
{
return Guid.NewGuid().ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NextLevelSeven.Test
{
static public class Randomized
{
private static readonly Random Rng = new Random();
static public int Number()
{
return Rng.Next(int.MaxValue);
}
static public int Number(int maxExclusiveValue)
{
return Rng.Next(maxExclusiveValue);
}
static public string String()
{
return Guid.NewGuid().ToString();
}
}
}
| isc | C# |
05dee98c829a0c0ad31fa862cba833584ed719a2 | Solve Spider warnings | NitorInc/NitoriWare,uulltt/NitoriWare,Barleytree/NitoriWare,plrusek/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare | Assets/Resources/Microgames/Spider/Scripts/SpiderFood.cs | Assets/Resources/Microgames/Spider/Scripts/SpiderFood.cs | using UnityEngine;
using System.Collections;
public class SpiderFood : MonoBehaviour
{
public float grabRadius;
public float initialScale;
public bool grabbed, eaten;
public float particleRate;
public float y;
private SpriteRenderer spriteRenderer;
private ParticleSystem particles;
void Awake ()
{
particles = GetComponent<ParticleSystem>();
particleRate = ParticleHelper.getEmissionRate(particles);
spriteRenderer = GetComponent<SpriteRenderer>();
ParticleHelper.setEmissionRate(particles, 0f);
}
void Update ()
{
Vector3 cursorPosition = CameraHelper.getCursorPosition();
if (!eaten)
{
spriteRenderer.color = Color.white;
if (!grabbed)
{
float distance = ((Vector2)(transform.position - cursorPosition)).magnitude;
if (distance <= grabRadius && Input.GetMouseButtonDown(0))
grabbed = true;
float scale = (1f + (Mathf.Sin(Time.time * 8f) / 5f)) * initialScale;
transform.localScale = new Vector3(scale, scale, 1f);
}
else
{
transform.localScale = Vector3.one * initialScale;
if (!Input.GetMouseButton(0))
grabbed = false;
else
transform.position = new Vector3(cursorPosition.x, cursorPosition.y, transform.position.z);
}
}
else
{
spriteRenderer.color = Color.clear;
var particleModule = particles.main;
particleModule.startColor = (Random.Range(0f, 1f) <= .55f) ? new Color(1f, .75f, .8f) : new Color(.08f, .025f, 0f);
}
}
}
| using UnityEngine;
using System.Collections;
public class SpiderFood : MonoBehaviour
{
public float grabRadius;
public float initialScale;
public bool grabbed, eaten;
public float particleRate;
public float y;
private SpriteRenderer spriteRenderer;
private ParticleSystem particles;
void Awake ()
{
particles = GetComponent<ParticleSystem>();
particleRate = ParticleHelper.getEmissionRate(particles);
spriteRenderer = GetComponent<SpriteRenderer>();
ParticleHelper.setEmissionRate(particles, 0f);
}
void Update ()
{
Vector3 cursorPosition = CameraHelper.getCursorPosition();
if (!eaten)
{
spriteRenderer.color = Color.white;
if (!grabbed)
{
float distance = ((Vector2)(transform.position - cursorPosition)).magnitude;
if (distance <= grabRadius && Input.GetMouseButtonDown(0))
grabbed = true;
float scale = (1f + (Mathf.Sin(Time.time * 8f) / 5f)) * initialScale;
transform.localScale = new Vector3(scale, scale, 1f);
}
else
{
transform.localScale = Vector3.one * initialScale;
if (!Input.GetMouseButton(0))
grabbed = false;
else
transform.position = new Vector3(cursorPosition.x, cursorPosition.y, transform.position.z);
}
}
else
{
spriteRenderer.color = Color.clear;
if (Random.Range(0f, 1f) <= .55f)
particles.startColor = new Color(1f, .75f, .8f);
else
particles.startColor = new Color(.08f, .025f, 0f);
}
}
}
| mit | C# |
b17b4e65f18d17dec8967f0b7455744c59edb8b1 | Add random selector | marcotmp/BehaviorTree | Assets/Scripts/BehaviorTree/Composites/RandomSelector.cs | Assets/Scripts/BehaviorTree/Composites/RandomSelector.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomSelector : Selector
{
private int taskIndex = 0;
public RandomSelector(string name) : base(name) { }
override public ReturnCode Update()
{
var returnCode = tasks[taskIndex].Update();
if (returnCode == ReturnCode.Fail)
{
taskIndex = GetRandomIndex();
return ReturnCode.Running;
}
else
{
return returnCode;
}
}
public override void Restart()
{
base.Restart();
taskIndex = GetRandomIndex();
}
private int GetRandomIndex()
{
var randomIndex = Random.Range(0, tasks.Count);
if (randomIndex == tasks.Count) randomIndex = tasks.Count - 1;
return randomIndex;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomSelector : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| unlicense | C# |
02a7ada6f13de462989a252a098e2143fb7fbb9d | Correct issue where settings.json cannot be found when using a shadow copied DLL. | jherby2k/AudioWorks | AudioWorks/src/AudioWorks.Common/ConfigurationManager.cs | AudioWorks/src/AudioWorks.Common/ConfigurationManager.cs | using System;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.Extensions.Configuration;
namespace AudioWorks.Common
{
/// <summary>
/// Manages the retrieval of configuration settings from disk.
/// </summary>
public static class ConfigurationManager
{
/// <summary>
/// Gets the configuration.
/// </summary>
/// <value>The configuration.</value>
[NotNull]
[CLSCompliant(false)]
public static IConfigurationRoot Configuration { get; }
static ConfigurationManager()
{
var settingsPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"AudioWorks");
const string settingsFileName = "settings.json";
// Copy the settings template if the file doesn't already exist
var settingsFile = Path.Combine(settingsPath, settingsFileName);
if (!File.Exists(settingsFile))
{
Directory.CreateDirectory(settingsPath);
File.Copy(
Path.Combine(
// ReSharper disable once AssignNullToNotNullAttribute
Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath),
settingsFileName),
settingsFile);
}
Configuration = new ConfigurationBuilder()
.SetBasePath(settingsPath)
.AddJsonFile(settingsFileName, true)
.Build();
}
}
}
| using System;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.Extensions.Configuration;
namespace AudioWorks.Common
{
/// <summary>
/// Manages the retrieval of configuration settings from disk.
/// </summary>
public static class ConfigurationManager
{
/// <summary>
/// Gets the configuration.
/// </summary>
/// <value>The configuration.</value>
[NotNull]
[CLSCompliant(false)]
public static IConfigurationRoot Configuration { get; }
static ConfigurationManager()
{
var settingsPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"AudioWorks");
const string settingsFileName = "settings.json";
// Copy the settings template if the file doesn't already exist
var settingsFile = Path.Combine(settingsPath, settingsFileName);
if (!File.Exists(settingsFile))
{
Directory.CreateDirectory(settingsPath);
File.Copy(
// ReSharper disable once AssignNullToNotNullAttribute
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), settingsFileName),
settingsFile);
}
Configuration = new ConfigurationBuilder()
.SetBasePath(settingsPath)
.AddJsonFile(settingsFileName, true)
.Build();
}
}
}
| agpl-3.0 | C# |
4b4568d274560cb7334e0e2a08d12bd67effb610 | Add FSharp entry to Document | sailro/cecil,joj/cecil,kzu/cecil,mono/cecil,xen2/cecil,jbevain/cecil,fnajera-rac-de/cecil,cgourlay/cecil,gluck/cecil,SiliconStudio/Mono.Cecil,saynomoo/cecil,furesoft/cecil,ttRevan/cecil | Mono.Cecil.Cil/Document.cs | Mono.Cecil.Cil/Document.cs | //
// Document.cs
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Cecil.Cil {
public enum DocumentType {
Other,
Text,
}
public enum DocumentHashAlgorithm {
None,
MD5,
SHA1,
}
public enum DocumentLanguage {
Other,
C,
Cpp,
CSharp,
Basic,
Java,
Cobol,
Pascal,
Cil,
JScript,
Smc,
MCpp,
FSharp,
}
public enum DocumentLanguageVendor {
Other,
Microsoft,
}
public sealed class Document {
string url;
byte type;
byte hash_algorithm;
byte language;
byte language_vendor;
byte [] hash;
public string Url {
get { return url; }
set { url = value; }
}
public DocumentType Type {
get { return (DocumentType) type; }
set { type = (byte) value; }
}
public DocumentHashAlgorithm HashAlgorithm {
get { return (DocumentHashAlgorithm) hash_algorithm; }
set { hash_algorithm = (byte) value; }
}
public DocumentLanguage Language {
get { return (DocumentLanguage) language; }
set { language = (byte) value; }
}
public DocumentLanguageVendor LanguageVendor {
get { return (DocumentLanguageVendor) language_vendor; }
set { language_vendor = (byte) value; }
}
public byte [] Hash {
get { return hash; }
set { hash = value; }
}
public Document (string url)
{
this.url = url;
this.hash = Empty<byte>.Array;
}
}
}
| //
// Document.cs
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Mono.Cecil.Cil {
public enum DocumentType {
Other,
Text,
}
public enum DocumentHashAlgorithm {
None,
MD5,
SHA1,
}
public enum DocumentLanguage {
Other,
C,
Cpp,
CSharp,
Basic,
Java,
Cobol,
Pascal,
Cil,
JScript,
Smc,
MCpp,
}
public enum DocumentLanguageVendor {
Other,
Microsoft,
}
public sealed class Document {
string url;
byte type;
byte hash_algorithm;
byte language;
byte language_vendor;
byte [] hash;
public string Url {
get { return url; }
set { url = value; }
}
public DocumentType Type {
get { return (DocumentType) type; }
set { type = (byte) value; }
}
public DocumentHashAlgorithm HashAlgorithm {
get { return (DocumentHashAlgorithm) hash_algorithm; }
set { hash_algorithm = (byte) value; }
}
public DocumentLanguage Language {
get { return (DocumentLanguage) language; }
set { language = (byte) value; }
}
public DocumentLanguageVendor LanguageVendor {
get { return (DocumentLanguageVendor) language_vendor; }
set { language_vendor = (byte) value; }
}
public byte [] Hash {
get { return hash; }
set { hash = value; }
}
public Document (string url)
{
this.url = url;
this.hash = Empty<byte>.Array;
}
}
}
| mit | C# |
9e0ae2122b8bd6fc801fb715e80d50791bea5f09 | Add verbose option alias to console app | atifaziz/NCrontab,atifaziz/NCrontab | NCrontabConsole/Program.cs | NCrontabConsole/Program.cs | #region License and Terms
//
// NCrontab - Crontab for .NET
// Copyright (c) 2008 Atif Aziz. 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.
//
#endregion
#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using NCrontab;
var verbose = false;
try
{
var argList = new List<string>(args);
var verboseIndex = argList.IndexOf("--verbose") is {} vi and >= 0 ? vi
: argList.IndexOf("-v");
// ReSharper disable once AssignmentInConditionalExpression
if (verbose = verboseIndex >= 0)
argList.RemoveAt(verboseIndex);
var (expression, startTimeString, endTimeString, format) =
argList.Count switch
{
3 => (argList[0], argList[1], argList[2], null),
> 3 => (argList[0], argList[1], argList[2], argList[3]),
_ => throw new ApplicationException("Missing required arguments. You must at least supply CRONTAB-EXPRESSION START-DATE END-DATE."),
};
expression = expression.Trim();
var options = new CrontabSchedule.ParseOptions
{
IncludingSeconds = expression.Split(' ').Length > 5,
};
var start = ParseDateArgument(startTimeString, "start");
var end = ParseDateArgument(endTimeString, "end");
format = format ?? (options.IncludingSeconds ? "ddd, dd MMM yyyy HH:mm:ss"
: "ddd, dd MMM yyyy HH:mm");
var schedule = CrontabSchedule.Parse(expression, options);
foreach (var occurrence in schedule.GetNextOccurrences(start, end))
Console.Out.WriteLine(occurrence.ToString(format));
return 0;
}
catch (Exception e)
{
var error =
verbose
? e.ToString()
: e is ApplicationException
? e.Message
: e.GetBaseException().Message;
Console.Error.WriteLine(error);
return 1;
}
static DateTime ParseDateArgument(string arg, string hint)
=> DateTime.TryParse(arg, null, DateTimeStyles.AssumeLocal, out var v) ? v
: throw new ApplicationException("Invalid " + hint + " date or date format argument.");
sealed class ApplicationException : Exception
{
public ApplicationException() {}
public ApplicationException(string message) : base(message) {}
}
| #region License and Terms
//
// NCrontab - Crontab for .NET
// Copyright (c) 2008 Atif Aziz. 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.
//
#endregion
#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using NCrontab;
var verbose = false;
try
{
var argList = new List<string>(args);
var verboseIndex = argList.IndexOf("--verbose");
// ReSharper disable once AssignmentInConditionalExpression
if (verbose = verboseIndex >= 0)
argList.RemoveAt(verboseIndex);
var (expression, startTimeString, endTimeString, format) =
argList.Count switch
{
3 => (argList[0], argList[1], argList[2], null),
> 3 => (argList[0], argList[1], argList[2], argList[3]),
_ => throw new ApplicationException("Missing required arguments. You must at least supply CRONTAB-EXPRESSION START-DATE END-DATE."),
};
expression = expression.Trim();
var options = new CrontabSchedule.ParseOptions
{
IncludingSeconds = expression.Split(' ').Length > 5,
};
var start = ParseDateArgument(startTimeString, "start");
var end = ParseDateArgument(endTimeString, "end");
format = format ?? (options.IncludingSeconds ? "ddd, dd MMM yyyy HH:mm:ss"
: "ddd, dd MMM yyyy HH:mm");
var schedule = CrontabSchedule.Parse(expression, options);
foreach (var occurrence in schedule.GetNextOccurrences(start, end))
Console.Out.WriteLine(occurrence.ToString(format));
return 0;
}
catch (Exception e)
{
var error =
verbose
? e.ToString()
: e is ApplicationException
? e.Message
: e.GetBaseException().Message;
Console.Error.WriteLine(error);
return 1;
}
static DateTime ParseDateArgument(string arg, string hint)
=> DateTime.TryParse(arg, null, DateTimeStyles.AssumeLocal, out var v) ? v
: throw new ApplicationException("Invalid " + hint + " date or date format argument.");
sealed class ApplicationException : Exception
{
public ApplicationException() {}
public ApplicationException(string message) : base(message) {}
}
| apache-2.0 | C# |
7b88cd194a07fc40642642ceca621ac8e8fbc18c | Add test category to authenticated test | xobed/RohlikAPI,xobed/RohlikAPI,xobed/RohlikAPI,notdev/RohlikAPI,xobed/RohlikAPI | RohlikAPITests/RohlikovacTests.cs | RohlikAPITests/RohlikovacTests.cs | using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;
namespace RohlikAPITests
{
[TestClass]
public class RohlikovacTests
{
private string[] GetCredentials()
{
string filePath = @"..\..\..\loginPassword.txt";
if (!File.Exists(filePath))
{
throw new FileNotFoundException("Test needs credentials. Create 'loginPassword.txt' in solution root directory. Enter [email protected]:yourPassword on first line.");
}
var passwordString = File.ReadAllText(filePath);
return passwordString.Split(':');
}
[TestMethod, TestCategory("Authenticated")]
public void RunTest()
{
var login = GetCredentials();
var rohlikApi = new AuthenticatedRohlikApi(login[0], login[1]);
var result = rohlikApi.RunRohlikovac();
if (result.Contains("error"))
{
Assert.Fail($"Failed to login to rohlik. Login used: {login[0]}");
}
}
}
} | using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;
namespace RohlikAPITests
{
[TestClass]
public class RohlikovacTests
{
private string[] GetCredentials()
{
string filePath = @"..\..\..\loginPassword.txt";
if (!File.Exists(filePath))
{
throw new FileNotFoundException("Test needs credentials. Create 'loginPassword.txt' in solution root directory. Enter [email protected]:yourPassword on first line.");
}
var passwordString = File.ReadAllText(filePath);
return passwordString.Split(':');
}
[TestMethod]
public void RunTest()
{
var login = GetCredentials();
var rohlikApi = new AuthenticatedRohlikApi(login[0], login[1]);
var result = rohlikApi.RunRohlikovac();
if (result.Contains("error"))
{
Assert.Fail($"Failed to login to rohlik. Login used: {login[0]}");
}
}
}
} | mit | C# |
92a6e6c6bc2a6e978c98efca92dc98b5a457ad8b | Tweak to content for display on ES marketing site | ReachmailInc/WebAPISamples,ReachmailInc/WebAPISamples,ReachmailInc/WebAPISamples,ReachmailInc/WebAPISamples,ReachmailInc/WebAPISamples,ReachmailInc/WebAPISamples,ReachmailInc/WebAPISamples | dotnet/samples/dotnet_send.cs | dotnet/samples/dotnet_send.cs | using System;
using Reachmail.Easysmtp.Post.Request;
public void Main()
{
var reachmail = Reachmail.Api.Create("<API Token>");
var request = new DeliveryRequest {
FromAddress = "[email protected]",
Recipients = new Recipients {
new Recipient {
Address = "[email protected]"
}
},
Subject = "Subject",
BodyText = "Text",
BodyHtml = "html",
Headers = new Headers {
{ "name", "value" }
},
Attachments = new Attachments {
new EmailAttachment {
Filename = "text.txt",
Data = "b2ggaGFp", // Base64 encoded
ContentType = "text/plain",
ContentDisposition = "attachment",
Cid = "<text.txt>"
}
},
Tracking = true,
FooterAddress = "[email protected]",
SignatureDomain = "signature.net"
};
var result = reachmail.Easysmtp.Post(request);
}
| using System;
using Reachmail.Easysmtp.Post.Request;
public void Main()
{
var reachmail = Reachmail.Api.Create("<API Token>");
var request = new DeliveryRequest {
FromAddress = "[email protected]",
Recipients = new Recipients {
new Recipient {
Address = "[email protected]"
}
},
Subject = "Subject",
BodyText = "Text",
BodyHtml = "<p>html</p>",
Headers = new Headers {
{ "name", "value" }
},
Attachments = new Attachments {
new EmailAttachment {
Filename = "text.txt",
Data = "b2ggaGFp", // Base64 encoded
ContentType = "text/plain",
ContentDisposition = "attachment",
Cid = "<text.txt>"
}
},
Tracking = true,
FooterAddress = "[email protected]",
SignatureDomain = "signature.net"
};
var result = reachmail.Easysmtp.Post(request);
} | mit | C# |
aa0ab9952519bc69715d7fb056f4305655a156a3 | Send message as DM, not default channel | discord-csharp/Contacts,MarkusGordathian/Contacts | ContactsBot/Modules/UserMotd.cs | ContactsBot/Modules/UserMotd.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Discord;
using Discord.WebSocket;
using Discord.Commands;
using System.Threading.Tasks;
namespace ContactsBot.Modules
{
class UserMotd : IMessageAction
{
private DiscordSocketClient _client;
private BotConfiguration _config;
public bool IsEnabled { get; private set; }
public void Install(IDependencyMap map)
{
_client = map.Get<DiscordSocketClient>();
_config = map.Get<BotConfiguration>();
}
public void Enable()
{
_client.UserJoined += ShowMotd;
IsEnabled = true;
}
public void Disable()
{
_client.UserJoined -= ShowMotd;
IsEnabled = false;
}
public async Task ShowMotd(SocketGuildUser user)
{
var channel = await user.Guild.GetDefaultChannelAsync();
try
{
await (await user.CreateDMChannelAsync()).SendMessageAsync(String.Format(_config.MessageOfTheDay, user.Mention));
}
catch (FormatException)
{
await channel.SendMessageAsync("Tell the admin to fix the MOTD formatting!");
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Discord;
using Discord.WebSocket;
using Discord.Commands;
using System.Threading.Tasks;
namespace ContactsBot.Modules
{
class UserMotd : IMessageAction
{
private DiscordSocketClient _client;
private BotConfiguration _config;
public bool IsEnabled { get; private set; }
public void Install(IDependencyMap map)
{
_client = map.Get<DiscordSocketClient>();
_config = map.Get<BotConfiguration>();
}
public void Enable()
{
_client.UserJoined += ShowMotd;
IsEnabled = true;
}
public void Disable()
{
_client.UserJoined -= ShowMotd;
IsEnabled = false;
}
public async Task ShowMotd(SocketGuildUser user)
{
var channel = await user.Guild.GetDefaultChannelAsync();
try
{
await channel.SendMessageAsync(String.Format(_config.MessageOfTheDay, user.Mention));
}
catch (FormatException)
{
await channel.SendMessageAsync("Tell the admin to fix the MOTD formatting!");
}
}
}
}
| mit | C# |
3dbf6a9d612b971fec258dfb8a64b0964c6dcbd0 | ADD display names to URL stat properties | diksito/url-shortner,diksito/url-shortner | ShortURLService/Models/UrlStat.cs | ShortURLService/Models/UrlStat.cs | using ShortURLService.Infrastructure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
namespace ShortURLService.Models
{
public class UrlStat
{
public int UrlStatId { get; set; }
[DisplayName("User Agent")]
public string UserAgent { get; set; }
[DisplayName("Host Address")]
public string UserHostAddress { get; set; }
[DisplayName("Language")]
public string UserLanguage { get; set; }
[DisplayName("Refferal URL")]
public string UrlRefferer { get; set; }
[DisplayName("Mobile")]
public bool IsMobile { get; set; }
public string Browser { get; set; }
[DisplayName("Browser Version")]
public int MajorVersion { get; set; }
public int UrlId { get; set; }
public virtual URL Url { get; set; }
/// <summary>
/// Default constructor
/// </summary>
public UrlStat()
{
}
/// <summary>
/// Bind properties with data that is coming from the request
/// </summary>
/// <param name="request">HTTP request</param>
public UrlStat(HttpRequestBase request)
{
if (string.IsNullOrEmpty(request.UrlReferrer.Host))
UrlRefferer = Constants.UNKNOWN;
else
UrlRefferer = request.UrlReferrer.Host;
if (string.IsNullOrEmpty(request.UserAgent))
UserAgent = Constants.UNKNOWN;
else
UserAgent = request.UserAgent;
if (string.IsNullOrEmpty(request.UserHostAddress))
UserHostAddress = Constants.UNKNOWN;
else
UserHostAddress = request.UserHostAddress;
if (string.IsNullOrEmpty(request.UserLanguages[0]))
UserLanguage = Constants.UNKNOWN;
else
UserLanguage = request.UserLanguages[0];
if (string.IsNullOrEmpty(request.Browser.Browser))
Browser = Constants.UNKNOWN;
else
Browser = request.Browser.Browser;
MajorVersion = request.Browser.MajorVersion;
IsMobile = request.Browser.IsMobileDevice;
}
}
} | using ShortURLService.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ShortURLService.Models
{
public class UrlStat
{
public int UrlStatId { get; set; }
public string UserAgent { get; set; }
public string UserHostAddress { get; set; }
public string UserLanguage { get; set; }
public string UrlRefferer { get; set; }
public bool IsMobile { get; set; }
public string Browser { get; set; }
public int MajorVersion { get; set; }
public int UrlId { get; set; }
public virtual URL Url { get; set; }
/// <summary>
/// Default constructor
/// </summary>
public UrlStat()
{
}
/// <summary>
/// Bind properties with data that is coming from the request
/// </summary>
/// <param name="request">HTTP request</param>
public UrlStat(HttpRequestBase request)
{
if (string.IsNullOrEmpty(request.UrlReferrer.Host))
UrlRefferer = Constants.UNKNOWN;
else
UrlRefferer = request.UrlReferrer.Host;
if (string.IsNullOrEmpty(request.UserAgent))
UserAgent = Constants.UNKNOWN;
else
UserAgent = request.UserAgent;
if (string.IsNullOrEmpty(request.UserHostAddress))
UserHostAddress = Constants.UNKNOWN;
else
UserHostAddress = request.UserHostAddress;
if (string.IsNullOrEmpty(request.UserLanguages[0]))
UserLanguage = Constants.UNKNOWN;
else
UserLanguage = request.UserLanguages[0];
if (string.IsNullOrEmpty(request.Browser.Browser))
Browser = Constants.UNKNOWN;
else
Browser = request.Browser.Browser;
MajorVersion = request.Browser.MajorVersion;
IsMobile = request.Browser.IsMobileDevice;
}
}
} | mit | C# |
ab17db50f0ccd76d9ca2014501eb296590e1a596 | Update IdConverter.cs | yuanrui/Examples,yuanrui/Examples,yuanrui/Examples,yuanrui/Examples,yuanrui/Examples | Simple.Common/Text/IdConverter.cs | Simple.Common/Text/IdConverter.cs | namespace Simple.Common.Text
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
public static class IdConverter
{
public static UInt64 ToLong(String id)
{
var bytes = Convert.FromBase64String(id);
Array.Reverse(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
public static String ToString(UInt64 id)
{
var bytes = BitConverter.GetBytes(id);
Array.Reverse(bytes);
return Convert.ToBase64String(bytes);
}
public static Guid ToGuid(UInt16 id)
{
var input = id.ToString("X4");
if (input.Length == 4)
{
//Bluetooth UUID
input = "0000" + input + "-0000-1000-8000-00805F9B34FB";
}
return Guid.ParseExact(input, "D");
}
public static UInt16 ToUInt16(Guid uuid)
{
UInt16 result = 0;
var id = uuid.ToString();
if (id.Length > 8)
{
id = id.Substring(4, 4);
UInt16.TryParse(id, NumberStyles.AllowHexSpecifier, CultureInfo.CurrentCulture, out result);
}
return result;
}
public static String ToUInt16Hex(Guid uuid)
{
var id = ToUInt16(uuid);
return "0x" + id.ToString("X4");
}
public static Guid ToGuid(DateTime time)
{
var input = Guid.NewGuid().ToString("N");
var timeToken = time.Year.ToString("x4") + time.Month.ToString("x2") + time.Day.ToString("x2")
+ time.Hour.ToString("x2") + time.Minute.ToString("x2") + time.Second.ToString("x2")
+ time.Millisecond.ToString("x4");
input = timeToken + input.Substring(timeToken.Length);
return Guid.ParseExact(input, "N");
}
}
}
| namespace Simple.Common.Text
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
public static class IdConverter
{
public static UInt64 ToLong(String id)
{
var bytes = Convert.FromBase64String(id);
Array.Reverse(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
public static String ToString(UInt64 id)
{
var bytes = BitConverter.GetBytes(id);
Array.Reverse(bytes);
return Convert.ToBase64String(bytes);
}
public static Guid ToGuid(UInt16 id)
{
var input = id.ToString("X4");
if (input.Length == 4)
{
//Bluetooth UUID
input = "0000" + input + "-0000-1000-8000-00805F9B34FB";
}
return Guid.ParseExact(input, "D");
}
public static UInt16 ToUInt16(Guid uuid)
{
UInt16 result = 0;
var id = uuid.ToString();
if (id.Length > 8)
{
id = id.Substring(4, 4);
UInt16.TryParse(id, NumberStyles.AllowHexSpecifier, CultureInfo.CurrentCulture, out result);
}
return result;
}
public static String ToUInt16Hex(Guid uuid)
{
var id = ToUInt16(uuid);
return "0x" + id.ToString("X4");
}
}
}
| apache-2.0 | C# |
0b8da5267d9cb4606dc81073c3b43b1fb295bc78 | Set assembly version correctly. xibosignage/xibo#834 | xibosignage/xibo-dotnetclient,dasgarner/xibo-dotnetclient | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 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("Xibo Open Source Digital Signage")]
[assembly: AssemblyDescription("Digital Signage Player")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xibo Digital Signage")]
[assembly: AssemblyProduct("Xibo")]
[assembly: AssemblyCopyright("Copyright Dan Garner © 2008-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("3bd467a4-4ef9-466a-b156-a79c13a863f7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.7.9.0")]
[assembly: AssemblyFileVersion("1.7.9.0")]
[assembly: NeutralResourcesLanguageAttribute("en-GB")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 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("Xibo Open Source Digital Signage")]
[assembly: AssemblyDescription("Digital Signage Player")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xibo Digital Signage")]
[assembly: AssemblyProduct("Xibo")]
[assembly: AssemblyCopyright("Copyright Dan Garner © 2008-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("3bd467a4-4ef9-466a-b156-a79c13a863f7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en-GB")]
| agpl-3.0 | C# |
ac108226fe4e50140bbe175e84fc420d2e1d5728 | Fix abstract methods not renamed | farmaair/ConfuserEx,fretelweb/ConfuserEx,yuligang1234/ConfuserEx,apexrichard/ConfuserEx,modulexcite/ConfuserEx,arpitpanwar/ConfuserEx,HalidCisse/ConfuserEx,manojdjoshi/ConfuserEx,AgileJoshua/ConfuserEx,Desolath/ConfuserEx3,Desolath/Confuserex,timnboys/ConfuserEx,mirbegtlax/ConfuserEx,jbeshir/ConfuserEx,JPVenson/ConfuserEx,mirbegtlax/ConfuserEx,engdata/ConfuserEx,yeaicc/ConfuserEx,KKKas/ConfuserEx,Immortal-/ConfuserEx,JPVenson/ConfuserEx,HalidCisse/ConfuserEx,MetSystem/ConfuserEx,yuligang1234/ConfuserEx | Confuser.Renamer/Analyzers/VTableAnalyzer.cs | Confuser.Renamer/Analyzers/VTableAnalyzer.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using Confuser.Core;
using Confuser.Renamer.References;
using dnlib.DotNet;
namespace Confuser.Renamer.Analyzers {
internal class VTableAnalyzer : IRenamer {
public void Analyze(ConfuserContext context, INameService service, IDnlibDef def) {
var method = def as MethodDef;
if (method == null || !method.IsVirtual)
return;
VTable vTbl = service.GetVTables()[method.DeclaringType];
VTableSignature sig = VTableSignature.FromMethod(method);
VTableSlot slot = vTbl.FindSlot(method);
Debug.Assert(slot != null);
if (!method.IsAbstract) {
foreach (VTableSlot baseSlot in slot.Overrides) {
// Better on safe side, add references to both methods.
service.AddReference(method, new OverrideDirectiveReference(slot, baseSlot));
service.AddReference(baseSlot.MethodDef, new OverrideDirectiveReference(slot, baseSlot));
}
}
}
public void PreRename(ConfuserContext context, INameService service, IDnlibDef def) {
//
}
public void PostRename(ConfuserContext context, INameService service, IDnlibDef def) {
var method = def as MethodDef;
if (method == null || !method.IsVirtual || method.Overrides.Count == 0)
return;
var methods = new HashSet<IMethodDefOrRef>(MethodDefOrRefComparer.Instance);
method.Overrides
.RemoveWhere(impl => MethodDefOrRefComparer.Instance.Equals(impl.MethodDeclaration, method));
}
private class MethodDefOrRefComparer : IEqualityComparer<IMethodDefOrRef> {
public static readonly MethodDefOrRefComparer Instance = new MethodDefOrRefComparer();
private MethodDefOrRefComparer() { }
public bool Equals(IMethodDefOrRef x, IMethodDefOrRef y) {
return new SigComparer().Equals(x, y) && new SigComparer().Equals(x.DeclaringType, y.DeclaringType);
}
public int GetHashCode(IMethodDefOrRef obj) {
return new SigComparer().GetHashCode(obj) * 5 + new SigComparer().GetHashCode(obj.DeclaringType);
}
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics;
using Confuser.Core;
using Confuser.Renamer.References;
using dnlib.DotNet;
namespace Confuser.Renamer.Analyzers {
internal class VTableAnalyzer : IRenamer {
public void Analyze(ConfuserContext context, INameService service, IDnlibDef def) {
var method = def as MethodDef;
if (method == null || !method.IsVirtual)
return;
VTable vTbl = service.GetVTables()[method.DeclaringType];
VTableSignature sig = VTableSignature.FromMethod(method);
VTableSlot slot = vTbl.FindSlot(method);
Debug.Assert(slot != null);
if (method.IsAbstract) {
service.SetCanRename(method, false);
} else {
foreach (VTableSlot baseSlot in slot.Overrides) {
// Better on safe side, add references to both methods.
service.AddReference(method, new OverrideDirectiveReference(slot, baseSlot));
service.AddReference(baseSlot.MethodDef, new OverrideDirectiveReference(slot, baseSlot));
}
}
}
public void PreRename(ConfuserContext context, INameService service, IDnlibDef def) {
//
}
public void PostRename(ConfuserContext context, INameService service, IDnlibDef def) {
var method = def as MethodDef;
if (method == null || !method.IsVirtual || method.Overrides.Count == 0)
return;
var methods = new HashSet<IMethodDefOrRef>(MethodDefOrRefComparer.Instance);
method.Overrides
.RemoveWhere(impl => MethodDefOrRefComparer.Instance.Equals(impl.MethodDeclaration, method));
}
private class MethodDefOrRefComparer : IEqualityComparer<IMethodDefOrRef> {
public static readonly MethodDefOrRefComparer Instance = new MethodDefOrRefComparer();
private MethodDefOrRefComparer() { }
public bool Equals(IMethodDefOrRef x, IMethodDefOrRef y) {
return new SigComparer().Equals(x, y) && new SigComparer().Equals(x.DeclaringType, y.DeclaringType);
}
public int GetHashCode(IMethodDefOrRef obj) {
return new SigComparer().GetHashCode(obj) * 5 + new SigComparer().GetHashCode(obj.DeclaringType);
}
}
}
} | mit | C# |
f71fd3943a8b2fc95caedfe3782cb5d06447acef | Debug flag | sintefneodroid/droid,sintefneodroid/droid | Editor/Windows/WindowManager.cs | Editor/Windows/WindowManager.cs | #if UNITY_EDITOR
using System;
using UnityEditor;
namespace droid.Editor.Windows {
public class WindowManager : EditorWindow {
static Type[] _desired_dock_next_toos = {
typeof(RenderTextureConfiguratorWindow),
typeof(CameraSynchronisationWindow),
#if NEODROID_DEBUG
typeof(DebugWindow),
#endif
typeof(SegmentationWindow),
typeof(EnvironmentsWindow),
typeof(TaskWindow),
typeof(DemonstrationWindow),
typeof(SimulationWindow)
};
[MenuItem(EditorWindowMenuPath._WindowMenuPath + "ShowAllWindows")]
[MenuItem(EditorWindowMenuPath._ToolMenuPath + "ShowAllWindows")]
public static void ShowWindow() {
//Show existing window instance. If one doesn't exist, make one.
GetWindow<RenderTextureConfiguratorWindow>(_desired_dock_next_toos);
GetWindow<CameraSynchronisationWindow>(_desired_dock_next_toos);
#if NEODROID_DEBUG
GetWindow<DebugWindow>(_desired_dock_next_toos);
#endif
GetWindow<SegmentationWindow>(_desired_dock_next_toos);
GetWindow<EnvironmentsWindow>(_desired_dock_next_toos);
GetWindow<TaskWindow>(_desired_dock_next_toos);
GetWindow<DemonstrationWindow>(_desired_dock_next_toos);
GetWindow<SimulationWindow>(_desired_dock_next_toos);
}
}
}
#endif
| #if UNITY_EDITOR
using System;
using UnityEditor;
namespace droid.Editor.Windows {
public class WindowManager : EditorWindow {
static Type[] _desired_dock_next_toos = {
typeof(RenderTextureConfiguratorWindow),
typeof(CameraSynchronisationWindow),
typeof(DebugWindow),
typeof(SegmentationWindow),
typeof(EnvironmentsWindow),
typeof(TaskWindow),
typeof(DemonstrationWindow),
typeof(SimulationWindow)
};
[MenuItem(EditorWindowMenuPath._WindowMenuPath + "ShowAllWindows")]
[MenuItem(EditorWindowMenuPath._ToolMenuPath + "ShowAllWindows")]
public static void ShowWindow() {
//Show existing window instance. If one doesn't exist, make one.
GetWindow<RenderTextureConfiguratorWindow>(_desired_dock_next_toos);
GetWindow<CameraSynchronisationWindow>(_desired_dock_next_toos);
GetWindow<DebugWindow>(_desired_dock_next_toos);
GetWindow<SegmentationWindow>(_desired_dock_next_toos);
GetWindow<EnvironmentsWindow>(_desired_dock_next_toos);
GetWindow<TaskWindow>(_desired_dock_next_toos);
GetWindow<DemonstrationWindow>(_desired_dock_next_toos);
GetWindow<SimulationWindow>(_desired_dock_next_toos);
}
}
}
#endif
| apache-2.0 | C# |
4151504ed8c6f20e964a862d8ccd9e1f89dad19b | Fix tools being installed to wrong path | nvisionative/Dnn.Platform,dnnsoftware/Dnn.Platform,dnnsoftware/Dnn.Platform,bdukes/Dnn.Platform,mitchelsellers/Dnn.Platform,bdukes/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,mitchelsellers/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,valadas/Dnn.Platform,nvisionative/Dnn.Platform,valadas/Dnn.Platform,nvisionative/Dnn.Platform,valadas/Dnn.Platform,bdukes/Dnn.Platform,mitchelsellers/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.Platform | Build/Program.cs | Build/Program.cs | using System;
using Cake.Frosting;
public class Program
{
public static int Main(string[] args)
{
return new CakeHost()
.UseContext<Context>()
.UseLifetime<Lifetime>()
.UseWorkingDirectory("..")
.SetToolPath("../tools")
.InstallTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1"))
.InstallTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0"))
.InstallTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0"))
.InstallTool(new Uri("nuget:?package=NuGet.CommandLine&version=5.8.0"))
.Run(args);
}
}
| using System;
using Cake.Frosting;
public class Program
{
public static int Main(string[] args)
{
return new CakeHost()
.UseContext<Context>()
.UseLifetime<Lifetime>()
.UseWorkingDirectory("..")
.InstallTool(new Uri("nuget:?package=GitVersion.CommandLine&version=5.0.1"))
.InstallTool(new Uri("nuget:?package=Microsoft.TestPlatform&version=16.8.0"))
.InstallTool(new Uri("nuget:?package=NUnitTestAdapter&version=2.3.0"))
.InstallTool(new Uri("nuget:?package=NuGet.CommandLine&version=5.8.0"))
.Run(args);
}
}
| mit | C# |
7a96d3d7ed98afa032540500b6fadd1fff091707 | build errors | mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati,duplicati/duplicati,duplicati/duplicati,mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati,mnaiman/duplicati,duplicati/duplicati | Duplicati/Library/Backend/Storj/StorjFile.cs | Duplicati/Library/Backend/Storj/StorjFile.cs | using Duplicati.Library.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Duplicati.Library.Backend.Storj
{
public class StorjFile : IFileEntry
{
public static readonly string STORJ_LAST_ACCESS = "DUPLICATI:LAST-ACCESS";
public static readonly string STORJ_LAST_MODIFICATION = "DUPLICATI:LAST-MODIFICATION";
public bool IsFolder { get; set; }
public DateTime LastAccess { get; set; }
public DateTime LastModification { get; set; }
public string Name { get; set; }
public long Size { get; set; }
public StorjFile()
{
}
public StorjFile(uplink.NET.Models.Object tardigradeObject)
{
IsFolder = tardigradeObject.IsPrefix;
var lastAccess = tardigradeObject.CustomMetadata.Entries.Where(e => e.Key == STORJ_LAST_ACCESS).FirstOrDefault();
if (lastAccess != null && !string.IsNullOrEmpty(lastAccess.Value))
{
LastAccess = DateTime.Parse(lastAccess.Value);
}
else
{
LastAccess = DateTime.MinValue;
}
var lastMod = tardigradeObject.CustomMetadata.Entries.Where(e => e.Key == STORJ_LAST_MODIFICATION).FirstOrDefault();
if (lastMod != null && !string.IsNullOrEmpty(lastMod.Value))
{
LastModification = DateTime.Parse(lastMod.Value);
}
else
{
LastModification = DateTime.MinValue;
}
Name = tardigradeObject.Key;
Size = tardigradeObject.SystemMetadata.ContentLength;
}
}
}
| using Duplicati.Library.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Duplicati.Library.Backend.Storj
{
public class StorjFile : IFileEntry
{
public static readonly string STORJ_LAST_ACCESS = "DUPLICATI:LAST-ACCESS";
public static readonly string STORJ_LAST_MODIFICATION = "DUPLICATI:LAST-MODIFICATION";
public bool IsFolder { get; set; }
public DateTime LastAccess { get; set; }
public DateTime LastModification { get; set; }
public string Name { get; set; }
public long Size { get; set; }
public StorjFile()
{
}
public StorjFile(uplink.NET.Models.Object tardigradeObject)
{
IsFolder = tardigradeObject.IsPrefix;
var lastAccess = tardigradeObject.CustomMetaData.Entries.Where(e => e.Key == STORJ_LAST_ACCESS).FirstOrDefault();
if (lastAccess != null && !string.IsNullOrEmpty(lastAccess.Value))
{
LastAccess = DateTime.Parse(lastAccess.Value);
}
else
{
LastAccess = DateTime.MinValue;
}
var lastMod = tardigradeObject.CustomMetaData.Entries.Where(e => e.Key == STORJ_LAST_MODIFICATION).FirstOrDefault();
if (lastMod != null && !string.IsNullOrEmpty(lastMod.Value))
{
LastModification = DateTime.Parse(lastMod.Value);
}
else
{
LastModification = DateTime.MinValue;
}
Name = tardigradeObject.Key;
Size = tardigradeObject.SystemMetaData.ContentLength;
}
}
}
| lgpl-2.1 | C# |
cc44af1ce0adfee5afa12594641709e831c32e9f | move State from App namespace to App.Connection | rit-sse-mycroft/core | Mycroft/App/Connection/State.cs | Mycroft/App/Connection/State.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mycroft.App.Connection
{
abstract class State
{
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mycroft.App
{
abstract class State
{
}
}
| bsd-3-clause | C# |
e0659b3e936ba7bf8f64ecb17cb5a118fe399f7a | use KeyedVirtualFolder | itamar82/simpleDLNA,nmaier/simpleDLNA,antonio-bakula/simpleDLNA,bra1nb3am3r/simpleDLNA | fsserver/Views/ByTitleView.cs | fsserver/Views/ByTitleView.cs | using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using NMaier.sdlna.FileMediaServer.Folders;
using NMaier.sdlna.Server;
namespace NMaier.sdlna.FileMediaServer.Views
{
class ByTitleView : IView
{
private class TitlesFolder : KeyedVirtualFolder<VirtualFolder>
{
public TitlesFolder(FileServer aServer, IFileServerFolder aParent) : base(aServer, aParent, "") { }
}
private static Regex regClean = new Regex(@"[^\d\w]+", RegexOptions.Compiled);
public string Description
{
get { return "Reorganizes files into folders by title"; }
}
public string Name
{
get { return "bytitle"; }
}
public void Transform(FileServer Server, IMediaFolder Root)
{
var root = Root as IFileServerFolder;
var titles = new TitlesFolder(Server, root);
SortFolder(Server, root, titles);
foreach (var i in root.ChildFolders.ToList()) {
root.ReleaseItem(i as IFileServerMediaItem);
}
foreach (var i in titles.ChildFolders.ToList()) {
root.AdoptItem(i as IFileServerFolder);
}
}
private void SortFolder(FileServer server, IFileServerFolder folder, TitlesFolder titles)
{
foreach (var f in folder.ChildFolders.ToList()) {
SortFolder(server, f as IFileServerFolder, titles);
}
foreach (var c in folder.ChildItems.ToList()) {
var pre = regClean.Replace(c.Title, "");
if (string.IsNullOrEmpty(pre)) {
pre = "Unnamed";
}
pre = pre.First().ToString().ToUpper();
titles.GetFolder(pre).AdoptItem(c as IFileServerMediaItem);
}
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using NMaier.sdlna.FileMediaServer.Folders;
using NMaier.sdlna.Server;
namespace NMaier.sdlna.FileMediaServer.Views
{
class ByTitleView : IView
{
private static Regex regClean = new Regex(@"[^\d\w]+", RegexOptions.Compiled);
public string Description
{
get { return "Reorganizes files into folders by title"; }
}
public string Name
{
get { return "bytitle"; }
}
public void Transform(FileServer Server, IMediaFolder Root)
{
var root = Root as IFileServerFolder;
var titles = new Dictionary<string, IFileServerFolder>();
SortFolder(Server, root, titles);
foreach (var i in root.ChildFolders.ToList()) {
root.ReleaseItem(i as IFileServerMediaItem);
}
foreach (var i in titles.Values) {
root.AdoptItem(i);
}
}
private void SortFolder(FileServer server, IFileServerFolder folder, IDictionary<string, IFileServerFolder> titles)
{
foreach (var f in folder.ChildFolders.ToList()) {
SortFolder(server, f as IFileServerFolder, titles);
}
foreach (var c in folder.ChildItems.ToList()) {
var pre = regClean.Replace(c.Title, "");
if (string.IsNullOrEmpty(pre)) {
pre = "Unnamed";
}
pre = pre.First().ToString().ToUpper();
IFileServerFolder dest;
if (!titles.TryGetValue(pre, out dest)) {
dest = new VirtualFolder(server, server.Root as IFileServerFolder, pre);
titles.Add(pre, dest);
server.RegisterPath(dest);
}
dest.AdoptItem(c as IFileServerMediaItem);
}
}
}
}
| bsd-2-clause | C# |
8eec4001efcb93098ef2fa657a3e174925f2f218 | Add back and cancel button commands | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/AddWalletPageViewModel.cs | WalletWasabi.Fluent/ViewModels/AddWalletPageViewModel.cs | using System.Reactive.Linq;
using ReactiveUI;
using System;
using System.Windows.Input;
namespace WalletWasabi.Fluent.ViewModels
{
public class AddWalletPageViewModel : NavBarItemViewModel
{
private string _walletName = "";
private bool _optionsEnabled;
public AddWalletPageViewModel(NavigationStateViewModel navigationState) : base(navigationState, NavigationTarget.Dialog)
{
Title = "Add Wallet";
BackCommand = ReactiveCommand.Create(() => navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear());
CancelCommand = ReactiveCommand.Create(() => navigationState.DialogScreen?.Invoke().Router.NavigationStack.Clear());
this.WhenAnyValue(x => x.WalletName)
.Select(x => !string.IsNullOrWhiteSpace(x))
.Subscribe(x => OptionsEnabled = x);
}
public override string IconName => "add_circle_regular";
public ICommand BackCommand { get; }
public ICommand CancelCommand { get; }
public string WalletName
{
get => _walletName;
set => this.RaiseAndSetIfChanged(ref _walletName, value);
}
public bool OptionsEnabled
{
get => _optionsEnabled;
set => this.RaiseAndSetIfChanged(ref _optionsEnabled, value);
}
}
}
| using System.Reactive.Linq;
using ReactiveUI;
using System;
namespace WalletWasabi.Fluent.ViewModels
{
public class AddWalletPageViewModel : NavBarItemViewModel
{
private string _walletName = "";
private bool _optionsEnabled;
public AddWalletPageViewModel(NavigationStateViewModel navigationState) : base(navigationState, NavigationTarget.Dialog)
{
Title = "Add Wallet";
this.WhenAnyValue(x => x.WalletName)
.Select(x => !string.IsNullOrWhiteSpace(x))
.Subscribe(x => OptionsEnabled = x);
}
public override string IconName => "add_circle_regular";
public string WalletName
{
get => _walletName;
set => this.RaiseAndSetIfChanged(ref _walletName, value);
}
public bool OptionsEnabled
{
get => _optionsEnabled;
set => this.RaiseAndSetIfChanged(ref _optionsEnabled, value);
}
}
}
| mit | C# |
39139cdbab5b92eee5b3f12a3dc01b0109fbf387 | Bump 0.17.1 | lstefano71/Nowin,pysco68/Nowin,pysco68/Nowin,lstefano71/Nowin,et1975/Nowin,modulexcite/Nowin,et1975/Nowin,pysco68/Nowin,modulexcite/Nowin,Bobris/Nowin,Bobris/Nowin,et1975/Nowin,Bobris/Nowin,modulexcite/Nowin,lstefano71/Nowin | Nowin/Properties/AssemblyInfo.cs | Nowin/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Nowin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Boris Letocha")]
[assembly: AssemblyProduct("Nowin")]
[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("fd085b68-3766-42af-ab6d-351b7741c685")]
// 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.17.1.0")]
[assembly: AssemblyFileVersion("0.17.1.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Nowin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Boris Letocha")]
[assembly: AssemblyProduct("Nowin")]
[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("fd085b68-3766-42af-ab6d-351b7741c685")]
// 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.17.0.0")]
[assembly: AssemblyFileVersion("0.17.0.0")]
| mit | C# |
b61d21b570c44bafbadd7892f9dddd0cff33cce1 | Make configurablerules class internal | dlwyatt/PSScriptAnalyzer,PowerShell/PSScriptAnalyzer,daviwil/PSScriptAnalyzer,juneb/PSScriptAnalyzer | Rules/ConfigurableScriptRule.cs | Rules/ConfigurableScriptRule.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic
{
// This is still an experimental class and we do not want to expose it
// as a public API as of yet. So we place it in builtinrules project
// and keep it internal as it consumed only by a handful of rules.
internal abstract class ConfigurableScriptRule : IScriptRule
{
public bool IsRuleConfigured { get; protected set; } = false;
public void ConfigureRule()
{
var arguments = Helper.Instance.GetRuleArguments(this.GetName());
//var configurableProps = GetConfigurableProperties();
try
{
var properties = this.GetType().GetProperties();
foreach (var property in properties)
{
if (arguments.ContainsKey(property.Name))
{
var type = property.PropertyType;
var obj = arguments[property.Name];
property.SetValue(
this,
System.Convert.ChangeType(obj, Type.GetTypeCode(type)));
}
}
}
catch
{
// return arguments with defaults
}
IsRuleConfigured = true;
}
// private GetConfigurableProperties()
// {
// }
public abstract IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName);
public abstract string GetCommonName();
public abstract string GetDescription();
public abstract string GetName();
public abstract RuleSeverity GetSeverity();
public abstract string GetSourceName();
public abstract SourceType GetSourceType();
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ConfigurablePropertyAttribute : Attribute
{
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic
{
public abstract class ConfigurableScriptRule : IScriptRule
{
public bool IsRuleConfigured { get; protected set; } = false;
public void ConfigureRule()
{
var arguments = Helper.Instance.GetRuleArguments(this.GetName());
//var configurableProps = GetConfigurableProperties();
try
{
var properties = this.GetType().GetProperties();
foreach (var property in properties)
{
if (arguments.ContainsKey(property.Name))
{
var type = property.PropertyType;
var obj = arguments[property.Name];
property.SetValue(
this,
System.Convert.ChangeType(obj, Type.GetTypeCode(type)));
}
}
}
catch
{
// return arguments with defaults
}
IsRuleConfigured = true;
}
// private GetConfigurableProperties()
// {
// }
public abstract IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName);
public abstract string GetCommonName();
public abstract string GetDescription();
public abstract string GetName();
public abstract RuleSeverity GetSeverity();
public abstract string GetSourceName();
public abstract SourceType GetSourceType();
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ConfigurablePropertyAttribute : Attribute
{
}
}
| mit | C# |
588be13727830cf02ce72e6fe385922bbb3fccc1 | clear tests | chsword/ResizingServer | source/ResizingClient.Tests/UnitTest1.cs | source/ResizingClient.Tests/UnitTest1.cs | using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ResizingClient.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
//var result=ResizingUtil.Upload(File.ReadAllBytes("d:\\a.jpg"), "a.jpg", "face").Result;
//Console.WriteLine(result.FormatUrl
// );
//Assert.IsTrue(result.IsSuccess);
}
}
}
| using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ResizingClient.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var result=ResizingUtil.Upload(File.ReadAllBytes("d:\\a.jpg"), "a.jpg", "face").Result;
Console.WriteLine(result.FormatUrl
);
Assert.IsTrue(result.IsSuccess);
}
}
}
| apache-2.0 | C# |
f1239676d91666360fbc744efa37e243da4a64fd | fix subtitles but actually for real? | overtools/OWLib | TankLib/teSubtitleThing.cs | TankLib/teSubtitleThing.cs | using System.Collections.Generic;
using System.IO;
using System.Text;
namespace TankLib {
public class teSubtitleThing {
public const int COUNT = 4;
public List<string> m_strings;
public teSubtitleThing(Stream stream) {
using (var reader = new BinaryReader(stream)) {
Read(reader);
}
}
public teSubtitleThing(BinaryReader reader) {
Read(reader);
}
private void Read(BinaryReader reader) {
var offsets = reader.ReadArray<ushort>(COUNT);
m_strings = new List<string>();
for (int i = 0; i < COUNT; i++) {
var offset = offsets[i];
if (offset == 0) continue;
reader.BaseStream.Position = offset;
while (reader.ReadByte() != 0)
{
}
var end = (int) reader.BaseStream.Position - 1;
reader.BaseStream.Position = offset;
var bytes = reader.ReadBytes(end - offset);
m_strings.Add(Encoding.UTF8.GetString(bytes));
}
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Text;
namespace TankLib {
public class teSubtitleThing {
public const int COUNT = 4;
public List<string> m_strings;
public teSubtitleThing(Stream stream) {
using (var reader = new BinaryReader(stream)) {
Read(reader);
}
}
public teSubtitleThing(BinaryReader reader) {
Read(reader);
}
private void Read(BinaryReader reader) {
var offsets = reader.ReadArray<ushort>(COUNT);
m_strings = new List<string>();
for (int i = 0; i < COUNT; i++) {
var offset = offsets[i];
if (offset == 0) continue;
reader.BaseStream.Position = offset;
while (reader.ReadByte() != 0)
{
}
var end = (int)reader.BaseStream.Position;
reader.BaseStream.Position = offset;
var bytes = reader.ReadBytes(end - offset);
m_strings.Add(Encoding.UTF8.GetString(bytes));
}
}
}
}
| mit | C# |
9739ae78b375044e2d68502b0cb296dd3aa194d8 | Update ValuesOut.cs | EricZimmerman/RegistryPlugins | RegistryExplorer.MountedDevices/ValuesOut.cs | RegistryExplorer.MountedDevices/ValuesOut.cs | using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.MountedDevices
{
public class ValuesOut:IValueOut
{
public ValuesOut(string deviceName, string deviceData)
{
DeviceName = deviceName;
DeviceData = deviceData;
}
public string DeviceName { get; }
public string DeviceData { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Name: {DeviceName}";
public string BatchValueData2 => $"Data: {DeviceData}";
public string BatchValueData3 => string.Empty ;
}
}
| using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.MountedDevices
{
public class ValuesOut:IValueOut
{
public ValuesOut(string deviceName, string deviceData)
{
DeviceName = deviceName;
DeviceData = deviceData;
}
public string DeviceName { get; }
public string DeviceData { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Name: {DeviceName}";
public string BatchValueData2 => $"Data: {DeviceData})";
public string BatchValueData3 => string.Empty ;
}
} | mit | C# |
f05ce1b951319683455bfc3d31a94668393c396b | Use SequenceEqual and check null | kazyx/kz-remote-api | Project/Util/SharedStructures.cs | Project/Util/SharedStructures.cs | using System.Collections.Generic;
using System.Linq;
namespace Kazyx.RemoteApi
{
/// <summary>
/// Response of getMethodTypes API.
/// </summary>
public class MethodType
{
/// <summary>
/// Name of API
/// </summary>
public string Name { set; get; }
/// <summary>
/// Request parameter types.
/// </summary>
public List<string> ReqTypes { set; get; }
/// <summary>
/// Response parameter types.
/// </summary>
public List<string> ResTypes { set; get; }
/// <summary>
/// Version of API
/// </summary>
public string Version { set; get; }
}
/// <summary>
/// Set of current value and its candidates.
/// </summary>
/// <typeparam name="T"></typeparam>
public class Capability<T>
{
/// <summary>
/// Current value of the specified parameter.
/// </summary>
public virtual T Current { set; get; }
/// <summary>
/// Candidate values of the specified parameter.
/// </summary>
public virtual List<T> Candidates { set; get; }
public override bool Equals(object o)
{
var other = o as Capability<T>;
if (other == null) { return false; }
if (!Current.Equals(other.Current)) { return false; }
if (Candidates?.Count != other.Candidates?.Count) { return false; }
return Candidates.SequenceEqual(other.Candidates);
}
}
}
| using System.Collections.Generic;
namespace Kazyx.RemoteApi
{
/// <summary>
/// Response of getMethodTypes API.
/// </summary>
public class MethodType
{
/// <summary>
/// Name of API
/// </summary>
public string Name { set; get; }
/// <summary>
/// Request parameter types.
/// </summary>
public List<string> ReqTypes { set; get; }
/// <summary>
/// Response parameter types.
/// </summary>
public List<string> ResTypes { set; get; }
/// <summary>
/// Version of API
/// </summary>
public string Version { set; get; }
}
/// <summary>
/// Set of current value and its candidates.
/// </summary>
/// <typeparam name="T"></typeparam>
public class Capability<T>
{
/// <summary>
/// Current value of the specified parameter.
/// </summary>
public virtual T Current { set; get; }
/// <summary>
/// Candidate values of the specified parameter.
/// </summary>
public virtual List<T> Candidates { set; get; }
public override bool Equals(object o)
{
var other = o as Capability<T>;
if (!Current.Equals(other.Current))
{
return false;
}
if (Candidates?.Count != other.Candidates?.Count)
{
return false;
}
for (int i = 0; i < Candidates.Count; i++)
{
if (!Candidates[i].Equals(other.Candidates[i]))
{
return false;
}
}
return true;
}
}
}
| mit | C# |
11678f30528dfc2ecc5463ad693822d1af2ad1ff | verify test failure | sailthru/sailthru-net-client | Sailthru/Sailthru.Tests/Test.cs | Sailthru/Sailthru.Tests/Test.cs | using NUnit.Framework;
using System;
namespace Sailthru.Tests
{
[TestFixture()]
public class Test
{
[Test()]
public void TestCase()
{
Assert.Fail();
}
}
}
| using NUnit.Framework;
using System;
namespace Sailthru.Tests
{
[TestFixture()]
public class Test
{
[Test()]
public void TestCase()
{
}
}
}
| mit | C# |
223107811b4f3536ceeced869bae45461bcf4fed | Fix heartbeat interval | DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer | Server/Context/ServerContext.cs | Server/Context/ServerContext.cs | using Lidgren.Network;
using LunaCommon.Message;
using Server.Client;
using Server.Lidgren;
using Server.Settings;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Net;
namespace Server.Context
{
public static class ServerContext
{
public static ConcurrentDictionary<IPEndPoint, ClientStructure> Clients { get; set; } =
new ConcurrentDictionary<IPEndPoint, ClientStructure>();
public static bool ServerRunning { get; set; }
public static bool ServerStarting { get; set; }
public static Stopwatch ServerClock { get; } = new Stopwatch();
public static long StartTime { get; set; }
public static string ModFilePath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LMPModControl.txt");
public static int PlayerCount => ClientRetriever.GetActiveClientCount();
public static string UniverseDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Universe");
public static string ConfigDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config");
public static string Players { get; } = ClientRetriever.GetActivePlayerNames();
public static int Day { get; set; }
public static long LastPlayerActivity { get; set; }
// Configuration object
public static NetPeerConfiguration Config { get; } = new NetPeerConfiguration("LMP")
{
AutoFlushSendQueue = false,
SendBufferSize = 500000, //500kb
ReceiveBufferSize = 500000, //500kb
//Set it to false so lidgren doesn't wait until msg.size = MTU for sending
Port = GeneralSettings.SettingsStore.Port,
MaximumConnections = GeneralSettings.SettingsStore.MaxPlayers,
SuppressUnreliableUnorderedAcks = true,
PingInterval = (float)TimeSpan.FromMilliseconds(GeneralSettings.SettingsStore.HearbeatMsInterval).TotalSeconds,
ConnectionTimeout = (float)TimeSpan.FromMilliseconds(GeneralSettings.SettingsStore.ConnectionMsTimeout).TotalSeconds
};
public static LidgrenServer LidgrenServer { get; } = new LidgrenServer();
public static MasterServerMessageFactory MasterServerMessageFactory { get; } = new MasterServerMessageFactory();
public static ServerMessageFactory ServerMessageFactory { get; } = new ServerMessageFactory();
public static ClientMessageFactory ClientMessageFactory { get; } = new ClientMessageFactory();
}
} | using Lidgren.Network;
using LunaCommon.Message;
using Server.Client;
using Server.Lidgren;
using Server.Settings;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Net;
namespace Server.Context
{
public static class ServerContext
{
public static ConcurrentDictionary<IPEndPoint, ClientStructure> Clients { get; set; } =
new ConcurrentDictionary<IPEndPoint, ClientStructure>();
public static bool ServerRunning { get; set; }
public static bool ServerStarting { get; set; }
public static Stopwatch ServerClock { get; } = new Stopwatch();
public static long StartTime { get; set; }
public static string ModFilePath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LMPModControl.txt");
public static int PlayerCount => ClientRetriever.GetActiveClientCount();
public static string UniverseDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Universe");
public static string ConfigDirectory { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config");
public static string Players { get; } = ClientRetriever.GetActivePlayerNames();
public static int Day { get; set; }
public static long LastPlayerActivity { get; set; }
// Configuration object
public static NetPeerConfiguration Config { get; } = new NetPeerConfiguration("LMP")
{
AutoFlushSendQueue = false,
SendBufferSize = 500000, //500kb
ReceiveBufferSize = 500000, //500kb
//Set it to false so lidgren doesn't wait until msg.size = MTU for sending
Port = GeneralSettings.SettingsStore.Port,
MaximumConnections = GeneralSettings.SettingsStore.MaxPlayers,
SuppressUnreliableUnorderedAcks = true,
PingInterval = GeneralSettings.SettingsStore.HearbeatMsInterval,
ConnectionTimeout = (float)TimeSpan.FromMilliseconds(GeneralSettings.SettingsStore.ConnectionMsTimeout).TotalSeconds
};
public static LidgrenServer LidgrenServer { get; } = new LidgrenServer();
public static MasterServerMessageFactory MasterServerMessageFactory { get; } = new MasterServerMessageFactory();
public static ServerMessageFactory ServerMessageFactory { get; } = new ServerMessageFactory();
public static ClientMessageFactory ClientMessageFactory { get; } = new ClientMessageFactory();
}
} | mit | C# |
631887d0cd7b2292255d36b48424a184be83e25a | Comment on NixCalamariPhysicalFileSystem | NoesisLabs/Calamari,allansson/Calamari,NoesisLabs/Calamari,merbla/Calamari,allansson/Calamari,merbla/Calamari | source/Calamari/Integration/FileSystem/NixPhysicalFileSystem.cs | source/Calamari/Integration/FileSystem/NixPhysicalFileSystem.cs | using System.IO;
namespace Calamari.Integration.FileSystem
{
public class NixCalamariPhysicalFileSystem : CalamariPhysicalFileSystem
{
protected override bool GetFiskFreeSpace(string directoryPath, out ulong totalNumberOfFreeBytes)
{
// This method will not work for UNC paths on windows
// (hence WindowsPhysicalFileSystem) but should be sufficient for Linux mounts
var pathRoot = Path.GetPathRoot(directoryPath);
foreach (var drive in DriveInfo.GetDrives())
{
if (!drive.Name.Equals(pathRoot)) continue;
totalNumberOfFreeBytes = (ulong)drive.TotalFreeSpace;
return true;
}
totalNumberOfFreeBytes = 0;
return false;
}
}
}
| using System.IO;
namespace Calamari.Integration.FileSystem
{
public class NixCalamariPhysicalFileSystem : CalamariPhysicalFileSystem
{
protected override bool GetFiskFreeSpace(string directoryPath, out ulong totalNumberOfFreeBytes)
{
var pathRoot = Path.GetPathRoot(directoryPath);
foreach (var drive in DriveInfo.GetDrives())
{
if (!drive.Name.Equals(pathRoot)) continue;
totalNumberOfFreeBytes = (ulong)drive.TotalFreeSpace;
return true;
}
totalNumberOfFreeBytes = 0;
return false;
}
}
}
| apache-2.0 | C# |
4a9bc29971ff72ac9f7eef8f6aaca7ba47f2e849 | Update the GelocationHandler example - seems people are still struggling with the callback concept. | jamespearce2006/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp,Livit/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp | CefSharp.Wpf.Example/Handlers/GeolocationHandler.cs | CefSharp.Wpf.Example/Handlers/GeolocationHandler.cs | // Copyright © 2010-2016 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Windows;
namespace CefSharp.Wpf.Example.Handlers
{
internal class GeolocationHandler : IGeolocationHandler
{
bool IGeolocationHandler.OnRequestGeolocationPermission(IWebBrowser browserControl, IBrowser browser, string requestingUrl, int requestId, IGeolocationCallback callback)
{
//You can execute the callback inline
//callback.Continue(true);
//return true;
//You can execute the callback in an `async` fashion
//Open a message box on the `UI` thread and ask for user input.
//You can open a form, or do whatever you like, just make sure you either
//execute the callback or call `Dispose` as it's an `unmanaged` wrapper.
var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
chromiumWebBrowser.Dispatcher.BeginInvoke((Action)(() =>
{
//Callback wraps an unmanaged resource, so we'll make sure it's Disposed (calling Continue will also Dipose of the callback, it's safe to dispose multiple times).
using (callback)
{
var result = MessageBox.Show(String.Format("{0} wants to use your computer's location. Allow? ** You must set your Google API key in CefExample.Init() for this to work. **", requestingUrl), "Geolocation", MessageBoxButton.YesNo);
//Execute the callback, to allow/deny the request.
callback.Continue(result == MessageBoxResult.Yes);
}
}));
//Yes we'd like to hadle this request ourselves.
return true;
}
void IGeolocationHandler.OnCancelGeolocationPermission(IWebBrowser browserControl, IBrowser browser, int requestId)
{
}
}
}
| // Copyright © 2010-2016 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Windows;
namespace CefSharp.Wpf.Example.Handlers
{
internal class GeolocationHandler : IGeolocationHandler
{
bool IGeolocationHandler.OnRequestGeolocationPermission(IWebBrowser browserControl, IBrowser browser, string requestingUrl, int requestId, IGeolocationCallback callback)
{
using (callback)
{
var result = MessageBox.Show(String.Format("{0} wants to use your computer's location. Allow? ** You must set your Google API key in CefExample.Init() for this to work. **", requestingUrl), "Geolocation", MessageBoxButton.YesNo);
callback.Continue(result == MessageBoxResult.Yes);
return result == MessageBoxResult.Yes;
}
}
void IGeolocationHandler.OnCancelGeolocationPermission(IWebBrowser browserControl, IBrowser browser, int requestId)
{
}
}
}
| bsd-3-clause | C# |
ccc3c573abd6e1ae018947db37f5f27d7475b483 | Fix resharper not fixing | DrabWeb/osu,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,naoey/osu,DrabWeb/osu,peppy/osu,EVAST9919/osu,UselessToucan/osu,naoey/osu,2yangk23/osu,naoey/osu,smoogipoo/osu,Frontear/osuKyzer,smoogipoo/osu,Nabile-Rahmani/osu,peppy/osu,DrabWeb/osu,johnneijzen/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu,ZLima12/osu,peppy/osu,ZLima12/osu,2yangk23/osu | osu.Game.Rulesets.Osu/Tests/TestCaseGameplayCursor.cs | osu.Game.Rulesets.Osu/Tests/TestCaseGameplayCursor.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Game.Graphics.Cursor;
using osu.Game.Rulesets.Osu.UI.Cursor;
using osu.Game.Tests.Visual;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class TestCaseGameplayCursor : OsuTestCase, IProvideCursor
{
private GameplayCursor cursor;
public override IReadOnlyList<Type> RequiredTypes => new [] { typeof(CursorTrail) };
public CursorContainer Cursor => cursor;
public bool ProvidingUserCursor => true;
[BackgroundDependencyLoader]
private void load()
{
Add(cursor = new GameplayCursor { RelativeSizeAxes = Axes.Both });
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Game.Graphics.Cursor;
using osu.Game.Rulesets.Osu.UI.Cursor;
using osu.Game.Tests.Visual;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class TestCaseGameplayCursor : OsuTestCase, IProvideCursor
{
private GameplayCursor cursor;
public override IReadOnlyList<Type> RequiredTypes => new [] { typeof(CursorTrail) };
public CursorContainer Cursor => cursor;
public bool ProvidingUserCursor => true;
[BackgroundDependencyLoader]
private void load()
{
Add(cursor = new GameplayCursor() { RelativeSizeAxes = Axes.Both });
}
}
}
| mit | C# |
a1aeac567710b95f27b07daede58b9a1ad56ab45 | Remove remaining cruft from `SkinnableAccuracyCounter` | peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,peppy/osu,smoogipooo/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu | osu.Game/Screens/Play/HUD/SkinnableAccuracyCounter.cs | osu.Game/Screens/Play/HUD/SkinnableAccuracyCounter.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Skinning;
namespace osu.Game.Screens.Play.HUD
{
public class SkinnableAccuracyCounter : SkinnableDrawable
{
public SkinnableAccuracyCounter()
: base(new HUDSkinComponent(HUDSkinComponents.AccuracyCounter), _ => new DefaultAccuracyCounter())
{
CentreComponent = false;
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Game.Skinning;
namespace osu.Game.Screens.Play.HUD
{
public class SkinnableAccuracyCounter : SkinnableDrawable
{
public Bindable<double> Current { get; } = new Bindable<double>();
public SkinnableAccuracyCounter()
: base(new HUDSkinComponent(HUDSkinComponents.AccuracyCounter), _ => new DefaultAccuracyCounter())
{
CentreComponent = false;
}
}
}
| mit | C# |
6896d61c6a42fb55019202744ce64266e9b4444d | Update RestEndpointAttribute.cs | tiksn/TIKSN-Framework | TIKSN.Core/Web/Rest/RestEndpointAttribute.cs | TIKSN.Core/Web/Rest/RestEndpointAttribute.cs | using System;
namespace TIKSN.Web.Rest
{
[AttributeUsage(AttributeTargets.Class)]
public class RestEndpointAttribute : Attribute
{
public RestEndpointAttribute(string apiKey, RestVerb verb, string resourceTemplate,
RestAuthenticationType authentication = RestAuthenticationType.None, string mediaType = "application/json")
{
this.ApiKey = apiKey;
this.Verb = verb;
this.ResourceTemplate = resourceTemplate;
this.MediaType = mediaType;
this.Authentication = authentication;
}
public string ApiKey { get; }
public RestAuthenticationType Authentication { get; }
public string MediaType { get; }
public string ResourceTemplate { get; }
public RestVerb Verb { get; }
}
}
| using System;
namespace TIKSN.Web.Rest
{
[AttributeUsage(AttributeTargets.Class)]
public class RestEndpointAttribute : Attribute
{
public RestEndpointAttribute(string apiKey, RestVerb verb, string resourceTemplate,
RestAuthenticationType authentication = RestAuthenticationType.None, string mediaType = "application/json")
{
this.ApiKey = new Guid(apiKey);
this.Verb = verb;
this.ResourceTemplate = resourceTemplate;
this.MediaType = mediaType;
this.Authentication = authentication;
}
public Guid ApiKey { get; }
public RestAuthenticationType Authentication { get; }
public string MediaType { get; }
public string ResourceTemplate { get; }
public RestVerb Verb { get; }
}
}
| mit | C# |
632d72f9802bd4155c007d99d2b85e174d422e12 | Use Operator<T>.Negate | farity/farity | Farity/Negate.cs | Farity/Negate.cs | using System;
using System.Linq.Expressions;
namespace Farity
{
public static partial class F
{
public static T Negate<T>(T n)
where T : struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T>,
IFormattable => Operator<T>.Negate(n);
}
} | using System;
using System.Linq.Expressions;
namespace Farity
{
public static partial class F
{
public static T Negate<T>(T n)
where T : struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T>,
IFormattable => (T) (object) Expression.Negate((Expression) (object) n);
}
} | mit | C# |
56a68b664a39d62c910502f5beaf5e9dda66e8ed | Handle message changing inventory size | k-t/SharpHaven | MonoHaven.Client/UI/Remote/ServerInventoryWidget.cs | MonoHaven.Client/UI/Remote/ServerInventoryWidget.cs | using System.Drawing;
using MonoHaven.UI.Widgets;
namespace MonoHaven.UI.Remote
{
public class ServerInventoryWidget : ServerWidget
{
public static ServerWidget Create(ushort id, ServerWidget parent, object[] args)
{
var size = (Point)args[0];
var widget = new InventoryWidget(parent.Widget);
widget.SetInventorySize(size);
return new ServerInventoryWidget(id, parent, widget);
}
private readonly InventoryWidget widget;
public ServerInventoryWidget(ushort id, ServerWidget parent, InventoryWidget widget)
: base(id, parent, widget)
{
this.widget = widget;
this.widget.Drop += (p) => SendMessage("drop", p);
this.widget.Transfer += OnTransfer;
}
public override void ReceiveMessage(string message, object[] args)
{
if (message == "sz")
widget.SetInventorySize((Point)args[0]);
else
base.ReceiveMessage(message, args);
}
private void OnTransfer(TransferEventArgs e)
{
var mods = ServerInput.ToServerModifiers(e.Modifiers);
SendMessage("xfer", e.Delta, mods);
}
}
}
| using System.Drawing;
using MonoHaven.UI.Widgets;
namespace MonoHaven.UI.Remote
{
public class ServerInventoryWidget : ServerWidget
{
public static ServerWidget Create(ushort id, ServerWidget parent, object[] args)
{
var size = (Point)args[0];
var widget = new InventoryWidget(parent.Widget);
widget.SetInventorySize(size);
return new ServerInventoryWidget(id, parent, widget);
}
public ServerInventoryWidget(ushort id, ServerWidget parent, InventoryWidget widget)
: base(id, parent, widget)
{
widget.Drop += (p) => SendMessage("drop", p);
widget.Transfer += OnTransfer;
}
private void OnTransfer(TransferEventArgs e)
{
var mods = ServerInput.ToServerModifiers(e.Modifiers);
SendMessage("xfer", e.Delta, mods);
}
}
}
| mit | C# |
96090eef85f1d62c62c740cce3058ce7be84fda8 | Change version to 1.3.0 | alexanderar/Mvc.CascadeDropDown,alexanderar/Mvc.CascadeDropDown,Li-Yanzhi/Mvc.CascadeDropDown,alexanderar/Mvc.CascadeDropDown,Li-Yanzhi/Mvc.CascadeDropDown,Li-Yanzhi/Mvc.CascadeDropDown | Mvc.CascadeDropDown.Test/Properties/AssemblyInfo.cs | Mvc.CascadeDropDown.Test/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("Mvc.CascadeDropDown.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mvc.CascadeDropDown.Test")]
[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("e8981c5c-8a57-45d7-ba19-d939112af931")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.3.0")]
[assembly: AssemblyFileVersion("1.3.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("Mvc.CascadeDropDown.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mvc.CascadeDropDown.Test")]
[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("e8981c5c-8a57-45d7-ba19-d939112af931")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
0257cbc516a0390031c1f1bc302fd40258757c6d | Bump version to 0.7.3 | quisquous/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot,sqt/cactbot,sqt/cactbot | CactbotOverlay/Properties/AssemblyInfo.cs | CactbotOverlay/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.7.3.0")]
[assembly: AssemblyFileVersion("0.7.3.0")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.7.2.0")]
[assembly: AssemblyFileVersion("0.7.2.0")] | apache-2.0 | C# |
ade17fc5e1935e36c8c5029f0bc905457376dc1d | Use the real command line. | GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,ivannaranjo/google-cloud-visualstudio,Deren-Liao/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,ivannaranjo/google-cloud-visualstudio,ILMTitan/google-cloud-visualstudio,ILMTitan/google-cloud-visualstudio,Deren-Liao/google-cloud-visualstudio,ILMTitan/google-cloud-visualstudio,ivannaranjo/google-cloud-visualstudio,ILMTitan/google-cloud-visualstudio,ILMTitan/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,Deren-Liao/google-cloud-visualstudio | GoogleCloudExtension/GoogleCloudExtension/ErrorDialogs/ValidationErrorDialogViewModel.cs | GoogleCloudExtension/GoogleCloudExtension/ErrorDialogs/ValidationErrorDialogViewModel.cs | // Copyright 2015 Google Inc. All Rights Reserved.
// Licensed under the Apache License Version 2.0.
using GoogleCloudExtension.Utils;
using System;
using System.Linq;
using System.Windows.Input;
namespace GoogleCloudExtension.ErrorDialogs
{
/// <summary>
/// The view model for the ValidationErrorDialog.
/// </summary>
public class ValidationErrorDialogViewModel : ViewModelBase
{
private readonly ValidationErrorDialogWindow _owner;
private readonly GCloudValidationResult _gcloudValidationResult;
private readonly DnxValidationResult _dnxValidationResult;
/// <summary>
/// Whether there are missing components to display.
/// </summary>
public bool ShowMissingComponents => (_gcloudValidationResult?.MissingComponents.Count ?? 0) != 0;
// Whether to show the error message about missing the gcloud SDK.
public bool ShowMissingGCloud => !(_gcloudValidationResult?.IsGCloudInstalled ?? true);
// Whether to show the error message about missing the DNX runtime.
public bool ShowMissingDnxRuntime => !(_dnxValidationResult?.IsValidDnxInstallation() ?? true);
// The command line to use to isntall the missing components.
public string InstallComponentsCommandLine { get; }
/// <summary>
/// The command to execute when pressing the OK button.
/// </summary>
public ICommand OnOkCommand { get; }
public ValidationErrorDialogViewModel(
ValidationErrorDialogWindow owner,
GCloudValidationResult gcloudValidationResult,
DnxValidationResult dnxValidationResult)
{
_owner = owner;
_gcloudValidationResult = gcloudValidationResult;
_dnxValidationResult = dnxValidationResult;
var missingComponentsList = String.Join(" ", _gcloudValidationResult?.MissingComponents?.Select(x => x.Id) ?? Enumerable.Empty<string>());
InstallComponentsCommandLine = $"gcloud components install {missingComponentsList}";
OnOkCommand = new WeakCommand(() => _owner.Close());
}
}
}
| // Copyright 2015 Google Inc. All Rights Reserved.
// Licensed under the Apache License Version 2.0.
using GoogleCloudExtension.Utils;
using System;
using System.Linq;
using System.Windows.Input;
namespace GoogleCloudExtension.ErrorDialogs
{
/// <summary>
/// The view model for the ValidationErrorDialog.
/// </summary>
public class ValidationErrorDialogViewModel : ViewModelBase
{
private readonly ValidationErrorDialogWindow _owner;
private readonly GCloudValidationResult _gcloudValidationResult;
private readonly DnxValidationResult _dnxValidationResult;
/// <summary>
/// Whether there are missing components to display.
/// </summary>
public bool ShowMissingComponents => (_gcloudValidationResult?.MissingComponents.Count ?? 0) != 0;
// Whether to show the error message about missing the gcloud SDK.
public bool ShowMissingGCloud => !(_gcloudValidationResult?.IsGCloudInstalled ?? true);
// Whether to show the error message about missing the DNX runtime.
public bool ShowMissingDnxRuntime => !(_dnxValidationResult?.IsValidDnxInstallation() ?? true);
// The command line to use to isntall the missing components.
public string InstallComponentsCommandLine { get; }
/// <summary>
/// The command to execute when pressing the OK button.
/// </summary>
public ICommand OnOkCommand { get; }
public ValidationErrorDialogViewModel(
ValidationErrorDialogWindow owner,
GCloudValidationResult gcloudValidationResult,
DnxValidationResult dnxValidationResult)
{
_owner = owner;
_gcloudValidationResult = gcloudValidationResult;
_dnxValidationResult = dnxValidationResult;
var missingComponentsList = String.Join(" ", _gcloudValidationResult?.MissingComponents?.Select(x => x.Id) ?? Enumerable.Empty<string>());
InstallComponentsCommandLine = $"gcloud components update {missingComponentsList}";
OnOkCommand = new WeakCommand(() => _owner.Close());
}
}
}
| apache-2.0 | C# |
f151bfc0efea4f16b612509b6f7f30ba686dd888 | Bump version to 0.8 | jamesfoster/DeepEqual | src/DeepEqual/Properties/AssemblyInfo.cs | src/DeepEqual/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("DeepEqual")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DeepEqual")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("2db8921a-dc9f-4b4a-b651-cd71eac66b39")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.8.0.0")]
[assembly: AssemblyFileVersion("0.8.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("DeepEqual")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DeepEqual")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("2db8921a-dc9f-4b4a-b651-cd71eac66b39")]
// 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.7.0.0")]
[assembly: AssemblyFileVersion("0.7.0.0")]
| mit | C# |
81862323c036d6dbb1e88c1135d7a689df1468a2 | Update BradleyWyatt.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/BradleyWyatt.cs | src/Firehose.Web/Authors/BradleyWyatt.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class BradleyWyatt : IAmACommunityMember
{
public string FirstName => "Bradley";
public string LastName => "Wyatt";
public string ShortBioOrTagLine => "Finding wayt to do the most work with the least effort possible";
public string StateOrRegion => "Chicago, Illinois";
public string EmailAddress => "[email protected]";
public string GravatarHash => "c4eaa00e143c7abb1362dc9a8a48da09";
public string TwitterHandle => "bwya77";
public string GitHubHandle => "bwya77";
public Uri WebSite => new Uri("https://www.thelazyadministrator.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.thelazyadministrator.com/feed/"); } }
}
}
| public class BradleyWyatt : IAmACommunityMember
{
public string FirstName => "Bradley";
public string LastName => "Wyatt";
public string ShortBioOrTagLine => "Finding wayt to do the most work with the least effort possible";
public string StateOrRegion => "Chicago, Illinois";
public string EmailAddress => "[email protected]";
public string GravatarHash => "c4eaa00e143c7abb1362dc9a8a48da09";
public string TwitterHandle => "bwya77";
public string GitHubHandle => "bwya77";
public Uri WebSite => new Uri("https://www.thelazyadministrator.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.thelazyadministrator.com/feed/"); } }
}
| mit | C# |
e2a9f256b8eba0030eccc05463019aeb81e50dc1 | Use polling rate of 30 | LibertyLocked/RestRPC,LibertyLocked/RestRPC,LibertyLocked/RestRPC,LibertyLocked/RestRPC | WebScriptHook.Service/Program.cs | WebScriptHook.Service/Program.cs | using CommandLine;
using System;
using System.IO;
using System.Threading;
using WebScriptHook.Framework;
using WebScriptHook.Framework.BuiltinPlugins;
using WebScriptHook.Framework.Plugins;
using WebScriptHook.Service.Plugins;
namespace WebScriptHook.Service
{
class Program
{
static WebScriptHookComponent wshComponent;
static void Main(string[] args)
{
string componentName = Guid.NewGuid().ToString();
Uri remoteUri;
var options = new CommandLineOptions();
if (Parser.Default.ParseArguments(args, options))
{
if (!string.IsNullOrWhiteSpace(options.Name)) componentName = options.Name;
remoteUri = new Uri(options.ServerUriString);
}
else
{
return;
}
wshComponent = new WebScriptHookComponent(componentName, remoteUri, TimeSpan.FromMilliseconds(30), Console.Out, LogType.All);
// Register custom plugins
wshComponent.PluginManager.RegisterPlugin(new Echo());
wshComponent.PluginManager.RegisterPlugin(new PluginList());
wshComponent.PluginManager.RegisterPlugin(new PrintToScreen());
// Load plugins in plugins directory if dir exists
if (Directory.Exists("plugins"))
{
var plugins = PluginLoader.LoadAllPluginsFromDir("plugins", "*.dll");
foreach (var plug in plugins)
{
wshComponent.PluginManager.RegisterPlugin(plug);
}
}
// Start WSH component
wshComponent.Start();
// TODO: Use a timer instead of Sleep
while (true)
{
wshComponent.Update();
Thread.Sleep(100);
}
}
}
}
| using CommandLine;
using System;
using System.IO;
using System.Threading;
using WebScriptHook.Framework;
using WebScriptHook.Framework.BuiltinPlugins;
using WebScriptHook.Framework.Plugins;
using WebScriptHook.Service.Plugins;
namespace WebScriptHook.Service
{
class Program
{
static WebScriptHookComponent wshComponent;
static void Main(string[] args)
{
string componentName = Guid.NewGuid().ToString();
Uri remoteUri;
var options = new CommandLineOptions();
if (Parser.Default.ParseArguments(args, options))
{
if (!string.IsNullOrWhiteSpace(options.Name)) componentName = options.Name;
remoteUri = new Uri(options.ServerUriString);
}
else
{
return;
}
wshComponent = new WebScriptHookComponent(componentName, remoteUri, Console.Out, LogType.All);
// Register custom plugins
wshComponent.PluginManager.RegisterPlugin(new Echo());
wshComponent.PluginManager.RegisterPlugin(new PluginList());
wshComponent.PluginManager.RegisterPlugin(new PrintToScreen());
// Load plugins in plugins directory if dir exists
if (Directory.Exists("plugins"))
{
var plugins = PluginLoader.LoadAllPluginsFromDir("plugins", "*.dll");
foreach (var plug in plugins)
{
wshComponent.PluginManager.RegisterPlugin(plug);
}
}
// Start WSH component
wshComponent.Start();
// TODO: Use a timer instead of Sleep
while (true)
{
wshComponent.Update();
Thread.Sleep(100);
}
}
}
}
| mit | C# |
d36c896df736bc30ba79d5b6825443137fa48213 | Mark version as alpha | fvilers/WebApi.Contrib | src/AssemblyVersion.cs | src/AssemblyVersion.cs | using System.Reflection;
// 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: AssemblyInformationalVersion("1.0.0-alpha")] | using System.Reflection;
// 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.*")]
| mit | C# |
ea067b72838bee73bbc297ee182d8e844e3be1db | Add HttpTestHandler.IsConnected | yufeih/Common | src/HttpTestHandler.cs | src/HttpTestHandler.cs | namespace System.Net.Http
{
using System;
using System.Threading;
using System.Threading.Tasks;
class HttpTestHandler : DelegatingHandler
{
private static Random random = new Random();
private bool once;
public TimeSpan Latency { get; set; } = TimeSpan.Zero;
public double NetworkAvailibility { get; set; } = 1;
public bool IsConnected { get; set; } = true;
public HttpStatusCode? StatusCode { get; set; }
public Func<HttpRequestMessage, bool> Predicate { get; set; }
public HttpTestHandler() { }
public HttpTestHandler(HttpMessageHandler handler) : base(handler ?? new HttpClientHandler()) { }
public void SetStatusCodeOnce(HttpStatusCode code, Func<HttpRequestMessage, bool> predicate = null)
{
StatusCode = code;
once = true;
}
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (Predicate != null && !Predicate(request))
{
return await base.SendAsync(request, cancellationToken);
}
if (StatusCode.HasValue)
{
var response = new HttpResponseMessage(StatusCode.Value);
if (once) { once = false; StatusCode = null; }
return response;
}
await Task.Delay(random.Next((int)Latency.TotalMilliseconds / 2) + (int)Latency.TotalMilliseconds);
if (random.NextDouble() > NetworkAvailibility || !IsConnected)
{
throw new HttpRequestException("Faked exception from " + typeof(HttpTestHandler).Name);
}
return await base.SendAsync(request, cancellationToken);
}
}
} | namespace System.Net.Http
{
using System;
using System.Threading;
using System.Threading.Tasks;
class HttpTestHandler : DelegatingHandler
{
private static Random random = new Random();
private bool once;
public TimeSpan Latency { get; set; } = TimeSpan.Zero;
public double NetworkAvailibility { get; set; } = 1;
public HttpStatusCode? StatusCode { get; set; }
public Func<HttpRequestMessage, bool> Predicate { get; set; }
public HttpTestHandler() { }
public HttpTestHandler(HttpMessageHandler handler) : base(handler ?? new HttpClientHandler()) { }
public void SetStatusCodeOnce(HttpStatusCode code, Func<HttpRequestMessage, bool> predicate = null)
{
StatusCode = code;
once = true;
}
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (Predicate != null && !Predicate(request))
{
return await base.SendAsync(request, cancellationToken);
}
if (StatusCode.HasValue)
{
var response = new HttpResponseMessage(StatusCode.Value);
if (once) { once = false; StatusCode = null; }
return response;
}
await Task.Delay(random.Next((int)Latency.TotalMilliseconds / 2) + (int)Latency.TotalMilliseconds);
if (random.NextDouble() > NetworkAvailibility)
{
throw new HttpRequestException("Faked exception from " + typeof(HttpTestHandler).Name);
}
return await base.SendAsync(request, cancellationToken);
}
}
} | mit | C# |
b000a4f87aa506f8857cf6263807a701b5c97972 | Update RemoteNLogViewerOptionsPartialConfigurationValidator.cs | tiksn/TIKSN-Framework | TIKSN.Core/Analytics/Logging/NLog/RemoteNLogViewerOptionsPartialConfigurationValidator.cs | TIKSN.Core/Analytics/Logging/NLog/RemoteNLogViewerOptionsPartialConfigurationValidator.cs | using FluentValidation;
using TIKSN.Configuration.Validator;
namespace TIKSN.Analytics.Logging.NLog
{
public class
RemoteNLogViewerOptionsPartialConfigurationValidator : PartialConfigurationFluentValidatorBase<
RemoteNLogViewerOptions>
{
public RemoteNLogViewerOptionsPartialConfigurationValidator() =>
this.RuleFor(instance => instance.Url.Scheme)
.Must(IsProperScheme)
.When(instance => instance.Url != null);
private static bool IsProperScheme(string scheme)
{
switch (scheme.ToLowerInvariant())
{
case "tcp":
case "tcp4":
case "tcp6":
case "udp":
case "udp4":
case "udp6":
case "http":
case "https":
return true;
default:
return false;
}
}
}
}
| using FluentValidation;
using TIKSN.Configuration.Validator;
namespace TIKSN.Analytics.Logging.NLog
{
public class RemoteNLogViewerOptionsPartialConfigurationValidator : PartialConfigurationFluentValidatorBase<RemoteNLogViewerOptions>
{
public RemoteNLogViewerOptionsPartialConfigurationValidator()
{
RuleFor(instance => instance.Url.Scheme)
.Must(IsProperScheme)
.When(instance => instance.Url != null);
}
private static bool IsProperScheme(string scheme)
{
switch (scheme.ToLowerInvariant())
{
case "tcp":
case "tcp4":
case "tcp6":
case "udp":
case "udp4":
case "udp6":
case "http":
case "https":
return true;
default:
return false;
}
}
}
} | mit | C# |
1d975e352cd52bd0c06d7f3d1353990f3b5fafe5 | Change Json Library | CloudBreadProject/CloudBread-Client-Unity,CloudBreadProject/CloudBread-Client-Unity,CloudBreadProject/CloudBread-Client-Unity,CloudBreadProject/CloudBread-Client-Unity | Assets/Scripts/CloudBread/AzureAuthentication.cs | Assets/Scripts/CloudBread/AzureAuthentication.cs | using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class AzureAuthentication : MonoBehaviour {
public class AuthenticationToken
{
}
public class FacebookGoogleAuthenticationToken : AuthenticationToken
{
public string access_token;
}
public class MicrosoftAuthenticationToken : AuthenticationToken
{
public string authenticationToken;
}
public enum AuthenticationProvider
{
// Summary:
// Microsoft Account authentication provider.
MicrosoftAccount = 0,
//
// Summary:
// Google authentication provider.
Google = 1,
//
// Summary:
// Twitter authentication provider.
Twitter = 2,
//
// Summary:
// Facebook authentication provider.
Facebook = 3,
}
private Action<string,WWW> Callback_Success;
private Action<string,WWW> Callback_Error;
public void Login(AuthenticationProvider provider, string ServerAddress, string token, Action<string, WWW> callback_success, Action<string, WWW> callback_error){
var path = ".auth/login/" + provider.ToString().ToLower();
AuthenticationToken authToken = CreateToken(provider, token);
string json = JsonUtility.ToJson(authToken);
print (json);
Callback_Success = callback_success;
Callback_Error = callback_error;
WWWHelper helper = WWWHelper.Instance;
helper.OnHttpRequest += OnHttpRequest;
helper.POST ("Login", ServerAddress + path, json);
}
public void OnHttpRequest(string id, WWW www) {
WWWHelper helper = WWWHelper.Instance;
helper.OnHttpRequest -= OnHttpRequest;
if (www.error != null) {
// Debug.Log ("[Error] " + www.error);
Callback_Error(id,www);
} else {
// Debug.Log (www.text);
Callback_Success(id, www);
}
}
private static AuthenticationToken CreateToken(AuthenticationProvider provider, string token)
{
AuthenticationToken authToken = new AuthenticationToken();
switch (provider)
{
case AuthenticationProvider.Facebook:
case AuthenticationProvider.Google:
case AuthenticationProvider.Twitter:
{
authToken = new FacebookGoogleAuthenticationToken() { access_token = token };
break;
}
case AuthenticationProvider.MicrosoftAccount:
{
authToken = new MicrosoftAuthenticationToken() { authenticationToken = token };
break;
}
}
return authToken;
}
}
| using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using AssemblyCSharp;
public class AzureAuthentication : MonoBehaviour {
public class AuthenticationToken
{
}
public class FacebookGoogleAuthenticationToken : AuthenticationToken
{
public string access_token;
}
public class MicrosoftAuthenticationToken : AuthenticationToken
{
public string authenticationToken;
}
public enum AuthenticationProvider
{
// Summary:
// Microsoft Account authentication provider.
MicrosoftAccount = 0,
//
// Summary:
// Google authentication provider.
Google = 1,
//
// Summary:
// Twitter authentication provider.
Twitter = 2,
//
// Summary:
// Facebook authentication provider.
Facebook = 3,
}
private Action<string,WWW> Callback_Success;
private Action<string,WWW> Callback_Error;
public void Login(AuthenticationProvider provider, string ServerAddress, string token, Action<string, WWW> callback_success, Action<string, WWW> callback_error){
var path = ".auth/login/" + provider.ToString().ToLower();
AuthenticationToken authToken = CreateToken(provider, token);
var json = JsonParser.Write(authToken);
print (json);
Callback_Success = callback_success;
Callback_Error = callback_error;
WWWHelper helper = WWWHelper.Instance;
helper.OnHttpRequest += OnHttpRequest;
helper.POST ("Login", ServerAddress + path, json);
}
public void OnHttpRequest(string id, WWW www) {
WWWHelper helper = WWWHelper.Instance;
helper.OnHttpRequest -= OnHttpRequest;
if (www.error != null) {
// Debug.Log ("[Error] " + www.error);
Callback_Error(id,www);
} else {
// Debug.Log (www.text);
Callback_Success(id, www);
}
}
private static AuthenticationToken CreateToken(AuthenticationProvider provider, string token)
{
AuthenticationToken authToken = new AuthenticationToken();
switch (provider)
{
case AuthenticationProvider.Facebook:
case AuthenticationProvider.Google:
case AuthenticationProvider.Twitter:
{
authToken = new FacebookGoogleAuthenticationToken() { access_token = token };
break;
}
case AuthenticationProvider.MicrosoftAccount:
{
authToken = new MicrosoftAuthenticationToken() { authenticationToken = token };
break;
}
}
return authToken;
}
}
| mit | C# |
15af11569eaf2d47c5a4251645b92dd17b26876c | Fix cherry pick | ITGlobal/CefSharp,gregmartinhtc/CefSharp,rlmcneary2/CefSharp,jamespearce2006/CefSharp,AJDev77/CefSharp,battewr/CefSharp,Livit/CefSharp,illfang/CefSharp,Livit/CefSharp,Octopus-ITSM/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,haozhouxu/CefSharp,joshvera/CefSharp,Haraguroicha/CefSharp,rlmcneary2/CefSharp,VioletLife/CefSharp,VioletLife/CefSharp,Livit/CefSharp,wangzheng888520/CefSharp,jamespearce2006/CefSharp,haozhouxu/CefSharp,Livit/CefSharp,dga711/CefSharp,joshvera/CefSharp,wangzheng888520/CefSharp,dga711/CefSharp,VioletLife/CefSharp,gregmartinhtc/CefSharp,Haraguroicha/CefSharp,illfang/CefSharp,dga711/CefSharp,Octopus-ITSM/CefSharp,NumbersInternational/CefSharp,VioletLife/CefSharp,Haraguroicha/CefSharp,AJDev77/CefSharp,jamespearce2006/CefSharp,windygu/CefSharp,yoder/CefSharp,battewr/CefSharp,ITGlobal/CefSharp,rover886/CefSharp,rover886/CefSharp,haozhouxu/CefSharp,zhangjingpu/CefSharp,zhangjingpu/CefSharp,illfang/CefSharp,battewr/CefSharp,NumbersInternational/CefSharp,ruisebastiao/CefSharp,twxstar/CefSharp,battewr/CefSharp,Haraguroicha/CefSharp,dga711/CefSharp,NumbersInternational/CefSharp,joshvera/CefSharp,twxstar/CefSharp,Haraguroicha/CefSharp,windygu/CefSharp,zhangjingpu/CefSharp,ruisebastiao/CefSharp,ruisebastiao/CefSharp,NumbersInternational/CefSharp,twxstar/CefSharp,wangzheng888520/CefSharp,windygu/CefSharp,ITGlobal/CefSharp,jamespearce2006/CefSharp,yoder/CefSharp,gregmartinhtc/CefSharp,illfang/CefSharp,wangzheng888520/CefSharp,Octopus-ITSM/CefSharp,rover886/CefSharp,rlmcneary2/CefSharp,AJDev77/CefSharp,Octopus-ITSM/CefSharp,windygu/CefSharp,twxstar/CefSharp,haozhouxu/CefSharp,rover886/CefSharp,gregmartinhtc/CefSharp,rover886/CefSharp,yoder/CefSharp,AJDev77/CefSharp,yoder/CefSharp,jamespearce2006/CefSharp,ruisebastiao/CefSharp,joshvera/CefSharp,ITGlobal/CefSharp | CefSharp/IsBrowserInitializedChangedEventArgs.cs | CefSharp/IsBrowserInitializedChangedEventArgs.cs | // Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
namespace CefSharp
{
/// <summary>
/// Event arguments to the IsBrowserInitializedChanged event handler.
/// </summary>
public class IsBrowserInitializedChangedEventArgs : EventArgs
{
public bool IsBrowserInitialized { get; private set; }
public IsBrowserInitializedChangedEventArgs(bool isBrowserInitialized)
{
IsBrowserInitialized = isBrowserInitialized;
}
}
};
/// <summary>
/// A delegate type used to listen to IsBrowserInitializedChanged events.
/// </summary>
public delegate void IsBrowserInitializedChangedEventHandler(object sender, IsBrowserInitializedChangedEventArgs args);
}
| // Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
namespace CefSharp
{
/// <summary>
/// Event arguments to the IsBrowserInitializedChanged event handler.
/// </summary>
public class IsBrowserInitializedChangedEventArgs : EventArgs
{
public bool IsBrowserInitialized { get; private set; }
public IsBrowserInitializedChangedEventArgs(bool isBrowserInitialized)
{
IsBrowserInitialized = isBrowserInitialized;
}
};
/// <summary>
/// A delegate type used to listen to IsBrowserInitializedChanged events.
/// </summary>
public delegate void IsBrowserInitializedChangedEventHandler(object sender, IsBrowserInitializedChangedEventArgs args);
}
| bsd-3-clause | C# |
d4e144d4f33f9b5e61b0b242096431314ed7ea33 | remove console logs from tests | yevhen/OrleansDashboard,yevhen/OrleansDashboard,OrleansContrib/OrleansDashboard,OrleansContrib/OrleansDashboard,yevhen/OrleansDashboard,OrleansContrib/OrleansDashboard | UnitTests/TypeFormatterTests.cs | UnitTests/TypeFormatterTests.cs | using System;
using OrleansDashboard;
using TestGrains;
using Xunit;
namespace UnitTests
{
public class TypeFormatterTests
{
[Fact]
public void TestSimpleType()
{
var example = "System.String";
var name = TypeFormatter.Parse(example);
Assert.Equal("System.String", name);
}
[Fact]
public void TestFriendlyNameForStrings()
{
var example = "TestGrains.GenericGrain`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]";
var name = TypeFormatter.Parse(example);
Assert.Equal("TestGrains.GenericGrain<String>", name);
}
[Fact]
public void TestGenericWithMultipleTs()
{
var example = typeof(IGenericGrain<Tuple<string, int>>).FullName;
var name = TypeFormatter.Parse(example);
Assert.Equal("TestGrains.IGenericGrain<Tuple<String, Int32>>", name);
}
[Fact]
public void TestGenericGrainWithMultipleTs()
{
var example = typeof(ITestGenericGrain<string, int>).FullName;
var name = TypeFormatter.Parse(example);
Assert.Equal("TestGrains.ITestGenericGrain<String, Int32>", name);
}
}
} | using System;
using OrleansDashboard;
using TestGrains;
using Xunit;
namespace UnitTests
{
public class TypeFormatterTests
{
[Fact]
public void TestSimpleType()
{
var example = "System.String";
var name = TypeFormatter.Parse(example);
Assert.Equal("System.String", name);
}
[Fact]
public void TestFriendlyNameForStrings()
{
var example = "TestGrains.GenericGrain`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]";
var name = TypeFormatter.Parse(example);
Assert.Equal("TestGrains.GenericGrain<String>", name);
}
[Fact]
public void TestGenericWithMultipleTs()
{
var example = typeof(IGenericGrain<Tuple<string, int>>).FullName;
Console.WriteLine(example);
var name = TypeFormatter.Parse(example);
Assert.Equal("TestGrains.IGenericGrain<Tuple<String, Int32>>", name);
}
[Fact]
public void TestGenericGrainWithMultipleTs()
{
var example = typeof(ITestGenericGrain<string, int>).FullName;
Console.WriteLine(example);
var name = TypeFormatter.Parse(example);
Assert.Equal("TestGrains.ITestGenericGrain<String, Int32>", name);
}
}
} | mit | C# |
a7bb761521e44eeeaa5eb8bd3d22c9fdfde41a30 | Update Read.cshtml | planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Views/Feed/Read.cshtml | src/Firehose.Web/Views/Feed/Read.cshtml | @using BlogMonster.Extensions
@using Firehose.Web.Infrastructure
@using Firehose.Web.Extensions
@using ThirdDrawer.Extensions.ClassExtensionMethods
@model System.ServiceModel.Syndication.SyndicationFeed
@{
Layout = "~/Views/Shared/_ContainerLayout.cshtml";
}
@foreach (var item in Model.Items)
{
var author = item.Authors.FirstOrDefault();
var authorName = author.Coalesce(a => a.Name, string.Empty);
var authorEmail = author.Coalesce(a => a.Email, string.Empty);
var link = item.Links.FirstOrDefault().Coalesce(l => l.Uri.ToString(), string.Empty);
var html = item.Content.Coalesce(c => c.ToHtml(),
item.Summary.Coalesce(c => c.ToHtml(), string.Empty)
);
<div class="syndicationItem">
<h1 class="syndicationItemTitle"><a href="@link" target="_blank">@Html.Raw(item.Title.Text)</a></h1>
<h2 class="syndicationItemDate">@item.PublishDate.ToString("dd MMMM yyyy")</h2>
@*<img class="syndicationItemPhoto" src="@authorEmail.GravatarImage()" alt="@authorName avatar" />*@
<h2 class="syndicationItemByLine">@authorName</h2>
@if (!string.IsNullOrWhiteSpace(@authorEmail))
{
<a href="mailto:@authorEmail">@authorEmail</a>
}
<br style="clear: both" />
<hr />
<div class="syndicationItemContent">
@Html.Raw(html)
</div>
<div class="syndicationItemFooter">
<hr />
<p>View the original of this post at <a href="@link">@link</a></p>
<hr />
</div>
</div>
}
| @using BlogMonster.Extensions
@using Firehose.Web.Infrastructure
@using ThirdDrawer.Extensions.ClassExtensionMethods
@model System.ServiceModel.Syndication.SyndicationFeed
@{
Layout = "~/Views/Shared/_ContainerLayout.cshtml";
}
@foreach (var item in Model.Items)
{
var author = item.Authors.FirstOrDefault();
var authorName = author.Coalesce(a => a.Name, string.Empty);
var authorEmail = author.Coalesce(a => a.Email, string.Empty);
var link = item.Links.FirstOrDefault().Coalesce(l => l.Uri.ToString(), string.Empty);
var html = item.Content.Coalesce(c => c.ToHtml(),
item.Summary.Coalesce(c => c.ToHtml(), string.Empty)
);
<div class="syndicationItem">
<h1 class="syndicationItemTitle"><a href="@link" target="_blank">@Html.Raw(item.Title.Text)</a></h1>
<h2 class="syndicationItemDate">@item.PublishDate.ToString("dd MMMM yyyy")</h2>
@*<img class="syndicationItemPhoto" src="@authorEmail.GravatarImage()" alt="@authorName avatar" />*@
<h2 class="syndicationItemByLine">@authorName</h2>
@if (!string.IsNullOrWhiteSpace(@authorEmail))
{
<a href="mailto:@authorEmail">@authorEmail</a>
}
<br style="clear: both" />
<hr />
<div class="syndicationItemContent">
@Html.Raw(html)
</div>
<div class="syndicationItemFooter">
<hr />
<p>View the original of this post at <a href="@link">@link</a></p>
<hr />
</div>
</div>
} | mit | C# |
a8cf02acb9e1a037e798319dc23556af11402d6b | fix ToInt to use InvariantCulture for parsing integer | acple/ParsecSharp | ParsecSharp/Parser/Text.Combinator.Extensions.cs | ParsecSharp/Parser/Text.Combinator.Extensions.cs | using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
namespace ParsecSharp
{
public static partial class Text
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<char, string> AsString(this Parser<char, char> parser)
=> parser.Map(x => x.ToString());
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<char, string> AsString(this Parser<char, IEnumerable<char>> parser)
=> parser.Map(x => new string(x.ToArray()));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<char, int> ToInt(this Parser<char, IEnumerable<char>> parser)
=> parser.AsString().ToInt();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<char, int> ToInt(this Parser<char, string> parser)
=> parser.Bind(value => (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var integer))
? Pure(integer)
: Fail<int>($"Expected digits but was '{value}'"));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<char, string> Join(this Parser<char, IEnumerable<string>> parser)
=> parser.Map(x => string.Concat(x));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<char, string> Join(this Parser<char, IEnumerable<string>> parser, string separator)
=> parser.Map(x => string.Join(separator, x));
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
namespace ParsecSharp
{
public static partial class Text
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<char, string> AsString(this Parser<char, char> parser)
=> parser.Map(x => x.ToString());
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<char, string> AsString(this Parser<char, IEnumerable<char>> parser)
=> parser.Map(x => new string(x.ToArray()));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<char, int> ToInt(this Parser<char, IEnumerable<char>> parser)
=> parser.AsString().ToInt();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<char, int> ToInt(this Parser<char, string> parser)
=> parser.Bind(digits => (int.TryParse(digits, out var integer))
? Pure(integer)
: Fail<int>($"Expected digits but was '{digits}'"));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<char, string> Join(this Parser<char, IEnumerable<string>> parser)
=> parser.Map(x => string.Concat(x));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<char, string> Join(this Parser<char, IEnumerable<string>> parser, string separator)
=> parser.Map(x => string.Join(separator, x));
}
}
| mit | C# |
c3fbe6da88daf89e73bd7b10a9fff9ed1915b878 | Add comments for DefaultBuild. | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | bootstrapping/DefaultBuild.cs | bootstrapping/DefaultBuild.cs | using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.FileSystem.FileSystemTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.NuGet.NuGetTasks;
using static Nuke.Core.EnvironmentInfo;
class DefaultBuild : GitHubBuild
{
// This is the application entry point for the build.
// It also defines the default target to execute.
public static void Main () => Execute<DefaultBuild>(x => x.Compile);
Target Restore => _ => _
.Executes(() =>
{
// You can remove either one of the restore tasks as needed.
NuGetRestore(SolutionFile);
if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017)
MSBuild(s => DefaultSettings.MSBuildRestore);
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile
.SetMSBuildVersion(MSBuildVersion)));
// If you have xproj-based projects, you need to downgrade to VS2015.
MSBuildVersion? MSBuildVersion =>
!IsUnix
? GlobFiles(SolutionDirectory, "*.xproj").Any()
? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015
: Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017
: default(MSBuildVersion);
}
| using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.FileSystem.FileSystemTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.NuGet.NuGetTasks;
using static Nuke.Core.EnvironmentInfo;
class DefaultBuild : GitHubBuild
{
public static void Main () => Execute<DefaultBuild>(x => x.Compile);
Target Restore => _ => _
.Executes(() =>
{
NuGetRestore(SolutionFile);
if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017)
MSBuild(s => DefaultSettings.MSBuildRestore);
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile
.SetMSBuildVersion(MSBuildVersion)));
MSBuildVersion? MSBuildVersion =>
!IsUnix
? GlobFiles(SolutionDirectory, "*.xproj").Any()
? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015
: Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017
: default(MSBuildVersion);
}
| mit | C# |
bcf80ca98dfb946c60c48cff0ff648077ebc5794 | Update fake-host.cs | axotion/Fake-Host | fake-host.cs | fake-host.cs | using System;
using System.IO;
using System.Security.Principal;
/* For example
* 127.0.0.1 google.com
* Where 127.0.0.1 is your server/whatever
* Also you can run it with parametr like xxx.xxx.xxx.xxx www.something.com
* */
struct Var{
public static string IP = "127.0.0.1";
public static string Dest = "www.google.com";
};
class HostChanger
{
public static void Main (string[] args)
{
if (args.Length > 1) {
Var.IP = args [0];
Var.Dest = args[1];
}
bool isAdmin;
WindowsIdentity identity = WindowsIdentity.GetCurrent ();
WindowsPrincipal principal = new WindowsPrincipal (identity);
isAdmin = principal.IsInRole (WindowsBuiltInRole.Administrator);
if(File.Exists("c:\\windows\\system32\\drivers\\etc\\hosts")){
if (isAdmin != false) {
File.SetAttributes ("c:\\windows\\system32\\drivers\\etc\\hosts", FileAttributes.Normal);
File.AppendAllText ("c:\\windows\\system32\\drivers\\etc\\hosts", Environment.NewLine + Var.IP+" "+Var.Dest+Environment.NewLine);
File.AppendAllText ("c:\\windows\\system32\\drivers\\etc\\hosts", Var.IP+" "+Var.Dest.Remove (0,4)+Environment.NewLine);
} else {
Console.WriteLine ("You must run it as admin");
Console.ReadKey ();
}
}
}
}
| using System;
using System.IO;
using System.Security.Principal;
/* For example
* 127.0.0.1 google.com
* Where 127.0.0.1 is your server/whatever
* Also yo can run it with parametr xxx.xxx.xxx.xxx www.something.com
* */
class Var{
public static string IP = "127.0.0.1";
public static string Dest = "www.google.com";
};
class HostChanger
{
public static void Main (string[] args)
{
if (args.Length > 0) {
Var.IP = args [0];
Var.Dest = args[1];
}
bool isAdmin;
WindowsIdentity identity = WindowsIdentity.GetCurrent ();
WindowsPrincipal principal = new WindowsPrincipal (identity);
isAdmin = principal.IsInRole (WindowsBuiltInRole.Administrator);
if (isAdmin != false) {
File.SetAttributes ("c:\\windows\\system32\\drivers\\etc\\hosts", FileAttributes.Normal);
File.AppendAllText ("c:\\windows\\system32\\drivers\\etc\\hosts", Environment.NewLine + Var.IP+" "+Var.Dest+Environment.NewLine);
File.AppendAllText ("c:\\windows\\system32\\drivers\\etc\\hosts", Var.IP+" "+Var.Dest.Remove (0,4)+Environment.NewLine);
} else {
Console.WriteLine ("You must run it as admin");
}
}
}
| mit | C# |
0ca71e02b9d259d5bd46c0cc7e3f39ebb0513d61 | Add doc | arkeine/Fierce-Galaxy,arkeine/Fierce-Galaxy | fierce-galaxy/FierceGalaxyInterface/IInvalidable.cs | fierce-galaxy/FierceGalaxyInterface/IInvalidable.cs | using System;
namespace FierceGalaxyInterface
{
/// <summary>
/// An invalidable object is an object "valid"
/// until the invalidate method is call.
///
/// Invalidable object can be share with other objects
/// without fear that they continu using it if no
/// longuer valid.
/// </summary>
public interface IInvalidable
{
event EventHandler OnInvalidate;
/// <summary>
/// When a player is invalidate, it send a event to all listener.
/// This event mean the listener shoult stop to use it.
/// </summary>
void Invalidate();
bool IsValid { get; }
}
}
| using System;
namespace FierceGalaxyInterface
{
public interface IInvalidable
{
event EventHandler OnInvalidate;
/// <summary>
/// When a player is invalidate, it send a event to all listener.
/// This event mean the listener shoult stop to use it.
/// </summary>
void Invalidate();
bool IsValid { get; }
}
}
| apache-2.0 | C# |
b2ebcabdd5c56fa734a6eaf8eacc8b8c5c3db9a6 | Fix potential crash during stable install migration due to multiple configuration files | NeoAdonis/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu | osu.Game/IO/StableStorage.cs | osu.Game/IO/StableStorage.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using osu.Framework.Platform;
namespace osu.Game.IO
{
/// <summary>
/// A storage pointing to an osu-stable installation.
/// Provides methods for handling installations with a custom Song folder location.
/// </summary>
public class StableStorage : DesktopStorage
{
private const string stable_default_songs_path = "Songs";
private readonly DesktopGameHost host;
private readonly Lazy<string> songsPath;
public StableStorage(string path, DesktopGameHost host)
: base(path, host)
{
this.host = host;
songsPath = new Lazy<string>(locateSongsDirectory);
}
/// <summary>
/// Returns a <see cref="Storage"/> pointing to the osu-stable Songs directory.
/// </summary>
public Storage GetSongStorage() => new DesktopStorage(songsPath.Value, host);
private string locateSongsDirectory()
{
var configurationFiles = GetFiles(".", $"osu!.{Environment.UserName}.cfg");
// GetFiles returns case insensitive results, so multiple files could exist.
// Prefer a case-correct match, but fallback to any available.
string usableConfigFile =
configurationFiles.FirstOrDefault(f => f.Contains(Environment.UserName, StringComparison.Ordinal))
?? configurationFiles.FirstOrDefault();
if (usableConfigFile != null)
{
using (var stream = GetStream(usableConfigFile))
using (var textReader = new StreamReader(stream))
{
string line;
while ((line = textReader.ReadLine()) != null)
{
if (!line.StartsWith("BeatmapDirectory", StringComparison.OrdinalIgnoreCase)) continue;
string customDirectory = line.Split('=').LastOrDefault()?.Trim();
if (customDirectory != null && Path.IsPathFullyQualified(customDirectory))
return customDirectory;
break;
}
}
}
return GetFullPath(stable_default_songs_path);
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using osu.Framework.Platform;
namespace osu.Game.IO
{
/// <summary>
/// A storage pointing to an osu-stable installation.
/// Provides methods for handling installations with a custom Song folder location.
/// </summary>
public class StableStorage : DesktopStorage
{
private const string stable_default_songs_path = "Songs";
private readonly DesktopGameHost host;
private readonly Lazy<string> songsPath;
public StableStorage(string path, DesktopGameHost host)
: base(path, host)
{
this.host = host;
songsPath = new Lazy<string>(locateSongsDirectory);
}
/// <summary>
/// Returns a <see cref="Storage"/> pointing to the osu-stable Songs directory.
/// </summary>
public Storage GetSongStorage() => new DesktopStorage(songsPath.Value, host);
private string locateSongsDirectory()
{
string configFile = GetFiles(".", $"osu!.{Environment.UserName}.cfg").SingleOrDefault();
if (configFile != null)
{
using (var stream = GetStream(configFile))
using (var textReader = new StreamReader(stream))
{
string line;
while ((line = textReader.ReadLine()) != null)
{
if (!line.StartsWith("BeatmapDirectory", StringComparison.OrdinalIgnoreCase)) continue;
string customDirectory = line.Split('=').LastOrDefault()?.Trim();
if (customDirectory != null && Path.IsPathFullyQualified(customDirectory))
return customDirectory;
break;
}
}
}
return GetFullPath(stable_default_songs_path);
}
}
}
| mit | C# |
106f5a99ace2220da62f3c7b37b1d49f16fc2b84 | build routes immediately | Drawaes/CondenserDotNet,deanshackley/CondenserDotNet | src/CondenserDotNet.Server.Extensions/ApplicationBuilderExtensions.cs | src/CondenserDotNet.Server.Extensions/ApplicationBuilderExtensions.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;
namespace CondenserDotNet.Server
{
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseCondenser(this IApplicationBuilder self)
{
self.UseMiddleware<RoutingMiddleware>();
//self.UseMiddleware<WebsocketMiddleware>();
self.UseMiddleware<ServiceCallMiddleware>();
//Resolve to start building routes
self.ApplicationServices.GetServices<RoutingHost>();
return self;
}
}
}
| using Microsoft.AspNetCore.Builder;
namespace CondenserDotNet.Server
{
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseCondenser(this IApplicationBuilder self)
{
self.UseMiddleware<RoutingMiddleware>();
//self.UseMiddleware<WebsocketMiddleware>();
self.UseMiddleware<ServiceCallMiddleware>();
return self;
}
}
}
| mit | C# |
65d94777a45daaaec5a04caf1d701f63d7f4d48c | simplify part settings retrieval for TitlePartDisplay (#5372) | petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,petedavis/Orchard2 | src/OrchardCore.Modules/OrchardCore.Title/Drivers/TitlePartDisplay.cs | src/OrchardCore.Modules/OrchardCore.Title/Drivers/TitlePartDisplay.cs | using System.Threading.Tasks;
using OrchardCore.ContentManagement.Display.ContentDisplay;
using OrchardCore.ContentManagement.Display.Models;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Views;
using OrchardCore.Title.Models;
using OrchardCore.Title.ViewModels;
namespace OrchardCore.Title.Drivers
{
public class TitlePartDisplay : ContentPartDisplayDriver<TitlePart>
{
public override IDisplayResult Display(TitlePart titlePart)
{
return Initialize<TitlePartViewModel>("TitlePart", model =>
{
model.Title = titlePart.ContentItem.DisplayText;
model.TitlePart = titlePart;
})
.Location("Detail", "Header:5")
.Location("Summary", "Header:5");
}
public override IDisplayResult Edit(TitlePart titlePart, BuildPartEditorContext context)
{
return Initialize<TitlePartViewModel>("TitlePart_Edit", model =>
{
model.Title = titlePart.ContentItem.DisplayText;
model.TitlePart = titlePart;
model.Settings = context.TypePartDefinition.GetSettings<TitlePartSettings>();
});
}
public override async Task<IDisplayResult> UpdateAsync(TitlePart model, IUpdateModel updater, UpdatePartEditorContext context)
{
await updater.TryUpdateModelAsync(model, Prefix, t => t.Title);
model.ContentItem.DisplayText = model.Title;
return Edit(model, context);
}
}
}
| using System.Linq;
using System.Threading.Tasks;
using OrchardCore.ContentManagement.Display.ContentDisplay;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Views;
using OrchardCore.Title.Models;
using OrchardCore.Title.ViewModels;
namespace OrchardCore.Title.Drivers
{
public class TitlePartDisplay : ContentPartDisplayDriver<TitlePart>
{
private readonly IContentDefinitionManager _contentDefinitionManager;
public TitlePartDisplay(IContentDefinitionManager contentDefinitionManager)
{
_contentDefinitionManager = contentDefinitionManager;
}
public override IDisplayResult Display(TitlePart titlePart)
{
return Initialize<TitlePartViewModel>("TitlePart", model =>
{
model.Title = titlePart.ContentItem.DisplayText;
model.TitlePart = titlePart;
})
.Location("Detail", "Header:5")
.Location("Summary", "Header:5");
}
public override IDisplayResult Edit(TitlePart titlePart)
{
return Initialize<TitlePartViewModel>("TitlePart_Edit", model =>
{
model.Title = titlePart.ContentItem.DisplayText;
model.TitlePart = titlePart;
model.Settings = GetSettings(titlePart);
});
}
public override async Task<IDisplayResult> UpdateAsync(TitlePart model, IUpdateModel updater)
{
await updater.TryUpdateModelAsync(model, Prefix, t => t.Title);
model.ContentItem.DisplayText = model.Title;
return Edit(model);
}
private TitlePartSettings GetSettings(TitlePart titlePart)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(titlePart.ContentItem.ContentType);
var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(x => string.Equals(x.PartDefinition.Name, nameof(TitlePart)));
return contentTypePartDefinition?.GetSettings<TitlePartSettings>();
}
}
}
| bsd-3-clause | C# |
df3e8fb0ef3564fd7f1e95e91b915c88da3bd868 | Update Assets/MRTK/SDK/Features/Utilities/ConstraintUtils.cs | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MRTK/SDK/Features/Utilities/ConstraintUtils.cs | Assets/MRTK/SDK/Features/Utilities/ConstraintUtils.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
using System.Collections.Generic;
using Microsoft.MixedReality.Toolkit.UI;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// Utilities for the management of constraints.
/// </summary>
internal static class ConstraintUtils
{
/// <summary>
/// Adds a constraint to the specified already-sorted list of constraints, maintaining
/// execution priority order. SortedSet is not used, as equal priorities
/// break duplicate-checking with SortedSet, as well as SortedSet not being
/// able to handle runtime-changing exec priorities.
/// </summary>
/// <param name="constraintList">Sorted list of existing priorites</param>
/// <param name="constraint">Constraint to add</param>
/// <param name="comparer">ConstraintExecOrderComparer for comparing two constraint priorities</param>
internal static void AddWithPriority(ref List<TransformConstraint> constraintList, TransformConstraint constraint, ConstraintExecOrderComparer comparer)
{
if (constraintList.Contains(constraint))
{
return;
}
if (constraintList.Count == 0 || comparer.Compare(constraintList[constraintList.Count-1], constraint) < 0)
{
constraintList.Add(constraint);
return;
}
else if (comparer.Compare(constraintList[0], constraint) > 0)
{
constraintList.Insert(0, constraint);
return;
}
else
{
int idx = constraintList.BinarySearch(constraint, comparer);
if(idx < 0)
{
// idx will be the two's complement of the index of the
// next element that is "larger" than the given constraint.
idx = ~idx;
}
constraintList.Insert(idx, constraint);
}
}
}
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEngine;
using System.Collections.Generic;
using Microsoft.MixedReality.Toolkit.UI;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// Utilities for the management of constraints.
/// </summary>
internal static class ConstraintUtils
{
/// <summary>
/// Adds a constraint to the specified already-sorted list of constraints, maintaining
/// execution priority order. SortedSet is not used, as equal priorities
/// break duplicate-checking with SortedSet, as well as SortedSet not being
/// able to handle runtime-changing exec priorities.
/// </summary>
/// <param name="constraintList">Sorted list of existing priorites</param>
/// <param name="constraint">Constraint to add</param>
/// <param name="comparer">ConstraintExecOrderComparer for comparing two constraint priorities</param>
internal static void AddWithPriority(ref List<TransformConstraint> constraintList, TransformConstraint constraint, ConstraintExecOrderComparer comparer)
{
if (constraintList.Contains(constraint))
{
return;
}
if (constraintList.Count == 0 || comparer.Compare(constraintList[constraintList.Count-1], constraint) < 0)
{
constraintList.Add(constraint);
return;
}
else if(comparer.Compare(constraintList[0], constraint) > 0)
{
constraintList.Insert(0, constraint);
return;
}
else
{
int idx = constraintList.BinarySearch(constraint, comparer);
if(idx < 0)
{
// idx will be the two's complement of the index of the
// next element that is "larger" than the given constraint.
idx = ~idx;
}
constraintList.Insert(idx, constraint);
}
}
}
}
| mit | C# |
7fd0175d643ad48af596013ce2350d13bef7cce3 | Fix handling of transient bindings to accomodate bindings that have been specified for an ancestral type | x335/WootzJs,kswoll/WootzJs,x335/WootzJs,kswoll/WootzJs,x335/WootzJs,kswoll/WootzJs | WootzJs.Injection/Context.cs | WootzJs.Injection/Context.cs | using System;
using System.Collections.Generic;
namespace WootzJs.Injection
{
public class Context
{
private ICache cache;
private IDictionary<Type, IBinding> transientBindings;
public Context(Context context = null, ICache cache = null, IDictionary<Type, IBinding> transientBindings = null)
{
cache = cache ?? new Cache();
this.cache = context != null ? new HybridCache(cache, context.Cache) : cache;
this.transientBindings = transientBindings;
}
public ICache Cache
{
get { return cache; }
}
public IBinding GetCustomBinding(Type type)
{
if (transientBindings == null)
return null;
while (type != null)
{
IBinding result;
if (transientBindings.TryGetValue(type, out result))
return result;
type = type.BaseType;
}
return null;
}
}
} | using System;
using System.Collections.Generic;
namespace WootzJs.Injection
{
public class Context
{
private ICache cache;
private IDictionary<Type, IBinding> transientBindings;
public Context(Context context = null, ICache cache = null, IDictionary<Type, IBinding> transientBindings = null)
{
cache = cache ?? new Cache();
this.cache = context != null ? new HybridCache(cache, context.Cache) : cache;
this.transientBindings = transientBindings;
}
public ICache Cache
{
get { return cache; }
}
public IBinding GetCustomBinding(Type type)
{
if (transientBindings == null)
return null;
IBinding result;
transientBindings.TryGetValue(type, out result);
return result;
}
}
} | mit | C# |
0c8f9be45984a58a62fad5bded588c4a7d3c3978 | change to public | Agrando/IdentityServer3,AscendXYZ/Thinktecture.IdentityServer.v3,maz100/Thinktecture.IdentityServer.v3,buddhike/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,chicoribas/IdentityServer3,delloncba/IdentityServer3,paulofoliveira/IdentityServer3,mvalipour/IdentityServer3,SonOfSam/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,angelapper/IdentityServer3,jonathankarsh/IdentityServer3,delRyan/IdentityServer3,Agrando/IdentityServer3,delloncba/IdentityServer3,buddhike/IdentityServer3,yanjustino/IdentityServer3,SonOfSam/IdentityServer3,codeice/IdentityServer3,bestwpw/IdentityServer3,kouweizhong/IdentityServer3,mvalipour/IdentityServer3,angelapper/IdentityServer3,mvalipour/IdentityServer3,maz100/Thinktecture.IdentityServer.v3,johnkors/Thinktecture.IdentityServer.v3,codeice/IdentityServer3,SonOfSam/IdentityServer3,bodell/IdentityServer3,angelapper/IdentityServer3,AscendXYZ/Thinktecture.IdentityServer.v3,tuyndv/IdentityServer3,openbizgit/IdentityServer3,wondertrap/IdentityServer3,tbitowner/IdentityServer3,delRyan/IdentityServer3,jackswei/IdentityServer3,iamkoch/IdentityServer3,ryanvgates/IdentityServer3,delRyan/IdentityServer3,olohmann/IdentityServer3,ascoro/Thinktecture.IdentityServer.v3.Fork,openbizgit/IdentityServer3,bodell/IdentityServer3,paulofoliveira/IdentityServer3,jackswei/IdentityServer3,charoco/IdentityServer3,faithword/IdentityServer3,EternalXw/IdentityServer3,IdentityServer/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,tonyeung/IdentityServer3,uoko-J-Go/IdentityServer,remunda/IdentityServer3,faithword/IdentityServer3,wondertrap/IdentityServer3,18098924759/IdentityServer3,ryanvgates/IdentityServer3,roflkins/IdentityServer3,yanjustino/IdentityServer3,EternalXw/IdentityServer3,tonyeung/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,tbitowner/IdentityServer3,delloncba/IdentityServer3,uoko-J-Go/IdentityServer,remunda/IdentityServer3,bestwpw/IdentityServer3,faithword/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,ascoro/Thinktecture.IdentityServer.v3.Fork,tuyndv/IdentityServer3,olohmann/IdentityServer3,remunda/IdentityServer3,codeice/IdentityServer3,IdentityServer/IdentityServer3,jonathankarsh/IdentityServer3,jonathankarsh/IdentityServer3,maz100/Thinktecture.IdentityServer.v3,openbizgit/IdentityServer3,buddhike/IdentityServer3,chicoribas/IdentityServer3,EternalXw/IdentityServer3,bestwpw/IdentityServer3,18098924759/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,chicoribas/IdentityServer3,wondertrap/IdentityServer3,charoco/IdentityServer3,IdentityServer/IdentityServer3,roflkins/IdentityServer3,kouweizhong/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,tuyndv/IdentityServer3,jackswei/IdentityServer3,olohmann/IdentityServer3,Agrando/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,18098924759/IdentityServer3,bodell/IdentityServer3,paulofoliveira/IdentityServer3,charoco/IdentityServer3,ryanvgates/IdentityServer3,tonyeung/IdentityServer3,yanjustino/IdentityServer3,iamkoch/IdentityServer3,kouweizhong/IdentityServer3,roflkins/IdentityServer3,iamkoch/IdentityServer3,tbitowner/IdentityServer3,uoko-J-Go/IdentityServer | source/Core/Plumbing/ClaimComparer.cs | source/Core/Plumbing/ClaimComparer.cs | /*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license
*/
using System;
using System.Collections.Generic;
using System.Security.Claims;
namespace Thinktecture.IdentityServer.Core.Plumbing
{
public class ClaimComparer : IEqualityComparer<Claim>
{
public bool Equals(Claim x, Claim y)
{
if (x == null && y == null) return true;
if (x == null && y != null) return false;
if (x != null && y == null) return false;
return (x.Type == y.Type &&
x.Value == y.Value);
}
public int GetHashCode(Claim claim)
{
if (Object.ReferenceEquals(claim, null)) return 0;
int typeHash = claim.Type == null ? 0 : claim.Type.GetHashCode();
int valueHash = claim.Value == null ? 0 : claim.Value.GetHashCode();
return typeHash ^ valueHash;
}
}
}
| /*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license
*/
using System;
using System.Collections.Generic;
using System.Security.Claims;
namespace Thinktecture.IdentityServer.Core.Plumbing
{
class ClaimComparer : IEqualityComparer<Claim>
{
public bool Equals(Claim x, Claim y)
{
return (x.Type == y.Type &&
x.Value == y.Value);
}
public int GetHashCode(Claim claim)
{
if (Object.ReferenceEquals(claim, null)) return 0;
int typeHash = claim.Type == null ? 0 : claim.Type.GetHashCode();
int valueHash = claim.Value == null ? 0 : claim.Value.GetHashCode();
return typeHash ^ valueHash;
}
}
}
| apache-2.0 | C# |
2469b77eda2bcc77cad681737070a3dcabff8ee0 | Improve asynchronous listener invocation | danielmundt/csremote | source/Remoting.Service/EventProxy.cs | source/Remoting.Service/EventProxy.cs | #region Header
// Copyright (C) 2012 Daniel Schubert
//
// 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.
#endregion Header
using System;
using System.Collections.Generic;
using System.Text;
namespace Remoting.Service
{
public delegate void EventCallback(Object obj);
public class EventProxy : MarshalByRefObject
{
public event EventCallback EventSent;
public override object InitializeLifetimeService()
{
// indicate that this lease never expires
return null;
}
public void OnEventSent(Object obj)
{
if (EventSent != null)
{
// asynchronous listener invocation
EventSent.BeginInvoke(obj, null, null);
}
}
}
} | #region Header
// Copyright (C) 2012 Daniel Schubert
//
// 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.
#endregion Header
using System;
using System.Collections.Generic;
using System.Text;
namespace Remoting.Service
{
public delegate void EventCallback(Object obj);
public class EventProxy : MarshalByRefObject
{
public event EventCallback EventSent;
public override object InitializeLifetimeService()
{
// indicate that this lease never expires
return null;
}
public void OnEventSent(Object obj)
{
if (EventSent != null)
{
Delegate[] delegates = EventSent.GetInvocationList();
foreach (Delegate del in delegates)
{
EventCallback listener = (EventCallback)del;
listener.BeginInvoke(obj, null, null);
}
}
}
}
} | mit | C# |
93c42ec6a585fe9b141897d95dbeaa2dc420879e | prepare for release. | AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,yamamoWorks/azure-activedirectory-library-for-dotnet,AzureAD/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,bjartebore/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet | src/ADAL.Common/CommonAssemblyInfo.cs | src/ADAL.Common/CommonAssemblyInfo.cs | //----------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//----------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: AssemblyProduct("Active Directory Authentication Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyCompany("Microsoft Open Technologies")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Open Technologies. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("3.9.0.0")]
// Keep major and minor versions in AssemblyFileVersion in sync with AssemblyVersion.
// Build and revision numbers are replaced on build machine for official builds.
[assembly: AssemblyFileVersion("3.9.00000.0000")]
// On official build, attribute AssemblyInformationalVersionAttribute is added as well
// with its value equal to the hash of the last commit to the git branch.
// e.g.: [assembly: AssemblyInformationalVersionAttribute("4392c9835a38c27516fc0cd7bad7bccdcaeab161")]
[assembly: CLSCompliant(false)]
| //----------------------------------------------------------------------
// Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//----------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: AssemblyProduct("Active Directory Authentication Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyCompany("Microsoft Open Technologies")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Open Technologies. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("3.8.0.0")]
// Keep major and minor versions in AssemblyFileVersion in sync with AssemblyVersion.
// Build and revision numbers are replaced on build machine for official builds.
[assembly: AssemblyFileVersion("3.8.00000.0000")]
// On official build, attribute AssemblyInformationalVersionAttribute is added as well
// with its value equal to the hash of the last commit to the git branch.
// e.g.: [assembly: AssemblyInformationalVersionAttribute("4392c9835a38c27516fc0cd7bad7bccdcaeab161")]
[assembly: CLSCompliant(false)]
| mit | C# |
ee47834e9ac4be3ab7875593ea92d08ec11ba6f6 | Switch to IAmACommunityMember | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/ThomasLee.cs | src/Firehose.Web/Authors/ThomasLee.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class ThomasLee : IAmACommunityMember
{
public string FirstName => "Thomas";
public string LastName => "Lee";
public string ShortBioOrTagLine => "Just this guy, living in the UK. A Grateful Dead and long time PowerShell Fan. MVP 17 times";
public string StateOrRegion => "Berkshire, UK";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "DoctorDNS";
public string GravatarHash => "9fac677a9811ddc033b9ec883606031d";
public string GitHubHandle => "DoctorDNS";
public GeoPosition Position => new GeoPosition(51.5566737,-0.6941204);
public Uri WebSite => new Uri("https://tfl09.blogspot.com");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://tfl09.blogspot.com/feeds/posts/default/"); }
}
public string FeedLanguageCode => "en";
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class ThomasLee : IAmAMicrosoftMVP
{
public string FirstName => "Thomas";
public string LastName => "Lee";
public string ShortBioOrTagLine => "Just this guy, living in the UK. A Grateful Dead and long time PowerShell Fan. MVP 17 times";
public string StateOrRegion => "Berkshire, UK";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "DoctorDNS";
public string GravatarHash => "9fac677a9811ddc033b9ec883606031d";
public string GitHubHandle => "DoctorDNS";
public GeoPosition Position => new GeoPosition(51.5566737,-0.6941204);
public Uri WebSite => new Uri("https://tfl09.blogspot.com");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://tfl09.blogspot.com/feeds/posts/default/"); }
}
public string FeedLanguageCode => "en";
}
}
| mit | C# |
71aacfe0e26169289c8a4be306c44d90bea35ae2 | add comment to IdentityNameHelper | peopleware/net-ppwcode-util-oddsandends | src/II/Security/IdentityNameHelper.cs | src/II/Security/IdentityNameHelper.cs | // Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Security.Principal;
using System.ServiceModel;
using System.Threading;
namespace PPWCode.Util.OddsAndEnds.II.Security
{
/// <summary>
/// Helper class for IdentityName.
/// </summary>
public static class IdentityNameHelper
{
/// <summary>
/// Gets the identity name of the security context of a remote party.
/// </summary>
/// <returns>The identity name.</returns>
public static string GetServiceSecurityContextIdentityName()
{
return ServiceSecurityContext.Current != null
&& !string.IsNullOrEmpty(ServiceSecurityContext.Current.WindowsIdentity.Name)
? ServiceSecurityContext.Current.WindowsIdentity.Name
: null;
}
/// <summary>
/// Gets the identity name of the current principal.
/// </summary>
/// <returns>The identity name.</returns>
public static string GetThreadCurrentPrincipalIdentityName()
{
return Thread.CurrentPrincipal != null
&& !string.IsNullOrEmpty(Thread.CurrentPrincipal.Identity.Name)
? Thread.CurrentPrincipal.Identity.Name
: null;
}
/// <summary>
/// Gets the name of the current windows user.
/// </summary>
/// <returns>The name of the current windows user.</returns>
public static string GetWindowsIdentityIdentityName()
{
WindowsIdentity current = WindowsIdentity.GetCurrent();
if (current == null)
{
return null;
}
WindowsPrincipal wp = new WindowsPrincipal(current);
return !string.IsNullOrEmpty(wp.Identity.Name) ? wp.Identity.Name : null;
}
/// <summary>
/// Gets the identity name.
/// </summary>
/// <returns>The identity name.</returns>
public static string GetIdentityName()
{
return
GetThreadCurrentPrincipalIdentityName() ??
GetServiceSecurityContextIdentityName() ??
GetWindowsIdentityIdentityName() ??
"Unknown";
}
}
} | // Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Security.Principal;
using System.ServiceModel;
using System.Threading;
namespace PPWCode.Util.OddsAndEnds.II.Security
{
/// <summary>
/// Helper class for IdentityName.
/// </summary>
public static class IdentityNameHelper
{
public static string GetServiceSecurityContextIdentityName()
{
return ServiceSecurityContext.Current != null
&& !string.IsNullOrEmpty(ServiceSecurityContext.Current.WindowsIdentity.Name)
? ServiceSecurityContext.Current.WindowsIdentity.Name
: null;
}
public static string GetThreadCurrentPrincipalIdentityName()
{
return Thread.CurrentPrincipal != null
&& !string.IsNullOrEmpty(Thread.CurrentPrincipal.Identity.Name)
? Thread.CurrentPrincipal.Identity.Name
: null;
}
public static string GetWindowsIdentityIdentityName()
{
WindowsIdentity current = WindowsIdentity.GetCurrent();
if (current == null)
{
return null;
}
WindowsPrincipal wp = new WindowsPrincipal(current);
return !string.IsNullOrEmpty(wp.Identity.Name) ? wp.Identity.Name : null;
}
public static string GetIdentityName()
{
return
GetThreadCurrentPrincipalIdentityName() ??
GetServiceSecurityContextIdentityName() ??
GetWindowsIdentityIdentityName() ??
"Unknown";
}
}
} | apache-2.0 | C# |
a4189351827dc7d54bd8f3bd82b9745106c1bc58 | Fix tests. | JohanLarsson/Gu.Analyzers | Gu.Analyzers.Test/GU0080TestAttributeCountMismatchTests/Diagnostics.cs | Gu.Analyzers.Test/GU0080TestAttributeCountMismatchTests/Diagnostics.cs | namespace Gu.Analyzers.Test.GU0080TestAttributeCountMismatchTests
{
using Gu.Roslyn.Asserts;
using NUnit.Framework;
internal class Diagnostics
{
private static readonly TestMethodAnalyzer Analyzer = new TestMethodAnalyzer();
private static readonly ExpectedDiagnostic ExpectedDiagnostic = ExpectedDiagnostic.Create("GU0080");
[Test]
public void TestAttributeAndParameter()
{
var testCode = @"
namespace RoslynSandbox
{
using NUnit.Framework;
public class FooTests
{
[Test]
public void Test↓(string text)
{
}
}
}";
AnalyzerAssert.Diagnostics(Analyzer, ExpectedDiagnostic, testCode);
}
[Test]
public void TestAttributeAndParameter_Multiple()
{
var testCode = @"
namespace RoslynSandbox
{
using NUnit.Framework;
public class FooTests
{
[Test]
public void Test↓(string text, int index, bool value)
{
}
}
}";
AnalyzerAssert.Diagnostics(Analyzer, ExpectedDiagnostic, testCode);
}
[TestCase("Test↓()")]
[TestCase("Test↓(1, 2)")]
public void TestCaseAttributeAndParameter(string signature)
{
var testCode = @"
namespace RoslynSandbox
{
using NUnit.Framework;
public class FooTests
{
[TestCase(1)]
public void Test↓(int i)
{
}
}
}";
testCode = testCode.AssertReplace("Test↓(int i)", signature);
AnalyzerAssert.Diagnostics(Analyzer, ExpectedDiagnostic, testCode);
}
[TestCase("Test↓()")]
[TestCase("Test↓(1, 2)")]
public void TestAndTestCaseAttributeAndParameter(string signature)
{
var testCode = @"
namespace RoslynSandbox
{
using NUnit.Framework;
public class FooTests
{
[TestCase(1)]
public void Test↓(int i)
{
}
}
}";
testCode = testCode.AssertReplace("Test↓(int i)", signature);
AnalyzerAssert.Diagnostics(Analyzer, ExpectedDiagnostic, testCode);
}
}
}
| namespace Gu.Analyzers.Test.GU0080TestAttributeCountMismatchTests
{
using Gu.Roslyn.Asserts;
using NUnit.Framework;
internal class Diagnostics
{
private static readonly TestMethodAnalyzer Analyzer = new TestMethodAnalyzer();
private static readonly ExpectedDiagnostic ExpectedDiagnostic = ExpectedDiagnostic.Create("GU0080");
[Test]
public void TestAttributeAndParameter()
{
var testCode = @"
namespace RoslynSandbox
{
using NUnit.Framework;
public class FooTests
{
[Test]
public void Test↓(string text)
{
}
}
}";
AnalyzerAssert.Diagnostics(Analyzer, ExpectedDiagnostic, testCode);
}
[Test]
public void TestAttributeAndParameter_Multiple()
{
var testCode = @"
namespace RoslynSandbox
{
using NUnit.Framework;
public class FooTests
{
[Test]
public void Test↓(string text, int index, bool value)
{
}
}
}";
AnalyzerAssert.Diagnostics(Analyzer, ExpectedDiagnostic, testCode);
}
[TestCase("Test↓()")]
[TestCase("Test↓(1, 2)")]
public void TestCaseAttributeAndParameter(string signature)
{
var testCode = @"
namespace RoslynSandbox
{
using NUnit.Framework;
public class FooTests
{
[TestCase(1)]
public void Test↓(int i)
{
}
}
}";
testCode = testCode.AssertReplace("Test(int i)", signature);
AnalyzerAssert.Diagnostics(Analyzer, ExpectedDiagnostic, testCode);
}
[TestCase("Test↓()")]
[TestCase("Test↓(1, 2)")]
public void TestAndTestCaseAttributeAndParameter(string signature)
{
var testCode = @"
namespace RoslynSandbox
{
using NUnit.Framework;
public class FooTests
{
[TestCase(1)]
public void Test↓(int i)
{
}
}
}";
testCode = testCode.AssertReplace("Test↓(int i)", signature);
AnalyzerAssert.Diagnostics(Analyzer, ExpectedDiagnostic, testCode);
}
}
}
| mit | C# |
7144b4d9766a915ba41d4fb2bff1ebedc8ff73da | revert to name Nimbus from Anubus in AssemblyInfo | rebase42/Anubus,rebase42/Anubus,rebase42/Anubus | src/Nimbus/Properties/AssemblyInfo.cs | src/Nimbus/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("Nimbus")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Nimbus")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("6c753fa6-3cf7-448b-898c-ea0cbcd8f638")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("Nimbus.Tests.Common", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Nimbus.UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Nimbus.IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Nimbus.Autofac")]
[assembly: InternalsVisibleTo("Nimbus.Windsor")]
[assembly: InternalsVisibleTo("Nimbus.LargeMessages.Azure")]
[assembly: InternalsVisibleTo("Nimbus.LargeMessages.FileSystem")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
| 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("Anubus")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Anubus")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("6c753fa6-3cf7-448b-898c-ea0cbcd8f638")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("Nimbus.Tests.Common", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Nimbus.UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Nimbus.IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("Nimbus.Autofac")]
[assembly: InternalsVisibleTo("Nimbus.Windsor")]
[assembly: InternalsVisibleTo("Nimbus.LargeMessages.Azure")]
[assembly: InternalsVisibleTo("Nimbus.LargeMessages.FileSystem")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
| mit | C# |
8a1c8475b8ec68d113c79dbab3a4519612bad701 | Update Interfaces BaseContext | countrywide/Umbraco-CMS,VDBBjorn/Umbraco-CMS,rasmusfjord/Umbraco-CMS,lars-erik/Umbraco-CMS,hfloyd/Umbraco-CMS,romanlytvyn/Umbraco-CMS,gavinfaux/Umbraco-CMS,lingxyd/Umbraco-CMS,wtct/Umbraco-CMS,dampee/Umbraco-CMS,leekelleher/Umbraco-CMS,Tronhus/Umbraco-CMS,lingxyd/Umbraco-CMS,iahdevelop/Umbraco-CMS,wtct/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,zidad/Umbraco-CMS,ehornbostel/Umbraco-CMS,lars-erik/Umbraco-CMS,hfloyd/Umbraco-CMS,leekelleher/Umbraco-CMS,mstodd/Umbraco-CMS,tcmorris/Umbraco-CMS,arknu/Umbraco-CMS,jchurchley/Umbraco-CMS,base33/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,arknu/Umbraco-CMS,ordepdev/Umbraco-CMS,abjerner/Umbraco-CMS,wtct/Umbraco-CMS,AzarinSergey/Umbraco-CMS,dawoe/Umbraco-CMS,christopherbauer/Umbraco-CMS,arvaris/HRI-Umbraco,corsjune/Umbraco-CMS,christopherbauer/Umbraco-CMS,WebCentrum/Umbraco-CMS,lars-erik/Umbraco-CMS,yannisgu/Umbraco-CMS,AndyButland/Umbraco-CMS,iahdevelop/Umbraco-CMS,wtct/Umbraco-CMS,gkonings/Umbraco-CMS,countrywide/Umbraco-CMS,markoliver288/Umbraco-CMS,DaveGreasley/Umbraco-CMS,mittonp/Umbraco-CMS,gregoriusxu/Umbraco-CMS,gkonings/Umbraco-CMS,marcemarc/Umbraco-CMS,Myster/Umbraco-CMS,engern/Umbraco-CMS,dawoe/Umbraco-CMS,ehornbostel/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dawoe/Umbraco-CMS,Khamull/Umbraco-CMS,gregoriusxu/Umbraco-CMS,engern/Umbraco-CMS,DaveGreasley/Umbraco-CMS,markoliver288/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,kasperhhk/Umbraco-CMS,abjerner/Umbraco-CMS,MicrosoftEdge/Umbraco-CMS,engern/Umbraco-CMS,Myster/Umbraco-CMS,mittonp/Umbraco-CMS,nvisage-gf/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,ordepdev/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,romanlytvyn/Umbraco-CMS,m0wo/Umbraco-CMS,sargin48/Umbraco-CMS,Spijkerboer/Umbraco-CMS,Pyuuma/Umbraco-CMS,DaveGreasley/Umbraco-CMS,neilgaietto/Umbraco-CMS,m0wo/Umbraco-CMS,gavinfaux/Umbraco-CMS,AzarinSergey/Umbraco-CMS,gregoriusxu/Umbraco-CMS,qizhiyu/Umbraco-CMS,Myster/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,bjarnef/Umbraco-CMS,bjarnef/Umbraco-CMS,Myster/Umbraco-CMS,AndyButland/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,sargin48/Umbraco-CMS,robertjf/Umbraco-CMS,yannisgu/Umbraco-CMS,Khamull/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,DaveGreasley/Umbraco-CMS,rustyswayne/Umbraco-CMS,TimoPerplex/Umbraco-CMS,Door3Dev/HRI-Umbraco,qizhiyu/Umbraco-CMS,Door3Dev/HRI-Umbraco,marcemarc/Umbraco-CMS,sargin48/Umbraco-CMS,sargin48/Umbraco-CMS,Pyuuma/Umbraco-CMS,neilgaietto/Umbraco-CMS,Khamull/Umbraco-CMS,christopherbauer/Umbraco-CMS,KevinJump/Umbraco-CMS,gregoriusxu/Umbraco-CMS,timothyleerussell/Umbraco-CMS,mittonp/Umbraco-CMS,gregoriusxu/Umbraco-CMS,jchurchley/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,kgiszewski/Umbraco-CMS,TimoPerplex/Umbraco-CMS,tcmorris/Umbraco-CMS,rasmusfjord/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,marcemarc/Umbraco-CMS,iahdevelop/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,zidad/Umbraco-CMS,iahdevelop/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,MicrosoftEdge/Umbraco-CMS,Khamull/Umbraco-CMS,jchurchley/Umbraco-CMS,abryukhov/Umbraco-CMS,Spijkerboer/Umbraco-CMS,Spijkerboer/Umbraco-CMS,corsjune/Umbraco-CMS,aaronpowell/Umbraco-CMS,hfloyd/Umbraco-CMS,christopherbauer/Umbraco-CMS,nvisage-gf/Umbraco-CMS,gavinfaux/Umbraco-CMS,robertjf/Umbraco-CMS,rasmuseeg/Umbraco-CMS,yannisgu/Umbraco-CMS,gavinfaux/Umbraco-CMS,aadfPT/Umbraco-CMS,abryukhov/Umbraco-CMS,gkonings/Umbraco-CMS,Scott-Herbert/Umbraco-CMS,KevinJump/Umbraco-CMS,Door3Dev/HRI-Umbraco,base33/Umbraco-CMS,timothyleerussell/Umbraco-CMS,lingxyd/Umbraco-CMS,mstodd/Umbraco-CMS,umbraco/Umbraco-CMS,countrywide/Umbraco-CMS,arvaris/HRI-Umbraco,arvaris/HRI-Umbraco,Scott-Herbert/Umbraco-CMS,NikRimington/Umbraco-CMS,romanlytvyn/Umbraco-CMS,m0wo/Umbraco-CMS,dawoe/Umbraco-CMS,timothyleerussell/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,neilgaietto/Umbraco-CMS,aadfPT/Umbraco-CMS,rasmusfjord/Umbraco-CMS,AndyButland/Umbraco-CMS,TimoPerplex/Umbraco-CMS,yannisgu/Umbraco-CMS,lars-erik/Umbraco-CMS,AndyButland/Umbraco-CMS,kasperhhk/Umbraco-CMS,Phosworks/Umbraco-CMS,arknu/Umbraco-CMS,lingxyd/Umbraco-CMS,Myster/Umbraco-CMS,timothyleerussell/Umbraco-CMS,markoliver288/Umbraco-CMS,mstodd/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,countrywide/Umbraco-CMS,mattbrailsford/Umbraco-CMS,ehornbostel/Umbraco-CMS,aadfPT/Umbraco-CMS,timothyleerussell/Umbraco-CMS,madsoulswe/Umbraco-CMS,yannisgu/Umbraco-CMS,corsjune/Umbraco-CMS,sargin48/Umbraco-CMS,engern/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,hfloyd/Umbraco-CMS,madsoulswe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,corsjune/Umbraco-CMS,ehornbostel/Umbraco-CMS,tcmorris/Umbraco-CMS,rustyswayne/Umbraco-CMS,hfloyd/Umbraco-CMS,markoliver288/Umbraco-CMS,abryukhov/Umbraco-CMS,rasmusfjord/Umbraco-CMS,AzarinSergey/Umbraco-CMS,gkonings/Umbraco-CMS,gavinfaux/Umbraco-CMS,robertjf/Umbraco-CMS,NikRimington/Umbraco-CMS,Jeavon/Umbraco-CMS-RollbackTweak,dampee/Umbraco-CMS,Jeavon/Umbraco-CMS-RollbackTweak,qizhiyu/Umbraco-CMS,rajendra1809/Umbraco-CMS,Tronhus/Umbraco-CMS,umbraco/Umbraco-CMS,AzarinSergey/Umbraco-CMS,ordepdev/Umbraco-CMS,zidad/Umbraco-CMS,aaronpowell/Umbraco-CMS,AndyButland/Umbraco-CMS,dampee/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,leekelleher/Umbraco-CMS,VDBBjorn/Umbraco-CMS,arvaris/HRI-Umbraco,tcmorris/Umbraco-CMS,VDBBjorn/Umbraco-CMS,Pyuuma/Umbraco-CMS,Spijkerboer/Umbraco-CMS,WebCentrum/Umbraco-CMS,mittonp/Umbraco-CMS,neilgaietto/Umbraco-CMS,romanlytvyn/Umbraco-CMS,tcmorris/Umbraco-CMS,TimoPerplex/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,qizhiyu/Umbraco-CMS,Tronhus/Umbraco-CMS,mstodd/Umbraco-CMS,Phosworks/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,VDBBjorn/Umbraco-CMS,ordepdev/Umbraco-CMS,nvisage-gf/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,Jeavon/Umbraco-CMS-RollbackTweak,WebCentrum/Umbraco-CMS,nvisage-gf/Umbraco-CMS,kgiszewski/Umbraco-CMS,qizhiyu/Umbraco-CMS,mstodd/Umbraco-CMS,Tronhus/Umbraco-CMS,Phosworks/Umbraco-CMS,ehornbostel/Umbraco-CMS,tompipe/Umbraco-CMS,Nicholas-Westby/Umbraco-CMS,corsjune/Umbraco-CMS,gkonings/Umbraco-CMS,rajendra1809/Umbraco-CMS,umbraco/Umbraco-CMS,Pyuuma/Umbraco-CMS,rasmuseeg/Umbraco-CMS,Pyuuma/Umbraco-CMS,aaronpowell/Umbraco-CMS,tompipe/Umbraco-CMS,rustyswayne/Umbraco-CMS,Phosworks/Umbraco-CMS,rustyswayne/Umbraco-CMS,kasperhhk/Umbraco-CMS,engern/Umbraco-CMS,bjarnef/Umbraco-CMS,markoliver288/Umbraco-CMS,MicrosoftEdge/Umbraco-CMS,m0wo/Umbraco-CMS,Jeavon/Umbraco-CMS-RollbackTweak,Phosworks/Umbraco-CMS,zidad/Umbraco-CMS,rajendra1809/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dampee/Umbraco-CMS,kasperhhk/Umbraco-CMS,kgiszewski/Umbraco-CMS,MicrosoftEdge/Umbraco-CMS,Spijkerboer/Umbraco-CMS,Khamull/Umbraco-CMS,bjarnef/Umbraco-CMS,nvisage-gf/Umbraco-CMS,romanlytvyn/Umbraco-CMS,lars-erik/Umbraco-CMS,christopherbauer/Umbraco-CMS,tcmorris/Umbraco-CMS,rajendra1809/Umbraco-CMS,TimoPerplex/Umbraco-CMS,umbraco/Umbraco-CMS,mittonp/Umbraco-CMS,rasmusfjord/Umbraco-CMS,KevinJump/Umbraco-CMS,NikRimington/Umbraco-CMS,rajendra1809/Umbraco-CMS,ordepdev/Umbraco-CMS,rustyswayne/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,m0wo/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,DaveGreasley/Umbraco-CMS,dampee/Umbraco-CMS,VDBBjorn/Umbraco-CMS,base33/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,MicrosoftEdge/Umbraco-CMS,madsoulswe/Umbraco-CMS,arknu/Umbraco-CMS,neilgaietto/Umbraco-CMS,AzarinSergey/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,abjerner/Umbraco-CMS,wtct/Umbraco-CMS,rasmuseeg/Umbraco-CMS,YsqEvilmax/Umbraco-CMS,iahdevelop/Umbraco-CMS,Jeavon/Umbraco-CMS-RollbackTweak,Door3Dev/HRI-Umbraco,tompipe/Umbraco-CMS,abryukhov/Umbraco-CMS,lingxyd/Umbraco-CMS,countrywide/Umbraco-CMS,Door3Dev/HRI-Umbraco,PeteDuncanson/Umbraco-CMS,markoliver288/Umbraco-CMS,marcemarc/Umbraco-CMS,kasperhhk/Umbraco-CMS,Tronhus/Umbraco-CMS,marcemarc/Umbraco-CMS,zidad/Umbraco-CMS,leekelleher/Umbraco-CMS | umbraco.MacroEngines.Juno/BaseContext.cs | umbraco.MacroEngines.Juno/BaseContext.cs | using System;
using System.Web.WebPages;
using umbraco.cms.businesslogic.macro;
using umbraco.interfaces;
namespace umbraco.MacroEngines
{
public abstract class BaseContext<T> : WebPage, IMacroContext {
private MacroModel _macro;
private INode _node;
protected T CurrentModel;
protected IParameterDictionary ParameterDictionary;
protected ICultureDictionary CultureDictionary;
public IParameterDictionary Parameter { get { return ParameterDictionary; } }
public ICultureDictionary Dictionary { get { return CultureDictionary; } }
public MacroModel Macro { get { return _macro; } }
public INode Node { get { return _node; } }
public T Current { get { return CurrentModel; } }
public new dynamic Model { get { return CurrentModel; } }
public virtual void SetMembers(MacroModel macro, INode node) {
if (macro == null)
throw new ArgumentNullException("macro");
if (node == null)
throw new ArgumentNullException("node");
_macro = macro;
ParameterDictionary = new UmbracoParameterDictionary(macro.Properties);
CultureDictionary = new UmbracoCultureDictionary();
_node = node;
}
protected override void ConfigurePage(WebPageBase parentPage) {
if (parentPage == null)
return;
//Inject SetMembers Into New Context
if (parentPage is IMacroContext) {
var macroContext = (IMacroContext)parentPage;
SetMembers(macroContext.Macro, macroContext.Node);
}
}
}
}
| using System;
using System.Web.WebPages;
using umbraco.cms.businesslogic.macro;
using umbraco.interfaces;
namespace umbraco.MacroEngines
{
public abstract class BaseContext<T> : WebPage, IMacroContext {
private MacroModel _macro;
private INode _node;
protected T CurrentModel;
protected ParameterDictionary ParameterDictionary;
protected CultureDictionary CultureDictionary;
public ParameterDictionary Parameter { get { return ParameterDictionary; } }
public CultureDictionary Dictionary { get { return CultureDictionary; } }
public MacroModel Macro { get { return _macro; } }
public INode Node { get { return _node; } }
public T Current { get { return CurrentModel; } }
public new dynamic Model { get { return CurrentModel; } }
public virtual void SetMembers(MacroModel macro, INode node) {
if (macro == null)
throw new ArgumentNullException("macro");
if (node == null)
throw new ArgumentNullException("node");
_macro = macro;
ParameterDictionary = new ParameterDictionary(macro.Properties);
CultureDictionary = new CultureDictionary();
_node = node;
}
protected override void ConfigurePage(WebPageBase parentPage) {
if (parentPage == null)
return;
//Inject SetMembers Into New Context
if (parentPage is IMacroContext) {
var macroContext = (IMacroContext)parentPage;
SetMembers(macroContext.Macro, macroContext.Node);
}
}
}
}
| mit | C# |
2cfd69eebb0e231fbf3c9024354ac0e37ea0c4f9 | Use 1.0.0 as the default informational version so it's easy to spot when it might have been un-patched during a build | merbla/serilog,vossad01/serilog,serilog/serilog,ajayanandgit/serilog,serilog/serilog,skomis-mm/serilog,CaioProiete/serilog,SaltyDH/serilog,richardlawley/serilog,Applicita/serilog,colin-young/serilog,adamchester/serilog,adamchester/serilog,colin-young/serilog,nblumhardt/serilog,zmaruo/serilog,joelweiss/serilog,Jaben/serilog,vorou/serilog,DavidSSL/serilog,JuanjoFuchs/serilog,khellang/serilog,clarkis117/serilog,harishjan/serilog,nblumhardt/serilog,harishjan/serilog,ravensorb/serilog,skomis-mm/serilog,ravensorb/serilog,jotautomation/serilog,joelweiss/serilog,merbla/serilog,clarkis117/serilog,redwards510/serilog | assets/CommonAssemblyInfo.cs | assets/CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")] | using System.Reflection;
[assembly: AssemblyVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.15")] | apache-2.0 | C# |
3e3569d53f539ff0c8aec1ca0dcadbcdbc4973b0 | Fix application exit. | MvvmFx/MvvmFx,tfreitasleal/MvvmFx | Samples/CaliburnMicro/BoundTreeView/BoundTreeView.WisejWeb/MainForm.cs | Samples/CaliburnMicro/BoundTreeView/BoundTreeView.WisejWeb/MainForm.cs | using System;
using System.Collections.Generic;
using MvvmFx.CaliburnMicro;
using MvvmFx.Windows.Data;
#if WISEJ
using Wisej.Web;
using LogManager = MvvmFx.WisejWeb.LogManager;
#else
using System.Windows.Forms;
using LogManager = MvvmFx.Windows.Forms.LogManager;
#endif
namespace BoundTreeView
{
public partial class MainForm : Form, IHaveDataContext
{
private readonly BindingManager _bindingManager = new BindingManager();
private bool _isBindingSet;
public MainForm()
{
InitializeComponent();
LogManager.GetLog = type => new MvvmFx.Logging.DebugLogger(type);
}
public new void Close()
{
Application.Exit();
}
#region IHaveDataContext implementation
public event EventHandler<DataContextChangedEventArgs> DataContextChanged = delegate { };
private MainFormViewModel _viewModel;
public object DataContext
{
get { return _viewModel; }
set
{
if (value != _viewModel)
{
_viewModel = value as MainFormViewModel;
DataContextChanged(this, new DataContextChangedEventArgs());
}
}
}
#endregion
#region Bind menu items
public void BindMenuItems(List<Control> namedElements)
{
if (_isBindingSet)
return;
// Binds the control visible and enabled properties.
WinFormExtensionMethods.BindToolStripItemProxyProperties(namedElements, _viewModel, _bindingManager);
_isBindingSet = true;
}
#endregion
}
} | using System;
using System.Collections.Generic;
using MvvmFx.CaliburnMicro;
using MvvmFx.Windows.Data;
#if WISEJ
using Wisej.Web;
using LogManager = MvvmFx.WisejWeb.LogManager;
#else
using System.Windows.Forms;
using LogManager = MvvmFx.Windows.Forms.LogManager;
#endif
namespace BoundTreeView
{
public partial class MainForm : Form, IHaveDataContext
{
private readonly BindingManager _bindingManager = new BindingManager();
private bool _isBindingSet;
public MainForm()
{
InitializeComponent();
LogManager.GetLog = type => new MvvmFx.Logging.DebugLogger(type);
}
#region IHaveDataContext implementation
public event EventHandler<DataContextChangedEventArgs> DataContextChanged = delegate { };
private MainFormViewModel _viewModel;
public object DataContext
{
get { return _viewModel; }
set
{
if (value != _viewModel)
{
_viewModel = value as MainFormViewModel;
DataContextChanged(this, new DataContextChangedEventArgs());
}
}
}
#endregion
#region Bind menu items
public void BindMenuItems(List<Control> namedElements)
{
if (_isBindingSet)
return;
// Binds the control visible and enabled properties.
WinFormExtensionMethods.BindToolStripItemProxyProperties(namedElements, _viewModel, _bindingManager);
_isBindingSet = true;
}
#endregion
}
} | mit | C# |
ca895608494b07ab142034c75d9a6be305a3a4fd | Remove unnecessary `!` | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | csharp/extractor/Semmle.Extraction.CIL/Entities/Base/LabelledEntity.cs | csharp/extractor/Semmle.Extraction.CIL/Entities/Base/LabelledEntity.cs | using System;
using System.Collections.Generic;
using System.IO;
namespace Semmle.Extraction.CIL
{
/// <summary>
/// An entity that needs to be populated during extraction.
/// This assigns a key and optionally extracts its contents.
/// </summary>
internal abstract class LabelledEntity : Extraction.LabelledEntity, IExtractedEntity
{
public override Context Context => (Context)base.Context;
protected LabelledEntity(Context cx) : base(cx)
{
}
public override Microsoft.CodeAnalysis.Location ReportingLocation => throw new NotImplementedException();
public void Extract(Context cx2)
{
cx2.Populate(this);
}
public override string ToString()
{
using var writer = new EscapingTextWriter();
WriteQuotedId(writer);
return writer.ToString();
}
public override TrapStackBehaviour TrapStackBehaviour => TrapStackBehaviour.NoLabel;
public abstract IEnumerable<IExtractionProduct> Contents { get; }
}
}
| using System;
using System.Collections.Generic;
using System.IO;
namespace Semmle.Extraction.CIL
{
/// <summary>
/// An entity that needs to be populated during extraction.
/// This assigns a key and optionally extracts its contents.
/// </summary>
internal abstract class LabelledEntity : Extraction.LabelledEntity, IExtractedEntity
{
public override Context Context => (Context)base.Context;
protected LabelledEntity(Context cx) : base(cx)
{
}
public override Microsoft.CodeAnalysis.Location ReportingLocation => throw new NotImplementedException();
public void Extract(Context cx2)
{
cx2.Populate(this);
}
public override string ToString()
{
using var writer = new EscapingTextWriter();
WriteQuotedId(writer);
return writer.ToString()!;
}
public override TrapStackBehaviour TrapStackBehaviour => TrapStackBehaviour.NoLabel;
public abstract IEnumerable<IExtractionProduct> Contents { get; }
}
}
| mit | C# |
6ed8c7c242beefc498465b3d2b60ca741ba9574d | Update AssemblyInfo.cs | fredatgithub/UsefulFunctions | ConsoleApplicationUsageDemo/Properties/AssemblyInfo.cs | ConsoleApplicationUsageDemo/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("ConsoleApplicationUsageDemo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Freddy Juhel")]
[assembly: AssemblyProduct("ConsoleApplicationUsageDemo")]
[assembly: AssemblyCopyright("Copyright © Freddy Juhel MIT 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("0ddf676e-4d88-42ed-8f50-f7262c2b301d")]
// 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("ConsoleApplicationUsageDemo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hewlett-Packard Company")]
[assembly: AssemblyProduct("ConsoleApplicationUsageDemo")]
[assembly: AssemblyCopyright("Copyright © Hewlett-Packard Company 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("0ddf676e-4d88-42ed-8f50-f7262c2b301d")]
// 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# |
bb661abfa65d44f1fb15f6d351f3fbcbb8e3984a | Clean up `OsuModSettingsTextBox` | smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu-new,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu | osu.Game/Graphics/UserInterface/OsuModSettingsTextBox.cs | osu.Game/Graphics/UserInterface/OsuModSettingsTextBox.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Input.Events;
using osuTK.Graphics;
namespace osu.Game.Graphics.UserInterface
{
public class OsuModSettingsTextBox : OsuTextBox
{
private const float border_thickness = 3;
private Color4 borderColourFocused;
private Color4 borderColourUnfocused;
[BackgroundDependencyLoader]
private void load(OsuColour colour)
{
borderColourUnfocused = colour.Gray4.Opacity(0.5f);
borderColourFocused = BorderColour;
updateBorder();
}
protected override void OnFocus(FocusEvent e)
{
base.OnFocus(e);
updateBorder();
}
protected override void OnFocusLost(FocusLostEvent e)
{
base.OnFocusLost(e);
updateBorder();
}
private void updateBorder()
{
BorderThickness = border_thickness;
BorderColour = HasFocus ? borderColourFocused : borderColourUnfocused;
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics.Colour;
using osu.Framework.Input.Events;
namespace osu.Game.Graphics.UserInterface
{
public class OsuModSettingsTextBox : OsuTextBox
{
private const float border_thickness = 3;
private SRGBColour borderColourFocused;
private SRGBColour borderColourUnfocused;
[BackgroundDependencyLoader]
private void load(OsuColour colour)
{
borderColourUnfocused = colour.Gray4.Opacity(0.5f);
borderColourFocused = BorderColour;
BorderThickness = border_thickness;
BorderColour = borderColourUnfocused;
}
protected override void OnFocus(FocusEvent e)
{
base.OnFocus(e);
BorderThickness = border_thickness;
BorderColour = borderColourFocused;
}
protected override void OnFocusLost(FocusLostEvent e)
{
base.OnFocusLost(e);
BorderThickness = border_thickness;
BorderColour = borderColourUnfocused;
}
}
}
| mit | C# |
503c5532714c2be5c00341c467b40bd475463816 | Update StephenOwen.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/StephenOwen.cs | src/Firehose.Web/Authors/StephenOwen.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class StephenOwen : IAmAMicrosoftMVP, IFilterMyBlogPosts
{
public string FirstName => "Stephen";
public string LastName => "Owen";
public string ShortBioOrTagLine => "FoxDeploy.SubjectMatter = writes about PowerShell";
public string StateOrRegion => "Atlanta";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "FoxDeploy";
public string GitHubHandle => "1RedOne";
public Uri WebSite => new Uri("http://www.FoxDeploy.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://foxdeploy.com/tag/powershell/feed/"); } }
public string GravatarHash => "3dd39b0d646f3b959b741eb0196c4c21";
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class StephenOwen : IAmAMicrosoftMVP, IFilterMyBlogPosts
{
public string FirstName => "Stephen";
public string LastName => "Owen";
public string ShortBioOrTagLine => "FoxDeploy.SubjectMatter = writes about PowerShell";
public string StateOrRegion => "Atlanta";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "FoxDeploy";
public string GitHubHandle => "1RedOne";
public Uri WebSite => new Uri("http://www.FoxDeploy.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://foxdeploy.com/tag/powershell/feed/"); } }
DateTime IAmAMicrosoftMVP.FirstAwarded => new DateTime(2015, 1, 1);
public string GravatarHash => "3dd39b0d646f3b959b741eb0196c4c21";
}
}
| mit | C# |
5a1f3c9364000fdf905bdd2b773d567367859e12 | Add Try block. bugid: 623 | MarimerLLC/csla,JasonBock/csla,BrettJaner/csla,ronnymgm/csla-light,rockfordlhotka/csla,jonnybee/csla,ronnymgm/csla-light,BrettJaner/csla,ronnymgm/csla-light,MarimerLLC/csla,rockfordlhotka/csla,MarimerLLC/csla,jonnybee/csla,jonnybee/csla,JasonBock/csla,rockfordlhotka/csla,BrettJaner/csla,JasonBock/csla | Source/Csla.test/Silverlight/Rollback/RollbackTests.cs | Source/Csla.test/Silverlight/Rollback/RollbackTests.cs | #if NUNIT
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestSetup = NUnit.Framework.SetUpAttribute;
#elif MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
using UnitDriven;
namespace Csla.Test.Silverlight.Rollback
{
#if SILVERLIGHT
[TestClass]
#endif
public class RollbackTests : TestBase
{
#if SILVERLIGHT
[TestMethod]
public void UnintializedProperty_RollsBack_AfterCancelEdit()
{
var context = GetContext();
RollbackRoot.BeginCreateLocal((o, e) =>
{
context.Assert.Try(() =>
{
var item = e.Object;
var initialValue = 0;// item.UnInitedP;
item.BeginEdit();
item.UnInitedP = 1000;
item.Another = "test";
item.CancelEdit();
context.Assert.AreEqual(initialValue, item.UnInitedP);
context.Assert.Success();
});
});
context.Complete();
}
#endif
}
}
| #if NUNIT
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestSetup = NUnit.Framework.SetUpAttribute;
#elif MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
using UnitDriven;
namespace Csla.Test.Silverlight.Rollback
{
#if SILVERLIGHT
[TestClass]
#endif
public class RollbackTests : TestBase
{
#if SILVERLIGHT
[TestMethod]
public void UnintializedProperty_RollsBack_AfterCancelEdit()
{
var context = GetContext();
RollbackRoot.BeginCreateLocal((o, e) =>
{
var item = e.Object;
var initialValue = 0;// item.UnInitedP;
item.BeginEdit();
item.UnInitedP = 1000;
item.Another = "test";
item.CancelEdit();
context.Assert.AreEqual(initialValue, item.UnInitedP);
context.Assert.Success();
});
context.Complete();
}
#endif
}
}
| mit | C# |
81dabbaa1e4cafebd5b6adb40c733d31b089a46a | Add null check to CommitCollection | gep13/GitVersion,GitTools/GitVersion,GitTools/GitVersion,asbjornu/GitVersion,gep13/GitVersion,asbjornu/GitVersion | src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs | src/GitVersion.LibGit2Sharp/Git/CommitCollection.cs | using GitVersion.Extensions;
using LibGit2Sharp;
namespace GitVersion;
internal sealed class CommitCollection : ICommitCollection
{
private readonly ICommitLog innerCollection;
internal CommitCollection(ICommitLog collection) => this.innerCollection = collection.NotNull();
public IEnumerator<ICommit> GetEnumerator()
=> this.innerCollection.Select(commit => new Commit(commit)).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IEnumerable<ICommit> GetCommitsPriorTo(DateTimeOffset olderThan)
=> this.SkipWhile(c => c.When > olderThan);
public IEnumerable<ICommit> QueryBy(CommitFilter commitFilter)
{
static object? GetReacheableFrom(object? item) =>
item switch
{
Commit c => (LibGit2Sharp.Commit)c,
Branch b => (LibGit2Sharp.Branch)b,
_ => null
};
var includeReachableFrom = GetReacheableFrom(commitFilter.IncludeReachableFrom);
var excludeReachableFrom = GetReacheableFrom(commitFilter.ExcludeReachableFrom);
var filter = new LibGit2Sharp.CommitFilter { IncludeReachableFrom = includeReachableFrom, ExcludeReachableFrom = excludeReachableFrom, FirstParentOnly = commitFilter.FirstParentOnly, SortBy = (LibGit2Sharp.CommitSortStrategies)commitFilter.SortBy };
var commitLog = ((IQueryableCommitLog)this.innerCollection).QueryBy(filter);
return new CommitCollection(commitLog);
}
}
| using LibGit2Sharp;
namespace GitVersion;
internal sealed class CommitCollection : ICommitCollection
{
private readonly ICommitLog innerCollection;
internal CommitCollection(ICommitLog collection) => this.innerCollection = collection;
public IEnumerator<ICommit> GetEnumerator() => this.innerCollection.Select(commit => new Commit(commit)).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IEnumerable<ICommit> GetCommitsPriorTo(DateTimeOffset olderThan) => this.SkipWhile(c => c.When > olderThan);
public IEnumerable<ICommit> QueryBy(CommitFilter commitFilter)
{
static object? GetReacheableFrom(object? item) =>
item switch
{
Commit c => (LibGit2Sharp.Commit)c,
Branch b => (LibGit2Sharp.Branch)b,
_ => null
};
var includeReachableFrom = GetReacheableFrom(commitFilter.IncludeReachableFrom);
var excludeReachableFrom = GetReacheableFrom(commitFilter.ExcludeReachableFrom);
var filter = new LibGit2Sharp.CommitFilter
{
IncludeReachableFrom = includeReachableFrom,
ExcludeReachableFrom = excludeReachableFrom,
FirstParentOnly = commitFilter.FirstParentOnly,
SortBy = (LibGit2Sharp.CommitSortStrategies)commitFilter.SortBy
};
var commitLog = ((IQueryableCommitLog)this.innerCollection).QueryBy(filter);
return new CommitCollection(commitLog);
}
}
| mit | C# |
7aaf4faff7d211ce2428103be258225244c0c608 | remove redundant conditional compilation | joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet | src/GraphQL/DataLoader/DataLoaderContextAccessor.cs | src/GraphQL/DataLoader/DataLoaderContextAccessor.cs | using System.Threading;
namespace GraphQL.DataLoader
{
public class DataLoaderContextAccessor : IDataLoaderContextAccessor
{
private readonly AsyncLocal<DataLoaderContext> _current = new AsyncLocal<DataLoaderContext>();
public DataLoaderContext Context
{
get => _current.Value;
set => _current.Value = value;
}
}
}
| #if NET45
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting;
#else
using System.Threading;
#endif
namespace GraphQL.DataLoader
{
public class DataLoaderContextAccessor : IDataLoaderContextAccessor
{
#if NET45
private const string LogicalDataKey = "__DataLoaderContext_Current__";
public DataLoaderContext Context
{
get
{
var handle = CallContext.LogicalGetData(LogicalDataKey) as ObjectHandle;
return handle?.Unwrap() as DataLoaderContext;
}
set
{
CallContext.LogicalSetData(LogicalDataKey, new ObjectHandle(value));
}
}
#else
private readonly AsyncLocal<DataLoaderContext> _current = new AsyncLocal<DataLoaderContext>();
public DataLoaderContext Context
{
get => _current.Value;
set => _current.Value = value;
}
#endif
}
}
| mit | C# |
95ef73bc40b66e5ed00af86f7b67d87271b84793 | Remove random context cleanup console output | gphoto/libgphoto2,gphoto/libgphoto2,msmeissn/libgphoto2,gphoto/libgphoto2,msmeissn/libgphoto2,jbreeden/libgphoto2,thusoy/libgphoto2,jbreeden/libgphoto2,gphoto/libgphoto2,thusoy/libgphoto2,jbreeden/libgphoto2,thusoy/libgphoto2,msmeissn/libgphoto2,thusoy/libgphoto2,jbreeden/libgphoto2,msmeissn/libgphoto2,jbreeden/libgphoto2,msmeissn/libgphoto2,gphoto/libgphoto2,thusoy/libgphoto2,gphoto/libgphoto2 | bindings/csharp/Context.cs | bindings/csharp/Context.cs | using System;
using System.Runtime.InteropServices;
namespace LibGPhoto2
{
public class Context : Object
{
[DllImport ("libgphoto2.so")]
internal static extern IntPtr gp_context_new ();
public Context ()
{
this.handle = new HandleRef (this, gp_context_new ());
}
[DllImport ("libgphoto2.so")]
internal static extern void gp_context_unref (HandleRef context);
protected override void Cleanup ()
{
gp_context_unref(handle);
}
}
}
| using System;
using System.Runtime.InteropServices;
namespace LibGPhoto2
{
public class Context : Object
{
[DllImport ("libgphoto2.so")]
internal static extern IntPtr gp_context_new ();
public Context ()
{
this.handle = new HandleRef (this, gp_context_new ());
}
[DllImport ("libgphoto2.so")]
internal static extern void gp_context_unref (HandleRef context);
protected override void Cleanup ()
{
System.Console.WriteLine ("cleanup context");
gp_context_unref(handle);
}
}
}
| lgpl-2.1 | C# |
150162594d83cfb7c12d9ceb6ccc638234af0ab3 | Update doc to match latest version on nuget.org | softlion/XamarinFormsGesture | Demo/DemoApp/DemoApp/MainPageViewModel.cs | Demo/DemoApp/DemoApp/MainPageViewModel.cs | using System;
using System.Windows.Input;
using Vapolia.Lib.Ui;
using Xamarin.Forms;
namespace DemoApp
{
public class MainPageViewModel : BindableObject
{
private readonly INavigation navigation;
private Point pan, pinch;
private double rotation, scale;
public Point Pan { get => pan; set { pan = value; OnPropertyChanged(); } }
public Point Pinch { get => pinch; set { pinch = value; OnPropertyChanged(); } }
public double Rotation { get => rotation; set { rotation = value; OnPropertyChanged(); } }
public double Scale { get => scale; set { scale = value; OnPropertyChanged(); } }
public MainPageViewModel(INavigation navigation)
{
this.navigation = navigation;
}
public ICommand PanPointCommand => new Command<(Point Point,GestureStatus Status)>(args =>
{
var point = args.Point;
Pan = point;
});
public ICommand PinchCommand => new Command<PinchEventArgs>(args =>
{
Pinch = args.Center;
Rotation = args.RotationDegrees;
Scale = args.Scale;
});
public ICommand OpenVapoliaCommand => new Command(async () =>
{
await navigation.PushAsync(new ContentPage {
Title = "Web",
Content = new Grid {
BackgroundColor = Color.Yellow,
Children = { new WebView { Source = new UrlWebViewSource { Url = "https://vapolia.fr" }, HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.Fill} }}});
});
public ICommand OpenVapoliaPointCommand => new Command<Point>(point =>
{
Pan = point;
OpenVapoliaCommand.Execute(null);
});
}
} | using System;
using System.Windows.Input;
using Vapolia.Lib.Ui;
using Xamarin.Forms;
namespace DemoApp
{
public class MainPageViewModel : BindableObject
{
private readonly INavigation navigation;
private Point pan, pinch;
private double rotation, scale;
public Point Pan { get => pan; set { pan = value; OnPropertyChanged(); } }
public Point Pinch { get => pinch; set { pinch = value; OnPropertyChanged(); } }
public double Rotation { get => rotation; set { rotation = value; OnPropertyChanged(); } }
public double Scale { get => scale; set { scale = value; OnPropertyChanged(); } }
public MainPageViewModel(INavigation navigation)
{
this.navigation = navigation;
}
public ICommand PanPointCommand => new Command<(Point Point,GestureStatus Status)>(args =>
{
var point = args.Point;
Pan = point;
});
public ICommand PinchCommand => new Command<PinchEventArgs>(args =>
{
Pinch = args.Center;
Rotation = args.Rotation * 180 / Math.PI;
Scale = args.Scale;
});
public ICommand OpenVapoliaCommand => new Command(async () =>
{
await navigation.PushAsync(new ContentPage {
Title = "Web",
Content = new Grid {
BackgroundColor = Color.Yellow,
Children = { new WebView { Source = new UrlWebViewSource { Url = "https://vapolia.fr" }, HorizontalOptions = LayoutOptions.Fill, VerticalOptions = LayoutOptions.Fill} }}});
});
public ICommand OpenVapoliaPointCommand => new Command<Point>(point =>
{
Pan = point;
OpenVapoliaCommand.Execute(null);
});
}
} | apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.